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
Esempio n. 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()
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()))
Esempio n. 4
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
Esempio n. 5
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
Esempio n. 6
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}")
Esempio n. 7
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
Esempio n. 8
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
Esempio n. 9
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"
Esempio n. 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")
Esempio n. 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
Esempio n. 12
0
def send_push_message(token, message, extra=None):
    try:
        bodyContent = {'message': "hello"}
        response = PushClient().publish(
            PushMessage(to=token, body='hello', data=extra))
        print(response.is_success())
    except PushServerError as exc:
        print(exc.errors)
        print("---")
        print(exc.response_data)
    except (ConnectionError, HTTPError) as exc:
        print(exc.errors)
        print("---")
Esempio n. 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
Esempio n. 14
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
Esempio n. 15
0
def send_push_message(token, message):
    try:
        extra = {"title": message}
        response = PushClient().publish(
            PushMessage(to=token,

                        body="notification",

                        data=extra))
        print(response.is_success())
    except PushServerError as exc:
        print(exc.errors)
        print(exc.response_data)
    except (ConnectionError, HTTPError) as exc:
        print(exc.errors)
Esempio n. 16
0
 def updateApp(btid):
     print(tokens['token'])
     message = btid
     extra = None
     response = PushClient().publish(
         PushMessage(to=tokens['token'], body=message, data=extra))
     return 'notif sent'
def send_push_message(message, token, extra=None):
    try:
        response = PushClient().publish(
            PushMessage(to=token, body=message, data=extra))
        return response
    except Exception as e:
        print(e)
Esempio n. 18
0
def send_push_message(message, title, extra=None):
    try:
        expotoken = [
            Object.expotoken for Object in ExpoPushToken.objects.all()
        ]
        PushMessage_packet = []
        for token_packet in expotoken:
            PushMessage_packet.append(
                PushMessage(to=token_packet,
                            title=title,
                            display_in_foreground=True,
                            body=message,
                            data=extra))

        response_wow = PushClient().publish_multiple(PushMessage_packet)
#        for response_element in response_wow:
#            response_element.validate_response()

    except PushServerError as exc:
        print("PushServerError")
    except (ConnectionError, HTTPError) as exc:
        print("ConnectionError")
    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.
        for response_element in response_wow:
            response_element.validate_response()
    except DeviceNotRegisteredError as exc:
        print("DeviceNotRegisterdError")
    except PushTicketError as exc:
        print("PushTicketError")
Esempio n. 19
0
def send_push_message(token, message, extra=None):
    try:
        response = PushClient().publish(
            PushMessage(to=token,
                        body=message))
        return response
    except PushServerError as exc:
        raise exc
Esempio n. 20
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)
Esempio n. 21
0
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()
Esempio n. 22
0
 def perform_create(self, serializer):
     requirement = serializer.save()
     student = requirement.student
     body = f'You have a new requirement in {requirement.subject}'
     if student.push_notification_token:
         push_message = PushMessage(to=student.push_notification_token,
                                    body=body,
                                    sound='default',
                                    channel_id='push-notifications')
         PushClient().publish(push_message)
Esempio n. 23
0
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
Esempio n. 24
0
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
Esempio n. 25
0
def send_push_message(token, message, notification_type, data={}):
    data['type'] = notification_type

    try:
        PushClient().publish(
            PushMessage(
                to=token,
                body=message,
                data=data
            )
        )
    except:
        pass
Esempio n. 26
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)
Esempio n. 27
0
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
Esempio n. 28
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
def notify_mobile(recipients: List[str], title: str, message: str):
    message += t('notifications.details')
    for user_email in recipients:
        user_devices = cast(List[str], user_dal.get_attributes(
            user_email, ['devices_to_notify']).get('devices_to_notify', []))
        for device_token in user_devices:
            PushClient().publish(
                PushMessage(
                    body=message,
                    sound='default',
                    title=title,
                    to=device_token,
                )
            )
Esempio n. 30
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)