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 new_pin_added(sender, instance, created, **kwargs): data = PinSerializer(instance=instance).data data = {k: str(v) for k, v in data.items()} message = messaging.Message( android=messaging.AndroidConfig( ttl=datetime.timedelta(seconds=3600), priority='high', notification=messaging.AndroidNotification( title='Pin-It', body='New pin added near you!', ), ), data=data, ) registration_ids = (FCMDevice.objects.values_list('registration_id', flat=True).distinct()) for reg_id in registration_ids: message.token = reg_id try: messaging.send(message) except Exception: pass
def notifyReceiver(fb, token, count): messageText = "message received" if (count): if (count == 1): messageText = "1 message received" else: messageText = "%d messages received" % count androidNotification = messaging.AndroidNotification( sound="default", click_action="FCM_PLUGIN_ACTIVITY", tag="ONLY EVER UPDATE THIS ONE") androidConfig = messaging.AndroidConfig(collapse_key="key", priority="high", notification=androidNotification) messageNotification = messaging.Notification(title="Together", body=messageText) message = messaging.Message(data={"action": ACTION_MESSAGE_RECEIVED}, notification=messageNotification, token=token, android=androidConfig) messaging.send(message, dry_run=False, app=fb)
def send_notification_to_all(message): registration_tokens = list( User.objects.exclude(fcm_token__isnull=True).exclude( fcm_token__exact='').values_list('fcm_token', flat=True)) topic = 'events' messaging.subscribe_to_topic(registration_tokens, topic) message = messaging.Message( android=messaging.AndroidConfig( ttl=datetime.timedelta(seconds=3600), priority='normal', notification=messaging.AndroidNotification( title=message["title"], body=message["message"], ), ), topic=topic, ) response = messaging.send(message) print(response) messaging.unsubscribe_from_topic(registration_tokens, topic)
def all_platforms_message(registration_token, title, body, data): # [START multi_platforms_message] message = 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' ), ), ) ) # [END multi_platforms_message] response = messaging.send(message) # See the BatchResponse reference documentation # for the contents of response. print(response)
def build_multiple_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 # Send a message to the device corresponding to the provided # registration token. #response = messaging.send(build_single_message()) # Response is a message ID string. #print('Successfully sent message:', response)
def send_to_topic(topic, message, priority=None): if priority is None: response = messaging.send( messaging.Message(data={ 'time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), 'message': message }, topic=topic)) else: response = messaging.send( messaging.Message(data={ 'time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), 'message': message }, topic=topic)) response = messaging.send( messaging.Message( data={ 'time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), 'message': message }, notification=messaging.Notification(title='Notification', body=message), android=messaging.AndroidConfig( priority=priority, restricted_package_name='', notification=messaging.AndroidNotification( icon='fcm_push_icon', sound='default', click_action='FCM_PLUGIN_ACTIVITY')), topic=topic))
def send_notify_ios_android(registration_token, title, body, data): # [START android_message] try: message = 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( payload=messaging.APNSPayload( aps=messaging.Aps( alert=messaging.ApsAlert( title=title, body=body, ), badge=1, ) ) ) ) # [END android_message] print("send_notify_ios_android.data===",data) response = messaging.send(message) print("send send_notify_ios_android====",response) except Exception as error: print(error) pass
def send_notifications(self, registration_tokens, title, body): message = messaging.MulticastMessage( notification=messaging.Notification( title=title, body=body, ), android=messaging.AndroidConfig( priority='normal', notification=messaging.AndroidNotification( icon='stock_ticker_update', color='#f45342'), ), apns=messaging.APNSConfig(payload=messaging.APNSPayload( aps=messaging.Aps(badge=42), ), ), tokens=registration_tokens) response = messaging.send_multicast(message) 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]) print('List of tokens that caused failures: {0}'.format( failed_tokens))
def all_platforms_message(): # [START multi_platforms_message] 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), ), ), topic='industry-tech', ) # [END multi_platforms_message] return message
def push_message(token, title, body): token = token message = messaging.Message( android=messaging.AndroidConfig( ttl=datetime.timedelta(seconds=3600), priority='normal', notification=messaging.AndroidNotification( title = title, body = body, icon='', color='#f45342', sound='default' ) ), token = token ) try: response = messaging.send(message) print("Successfully sent message:", response) except Exception: print(Exception) return
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', 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 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', notification=messaging.AndroidNotification( title='제목', body='내용', icon='', color='#f45342', sound='default' ), ), 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 accept_request(): """ Accept join request """ id_token = request.args.get('id_token') request_id = request.args.get('request_id') response = request.args.get('response') decoded_token = auth.verify_id_token(id_token) uid = decoded_token['uid'] user_doc_ref = db_ref.collection(u'users').document(uid) user_details = user_doc_ref.get().to_dict() notificaions = user_details.get('notifications') notification_to_react_ = [ i for i in notificaions if str(i.get('request_id')) == request_id ] notification_to_react = notification_to_react_[0] # requester information requester_uid = notification_to_react.get('requester_uid') requested_node_name = notification_to_react.get('node_name') requester_user_doc_ref = db_ref.collection(u'users').document( requester_uid) requester_user_details = requester_user_doc_ref.get().to_dict() node_doc_ref = db_ref.collection(u'nodes').document(requested_node_name) if (response == "accept"): # add node to connected nodes requester_user_details.get('connected_nodes').append(node_doc_ref) requester_user_doc_ref.update(user_details, option=None) # add user to connected users in nodes coll node_details = node_doc_ref.get().to_dict() node_details.get('connected_users').append(requester_user_doc_ref) # add details to connected_nodes_data (repeat data) node_profile_pic = node_details.get('profile_pic') node_description = node_details.get('node_description') requester_user_details.get('connected_nodes_data').append({ "name": requested_node_name, "profile_pic": node_profile_pic, "node_description": node_description }) requester_user_details.get('requested_nodes').remove(node_doc_ref) node_doc_ref.update(node_details, option=None) requester_user_doc_ref.update(requester_user_details, option=None) # remove the notificaiton user_details.get('notifications').remove(notification_to_react) user_doc_ref.update(user_details, option=None) token = requester_user_details.get('fcm_token') full_name = user_details.get('full_name') message = messaging.Message( android=messaging.AndroidConfig( priority='normal', notification=messaging.AndroidNotification( title="Request Accepted! - {}".format(requested_node_name), body="Your join request was accepted by {}".format( full_name), icon='fcm_push_icon', color='#364156'), ), token=token, ) messaging.send(message) return jsonify(status="SUCCESS", operation="accept user join request") if (response == "notAccept"): # remove the notificaiton user_details.get('notifications').remove(notification_to_react) user_doc_ref.update(user_details, option=None) requester_user_details.get('requested_nodes').remove(node_doc_ref) requester_user_doc_ref.update(requester_user_details, option=None) token = requester_user_details.get('fcm_token') message = messaging.Message( android=messaging.AndroidConfig( priority='normal', notification=messaging.AndroidNotification( title="Sorry! - {}".format(requested_node_name), body="Your request was not accepted.", icon='fcm_push_icon', color='#364156'), ), token=token, ) messaging.send(message) return jsonify(status="SUCCESS", operation="ignore join request")
def join_node(): """ Join a user to a node """ id_token = request.args.get('id_token') node_name = request.args.get('node_name') try: # check whether user already connected to requested node node_doc_ref = db_ref.collection(u'nodes').document(node_name) decoded_token = auth.verify_id_token(id_token) uid = decoded_token['uid'] # if user hasnt verified email then avoid beign able to join nodes user_recode = auth.get_user(uid) if (not user_recode.email_verified): raise Exception('EMAIL_NOT_VERIFIED') user_doc_ref = db_ref.collection(u'users').document(uid) user_details = user_doc_ref.get().to_dict() connected_nodes = user_details.get('connected_nodes') if (node_doc_ref not in connected_nodes): # if user is not connected to the node but # already requested to join requested_nodes = user_details.get('requested_nodes') if (node_doc_ref not in requested_nodes): # if user not joined and not requested to the node # if noone in the node then requesting user must be able # to join without requesting permissions node_details = node_doc_ref.get().to_dict() connected_users = node_details.get('connected_users') if (len(connected_users) == 0): # add node to connected nodes user_details = user_doc_ref.get().to_dict() #return (str(user_details)) user_details.get('connected_nodes').append(node_doc_ref) user_doc_ref.update(user_details, option=None) # add user to connected users in nodes coll node_details = node_doc_ref.get().to_dict() node_details.get('connected_users').append(user_doc_ref) # add details to connected_nodes_data (repeat data) node_profile_pic = node_details.get('profile_pic') node_description = node_details.get('node_description') user_details.get('connected_nodes_data').append({ "name": node_name, "profile_pic": node_profile_pic, "node_description": node_description }) user_doc_ref.update(user_details, option=None) node_doc_ref.update(node_details, option=None) return jsonify(status="SUCCESS", operation="JOINED") # append requesting node to requested_nodes user_details.get('requested_nodes').append(node_doc_ref) # need to send join request to first user in connected_users in requested node node_details = node_doc_ref.get().to_dict() connected_users = node_details.get('connected_users') node_admin_user = connected_users[0] node_admin_user_details = node_admin_user.get().to_dict() requester_full_name = user_details.get('full_name') requester_profile_pic = user_details.get('profile_pic') request_id = random.randint(0, 10000) # need to append notification details to notification array notification = { "type": "JOIN_REQUEST", "requester_uid": uid, "node_name": node_name, "requester_name": requester_full_name, "request_id": request_id, "profile_pic": requester_profile_pic } node_admin_user_details.get('notifications').append( notification) # save changes node_admin_user.update(node_admin_user_details, option=None) user_doc_ref.update(user_details, option=None) token = node_admin_user_details.get('fcm_token') message = messaging.Message( android=messaging.AndroidConfig( priority='normal', notification=messaging.AndroidNotification( title="Join Request", body="{} sent a join request".format( requester_full_name), icon='fcm_push_icon', color='#364156'), ), token=token, ) messaging.send(message) return jsonify(status="SUCCESS", operation="Join request send") return jsonify(status="FAILED", operation="Join request send", reason="ALREADY_REQUESTED") return jsonify(status="FAILED", operation="Join request send", reason="ALREADY_JOINED") except Exception as e: return jsonify(error=str(e), status="FAILED")
def test_firebase_call(): print('1') if not firebase_admin._apps: cred = credentials.Certificate(cred_cert) default_app = firebase_admin.initialize_app(cred) print('2') body = 'Remind time 00:00' n = messaging.Notification(title='test_firebase_call', body=body, image=None) priority = 'normal' myicon = 'https://rusel.by/static/rok/img/test-192.png' mybadge = 'https://rusel.by/static/rok/img/test-72.png' click_action = 'https://rusel.by/todo/99999/' an = messaging.AndroidNotification(title = 'test_firebase_call', body = body, icon = myicon, color = None, sound = None, tag = None, click_action = click_action, body_loc_key = None, \ body_loc_args = None, title_loc_key = None, title_loc_args = None, channel_id = None, image = None, ticker = None, sticky = None, \ event_timestamp = None, local_only = None, priority = None, vibrate_timings_millis = None, default_vibrate_timings = None, \ default_sound = None, light_settings = None, default_light_settings = None, visibility = None, notification_count = None) añ = messaging.AndroidConfig(collapse_key=None, priority=priority, ttl=None, restricted_package_name=None, data=None, notification=an, fcm_options=None) actions = [] a1 = messaging.WebpushNotificationAction( 'postpone', 'Postpone', icon='https://rusel.by/static/todo/icon/remind-today.png') a2 = messaging.WebpushNotificationAction( 'done', 'Done', icon='https://rusel.by/static/rok/icon/delete.png') actions.append(a1) actions.append(a2) print('3') #wn = messaging.WebpushNotification(title = task.name, body = body, icon = icon, actions = actions, badge = None, data = None, direction = None, image = None, language = None, renotify = True, require_interaction = True, silent = False, tag = None, timestamp_millis = None, vibrate = None, custom_data = None) wn = messaging.WebpushNotification( title='test_firebase_call', body=body, icon=myicon, badge=mybadge, actions=actions, tag='99999', custom_data={"click_action": click_action}) wo = messaging.WebpushFCMOptions(click_action) wc = messaging.WebpushConfig(headers=None, data=None, notification=wn, fcm_options=None) tokens = [] tokens.append( 'dq6oUJNrQ2IYcm3mVtzfw8:APA91bE_3q9CdIAMWw6Blh0uGmLve5dv_AeHY4kJec6tGM34Vw3wMN6WIEZveI60Yl0neNeeSzmD1zwcvuC0A49Ht7t90mHxD47jE8duyQX0090qRflS7hVo0lm-qJ_wLJsJ59_nJFtQ' ) print('4') mm = messaging.MulticastMessage(tokens=tokens, data=None, notification=n, android=None, webpush=wc, apns=None, fcm_options=None) print('5') r = messaging.send_multicast(mm, dry_run=False, app=None) print('6') ret_resp = '[' + str(len(r.responses)) + ']: ' npp = 0 for z in r.responses: if (len(ret_resp) > 0): ret_resp += ', ' if z.success: ret_resp += '1' else: ret_resp += '0 ' + z.exception.code if (z.exception.code == 'NOT_FOUND'): ss[npp].delete() npp += 1 if z.message_id: ret_resp += ':' + z.message_id
def test_no_body_loc_key(self): notification = messaging.AndroidNotification(body_loc_args=['foo']) excinfo = self._check_notification(notification) expected = 'AndroidNotification.body_loc_key is required when specifying body_loc_args.' assert str(excinfo.value) == expected
def test_invalid_body_loc_key(self, data): notification = messaging.AndroidNotification(body_loc_key=data) excinfo = self._check_notification(notification) assert str(excinfo.value ) == 'AndroidNotification.body_loc_key must be a string.'
def test_invalid_click_action(self, data): notification = messaging.AndroidNotification(click_action=data) excinfo = self._check_notification(notification) assert str(excinfo.value ) == 'AndroidNotification.click_action must be a string.'
message = messaging.Message( notification=messaging.Notification( title="213", body="921", image="", ), data={ 'url': "", }, android=messaging.AndroidConfig( # collapse_key=, priority='high', ttl=datetime.timedelta(hours=6), # data={}, notification=messaging.AndroidNotification(color='#1c2676'), # for analyzing on all platforms and link on web. https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages # fcm_options={}, ), # apns' config is more complicated than android's. So, I only listed useful options here and please refer Apple docs for more detail. apns=messaging.APNSConfig( headers={ # "apns-collapse-id": "qqq", # TODO to fit Ruby form # "apns-expiration": "1585190586", # "apns-priority": "10", # default }, payload=messaging.APNSPayload( aps=messaging.Aps( # override notification field
# This is registration token received on mobile phone from the client FCM SDKs. # There is no way to receive it in Python: it is specific to the given app installation on the phone. # Every chat client has such a token. All the communication is encrypted with this token. # How it is received - see Android application at # https://medium.com/@min2bhandari/firebase-cloud-messaging-with-kotlin-165ac1b0d841 # replace this token with yours! recipient_token = "eT6B_xQRRFGVtK8xa71zBp:APA91bE9IK2wQtJkoLvEQdjhASPvmdFzxJs-sWedpbh3nSbUWinmtVZ10A8bun4YxG5UXaQHK3ExRZajQSYetdk-Yil-TEkKNjz03b_n45Yp5zV9ZHExtlIlbwr5dd5ukpNSQbx9RkuO" # send Notification to a single recipient notification = messaging.Message(android=messaging.AndroidConfig( ttl=datetime.timedelta(seconds=3600), priority='normal', notification=messaging.AndroidNotification(title='Try', body='It works!', icon='stock_ticker_update', color='#f45342')), token=recipient_token) # send (it must appear in Phone's tray as a pop-up notification) response = messaging.send(notification) # create Notification to all users of our chat notification = messaging.Message(android=messaging.AndroidConfig( ttl=datetime.timedelta(seconds=3600), priority='normal', notification=messaging.AndroidNotification(title='Try', body='It works!', icon='stock_ticker_update', color='#f45342')), topic="ThresholdChat") # send (it must appear in Phone's tray as a pop-up notification)
def fcm_push(notification_id, tokens=None): """ FCM message push, either to all users subscribed to the topic(category slug), or to a specific user targeted by the specified token. :param notification_id: Notification id. :param tokens: Specific tokens of clients to push the notification to. :return: None """ try: notification = Notification.objects.get(id=notification_id) app_config = notification.category.app_config except Notification.DoesNotExist: return False base_notification = messaging.Notification( title=notification.category.name, body=notification.template, ) android_conf = messaging.AndroidConfig( notification=messaging.AndroidNotification( click_action=notification.android_onclick_activity)) if app_config is not None and app_config.assets is not None: icon_url = os.path.join( settings.STATIC_URL, app_config.base_urls.static, 'assets', app_config.assets.logo, ) else: icon_url = os.path.join( settings.STATIC_URL, 'notifications', settings.DISCOVERY.get_app_configuration( 'notifications').base_urls.static, 'bell_icon.svg') webpush_conf = messaging.WebpushConfig( notification=messaging.WebpushNotification( icon=icon_url, actions=[ messaging.WebpushNotificationAction( action=notification.web_onclick_url, title=f'Open {notification.web_onclick_url}') ])) # If tokens are provided, make a multicast message # else it is assumed that it is a topic based broadcast if tokens: message = messaging.MulticastMessage(notification=base_notification, android=android_conf, webpush=webpush_conf, tokens=tokens) else: message = messaging.Message(notification=base_notification, android=android_conf, webpush=webpush_conf, topic=notification.category.slug) try: # use dry_run = True for testing purpose if tokens: _ = messaging.send_multicast(message, dry_run=False) else: _ = messaging.send(message, dry_run=False) except messaging.ApiCallError as e: return False except ValueError as e: return False return True
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() return None
cond3_ok = jres["cond3"] > 0 cond4_ok = jres["cond4"] > 0 ok = cond1_ok and cond2_ok and cond3_ok and cond4_ok #Can add all the conditions that we want log(res.status_code, cond1_ok, cond2_ok, cond3_ok, cond4_ok) except e: log(e) pass if not ok and (now - mint) > lass: cred = credentials.Certificate(CERTIFICATE_FIREBASE) firebase_admin.initialize_app(cred) # See documentation on defining a message payload. message = messaging.Message( notification=messaging.Notification( title='Server on ' + HOST, body='Something went wrong !!', ), android=messaging.AndroidConfig( priority='high', notification=messaging.AndroidNotification(sound='default'), ), topic=topic, ) # Send a message to the devices subscribed to the provided topic. response = messaging.send(message) # Response is a message ID string. print('Successfully sent message:', response) last = open("last", "w") last.write(str(now)) last.close()
def submit(): if patientID.get() == '': tkMessageBox.showinfo(message="select patientID") return if coughpath.get() == '': tkMessageBox.showinfo(message="Select audio file") return signal_path = coughpath.get() coughpath.set('') symptoms, fcmtoken = get_patient_symptoms(patientID.get()) print('symptoms', np.shape(symptoms)) events_path = Prediction.extractEvents(signal_path, patientID.get()) output = Prediction.disease_classify(events_path, patientID.get(), symptoms) db_root = db.reference() new_user = db_root.child(patientID.get()).child(timestamp).push({ 'PatientID': patientID.get(), 'Symptoms': str(symptoms), 'advice': output }) message = messaging.Message(android=messaging.AndroidConfig( ttl=datetime.timedelta(seconds=3600), priority='normal', notification=messaging.AndroidNotification(title=patientID.get(), body=output, icon='stock_ticker_update', color='#f45342'), ), token=fcmtoken) # 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) tkMessageBox.showinfo(message=output) #upload raw audio to the cloud storage fileUpload = bucket.blob(patientID.get() + '/' + timestamp + '/' + timestamp) fileUpload.upload_from_filename(signal_path) #upload extracted events to the cloud ''' for file in os.listdir('recordings/'+patientid+'/cough'): fileUpload = bucket.blob(patientid + '/' + timestamp + '/cough/' + file) fileUpload.upload_from_filename('recordings/'+patientid+'/cough/'+ file) for file in os.listdir('recordings/' + patientid + '/noncough'): fileUpload = bucket.blob(patientid + '/' + timestamp + '/noncough/' + file) fileUpload.upload_from_filename('recordings/' + patientid + '/noncough/' + file) ''' print("Data sync completed")
def construct_body(title: str, topic: str, category: str = None, data: dict = None, body_text: str = '', alert_sound: str = 'default', critical: bool = False, web_badge: str = '', web_icon: str = '', vibration_pattern: Sequence[int] = None, priority: str = 'normal'): if data is None: data = {} if vibration_pattern is None: vibration_pattern = DEFAULT_VIBRATION_PATTERN android_notification_additional_config = {} aps_additional_config = {} if category is not None: android_notification_additional_config['click_action'] = category aps_additional_config['category'] = category # https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/PayloadKeyReference.html#//apple_ref/doc/uid/TP40008194-CH17-SW5 fcm_body = { 'data': data, 'android': messaging.AndroidConfig( priority=ANDROID_PRIORITIES[priority], # normal and high ttl=300, notification=messaging.AndroidNotification( title=title, body=body_text, **android_notification_additional_config, ), ), 'webpush': messaging.WebpushConfig( headers={ 'TTL': '300', 'Urgency': priority, # can be very-low, low, normal, or high 'Topic': topic, }, # Send everything in a dict instead so that we can handle the notifications ourselves. data=dict( notification=json.dumps(dict( title=title, body=body_text, # URL for badge icon badge=web_badge, icon=web_icon, # URL for icon # should the user be renotified if an old notification is replaced by a new one # renotify=True, # Should the notification remain active until the user clicks or dismisses it rather than closing automatically require_interaction=False, silent=False, # should the notification be comletely silent regardless of device settings # vibration pattern vibrate=vibration_pattern, )), **data ), # fcm_options=messaging.WebpushFcmOptions( # link='', # link to open when the user clicks on the notification # ), ), 'apns': messaging.APNSConfig( headers={ # The date at which the notification is no longer valid. This value # is a Unix epoch expressed in seconds (UTC). If the value is # nonzero, APNs stores the notification and tries to deliver it at # least once, repeating the attempt as needed until the specified # date. If the value is 0, APNs attempts to deliver the # notification only once and does not store the notification. 'apns-expiration': str(int(datetime.timestamp( datetime.utcnow() + FIVE_MINUTES))), # This should be the default, but we will specify it here manually. # 10 should be immediate, while 5 does it based off of power # considerations. 'apns-priority': IOS_PRIORITIES[priority], # Generally the app's bundle ID. # 'apns-topic': settings.FCM_NOTIFICATIONS['bundle_id'], # 64 bytes at most and is used to collapse notifications if the # notifications are the same. 'apns-collpase-id': topic, }, payload=messaging.APNSPayload( aps=messaging.Aps( alert=messaging.ApsAlert( title=title, # short string that descirbes purpose # subtitle='', body=body_text, # body text of message ), # badge=0, # badge counter sound=messaging.CriticalSound( alert_sound, critical=critical, volume=1), # sound to play content_available=True, # use 1 to indicate that the system has new data to handle # used for grouping along with a Notification Content app extension mutable_content=True, custom_data=data, **aps_additional_config, ), **data ), ), } return fcm_body
def test_invalid_tag(self, data): notification = messaging.AndroidNotification(tag=data) excinfo = self._check_notification(notification) assert str( excinfo.value) == 'AndroidNotification.tag must be a string.'
def remind_one_task(log, task): if not firebase_admin._apps: cred = credentials.Certificate(cred_cert) firebase_admin.initialize_app(cred) body = task['term'] + ' - ' + task['group'] n = messaging.Notification(title=task['name'], body=body, image=None) if (task['important']): priority = 'high' else: priority = 'normal' myicon = HOST + '/static/rusel.png' mybadge = '' click_action = HOST + '/todo/' + str(task['id']) + '/' an = messaging.AndroidNotification(title=task['name'], body=body, icon=myicon, color=None, sound=None, tag=None, click_action=click_action, body_loc_key=None, \ body_loc_args=None, title_loc_key=None, title_loc_args=None, channel_id=None, image=None, ticker=None, sticky=None, \ event_timestamp=None, local_only=None, priority=None, vibrate_timings_millis=None, default_vibrate_timings=None, \ default_sound=None, light_settings=None, default_light_settings=None, visibility=None, notification_count=None) messaging.AndroidConfig(collapse_key=None, priority=priority, ttl=None, restricted_package_name=None, data=None, notification=an, fcm_options=None) actions = [] a1 = messaging.WebpushNotificationAction('postpone', 'Postpone 1 hour', icon=HOST+'/static/icons/postpone.png') a2 = messaging.WebpushNotificationAction('done', 'Done', icon=HOST+'/static/icons/completed.png') actions.append(a1) actions.append(a2) wn = messaging.WebpushNotification(title=task['name'], body=body, icon=myicon, badge=mybadge, actions=actions, tag=str(task['id']), custom_data={"click_action": click_action}) messaging.WebpushFCMOptions(click_action) wc = messaging.WebpushConfig(headers=None, data=None, notification=wn, fcm_options=None) resp = requests.get(TASK_API_TOKENS.format(task['user_id']), headers=headers, verify=verify) data = resp.json() if ('result' not in data) or (len(data['result']) == 0): log('[TODO] No tokens for user_id = ' + str(task['user_id'])) return tokens = data['result'] mm = messaging.MulticastMessage(tokens=tokens, data=None, notification=n, android=None, webpush=wc, apns=None, fcm_options=None) r = messaging.send_multicast(mm, dry_run=False, app=None) ret_resp = '[' + str(len(r.responses)) + ']' log('[TODO] Remind task ID: {}, ok: {}, err: {}, resp: {}, name: "{}"'.format(task['id'], r.success_count, r.failure_count, ret_resp, task['name'])) npp = 1 for z in r.responses: if z.success: status = 'Success' error_desc = '' else: status = 'Fail' error_desc = ', ' + z.exception.code msg = '' if z.message_id: msg += ', message_id = "' + z.message_id + '"' log(' {}. {}{}{}'.format(npp, status, error_desc, msg)) log(' token "' + tokens[npp-1] + '"') if (not z.success) and (z.exception.code == 'NOT_FOUND'): resp = requests.get(TASK_API_DEL_TOKEN.format(task['user_id'], tokens[npp-1]), headers=headers, verify=verify) data = resp.json() if ('result' not in data) and data['result']: log(' [!] Token deleted.') npp += 1 requests.get(TASK_API_REMINDED.format(task['id']), headers=headers, verify=verify)
def sendNotification(self,user_ids,title,body=None,data=None,color=None,dry_run=False): """Sends notifications to a user or group or users Args: user_ids: A string or list of strings of users to receive the notification (Mandatory) title: A title for the notification (Mandatory), is of type string body: A body for the notification (Optional), is of type string color: A color for the notification (Optional), is of type string -- red is default data: A dictionary for the custom data attribute in the notification dry_run: A boolean indicating whether to run the operation in dry run mode (optional). Returns: response: A message ID string that uniquely identifies the sent the message. Raises: ValueError: If user_ids or title is None or Color is invalid ApiCallError: If an error occurs while communicating with the remote database server. TypeError: If types are incorrect """ if user_ids is None: raise ValueError("user_ids must be supplied as a string or list of strings") if title is None: raise ValueError("title must be supplied as a string") if color is None: color = '#f45342' if body is None: body = '\n' if data is None: data = { 'message': 'None' } # user_ids_type_valid = (not isinstance(user_ids, str)) and (not self.__is_list_of_strings__(user_ids)) ) if not isinstance(user_ids, str) and not self.__is_list_of_strings__(user_ids): raise TypeError("user_id must be a string or list of strings") if not isinstance(title, str): raise TypeError("title must be a string") if not isinstance(body, str): raise TypeError("body must be a string") if not isinstance(color, str): raise TypeError("color must be a sring") if not self.__check_color__(color): raise ValueError("Invalid Color") notification=messaging.AndroidNotification( title=title, body=body, color=color ) if isinstance(user_ids, str): response = self.__send__(user_ids,notification,data,dry_run=dry_run) elif self.__is_list_of_strings__(user_ids): response = self.__send_many__(user_ids,notification,data,dry_run=dry_run) else: raise Exception("Unknown error occured") return response
def PostNotice(self, request, context): notice = request.notice title = notice.title content = notice.content result_code = ResultCode.UNKNOWN_RESULT_CODE result_message = "Unknown post notice Result" db = pwdb.database with db.atomic() as transaction: try: # notice를 작성 NoticeModel.create( title=title, content=content, created_at=datetime.datetime.now(), ) user_query = (FCMModel.select(FCMModel.user_email, FCMModel.fcm_key)) # 모든 사용자에게 push를 보내는 부분 for row in user_query: message = messaging.Message( android=messaging.AndroidConfig( ttl=datetime.timedelta(seconds=3600), priority='normal', notification=messaging.AndroidNotification( title='알림인데', body='백그라운드 자비 좀', icon='', color='#f45342', sound='default'), ), data={ 'score': '850', 'time': '2:45', }, token=row.fcm_key, ) try: response = messaging.send(message) PushLog.create(receiver_email=row.user_email, content=content, created_at=datetime.datetime.now()) except Exception as ee: print(str(row.user_email) + "'s key is not valid.") pass result_code = ResultCode.SUCCESS result_message = "post notice success" except Exception as e: transaction.rollback() result_code = ResultCode.ERROR result_message = str(e) print("EXCEPTION: " + str(e)) return PostNoticeResponse(result=CommonResult( result_code=result_code, message=result_message, ), )