Exemplo n.º 1
0
  def parse(self, notification):
    """
      Parse inbound sms notification received in webhook. It parses the notification and returns simplified version of the response.

      Args:
        params (dict): Single parameter to hold all options
        notification (:obj:`JSON`): JSON received in the subscription webhook.

    """
    parsed_notification = response_converter(notification)
    top_level_notification_key = list(parsed_notification.keys())[0]
    if (top_level_notification_key=='sms_subscription_cancellation_notification'):
      return {
        'subscription_id': id_from(parsed_notification[top_level_notification_key]['link'][0]['href']),
        'notification_id': parsed_notification[top_level_notification_key]['id'],
        'notification_date_time': parsed_notification[top_level_notification_key]['date_time'],
        'type': self.types[top_level_notification_key]
      }
    elif (top_level_notification_key == 'outbound_sms_message_notification') or (top_level_notification_key == 'inbound_sms_message_notification'):
      outbound_sms_messages = parsed_notification[top_level_notification_key]
      inbound_sms_messages = parsed_notification[top_level_notification_key]
      notification_id = parsed_notification[top_level_notification_key]['id']
      notification_date_time = parsed_notification[top_level_notification_key]['date_time']
      return {
        **outbound_sms_messages,
        **inbound_sms_messages,
        'notification_id': notification_id,
        'notification_date_time': notification_date_time,
        'type': self.types[top_level_notification_key]
      }
    elif (top_level_notification_key == 'sms_event_notification'):
      event_description = parsed_notification[top_level_notification_key]['event_description']
      event_type = parsed_notification[top_level_notification_key]['event_type']
      event_links = parsed_notification[top_level_notification_key]['link']
      event_id = parsed_notification[top_level_notification_key]['id']
      event_date_time = parsed_notification[top_level_notification_key]['date_time']
      return {
        'notification_id': event_id,
        'notification_date_time': event_date_time,
        'message_id': id_from(event_links[0]['href']),
        'type': self.types[top_level_notification_key],
        'event_details': {
          'description': event_description,
          'type': event_type
        }
      }
    else:
      return parsed_notification[top_level_notification_key]
Exemplo n.º 2
0
    def resend_code(self, params):
        """
      Resending the authentication code via same code resource, invalidating the previously sent code.

      Args:
        params (dict): Single parameter to hold all options
        params['code_id'] (:obj:`str`): ID of the authentication code.
        params['destination_address'] (:obj:`array[str]`): Destination address of the authentication code being sent. For sms type authentication codes, it should contain a E164 phone number. For e-mail type authentication codes, it should contain a valid e-mail address.
        params['message'] (:obj:`str`): Message text sent to the destination, containing the placeholder for the code within the text. CPaaS requires to have *{code}* string within the text in order to generate a code and inject into the text. For email type code, one usage is to have the *{code}* string located within the link in order to get a unique link.
        params['method'] (:obj:`str`, optional): Type of the authentication code delivery method, sms and email are supported types. Possible values: sms, email
        params['expiry'] (:obj:`int`, optional): Lifetime duration of the code sent in seconds. This can contain values between 30 and 3600 seconds.
        params['length'] (:obj:`int`, optional): Length of the authentication code tha CPaaS should generate for this request. It can contain values between 4 and 10.
        params['type'] (:obj:`str`, optional): Type of the code that is generated. If not provided, default value is numeric. Possible values: numeric, alphanumeric, alphabetic

    """
        destination_address = params.get('destination_address')
        address = destination_address if type(
            destination_address) is list else [destination_address]

        options = {
            'body': {
                'code': {
                    'address': address,
                    'method': params.get('method') or 'sms',
                    'format': {
                        'length': params.get('length') or 6,
                        'type': params.get('type') or 'numeric'
                    },
                    'expiry': params.get('expiry') or 120,
                    'message': params.get('message')
                }
            }
        }

        url = '{}/codes/{}'.format(self.base_url, params.get('code_id'))

        response = self.api.send_request(url, options, 'put')

        if (is_test_response(response)):
            return response.json()
        # check if error_response.
        elif (check_if_error_response(response)):
            return build_error_response(response)

        # build custom_response.
        response = response.json()
        custom_response = {'code_id': id_from(response['code']['resourceURL'])}
        return custom_response
Exemplo n.º 3
0
    def subscribe(self, params):
        """
      Create a new subscription.

      Args:
        params (dict): Single parameter to hold all options
        params['type'] (:obj:`str`): Type of conversation. Possible values - SMS. Check conversation.types for more options
        params['webhook_url'] (:obj:`str`): The webhook that has been acquired during SMS API subscription, which the incoming notifications supposed to be sent to.
        params['destination_address'] (:obj:`str`, optional): The address that incoming messages are received for this subscription. If does not exist, CPaaS uses the default assigned DID number to subscribe against. It is suggested to provide the intended E164 formatted DID number within this parameter.
   
    """
        message_type = params.get('type')

        if (message_type == self.types['SMS']):
            # create a notifyURL with webhookURL
            channel = NotificationChannel(self.api).create_channel(params)
            options = {
                'body': {
                    'subscription': {
                        'callbackReference': {
                            'notifyURL': channel['channel_id']
                        },
                        'clientCorrelator': self.api.config.client_correlator,
                        'destinationAddress': params.get('destination_address')
                    }
                }
            }
            url = '{}/inbound/subscriptions'.format(self.base_url)

            response = self.api.send_request(url, options, 'post')

            if (is_test_response(response)):
                return response.json()
            # check if error_response.
            elif (check_if_error_response(response)):
                return build_error_response(response)

            # build custom_response.
            response = response.json()
            custom_response = {
                'webhook_url':
                params.get('webhook_url'),
                'destination_address':
                response['subscription']['destinationAddress'],
                'subscription_id':
                id_from(response['subscription']['resourceURL'])
            }
            return custom_response
Exemplo n.º 4
0
    def get_subscriptions(self, params):
        """
      Read all active subscriptions.

      Args:
        params (dict): Single parameter to hold all options
        params['type'] (:obj:`str`): Type of conversation. Possible values - SMS. Check conversation.types for more options

    """
        url = ''
        message_type = params.get('type')

        if (message_type == this.types['SMS']):
            url = '{}/inbound/subscriptions'.format(self.base_url)

            response = self.api.send_request(url, {})

            if (is_test_response(response)):
                return response.json()
            # check if error_response.
            elif (check_if_error_response(response)):
                return build_error_response(response)

            # build custom_response.
            response = response.json()
            custom_response = []
            if (("subscriptionList" in response)
                    and ("subscription" in response["subscriptionList"])):
                for subscription in response["subsctiptionList"][
                        "subscription"]:
                    custom_response.append({
                        'notify_url':
                        subscription['callbackReference']['notifyURL'],
                        'destination_address':
                        subscription['destinationAddress'],
                        'subscription_id':
                        id_from(subscription['resourceURL'])
                    })
                return custom_response
Exemplo n.º 5
0
    def get_subscription(self, params):
        """
      Read active subscription

      Args:
        params (dict): Single parameter to hold all options
        params['type'] (:obj:`str`): Type of conversation. Possible values - SMS. Check conversation.types for more options
        params['subscription_id'] (:obj:`str`): Resource ID of the subscription
  
    """
        url = ''
        message_type = params.get('type')

        if (message_type == self.types['SMS']):
            url = '{}/inbound/subscriptions/{}'.format(
                self.base_url, params.get('subscription_id'))

            response = self.api.send_request(url, {})

            if (is_test_response(response)):
                return response.json()
            # check if error_response.
            elif (check_if_error_response(response)):
                return build_error_response(response)

            # build custom_response.
            response = response.json()
            if ("subscription" in response):
                custom_response = {
                    'notify_url':
                    response['subscription']['callbackReference']['notifyURL'],
                    'destination_address':
                    response['subcription']['destinationAddress'],
                    'subscription_id':
                    id_from(response['subscription']['resourceURL'])
                }
                return custom_response