コード例 #1
0
def send_notification(client: insight.User, title: str, body: str) -> None:
    """
    Send a notification with the given title and body to the client. Can raise TypeError. Uses the Exponent Server
    Software Development Kit. Further documentation available at: https://docs.expo.io/push-notifications/overview/
    :param client: The intended recipient of the notification to.
    :param title: The title of the notification.
    :param body: The body of the notification.
    """
    if type(client) is not insight.User:  # Check that an instance of User is passed
        raise TypeError("Expected type <class 'User'> got type ", type(client))

    try:
        response = PushClient().publish(
            build_notification(client.notification_token, title, body)  # Build a valid expo notification
        )  # Send the notification
        response.validate_response()  # Check that we got a valid response from the expo server
    except PushServerError:  # Format or validation error
        print("PushServerError, likely caused due to format or validation error", file=sys.stderr)
    except (ConnectionError, HTTPError):  # Encountered some Connection or HTTP error - retry a few times in
        print("Connection or HTTP error", file=sys.stderr)
    except DeviceNotRegisteredError:  # Device token is outdated, or wrong
        print("Device not registered", file=sys.stderr)
    except PushResponseError:  # Did not deliver the notification
        print("PushResponseError", file=sys.stderr)
    return
コード例 #2
0
def send_push_notification(expo_token: str,
                           title: str,
                           body: str,
                           data: Dict[Any, Any] = None) -> bool:
    """Send notification to specified expo token
    :expo_token: token to send notificaton to
    :title: notification title
    :body: notification body
    :data: extra notification data (total payload must be under 4096 bytes)
    :raises: ConnectionError, DeviceNotRegisterdError, HTTPError,
             InvalidExpoToken, PushServerError, PushResponseError
    """
    assert expo_token, "Expo token cannot be None"
    if PushClient().is_exponent_push_token(expo_token):
        try:
            message = PushMessage(to=expo_token,
                                  title=title,
                                  body=body,
                                  data=data)
            response = PushClient().publish(message)
            response.validate_response()
            return True
        except PushServerError as e:
            logging.error(f"Push Server Error\n{e}")
            logging.error(f"Response\n{e.response}")
            logging.error(f"Args\n{e.args}")
        except (ConnectionError, HTTPError) as e:
            logging.error(f"Connection/HTTPError\n{e}")
        except DeviceNotRegisteredError as e:
            logging.warning(f'Inactive token\n{e}')
        except PushResponseError as e:
            logging.error(f'Notification error\n{e}')
        return False
    else:
        raise InvalidExpoToken()
コード例 #3
0
def push(token, title, msg):
    if log_instead_of_pushing:
        print('would send a notification to {} with title "{}" and body "{}"'.
              format(token, title, msg))
        return
    try:
        response = PushClient().publish(
            PushMessage(to=token, title=title, body=msg))
    except PushServerError as e:
        print('got "{}" while sending "{}" to {}'.format(e.errors, msg, token))
    except (ConnectionError, HTTPError) as e:
        print('got a connection error while sending "{}" to {}'.format(
            msg, token))
    except ValueError as e:
        print('Invalid push token, notifications will not work. Whatevz.')
        return

    try:
        response.validate_response()
        print('sent {} to {}'.format(msg, token))
    except DeviceNotRegisteredError:
        print('{} is inactive'.format(token))
    except PushResponseError as e:
        print('error while sending "{}" to {}: {}'.format(
            msg, token, e.push_response._asdict()))
コード例 #4
0
    def send_push_message(self, token, message, extra=None, priority='high'):
        try:
            response = PushClient().publish(PushMessage(to=token, body=message, data=extra, priority=priority))
        except Exception as exc:
            # Encountered some likely formatting/validation error.
            if getattr(settings, 'DJANGO_SENTRY_URL', None):
                sentry_logger.exception('PushServerError: %s' % exc, exc_info=exc, extra={
                    'token': token,
                    'push_message': message,
                    'extra': extra,
                    'errors': getattr(exc, 'errors', None),
                    'response_data': getattr(exc, 'response_data', None),
                })
            raise

        try:
            # We got a response back, but we don't know whether it's an error yet.
            # This call raises errors so we can handle them with normal exception flows.
            response.validate_response()
        except Exception as exc:
            # Encountered some other per-notification error.
            push_response = getattr(exc, 'push_response', None)
            if getattr(settings, 'DJANGO_SENTRY_URL', None):
                sentry_logger.exception('PushResponseError or DeviceNotRegisteredError: %s' % exc, exc_info=exc, extra={
                    'token': token,
                    'push_message': message,
                    'extra': extra,
                    'push_response': push_response._asdict() if push_response else None,
                })
            raise
コード例 #5
0
def send_push_message(token, message, extra=None):
    try:
        response = PushClient().publish(
            PushMessage(to=token, body=message, data=extra))
    except PushServerError as exc:
        # Encountered some likely formatting/validation error.
        print("push server error")
        raise
    except (ConnectionError, HTTPError) as exc:
        # Encountered some Connection or HTTP error - retry a few times in
        # case it is transient.
        print("connection error")
        raise

    try:
        # We got a response back, but we don't know whether it's an error yet.
        # This call raises errors so we can handle them with normal exception
        # flows.
        response.validate_response()
    except DeviceNotRegisteredError:
        # Mark the push token as inactive
        # from notifications.models import PushToken
        # PushToken.objects.filter(token=token).update(active=False)
        print("device not registered")
        raise
    except PushResponseError as exc:
        # Encountered some other per-notification error.
        print("push response error")

        raise
コード例 #6
0
def send_push_message(db, username, message, title, data=None):
    data['created'] = str(data['created'])
    data['updated'] = str(data['updated'])
    data['_id'] = str(data['_id'])
    users = db['user']
    user = users.find_one({"username": username})
    if 'device_token' in user:
        response = PushClient().publish(
            PushMessage(
                to=user['device_token'],
                body=message,
                data=data,
                sound='default',
                title=title,
                ttl=500,
                priority='high',
            ))
        try:
            # We got a response back, but we don't know whether it's an error yet
            # This call raises errors so we can handle them with normal exception
            # flows.
            response.validate_response()
        except DeviceNotRegisteredError:
            # Mark the push token as inactive
            print("device is not registered")
        except PushResponseError as exc:
            print("there is some push notification error")

    else:
        print("Cannot send the push notification to {}".format(username))
    return "Hello"
コード例 #7
0
def send_notification(to, title, body, data):
    """Send notifications using the appropiate provider."""
    user_token = UserToken.query.filter_by(user_id=to).first()
    if user_token is None:
        raise UserTokenDoesNotExist(f"UserToken {to} does not exist")
    try:
        logger.info("Attempting to send notification")
        response = PushClient().publish(
            PushMessage(to=user_token.push_token,
                        title=title,
                        body=body,
                        data=data))
    except (  # pylint: disable= W0706
            PushServerError,
            RequestsConnectionError,
            HTTPError,
    ) as e:
        logger.error(e)
        raise
    try:
        response.validate_response()
    except DeviceNotRegisteredError as e:
        # TODO: set invalid
        logger.error(e)
        raise
    except PushResponseError as e:  # pylint: disable=W0706
        logger.error(e)
        raise
コード例 #8
0
    def _make_push(cls, user_id, token, title, subtitle, extra):
        try:
            response = PushClient().publish(
                PushMessage(to=token,
                            title=title,
                            body=subtitle,
                            data=extra))
        except PushServerError as exc:
            # Encountered some likely formatting/validation error.
            cls.logger().error(f"Failed to push notification. Token: {token[:10]}.., Msg: {subtitle}, Extra: {extra}, Error: {exc.errors}, Response Data: {exc.response_data}")
            
        except (ConnectionError, HTTPError) as exc:
            # Encountered some Connection or HTTP error - retry a few times in
            # case it is transient.
            cls.logger().error(f"Failed to push notification. Token: {token[:10]}.., Msg: {subtitle}, Extra: {extra}, Error: {exc}")


        try:
            # We got a response back, but we don't know whether it's an error yet.
            # This call raises errors so we can handle them with normal exception
            # flows.
            response.validate_response()
        except DeviceNotRegisteredError:
            # Mark the push token as inactive
            UsersDAO.delete_tkn(user_id)
        except PushResponseError as exc:
            # Encountered some other per-notification error.
            cls.logger().error(f"Failed to push notification. Token: {token[:10]}.., Msg: {subtitle}, Extra: {extra}, Error: {exc.errors}, Response Data: {exc.push_response._asdict}")
コード例 #9
0
def send_push_notification(token, message, extra=None):
    try:
        response = PushClient().publish(
            PushMessage(to=token, body=message, data=extra))
    except (ConnectionError, HTTPError, PushServerError) as exc:
        # Encountered some likely formatting/validation error or an http connection error
        logger.error('could not send notification to client',
                     exc_info={
                         'token': token,
                         'message': message,
                         'extra': extra,
                         'errors': exc.errors,
                         'response_data': exc.response_data,
                     })
        raise
    try:
        # We got a response back, but we don't know whether it's an error yet.
        # This call raises errors so we can handle them with normal exception
        # flows.
        response.validate_response()
    except PushResponseError as exc:
        # Encountered some other per-notification error.
        logger.error('Encountered some other per-notification error',
                     exc_info={
                         'token': token,
                         'message': message,
                         'extra': extra,
                         'push_response': exc.push_response._asdict(),
                     })
        raise
コード例 #10
0
def send_notification(client, title, body):
    """
    Send a notification with the given title and body to the client.
    :param client: intended recipient of the notification to (User)
    :param title: title of the notification (str)
    :param body: body of the notification (str)
    """
    if type(client) is not User:  # Check that an instance of User is passed
        raise TypeError("Expected type <class 'User'> got type ", type(client))

    try:
        response = PushClient().publish(
            build_notification(client.notification_token, title,
                               body)  # Build a valid expo notification
        )  # Send the notification
        response.validate_response(
        )  # Check that we got a valid response from the expo server
    except PushServerError:  # Format or validation error
        print(
            "PushServerError, likely caused due to format or validation error",
            file=sys.stderr)
    except (
            ConnectionError, HTTPError
    ):  # Encountered some Connection or HTTP error - retry a few times in
        print("Connection or HTTP error", file=sys.stderr)
    except DeviceNotRegisteredError:  # Device token is outdated, or wrong
        print("Device not registered", file=sys.stderr
              )  # Todo: Should remove device (or ignore), or request new token
    except PushResponseError:  # Did not deliver the notification
        print("PushResponseError")
コード例 #11
0
    def send_push_message(self, token, title, message, extra=None):

        #print("Here push tocke",token)
        try:
            response = PushClient().publish(
                PushMessage(to=token,
                            title=title,
                            body=message,
                            sound="default",
                            badge=0,
                            channel_id="order-notification",
                            data=extra))
        except PushServerError as exc:
            # Encountered some likely formatting/validation error.
            rollbar.report_exc_info(
                extra_data={
                    'token': token,
                    'message': message,
                    'extra': extra,
                    'errors': exc.errors,
                    'response_data': exc.response_data,
                })
            pass
        except (ConnectionError, HTTPError) as exc:
            # Encountered some Connection or HTTP error - retry a few times in
            # case it is transient.
            rollbar.report_exc_info(extra_data={
                'token': token,
                'message': message,
                'extra': extra
            })
            #raise self.retry(exc=exc)
            pass
        try:
            # We got a response back, but we don't know whether it's an error yet.
            # This call raises errors so we can handle them with normal exception
            # flows.
            response.validate_response()
        except DeviceNotRegisteredError:
            # Mark the push token as inactive
            #from notifications.models import PushToken
            #PushToken.objects.filter(token=token).update(active=False)
            pass
        except PushResponseError as exc:
            # Encountered some other per-notification error.
            rollbar.report_exc_info(
                extra_data={
                    'token': token,
                    'message': message,
                    'extra': extra,
                    'push_response': exc.push_response._asdict(),
                })
            #raise self.retry(exc=exc)
            pass
コード例 #12
0
def send_push_message(message):
    try:
        response = PushClient().publish(message)
    except PushServerError as exc:
        raise
    except (ConnectionError, HTTPError) as exc:
        raise
    try:
        response.validate_response()
    except DeviceNotRegisteredError:
        pass
        # from notifications.models import PushToken
        # PushToken.objects.filter(token=token).update(active=False)
    except PushResponseError as exc:
        raise
コード例 #13
0
def send_push_message(token, message, extra=None):
    response = PushClient().publish(PushMessage(to=token, body=message, data=extra))
    try:
        # We got a response back, but we don't know whether it's an error yet.
        # This call raises errors so we can handle them with normal exception
        # flows.
        response.validate_response()
    except DeviceNotRegisteredError:
        # self.user_svc.edit_user()
        # Mark the push token as inactive
        # PushToken.objects.filter(token=token).update(active=False)
        print("device not registered")
    except Exception as exc:
        # Encountered some other per-notification error.
        raise exc
コード例 #14
0
def send_push_message(token, message, user, extra=None):
    app.apscheduler.remove_job(user)
    try:
        response = PushClient().publish(
            PushMessage(to=token, body=message, data=extra))
    except PushServerError as exc:
        # Encountered some likely formatting/validation error.
        rollbar.report_exc_info(
            extra_data={
                'token': token,
                'message': message,
                'extra': extra,
                'errors': exc.errors,
                'response_data': exc.response_data,
            })
        raise
    except (ConnectionError, HTTPError) as exc:
        # Encountered some Connection or HTTP error - retry a few times in
        # case it is transient.
        rollbar.report_exc_info(extra_data={
            'token': token,
            'message': message,
            'extra': extra
        })
        raise self.retry(exc=exc)

    try:
        # We got a response back, but we don't know whether it's an error yet.
        # This call raises errors so we can handle them with normal exception
        # flows.
        response.validate_response()
    except DeviceNotRegisteredError:
        # Mark the push token as inactive
        from notifications.models import PushToken
        PushToken.objects.filter(token=token).update(active=False)
    except PushResponseError as exc:
        # Encountered some other per-notification error.
        rollbar.report_exc_info(
            extra_data={
                'token': token,
                'message': message,
                'extra': extra,
                'push_response': exc.push_response._asdict(),
            })
        raise self.retry(exc=exc)
コード例 #15
0
ファイル: notifier.py プロジェクト: admtlab/PittGrubServer
def send_push_notification(expo_token: str,
                           title: str,
                           body: str,
                           data: Dict[Any, Any]=None):
    """Send notification to specified expo token
    :expo_token: token to send notificaton to
    :title: notification title
    :body: notification body
    :data: extra notification data (total payload must be under 4096 bytes)
    :raises: ConnectionError, DeviceNotRegisterdError, HTTPError,
             InvalidExpoToken, PushServerError, PushResponseError
    """
    assert expo_token, "Expo token cannot be None"
    if PushClient().is_exponent_push_token(expo_token):
        message = PushMessage(to=expo_token, title=title, body=body, data=data)
        response = PushClient().publish(message)
        response.validate_response()
    else:
        raise InvalidExpoToken()
コード例 #16
0
ファイル: push.py プロジェクト: rajath89/hospital
def send_push_message(token, message, extra=None):
    try:
        response = PushClient().publish(
            PushMessage(to=token, body=message, data=extra))
    except PushServerError as exc:

        rollbar.report_exc_info(
            extra_data={
                'token': token,
                'message': message,
                'extra': extra,
                'errors': exc.errors,
                'response_data': exc.response_data,
            })
        raise
    except (ConnectionError, HTTPError) as exc:

        rollbar.report_exc_info(extra_data={
            'token': token,
            'message': message,
            'extra': extra
        })
        raise self.retry(exc=exc)

    try:

        response.validate_response()
    except DeviceNotRegisteredError:
        # Mark the push token as inactive
        from notifications.models import PushToken
        PushToken.objects.filter(token=token).update(active=False)
    except PushResponseError as exc:

        rollbar.report_exc_info(
            extra_data={
                'token': token,
                'message': message,
                'extra': extra,
                'push_response': exc.push_response._asdict(),
            })
        raise self.retry(exc=exc)

    return response
コード例 #17
0
ファイル: notifications.py プロジェクト: yjsyyyjszf/s4fe
def send_push_message(token, message, extra=None):
    try:
        response = PushClient().publish(
            PushMessage(to=token,
                        body=message,
                        data=extra))
    except PushServerError as exc:
        logger.error("Formatting/validation error !", exc_info=True)
        return False
    except (ConnectionError, HTTPError) as exc:
        logger.error("Connection or HTTP error !", exc_info=True)
        return False

    try:
        response.validate_response()
        logger.info(response, exc_info=True)
        return True
    except DeviceNotRegisteredError:
        logger.error("Device not registered !", exc_info=True)
        return False
コード例 #18
0
ファイル: views.py プロジェクト: ColinJS/joinme-api
def send_push_message(token, message, extra=None, title=None, badge=0):
    try:
        response = PushClient().publish(
            PushMessage(to=token,
                        title=title,
                        body=message,
                        data=extra,
                        badge=badge))
    except PushServerError as exc:
        pass
    except (ConnectionError, HTTPError) as exc:
        pass

    try:
        # We got a response back, but we don't know whether it's an error yet.
        # This call raises errors so we can handle them with normal exception
        # flows.
        response.validate_response()
    except DeviceNotRegisteredError:
        pass
    except PushResponseError as exc:
        pass
コード例 #19
0
def send_push_message(request):
    user_id = request.data.get('user_id')
    user_profile = ProfileToken.objects.get(user_id=user_id)
    user_token = user_profile.user_token
    title = request.data['title']
    message = request.data['message']

    try:
        response = PushClient().publish(
            PushMessage(to=user_token, title=title, body=message))
    except:
        return Response(
            {'error': 'Não foi possível enviar notificação ao vendedor.'},
            status=HTTP_404_NOT_FOUND)
    try:
        response.validate_response()
    except:
        return Response(
            {'error': 'Não foi possível validar o token de notificação.'},
            status=HTTP_400_BAD_REQUEST)

    return Response(status=HTTP_200_OK)
コード例 #20
0
def send_push_message(token, message, extra=None):
    try:
        response = PushClient().publish(
            PushMessage(to=token, body=message, data=extra))
    except PushServerError as exc:
        # Encountered some likely formatting/validation error.
        print("pushservererror", exc)
        raise
    except (ConnectionError, HTTPError) as exc:
        # Encountered some Connection or HTTP error - retry a few times in
        # case it is transient.
        print("connection error ", exc)
        raise

    try:
        # We got a response back, but we don't know whether it's an error yet.
        # This call raises errors so we can handle them with normal exception
        # flows.
        response.validate_response()
    except PushResponseError as exc:
        # Encountered some other per-notification error.
        print("pushresponse failed > ", exc)
        raise
コード例 #21
0
    def send_notification(
            self, notification: MobileNotification) -> ExpoNotificationResult:
        if notification.is_pushed:
            logger.warning(
                "Attempted to push a notification that was already pushed.  Aborting..."
            )
            return ExpoNotificationResult(success=False)
        if notification.profile.expo_push_token is None:
            logger.warning(
                "Attempted to push a notification, but no token is configured for owner.  Aborting..."
            )
            return ExpoNotificationResult(success=False)
        token: str = notification.profile.expo_push_token
        try:
            response = PushClient().publish(
                PushMessage(to=token,
                            body=notification.message,
                            data={'notification_id': notification.id}))
        except PushServerError as exc:
            logger.warning(
                f"Attempted to send a push notification, but received error: {exc}"
            )
            return ExpoNotificationResult(success=False)

        try:
            response.validate_response()
        except DeviceNotRegisteredError:
            logger.warning(
                "Attempted to send a push notification, but the device is not registered."
            )
            return ExpoNotificationResult(success=False)
        except PushResponseError as exc:
            logger.warning(
                f"Attempted to send a push notification, but received an error: {exc}"
            )
            return ExpoNotificationResult(success=False)
        return ExpoNotificationResult(success=True)
コード例 #22
0
def send_push_message(target_token, message, extra=None):
    try:
        response = PushClient().publish(
            PushMessage(to=target_token, body=message, data=extra))

    except PushServerError as e:
        print('푸시 서버에 전송되지 않음.', e)

    except (ConnectionError, HTTPError) as e:
        print('푸시 서버에 전송되지 않음.', e)

    try:
        # 푸시 서버에서 응답을 받긴 함
        response.validate_response()
        return True
    except DeviceNotRegisteredError:
        user = User.objects.filter(notification_token=target_token)[0]
        user.notification_token = None
        user.save()
        return False

    except PushResponseError as e:
        print(e)
        return False