Example #1
0
def send_to_token(registration_token):
   
    # See documentation on defining a message payload.
    message = messaging.Message(
        data={
            'title': 'Python says:',
            'body': 'Push with Python works well!!'
        },
        token=registration_token,
    )

    # message = messaging.Message(
    #     android=messaging.AndroidConfig(
    #         ttl=datetime.timedelta(seconds=3600),
    #         priority='normal',
    #         notification=messaging.AndroidNotification(
    #             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.',
    #             icon='stock_ticker_update',
    #             color='#f45342'
    #         ),
    #     ),
    #     token=registration_token,
    #     # topic='industry-tech',
    # )

    # 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_to_device(msg, mobile_device):
    if not firebase_app:
        return

    kwargs = dict(data=msg, token=mobile_device.device_token)

    if mobile_device.platform == 'android':
        kwargs['android'] = AndroidConfig(priority='high')
    else:
        kwargs['apns'] = APNSConfig(
            headers={
                'apns-push-type': 'background',
                'apns-priority': '5'
            },
            payload=APNSPayload(
                aps=Aps(content_available=True, category='post')))

    try:
        message = Message(**kwargs)
        return send(message, app=firebase_app)
    except (UnregisteredError, SenderIdMismatchError,
            firebase_admin.exceptions.InternalError):
        MobileDevice.objects.filter(
            device_token=mobile_device.device_token).update(
                deactivated_at=now())
    except:
        import traceback
        traceback.print_exc()
        sentryClient.captureException()
Example #3
0
    def SendFireBaseThread():
        if("" == FCM.cred):
            FCM.cred = credentials.Certificate("/home/pi/Pz/FireBase/macro-aurora-227313-firebase-adminsdk-eq075-137ba0b44f.json")
            firebase_admin.initialize_app(FCM.cred)

        connection = SQLalchemy.GetDBConnection()
        query = "select info.token, fcm.Title, fcm.Content, fcm.SendTime, fcm.MsgGUID from FCM as fcm, UserInfo as info where fcm.Id = info.id"
        rows = connection.QueryExecute(query)
        osDefine.Logger(query)

        if(0 == rows.rowcount):
            return ""

        for row in rows:
            try:
                # See documentation on defining a message payload.
                message = messaging.Message(
                    token=row[0].strip(),
                    data={
                        "Title" : row[1].strip(),
                        "Content" : row[2].strip(),
                        "Time" : row[3].strip(),
                        "MsgGUID" : row[4].strip(),
                    },
                )

                # Send a message to the device corresponding to the provided
                # registration token.
                response = messaging.send(message)
                osDefine.Logger(response)
            except Exception as e:
                osDefine.Logger(e)
Example #4
0
    def send_message(self, user_token, title, *args, **kwargs):
        if not user_token:
            return None

        body = kwargs.get('body', None)
        message = messaging.Message(notification=messaging.Notification(title, body), token=user_token)
        return messaging.send(message)
Example #5
0
def send(parent, clients, notif_fn, *args, **kwargs):
    """Sends a notification.

    Args:
        user: User - The entity being sent the notification.
        clients: [ClientState] - Clients to send the notification.
        notif_fn: function - *args and **kwargs are passed to this function,
            a ClientMessage will be passed as a 'client' kwarg.
    """
    with ds_util.client.transaction():
        fcm_send_event = FcmSendEvent.to_entity(
            {
                'date': datetime.datetime.utcnow(),
                'messages': []
            },
            parent=parent)
        logging.debug('Sending notification to %s clients', len(clients))
        for client_state in clients:
            message = notif_fn(*args, client=client_state, **kwargs)
            try:
                response = messaging.send(message, app=firebase_util.get_app())
                logging.debug('fcm_util.send: Success: %s, %s, %s', parent,
                              message, response)
                _add_delivery(fcm_send_event, client_state, message, response)
            except Exception as e:
                logging.exception('fcm_util.send: Failure: %s', parent)
                _add_delivery(fcm_send_event, client_state, message, e)
        ds_util.client.put(fcm_send_event)
Example #6
0
def send_to_topic():
    # [START send_to_topic]
    # The topic name can be optionally prefixed with "/topics/".
    topic = 'notify'

    # See documentation on defining a message payload.
    message = messaging.Message(
        data={
            'score': '850',
            'time': '2:45',
        },
        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)

    registration_tokens = [
        'chCK9jrYEQ8:APA91bEf0ZxbIsw0yCvHw1SrnitL1iDLV3eus-bXcfnuyDCSHlJwyh2saKLpEpHrJUDJT6ExcF0YIk0oA83Ps_IjlBk-MAxX3_74m6fQtHql1kP5Ks0lehn2xbdbA5TQ87aj6B0_R2kN',
        # ...
    ]

    # Unubscribe the devices corresponding to the registration tokens from the
    # topic.
    response = messaging.subscribe_to_topic(registration_tokens, topic)
    # See the TopicManagementResponse reference documentation
    # for the contents of response.
    print(response, 'tokens were subscribed successfully')
def send_to_device(registration_token, msg):
    message = Message(
        data=msg,
        android=AndroidConfig(priority="high"),
        apns=APNSConfig(payload=APNSPayload(aps=Aps(content_available=True))),
        token=registration_token)
    return send(message)
Example #8
0
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})
Example #9
0
 def notify(self, body=None, notification=None):
     '''
     body 는 모든 key 와 value 가 string 인 딕셔너리입니다.
     '''
     response = messaging.send(
         self.make_message(body=body, notification=notification))
     return response
Example #10
0
def process_message():
    if current_app.config['PUBSUB_VERIFICATION_TOKEN'] != request.args.get(
            'token', ''):
        return 'invalid request', 400

    # deserialize the envelope into a dict
    envelope = json.loads(request.data.decode('utf-8'))
    logging.debug('ENVELOPE: {}'.format(envelope))

    # base64 decode the 'data' element in the message
    data = base64.b64decode(envelope['message']['data'])

    if data == 'RESTOCKBANANAS':
        # query the metadata server for the staff app token
        metadata = requests.get(current_app.config['METADATA_SERVER'],
                                headers={'Metadata-Flavor': 'Google'})
        push_token = metadata.json()['attributes']['staff-app-token']

        logging.debug('PUSH TOKEN: {}'.format(push_token))

        message = messaging.Message(
            data={'msg': 'Time to restock the bananas'}, token=push_token)
        response = messaging.send(message)
        logging.debug('SEND: {}'.format(message.__dict__))
        logging.debug('RESP: {}'.format(response))

    return '', 204
Example #11
0
    def send_message(
        self,
        message: messaging.Message,
        app: "firebase_admin.App" = SETTINGS["DEFAULT_FIREBASE_APP"],
        **more_send_message_kwargs,
    ) -> Union[Optional[messaging.SendResponse], FirebaseError]:
        """
        Send single message. The message's token should be blank (and will be
        overridden if not). Responds with message ID string.

        :param message: firebase.messaging.Message. If `message` includes a token/id, it
        will be overridden.
        :param app: firebase_admin.App. Specify a specific app to use
        :param more_send_message_kwargs: Parameters for firebase.messaging.send_all()
        - dry_run: bool. Whether to actually send the notification to the device
        If there are any new parameters, you can still specify them here.

        :raises FirebaseError
        :returns messaging.SendResponse or FirebaseError if the device was
        deactivated due to an error.
        """
        message.token = self.registration_id
        try:
            return messaging.SendResponse(
                {
                    "name":
                    messaging.send(
                        message, app=app, **more_send_message_kwargs)
                },
                None,
            )
        except FirebaseError as e:
            self.deactivate_devices_with_error_result(self.registration_id, e)
            return e
Example #12
0
def relay_to_android():
    try:
        content = request.json
        username = content.pop('android_username')
    except:
        print("Missing Data")
        return Response(status=400)

    print('Content: ' + str(content))
    print('Username: '******'path': request.path[1:]})

    #Find User from Database
    user_query = User.query.filter_by(username=username).first()
    if user_query is None:
        return Response(status=409)

    fb_message = messaging.Message(
        data=content,
        token=user_query.FBToken,
    )
    try:
        response = messaging.send(fb_message)
    except:
        print("Message failed to send.")
        return Response(status=410)
    return Response(status=200)
Example #13
0
    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
Example #14
0
def handle_notification(req):
    notification_title = req.title
    notification_body = req.body
    start_app = req.start_app

    rospy.loginfo("Notification Title : " + notification_title)
    rospy.loginfo("Notification Body : " + notification_body)
    rospy.loginfo("Start App : " + start_app)

    message = messaging.Message(topic='tms_ur_notification',
                                notification=messaging.Notification(
                                    title=notification_title,
                                    body=notification_body),
                                data={
                                    'notification.title': notification_title,
                                    'notification.body': notification_body,
                                    'start_app': start_app
                                })
    message_response = messaging.send(message)

    rospy.loginfo("Result : " + message_response)

    response = tms_ur_notificationResponse()
    response.result = message_response

    return response
Example #15
0
def notify_user(notifications_token: str, message: dict):
    """
    Notifies a user using his notifications token (provided from the apps)
    :param notifications_token: the user's notification token
    :param message: the message should be a dict normal use case consists of two keys (title,message)
    :return: None
    """
    if notifications_token == '' or notifications_token is None:
        raise ValueError(
            'notifications_token must not be empty, you should provide the user\'s notification token'
        )

    if len(message.keys()) < 2:
        raise ValueError('you must provide a message in the notification')

    if type(message) is not dict:
        raise TypeError(
            'The message must be a dictionary containing a title and message')

    if message['title'] is None and SETTINGS.get("APP_NAME", None) is not None:
        message['title'] = SETTINGS.get("APP_NAME")
    else:
        raise ImproperlyConfigured(
            "You should provide either a title entry in the message dict, or provide an APP_NAME"
            "property in the settings module.")

    msg = messaging.Message(data=message, token=notifications_token)
    response = messaging.send(msg)
    logger.info(response)
Example #16
0
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}')
Example #17
0
    def post(self, request):
        """
        Post multiple contact records.
        Push notifications if required.
        :param request: The request object posted by the caller
        :return: The appropriate status code
        """
        try:
            Contact.objects.bulk_create([
                Contact(datetime=c['datetime'],
                        tag=Tag.objects.get(tagID=c['tag']),
                        place=Place.objects.get(placeID=c['place']))
                for c in request.data
            ])

            for c in request.data:
                try:
                    tagToToken = TagToToken.objects.get(tag=c['tag'])
                    token = tagToToken.token
                    message = messaging.Message(
                        notification=messaging.Notification(
                            title="Warning!",
                            body="You are in close distance with others."),
                        token=token,
                    )
                    response = messaging.send(message)
                    print(response)
                except TagToToken.DoesNotExist:
                    print("Token does not exist")
                    pass
            return Response("Added successfully",
                            status=status.HTTP_201_CREATED)
        except Exception as e:
            return Response(str(e), status=status.HTTP_400_BAD_REQUEST)
Example #18
0
File: fcm.py Project: sn94/uvSkin
    def messaging_from_firestore2(self):
        #consulta lo de cloud firestore
        # Use a service account
        import firebase_admin
        from firebase_admin import credentials

        #cred = credentials.Certificate('uvapp-246400-9e75d4d9608a.json')
        #'uvapp-246400-04d67e9d0c21firebasecount.json'
        #'uvapp-246400-6c35cea9bf32default.json
        cred = credentials.Certificate(
            'uvapp-246400-04d67e9d0c21firebasecount.json')
        app = firebase_admin.initialize_app(cred)

        from firebase_admin import firestore
        db = firestore.client()
        users_ref = db.collection(u'usuarios')
        docs = users_ref.get()

        from firebase_admin import messaging
        for doc in docs:
            #registro_id= doc.id
            registro_user = doc.to_dict()
            token = registro_user['token']
            a_notification = messaging.Notification(title="hola",
                                                    body="quetal")
            message = messaging.Message(data=None,
                                        notification=a_notification,
                                        token=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)
            #self.send_a_notification_sdk_admin( "iuv alto","cuidate",token )
        firebase_admin.delete_app(app)  #borrar instancia anterior
Example #19
0
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)
Example #20
0
def send_data(token, data):
    message = messaging.Message(
        data=data,
        token=token,
    )

    return messaging.send(message, app=app)
Example #21
0
def notify_user(notifications_token: str, message: dict):
    """
    Notifies a user using his notifications token (provided from the apps)
    :param notifications_token: the user's notification token
    :param message: the message should be a dict normal use case consists of two keys (title,message)
    :return: None
    """
    if notifications_token == '' or notifications_token is None:
        raise ValueError(
            'notifications_token must not be empty, you should provide the user\'s notification token'
        )

    if message['message'] is None or message['message'] == '':
        raise ValueError('you must provide a message in the notification')

    if type(message) is not dict:
        raise TypeError(
            'The message must be a dictionary containing a title and message')

    if message['title'] is None:
        message['title'] = settings.APP_NAME

    msg = messaging.Message(data=message, token=notifications_token)
    response = messaging.send(msg)
    logger.info(response)
Example #22
0
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)
Example #23
0
def send_cancel_notification(to_doc, about_doc):
    print(to_doc.to_dict(), "==================", about_doc.to_dict())

    to = to_doc.to_dict()
    about = about_doc.to_dict()

    notification = messaging.Message(
        data={
            'notification_id': str(about_doc.id),
            'title': 'CANCEL',
            'body': str(about["report"]),  # f'Report about {about["report_type"]} nearby',
            'priority': str(about["priority"]) if "priority" in about.keys() else DEFAULT_PRIORITY,
            'tag': str(about["tag"]) if "tag" in about.keys() else 'test'  # TODO: extract tag from report verif
        },
        token=to["token"]
    )

    response = messaging.send(notification)
    print("Sent Notification", response)

    def update_sent_notifications(of_doc, about_doc):
        db.collection('users').document(of_doc.id).collection('notifications_sent').add({
            'notification_id': about_doc.id
        })

    threading.Thread(target=update_sent_notifications(of_doc=to_doc, about_doc=about_doc)).start()
def sendAchievementNotification(user_id, db, achievement_type,
                                achievement_level):
    content = formNotificationDict(user_id, achievement_type,
                                   achievement_level)

    firebase_tokens = db.session.query(FirebaseToken).filter_by(
        user_id=user_id).all()
    db.session.query(UserData).filter_by(user_id=user_id).update(
        dict(notifications_are_checked=False))

    for token_data in firebase_tokens:
        try:
            message = messaging.Message(data=content, token=token_data.token)
            messaging.send(message)
        except Exception as e:
            db.session.delete(token_data)
Example #25
0
def send_notification(to_doc, about_doc, action='SEND'):
    print(to_doc.to_dict(), "==================", about_doc.to_dict())

    to = to_doc.to_dict()
    about = about_doc.to_dict()

    notification = messaging.Message(
        data={
            'notification_id': str(about_doc.id),
            'title': 'CANCEL' if action is 'CANCEL' else str(about["report_type"]),
            'body': str(about["report"]),  # f'Report about {about["report_type"]} nearby',
            'priority': str(about["priority"]) if "priority" in about.keys() else DEFAULT_PRIORITY,
            'tag': str(about["tag"]) if "tag" in about.keys() else 'test'  # TODO: extract tag from report verif
        },
        token=to["token"]
    )

    response = messaging.send(notification)
    print("Sent Notification", response)

    def update_sent_notifications(of_doc, about_doc, action='SEND'):
        if action == 'SEND':
            db.collection('users').document(of_doc.id).collection('notifications_sent').document(about_doc.id).set({
                'notification_id': about_doc.id
            })
        else:
            docs_to_delete = db.collection('users').document(of_doc.id).collection('notifications_sent').where(
                'notification', '==', about_doc.id).stream()
            for doc_to_delete in docs_to_delete:
                doc_to_delete.delete()

    threading.Thread(target=update_sent_notifications(of_doc=to_doc, about_doc=about_doc, action=action)).start()
 def send_firebase_message(from_username, to_username, message, notification_type):
     try:
         token = User.get_user_by_username(to_username)["user"]["firebase_token"]
         message = messaging.Message(
             notification=messaging.Notification(
                 title=from_username,
                 body=message
             ),
             data={
                 'notification_type': notification_type
             },
             token=token
         )
         messaging.send(message)
     except UserNotFoundException:
         raise UserNotFoundException
Example #27
0
    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)
Example #28
0
 def send(self, locator: str, title: str, content: str) -> str:
     notification = messaging.Notification(body=content)
     message = messaging.Message(data={
         'title': title,
         'body': content,
     },
                                 token=locator)
     return messaging.send(message)
Example #29
0
    def send(self):
        """ Attempt to send the notification.

        Returns:
            string: ID for the sent message.
        """
        from firebase_admin import messaging
        return messaging.send(self._fcm_message(), app=self._app)
Example #30
0
def send_notification(to_user_token, title, body):
    message = messaging.Message(
        notification=messaging.Notification(body=body, title=title),
        token=to_user_token,
    )

    response = messaging.send(message)
    print('Successfully sent message:', response)
Example #31
0
 def broadcast(self, code: str, title: str, content: str) -> str:
     notification = messaging.Notification(body=content)
     message = messaging.Message(data={
         'title': title,
         'body': content,
     },
                                 topic=code)
     return messaging.send(message)
Example #32
0
def send_fcm_push(title, body, image_url=None):
    if cred is None:
        return
    # See documentation on defining a message payload.
    data = {}
    # data = {
    #     'title': title,
    #     'body': body,
    # }
    if image_url:
        data['imageUrl'] = image_url
    message = messaging.Message(
        notification=messaging.Notification(
            title=title,
            body=body,
        ),
        data=data,
        topic=TOPIC,
    )
    message_id = messaging.send(message)
    return message_id