U
    3d                     @   sP   d dl Z d dlZd dlmZ d dlmZ d dlmZ d dlZG dd deZ	dS )    N)AWSQueryConnection)
RegionInfo)jsonc                       sJ  e Zd ZdZejdddZejdddZejdddZ	dG fdd	Z
dd Zdd ZdHddZdd Zdd Zdd Zdd Zdd Zdd  ZdId!d"Zd#d$ Zd%d& ZdJd(d)Zd*d+ ZdKd,d-ZdLd.d/ZdMd0d1ZdNd2d3ZdOd4d5ZdPd6d7ZdQd8d9ZdRd:d;Z dSd<d=Z!dTd>d?Z"dUd@dAZ#dVdBdCZ$dWdEdFZ%  Z&S )XSNSConnectiona  
    Amazon Simple Notification Service
    Amazon Simple Notification Service (Amazon SNS) is a web service
    that enables you to build distributed web-enabled applications.
    Applications can use Amazon SNS to easily push real-time
    notification messages to interested subscribers over multiple
    delivery protocols. For more information about this product see
    `http://aws.amazon.com/sns`_. For detailed information about
    Amazon SNS features and their associated API calls, see the
    `Amazon SNS Developer Guide`_.

    We also provide SDKs that enable you to access Amazon SNS from
    your preferred programming language. The SDKs contain
    functionality that automatically takes care of tasks such as:
    cryptographically signing your service requests, retrying
    requests, and handling error responses. For a list of available
    SDKs, go to `Tools for Amazon Web Services`_.
    ZBotoZsns_region_namez	us-east-1Zsns_region_endpointzsns.us-east-1.amazonaws.comZsns_versionz
2010-03-31NTr   /c                    sT   |st | | j| jtd}|| _tt| j||||||||| jj|	|
||||d d S )N)Zconnection_cls)security_tokenvalidate_certsprofile_name)r   DefaultRegionNameDefaultRegionEndpointr   regionsuper__init__endpoint)selfZaws_access_key_idZaws_secret_access_keyZ	is_secureportproxyZ
proxy_portZ
proxy_userZ
proxy_passdebugZhttps_connection_factoryr   pathr   r   r	   	__class__ 7/tmp/pip-unpacked-wheel-d7dsrkjd/boto/sns/connection.pyr   9   s,          zSNSConnection.__init__c           
      C   sj   t | dd d}t|ttdt|d D ]4\}}|\}}d||f }	||d|	 < ||d|	 < q0dS )	aA  
            Serialize a parameter 'name' which value is a 'dictionary' into a list of parameters.

            See: http://docs.aws.amazon.com/sns/latest/api/API_SetPlatformApplicationAttributes.html
            For example::

                dictionary = {'PlatformPrincipal': 'foo', 'PlatformCredential': 'bar'}
                name = 'Attributes'

            would result in params dict being populated with:
                Attributes.entry.1.key    = PlatformPrincipal
                Attributes.entry.1.value  = foo
                Attributes.entry.2.key    = PlatformCredential
                Attributes.entry.2.value  = bar

      :param params: the resulting parameters will be added to this dict
      :param dictionary: dict - value of the serialized parameter
      :param name: name of the serialized parameter
      c                 S   s   | d S )Nr   r   )xr   r   r   <lambda>b       z:SNSConnection._build_dict_as_list_params.<locals>.<lambda>)key   z%s.entry.%sz%s.keyz%s.valueN)sorteditemsziplistrangelen)
r   params
dictionarynamer   kvindexr   valueprefixr   r   r   _build_dict_as_list_paramsN   s    $z(SNSConnection._build_dict_as_list_paramsc                 C   s   dgS )Nzhmac-v4r   )r   r   r   r   _required_auth_capabilityi   s    z'SNSConnection._required_auth_capabilityc                 C   s   i }|r||d< |  d|S )z
        :type next_token: string
        :param next_token: Token returned by the previous call to
                           this method.

        	NextTokenZ
ListTopics_make_requestr   
next_tokenr$   r   r   r   get_all_topicsl   s    zSNSConnection.get_all_topicsc                 C   s   d|i}|  d|S )zu
        Get attributes of a Topic

        :type topic: string
        :param topic: The ARN of the topic.

        TopicArnZGetTopicAttributesr.   r   topicr$   r   r   r   get_topic_attributesx   s    z"SNSConnection.get_topic_attributesc                 C   s   |||d}|  d|S )a  
        Get attributes of a Topic

        :type topic: string
        :param topic: The ARN of the topic.

        :type attr_name: string
        :param attr_name: The name of the attribute you want to set.
                          Only a subset of the topic's attributes are mutable.
                          Valid values: Policy | DisplayName

        :type attr_value: string
        :param attr_value: The new value for the attribute.

        )r3   ZAttributeNameZAttributeValueZSetTopicAttributesr.   )r   r5   	attr_name
attr_valuer$   r   r   r   set_topic_attributes   s
    z"SNSConnection.set_topic_attributesc                 C   s2   ||d}|  ||d |  ||d | d|S )a  
        Adds a statement to a topic's access control policy, granting
        access for the specified AWS accounts to the specified actions.

        :type topic: string
        :param topic: The ARN of the topic.

        :type label: string
        :param label: A unique identifier for the new policy statement.

        :type account_ids: list of strings
        :param account_ids: The AWS account ids of the users who will be
                            give access to the specified actions.

        :type actions: list of strings
        :param actions: The actions you want to allow for each of the
                        specified principal(s).

        r3   ZLabelzAWSAccountId.memberzActionName.memberZAddPermission)Zbuild_list_paramsr/   )r   r5   labelZaccount_idsactionsr$   r   r   r   add_permission   s    zSNSConnection.add_permissionc                 C   s   ||d}|  d|S )a  
        Removes a statement from a topic's access control policy.

        :type topic: string
        :param topic: The ARN of the topic.

        :type label: string
        :param label: A unique identifier for the policy statement
                      to be removed.

        r:   ZRemovePermissionr.   )r   r5   r;   r$   r   r   r   remove_permission   s    zSNSConnection.remove_permissionc                 C   s   d|i}|  d|S )zt
        Create a new Topic.

        :type topic: string
        :param topic: The name of the new topic.

        NameZCreateTopicr.   r4   r   r   r   create_topic   s    zSNSConnection.create_topicc                 C   s   d|i}|  d|ddS )zs
        Delete an existing topic

        :type topic: string
        :param topic: The ARN of the topic

        r3   ZDeleteTopicr   GETr.   r4   r   r   r   delete_topic   s    zSNSConnection.delete_topicc                 C   s   |dkrt dd|i}|dk	r(||d< |dk	r8||d< |dk	rH||d< |dk	rX||d< |dk	rt| }t|dd	D ]l\}	}
||
 }|
|d
|	< d|kr|d |d|	< d|kr|d |d|	< d|krx|d |d|	< qx| d|ddS )a{  
        Sends a message to all of a topic's subscribed endpoints

        :type topic: string
        :param topic: The topic you want to publish to.

        :type message: string
        :param message: The message you want to send to the topic.
                        Messages must be UTF-8 encoded strings and
                        be at most 4KB in size.

        :type message_structure: string
        :param message_structure: Optional parameter. If left as ``None``,
                                  plain text will be sent. If set to ``json``,
                                  your message should be a JSON string that
                                  matches the structure described at
                                  http://docs.aws.amazon.com/sns/latest/dg/PublishTopic.html#sns-message-formatting-by-protocol

        :type message_attributes: dict
        :param message_attributes: Message attributes to set. Should be
            of the form:

            .. code-block:: python

                {
                    "name1": {
                        "data_type": "Number",
                        "string_value": "42"
                    },
                    "name2": {
                        "data_type": "String",
                        "string_value": "Bob"
                    }
                }

        :type subject: string
        :param subject: Optional parameter to be used as the "Subject"
                        line of the email notifications.

        :type target_arn: string
        :param target_arn: Optional parameter for either TopicArn or
                           EndpointArn, but not both.

        Nz!'message' is a required parameterMessageSubjectr3   Z	TargetArnZMessageStructurer   )startz MessageAttributes.entry.{0}.NameZ	data_typez*MessageAttributes.entry.{0}.Value.DataTypeZstring_valuez-MessageAttributes.entry.{0}.Value.StringValueZbinary_valuez-MessageAttributes.entry.{0}.Value.BinaryValueZPublishr   POST)	TypeErrorr   keys	enumerateformatr/   )r   r5   messagesubjectZ
target_arnZmessage_structureZmessage_attributesr$   rH   ir&   	attributer   r   r   publish   s4    .zSNSConnection.publishc                 C   s   |||d}|  d|S )aU  
        Subscribe to a Topic.

        :type topic: string
        :param topic: The ARN of the new topic.

        :type protocol: string
        :param protocol: The protocol used to communicate with
                         the subscriber.  Current choices are:
                         email|email-json|http|https|sqs|sms|application

        :type endpoint: string
        :param endpoint: The location of the endpoint for
                         the subscriber.
                         * For email, this would be a valid email address
                         * For email-json, this would be a valid email address
                         * For http, this would be a URL beginning with http
                         * For https, this would be a URL beginning with https
                         * For sqs, this would be the ARN of an SQS Queue
                         * For sms, this would be a phone number of an
                           SMS-enabled device
                         * For application, the endpoint is the EndpointArn
                           of a mobile app and device.
        )r3   ProtocolZEndpointZ	Subscriber.   )r   r5   protocolr   r$   r   r   r   	subscribe$  s
    zSNSConnection.subscribec                 C   s   |j d}|j}t|| d }d}| |d|}|d}d|kr^t	
|d }	ni }	d|	krrd|	d< d|	krg |	d< |	d D ]}
|
d	 |krd
}q|sddddi||dd|iid}|	d | |dt	|	 |S )a  
        Subscribe an SQS queue to a topic.

        This is convenience method that handles most of the complexity involved
        in using an SQS queue as an endpoint for an SNS topic.  To achieve this
        the following operations are performed:

        * The correct ARN is constructed for the SQS queue and that ARN is
          then subscribed to the topic.
        * A JSON policy document is contructed that grants permission to
          the SNS topic to send messages to the SQS queue.
        * This JSON policy is then associated with the SQS queue using
          the queue's set_attribute method.  If the queue already has
          a policy associated with it, this process will add a Statement to
          that policy.  If no policy exists, a new policy will be created.

        :type topic: string
        :param topic: The ARN of the new topic.

        :type queue: A boto Queue object
        :param queue: The queue you wish to subscribe to the SNS Topic.
        r   utf-8FZsqsPolicyVersionz
2008-10-17Z	StatementSidTzSQS:SendMessageZAllowZAWS*Z
StringLikezaws:SourceArn)ActionZEffectZ	PrincipalResourcerV   	Condition)idsplitZarnhashlibmd5encode	hexdigestrR   Zget_attributesr   loadsappendZset_attributedumps)r   r5   queuetZq_arnZsidZ
sid_existsrespattrpolicysZ	statementr   r   r   subscribe_sqs_queueB  s6    

z!SNSConnection.subscribe_sqs_queueFc                 C   s"   ||d}|rd|d< |  d|S )aU  
        Get properties of a Topic

        :type topic: string
        :param topic: The ARN of the new topic.

        :type token: string
        :param token: Short-lived token sent to and endpoint during
                      the Subscribe operation.

        :type authenticate_on_unsubscribe: bool
        :param authenticate_on_unsubscribe: Optional parameter indicating
                                            that you wish to disable
                                            unauthenticated unsubscription
                                            of the subscription.

        )r3   TokentrueZAuthenticateOnUnsubscribeZConfirmSubscriptionr.   )r   r5   tokenZauthenticate_on_unsubscriber$   r   r   r   confirm_subscriptionv  s    
z"SNSConnection.confirm_subscriptionc                 C   s   d|i}|  d|S )z
        Allows endpoint owner to delete subscription.
        Confirmation message will be delivered.

        :type subscription: string
        :param subscription: The ARN of the subscription to be deleted.

        ZSubscriptionArnZUnsubscriber.   )r   Zsubscriptionr$   r   r   r   unsubscribe  s    	zSNSConnection.unsubscribec                 C   s   i }|r||d< |  d|S )z
        Get list of all subscriptions.

        :type next_token: string
        :param next_token: Token returned by the previous call to
                           this method.

        r-   ZListSubscriptionsr.   r0   r   r   r   get_all_subscriptions  s    	z#SNSConnection.get_all_subscriptionsc                 C   s    d|i}|r||d< |  d|S )aY  
        Get list of all subscriptions to a specific topic.

        :type topic: string
        :param topic: The ARN of the topic for which you wish to
                      find subscriptions.

        :type next_token: string
        :param next_token: Token returned by the previous call to
                           this method.

        r3   r-   ZListSubscriptionsByTopicr.   )r   r5   r1   r$   r   r   r   get_all_subscriptions_by_topic  s    z,SNSConnection.get_all_subscriptions_by_topicc                 C   sH   i }|dk	r||d< |dk	r$||d< |dk	r:|  ||d | jd|dS )a  
        The `CreatePlatformApplication` action creates a platform
        application object for one of the supported push notification
        services, such as APNS and GCM, to which devices and mobile
        apps may register. You must specify PlatformPrincipal and
        PlatformCredential attributes when using the
        `CreatePlatformApplication` action. The PlatformPrincipal is
        received from the notification service. For APNS/APNS_SANDBOX,
        PlatformPrincipal is "SSL certificate". For GCM,
        PlatformPrincipal is not applicable. For ADM,
        PlatformPrincipal is "client id". The PlatformCredential is
        also received from the notification service. For
        APNS/APNS_SANDBOX, PlatformCredential is "private key". For
        GCM, PlatformCredential is "API key". For ADM,
        PlatformCredential is "client secret". The
        PlatformApplicationArn that is returned when using
        `CreatePlatformApplication` is then used as an attribute for
        the `CreatePlatformEndpoint` action. For more information, see
        `Using Amazon SNS Mobile Push Notifications`_.

        :type name: string
        :param name: Application names must be made up of only uppercase and
            lowercase ASCII letters, numbers, underscores, hyphens, and
            periods, and must be between 1 and 256 characters long.

        :type platform: string
        :param platform: The following platforms are supported: ADM (Amazon
            Device Messaging), APNS (Apple Push Notification Service),
            APNS_SANDBOX, and GCM (Google Cloud Messaging).

        :type attributes: map
        :param attributes: For a list of attributes, see
            `SetPlatformApplicationAttributes`_

        Nr?   Platform
AttributesZCreatePlatformApplicationactionr$   r+   r/   )r   r&   platform
attributesr$   r   r   r   create_platform_application  s    %z)SNSConnection.create_platform_applicationc                 C   s8   i }|dk	r||d< |dk	r*|  ||d | jd|dS )a  
        The `SetPlatformApplicationAttributes` action sets the
        attributes of the platform application object for the
        supported push notification services, such as APNS and GCM.
        For more information, see `Using Amazon SNS Mobile Push
        Notifications`_.

        :type platform_application_arn: string
        :param platform_application_arn: PlatformApplicationArn for
            SetPlatformApplicationAttributes action.

        :type attributes: map
        :param attributes:
        A map of the platform application attributes. Attributes in this map
            include the following:


        + `PlatformCredential` -- The credential received from the notification
              service. For APNS/APNS_SANDBOX, PlatformCredential is "private
              key". For GCM, PlatformCredential is "API key". For ADM,
              PlatformCredential is "client secret".
        + `PlatformPrincipal` -- The principal received from the notification
              service. For APNS/APNS_SANDBOX, PlatformPrincipal is "SSL
              certificate". For GCM, PlatformPrincipal is not applicable. For
              ADM, PlatformPrincipal is "client id".
        + `EventEndpointCreated` -- Topic ARN to which EndpointCreated event
              notifications should be sent.
        + `EventEndpointDeleted` -- Topic ARN to which EndpointDeleted event
              notifications should be sent.
        + `EventEndpointUpdated` -- Topic ARN to which EndpointUpdate event
              notifications should be sent.
        + `EventDeliveryFailure` -- Topic ARN to which DeliveryFailure event
              notifications should be sent upon Direct Publish delivery failure
              (permanent) to one of the application's endpoints.

        NPlatformApplicationArnrs   Z SetPlatformApplicationAttributesrt   rv   )r   platform_application_arnrx   r$   r   r   r   #set_platform_application_attributes  s    'z1SNSConnection.set_platform_application_attributesc                 C   s"   i }|dk	r||d< | j d|dS )a  
        The `GetPlatformApplicationAttributes` action retrieves the
        attributes of the platform application object for the
        supported push notification services, such as APNS and GCM.
        For more information, see `Using Amazon SNS Mobile Push
        Notifications`_.

        :type platform_application_arn: string
        :param platform_application_arn: PlatformApplicationArn for
            GetPlatformApplicationAttributesInput.

        Nrz   Z GetPlatformApplicationAttributesrt   r.   r   r{   r$   r   r   r   #get_platform_application_attributes  s    z1SNSConnection.get_platform_application_attributesc                 C   s"   i }|dk	r||d< | j d|dS )a  
        The `ListPlatformApplications` action lists the platform
        application objects for the supported push notification
        services, such as APNS and GCM. The results for
        `ListPlatformApplications` are paginated and return a limited
        list of applications, up to 100. If additional records are
        available after the first page results, then a NextToken
        string will be returned. To receive the next page, you call
        `ListPlatformApplications` using the NextToken string received
        from the previous call. When there are no more records to
        return, NextToken will be null. For more information, see
        `Using Amazon SNS Mobile Push Notifications`_.

        :type next_token: string
        :param next_token: NextToken string is used when calling
            ListPlatformApplications action to retrieve additional records that
            are available after the first page results.

        Nr-   ZListPlatformApplicationsrt   r.   r0   r   r   r   list_platform_applications,  s    z(SNSConnection.list_platform_applicationsc                 C   s2   i }|dk	r||d< |dk	r$||d< | j d|dS )a  
        The `ListEndpointsByPlatformApplication` action lists the
        endpoints and endpoint attributes for devices in a supported
        push notification service, such as GCM and APNS. The results
        for `ListEndpointsByPlatformApplication` are paginated and
        return a limited list of endpoints, up to 100. If additional
        records are available after the first page results, then a
        NextToken string will be returned. To receive the next page,
        you call `ListEndpointsByPlatformApplication` again using the
        NextToken string received from the previous call. When there
        are no more records to return, NextToken will be null. For
        more information, see `Using Amazon SNS Mobile Push
        Notifications`_.

        :type platform_application_arn: string
        :param platform_application_arn: PlatformApplicationArn for
            ListEndpointsByPlatformApplicationInput action.

        :type next_token: string
        :param next_token: NextToken string is used when calling
            ListEndpointsByPlatformApplication action to retrieve additional
            records that are available after the first page results.

        Nrz   r-   Z"ListEndpointsByPlatformApplicationrt   r.   )r   r{   r1   r$   r   r   r   &list_endpoints_by_platform_applicationF  s    z4SNSConnection.list_endpoints_by_platform_applicationc                 C   s"   i }|dk	r||d< | j d|dS )a  
        The `DeletePlatformApplication` action deletes a platform
        application object for one of the supported push notification
        services, such as APNS and GCM. For more information, see
        `Using Amazon SNS Mobile Push Notifications`_.

        :type platform_application_arn: string
        :param platform_application_arn: PlatformApplicationArn of platform
            application object to delete.

        Nrz   ZDeletePlatformApplicationrt   r.   r}   r   r   r   delete_platform_applicationi  s    z)SNSConnection.delete_platform_applicationc                 C   sX   i }|dk	r||d< |dk	r$||d< |dk	r4||d< |dk	rJ|  ||d | jd|dS )am  
        The `CreatePlatformEndpoint` creates an endpoint for a device
        and mobile app on one of the supported push notification
        services, such as GCM and APNS. `CreatePlatformEndpoint`
        requires the PlatformApplicationArn that is returned from
        `CreatePlatformApplication`. The EndpointArn that is returned
        when using `CreatePlatformEndpoint` can then be used by the
        `Publish` action to send a message to a mobile app or by the
        `Subscribe` action for subscription to a topic. For more
        information, see `Using Amazon SNS Mobile Push
        Notifications`_.

        :type platform_application_arn: string
        :param platform_application_arn: PlatformApplicationArn returned from
            CreatePlatformApplication is used to create a an endpoint.

        :type token: string
        :param token: Unique identifier created by the notification service for
            an app on a device. The specific name for Token will vary,
            depending on which notification service is being used. For example,
            when using APNS as the notification service, you need the device
            token. Alternatively, when using GCM or ADM, the device token
            equivalent is called the registration ID.

        :type custom_user_data: string
        :param custom_user_data: Arbitrary user data to associate with the
            endpoint. SNS does not use this data. The data must be in UTF-8
            format and less than 2KB.

        :type attributes: map
        :param attributes: For a list of attributes, see
            `SetEndpointAttributes`_.

        Nrz   rk   ZCustomUserDatars   ZCreatePlatformEndpointrt   rv   )r   r{   rm   Zcustom_user_datarx   r$   r   r   r   create_platform_endpoint{  s    %z&SNSConnection.create_platform_endpointc                 C   s"   i }|dk	r||d< | j d|dS )a   
        The `DeleteEndpoint` action, which is idempotent, deletes the
        endpoint from SNS. For more information, see `Using Amazon SNS
        Mobile Push Notifications`_.

        :type endpoint_arn: string
        :param endpoint_arn: EndpointArn of endpoint to delete.

        NEndpointArnZDeleteEndpointrt   r.   r   endpoint_arnr$   r   r   r   delete_endpoint  s    
zSNSConnection.delete_endpointc                 C   s8   i }|dk	r||d< |dk	r*|  ||d | jd|dS )a!  
        The `SetEndpointAttributes` action sets the attributes for an
        endpoint for a device on one of the supported push
        notification services, such as GCM and APNS. For more
        information, see `Using Amazon SNS Mobile Push
        Notifications`_.

        :type endpoint_arn: string
        :param endpoint_arn: EndpointArn used for SetEndpointAttributes action.

        :type attributes: map
        :param attributes:
        A map of the endpoint attributes. Attributes in this map include the
            following:


        + `CustomUserData` -- arbitrary user data to associate with the
              endpoint. SNS does not use this data. The data must be in UTF-8
              format and less than 2KB.
        + `Enabled` -- flag that enables/disables delivery to the endpoint.
              Message Processor will set this to false when a notification
              service indicates to SNS that the endpoint is invalid. Users can
              set it back to true, typically after updating Token.
        + `Token` -- device token, also referred to as a registration id, for
              an app and mobile device. This is returned from the notification
              service when an app and mobile device are registered with the
              notification service.

        Nr   rs   ZSetEndpointAttributesrt   rv   )r   r   rx   r$   r   r   r   set_endpoint_attributes  s    z%SNSConnection.set_endpoint_attributesc                 C   s"   i }|dk	r||d< | j d|dS )av  
        The `GetEndpointAttributes` retrieves the endpoint attributes
        for a device on one of the supported push notification
        services, such as GCM and APNS. For more information, see
        `Using Amazon SNS Mobile Push Notifications`_.

        :type endpoint_arn: string
        :param endpoint_arn: EndpointArn for GetEndpointAttributes input.

        Nr   ZGetEndpointAttributesrt   r.   r   r   r   r   get_endpoint_attributes  s    z%SNSConnection.get_endpoint_attributesrA   c                 C   s   d|d< | j ||||d}| d}tj| |jdkrHt|S tj	d|j|j
f  tj	d|  | |j|j
|d S )NZJSONZContentType)ru   verbr   r$   rS      z%s %sz%s)Zmake_requestreaddecodebotologr   statusr   ra   errorreasonResponseError)r   ru   r$   r   r   responsebodyr   r   r   r/     s     

zSNSConnection._make_request)NNTNNNNNr   NNr   NTN)N)NNNNNN)F)N)N)NNN)NN)N)N)NN)N)NNNN)N)NN)N)r   rA   )'__name__
__module____qualname____doc__r   configgetr
   r   Z
APIVersionr   r+   r,   r2   r6   r9   r=   r>   r@   rB   rO   rR   rj   rn   ro   rp   rq   ry   r|   r~   r   r   r   r   r   r   r   r/   __classcell__r   r   r   r   r       s~   
                      
    
L5 


  
0  
0 

  
#
     
1

&
r   )
uuidr]   Zboto.connectionr   Zboto.regioninfor   Zboto.compatr   r   r   r   r   r   r   <module>   s   