U
    3d5z                     @   s   d dl Z d dlZd dlZd dlmZmZ d dlmZ d dlm	Z	m
Z
 d dlmZmZ d dlmZ d dlmZmZ d dlmZ G d	d
 d
eZG dd deZG dd deZG dd deZG dd deZG dd deZdS )    N)sixjson)OriginAccessIdentity)ObjectStreamingObject)ActiveTrustedSignersTrustedSigners)LoggingInfo)S3OriginCustomOrigin)ACLc                	   @   s6   e Zd ZdddZdd Zdd	 Zd
d Zdd ZdS )DistributionConfigNF c
           
      C   sX   || _ || _|| _|r|| _ntt | _g | _|r<|| _|| _|| _	|	| _
|| _dS )a+
  
        :param origin: Origin information to associate with the
                       distribution.  If your distribution will use
                       an Amazon S3 origin, then this should be an
                       S3Origin object. If your distribution will use
                       a custom origin (non Amazon S3), then this
                       should be a CustomOrigin object.
        :type origin: :class:`boto.cloudfront.origin.S3Origin` or
                      :class:`boto.cloudfront.origin.CustomOrigin`

        :param enabled: Whether the distribution is enabled to accept
                        end user requests for content.
        :type enabled: bool

        :param caller_reference: A unique number that ensures the
                                 request can't be replayed.  If no
                                 caller_reference is provided, boto
                                 will generate a type 4 UUID for use
                                 as the caller reference.
        :type enabled: str

        :param cnames: A CNAME alias you want to associate with this
                       distribution. You can have up to 10 CNAME aliases
                       per distribution.
        :type enabled: array of str

        :param comment: Any comments you want to include about the
                        distribution.
        :type comment: str

        :param trusted_signers: Specifies any AWS accounts you want to
                                permit to create signed URLs for private
                                content. If you want the distribution to
                                use signed URLs, this should contain a
                                TrustedSigners object; if you want the
                                distribution to use basic URLs, leave
                                this None.
        :type trusted_signers: :class`boto.cloudfront.signers.TrustedSigners`

        :param default_root_object: Designates a default root object.
                                    Only include a DefaultRootObject value
                                    if you are going to assign a default
                                    root object for the distribution.
        :type comment: str

        :param logging: Controls whether access logs are written for the
                        distribution. If you want to turn on access logs,
                        this should contain a LoggingInfo object; otherwise
                        it should contain None.
        :type logging: :class`boto.cloudfront.logging.LoggingInfo`

        N)
connectionoriginenabledcaller_referencestruuidZuuid4cnamescommenttrusted_signersloggingdefault_root_object)
selfr   r   r   r   r   r   r   r   r    r   @/tmp/pip-unpacked-wheel-d7dsrkjd/boto/cloudfront/distribution.py__init__#   s    8zDistributionConfig.__init__c                 C   s
   d| j  S )NzDistributionConfig:%s)r   r   r   r   r   __repr__j   s    zDistributionConfig.__repr__c                 C   s  d}|d7 }| j r || j  7 }|d| j 7 }| jD ]}|d| 7 }q4| jrZ|d| j 7 }|d7 }| jrr|d7 }n|d7 }|d	7 }| jr|d
7 }| jD ]"}|dkr|d7 }q|d| 7 }q|d7 }| jr|d7 }|d| jj 7 }|d| jj	 7 }|d7 }| j
r| j
}|d| 7 }|d7 }|S )N'<?xml version="1.0" encoding="UTF-8"?>
zM<DistributionConfig xmlns="http://cloudfront.amazonaws.com/doc/2010-07-15/">
(  <CallerReference>%s</CallerReference>
  <CNAME>%s</CNAME>
  <Comment>%s</Comment>
  <Enabled>truefalse</Enabled>
<TrustedSigners>
Selfz  <Self></Self>
*  <AwsAccountNumber>%s</AwsAccountNumber>
</TrustedSigners>

<Logging>
  <Bucket>%s</Bucket>
  <Prefix>%s</Prefix>
</Logging>
z*<DefaultRootObject>%s</DefaultRootObject>
z</DistributionConfig>
)r   to_xmlr   r   r   r   r   r   bucketprefixr   )r   scnamesignerZdror   r   r   r0   m   s>    



zDistributionConfig.to_xmlc                 C   s`   |dkrt  | _| jS |dkr,t | _| jS |dkrBt | _| jS |dkrXt | _| jS d S d S )Nr   ZLoggingr
   r   )r   r   r	   r   r
   r   r   r   nameattrsr   r   r   r   startElement   s    zDistributionConfig.startElementc                 C   sz   |dkr| j | n`|dkr&|| _nP|dkrJ| dkrBd| _qvd| _n,|dkrZ|| _n|dkrj|| _nt| || d S )	NCNAMECommentEnabledr%   TFZCallerReferenceZDefaultRootObject)r   appendr   lowerr   r   r   setattrr   r7   valuer   r   r   r   
endElement   s    zDistributionConfig.endElement)	NNFr   Nr   NNN)__name__
__module____qualname__r   r   r0   r9   rB   r   r   r   r   r   !   s             
G#r   c                       s&   e Zd Zd fdd	Zdd Z  ZS )	StreamingDistributionConfigNr   Fc	           	   
      s$   t t| j||||||||d d S )N)r   r   r   r   r   r   r   r   )superrF   r   )	r   r   r   r   r   r   r   r   r   	__class__r   r   r      s      z$StreamingDistributionConfig.__init__c                 C   s  d}|d7 }| j r || j  7 }|d| j 7 }| jD ]}|d| 7 }q4| jrZ|d| j 7 }|d7 }| jrr|d7 }n|d7 }|d	7 }| jr|d
7 }| jD ]"}|dkr|d7 }q|d| 7 }q|d7 }| jr|d7 }|d| jj 7 }|d| jj	 7 }|d7 }|d7 }|S )Nr    zV<StreamingDistributionConfig xmlns="http://cloudfront.amazonaws.com/doc/2010-07-15/">
r!   r"   r#   r$   r%   r&   r'   r(   r)   z
  <Self/>
r*   r+   r,   r-   r.   r/   z</StreamingDistributionConfig>
)
r   r0   r   r   r   r   r   r   r1   r2   )r   r3   r4   r5   r   r   r   r0      s8    



z"StreamingDistributionConfig.to_xml)Nr   Fr   Nr   NN)rC   rD   rE   r   r0   __classcell__r   r   rH   r   rF      s            	rF   c                	   @   s6   e Zd ZdddZdd Zdd	 Zd
d Zdd ZdS )DistributionSummaryNr   Fc
           
      C   s\   || _ || _|| _|| _|| _|| _|	| _g | _|r@| j| || _	d | _
d | _d| _d S )NF)r   domain_nameidlast_modified_timestatusr   r   r   r=   r   r   etag	streaming)
r   r   rL   rM   rN   rO   r   r4   r   r   r   r   r   r      s    zDistributionSummary.__init__c                 C   s
   d| j  S )NzDistributionSummary:%srL   r   r   r   r   r      s    zDistributionSummary.__repr__c                 C   sF   |dkrt  | _| jS |dkr,t | _| jS |dkrBt | _| jS d S )Nr   r
   r   )r   r   r
   r   r   r6   r   r   r   r9      s    z DistributionSummary.startElementc                 C   s   |dkr|| _ n|dkr || _n|dkr0|| _n|dkr@|| _nv|dkrP|| _nf|dkrf| j| nP|dkrv|| _n@|dkr| d	krd
| _	qd| _	n|dkrd
| _
nt| || d S )NIdStatusLastModifiedTime
DomainNameZOriginr:   r;   r<   r%   TFStreamingDistributionSummary)rM   rO   rN   rL   r   r   r=   r   r>   r   rQ   r?   r@   r   r   r   rB      s*    zDistributionSummary.endElementc                 C   s   | j | jS N)r   Zget_distribution_inforM   r   r   r   r   get_distribution  s    z$DistributionSummary.get_distribution)	Nr   r   Nr   Nr   r   F)rC   rD   rE   r   r   r9   rB   rY   r   r   r   r   rK      s              
rK   c                   @   s   e Zd Zdd ZdS )rW   c                 C   s   | j | jS rX   )r   Zget_streaming_distribution_inforM   r   r   r   r   rY     s    z-StreamingDistributionSummary.get_distributionN)rC   rD   rE   rY   r   r   r   r   rW     s   rW   c                   @   s   e Zd Zd+ddZdd Zdd Zd	d
 Zd,ddZdd Zdd Z	dd Z
dd Zdd Zd-ddZd.ddZd/ddZd0dd Zd1d!d"Zed#d$ Zed2d%d&Zed3d'd(Zed)d* ZdS )4DistributionNr   c                 C   sF   || _ || _|| _|| _|| _|| _d| _d | _d | _d | _	t
| _d S )Nr   )r   configrL   rM   rN   rO    in_progress_invalidation_batchesactive_signersrP   _bucketr   _object_classr   r   r[   rL   rM   rN   rO   r   r   r   r   "  s    zDistribution.__init__c                 C   s
   d| j  S )NzDistribution:%srR   r   r   r   r   r   0  s    zDistribution.__repr__c                 C   s4   |dkrt  | _| jS |dkr,t | _| jS d S d S )Nr   r   )r   r[   r   r]   r6   r   r   r   r9   3  s    zDistribution.startElementc                 C   sd   |dkr|| _ nP|dkr || _n@|dkr0|| _n0|dkrDt|| _n|dkrT|| _nt| || d S )NrS   rU   rT   ZInProgressInvalidationBatchesrV   )rM   rN   rO   intr\   rL   r?   r@   r   r   r   rB   =  s    zDistribution.endElementc              	   C   s   t | j| jj| jj| jj| jj| jj| jj| jj	}|dk	rB||_|dk	rP||_|dk	r^||_| j
| j| j|| _|| _t| _dS )a  
        Update the configuration of the Distribution.  The only values
        of the DistributionConfig that can be directly updated are:

         * CNAMES
         * Comment
         * Whether the Distribution is enabled or not

        Any changes to the ``trusted_signers`` or ``origin`` properties of
        this distribution's current config object will also be included in
        the update. Therefore, to set the origin access identity for this
        distribution, set ``Distribution.config.origin.origin_access_identity``
        before calling this update method.

        :type enabled: bool
        :param enabled: Whether the Distribution is active or not.

        :type cnames: list of str
        :param cnames: The DNS CNAME's associated with this
                        Distribution.  Maximum of 10 values.

        :type comment: str or unicode
        :param comment: The comment associated with the Distribution.

        N)r   r   r[   r   r   r   r   r   r   r   Zset_distribution_configrM   rP   r   r_   r   r   r   r   Z
new_configr   r   r   updateK  s"      zDistribution.updatec                 C   s   | j dd dS )ze
        Activate the Distribution.  A convenience wrapper around
        the update method.
        Tr   Nrc   r   r   r   r   enablet  s    zDistribution.enablec                 C   s   | j dd dS )zg
        Deactivate the Distribution.  A convenience wrapper around
        the update method.
        Frd   Nre   r   r   r   r   disable{  s    zDistribution.disablec                 C   s   | j | j| j dS )z
        Delete this CloudFront Distribution.  The content
        associated with the Distribution is not deleted from
        the underlying Origin bucket in S3.
        N)r   Zdelete_distributionrM   rP   r   r   r   r   delete  s    zDistribution.deletec                 C   s   t | jjtr| js| jjj}|dd}ddlm} || j	j
| j	j| j	j| j	j| j	j| j	jd}||| _| | j_| j| j | jS tdd S )Nz.s3.amazonaws.comr   r   )S3Connection)proxy
proxy_port
proxy_user
proxy_passz%Unable to get_objects on CustomOrigin)
isinstancer[   r   r
   r^   Zdns_namereplaceZboto.s3.connectionri   r   Zaws_access_key_idZaws_secret_access_keyrj   rk   rl   rm   Z
get_bucketdistributionZset_key_classr_   NotImplementedError)r   Zbucket_dns_nameZbucket_nameri   Zs3r   r   r   _get_bucket  s"    
zDistribution._get_bucketc                 C   s$   |   }g }|D ]}|| q|S )z
        Return a list of all content objects in this distribution.

        :rtype: list of :class:`boto.cloudfront.object.Object`
        :return: The content objects
        )rr   r=   )r   r1   objskeyr   r   r   get_objects  s
    zDistribution.get_objectsFc                 C   sv   t | jjtrr| jjjrh| jjjdd }| j|}| }|rLt	 |_
|j
d|j || n
|d dS )as  
        Sets the S3 ACL grants for the given object to the appropriate
        value based on the type of Distribution.  If the Distribution
        is serving private content the ACL will be set to include the
        Origin Access Identity associated with the Distribution.  If
        the Distribution is serving public content the content will
        be set up with "public-read".

        :type object: :class:`boto.cloudfront.object.Object`
        :param enabled: The Object whose ACL is being set

        :type replace: bool
        :param replace: If False, the Origin Access Identity will be
                        appended to the existing ACL for the object.
                        If True, the ACL for the object will be
                        completely replaced with one that grants
                        READ permission to the Origin Access Identity.

        /READpublic-readN)rn   r[   r   r
   origin_access_identitysplitr   Zget_origin_access_identity_infoZget_aclr   ZaclZadd_user_grantZ
s3_user_idZset_aclZset_canned_acl)r   objectro   rM   Zoaipolicyr   r   r   set_permissions  s    
zDistribution.set_permissionsc                 C   s"   |   }|D ]}| || qdS )a   
        Sets the S3 ACL grants for all objects in the Distribution
        to the appropriate value based on the type of Distribution.

        :type replace: bool
        :param replace: If False, the Origin Access Identity will be
                        appended to the existing ACL for the object.
                        If True, the ACL for the object will be
                        completely replaced with one that grants
                        READ permission to the Origin Access Identity.

        N)rr   r~   )r   ro   r1   rt   r   r   r   set_permissions_all  s    z Distribution.set_permissions_allTc                 C   sP   | j jjrd}nd}|  }||}|j|||d | j jjrL| || |S )a  
        Adds a new content object to the Distribution.  The content
        for the object will be copied to a new Key in the S3 Bucket
        and the permissions will be set appropriately for the type
        of Distribution.

        :type name: str or unicode
        :param name: The name or key of the new object.

        :type content: file-like object
        :param content: A file-like object that contains the content
                        for the new object.

        :type headers: dict
        :param headers: A dictionary containing additional headers
                        you would like associated with the new
                        object in S3.

        :rtype: :class:`boto.cloudfront.object.Object`
        :return: The newly created object.
        privatery   )headersr}   )r[   r   rz   rr   Znew_keyZset_contents_from_filer~   )r   r7   contentr   ro   r}   r1   r|   r   r   r   
add_object  s    


zDistribution.add_objectc	              
   C   sr   | j ||||||||d}	d|kr(d}
nd}
g }dD ]&}||	kr4d||	| f }|| q4||
 d| }|S )a  
        Creates a signed CloudFront URL that is only valid within the specified
        parameters.

        :type url: str
        :param url: The URL of the protected object.

        :type keypair_id: str
        :param keypair_id: The keypair ID of the Amazon KeyPair used to sign
            theURL.  This ID MUST correspond to the private key
            specified with private_key_file or private_key_string.

        :type expire_time: int
        :param expire_time: The expiry time of the URL. If provided, the URL
            will expire after the time has passed. If not provided the URL will
            never expire. Format is a unix epoch.
            Use int(time.time() + duration_in_sec).

        :type valid_after_time: int
        :param valid_after_time: If provided, the URL will not be valid until
            after valid_after_time. Format is a unix epoch.
            Use int(time.time() + secs_until_valid).

        :type ip_address: str
        :param ip_address: If provided, only allows access from the specified
            IP address.  Use '192.168.0.10' for a single IP or
            use '192.168.0.0/24' CIDR notation for a subnet.

        :type policy_url: str
        :param policy_url: If provided, allows the signature to contain
            wildcard globs in the URL.  For example, you could
            provide: 'http://example.com/media/\*' and the policy
            and signature would allow access to all contents of
            the media subdirectory. If not specified, only
            allow access to the exact url provided in 'url'.

        :type private_key_file: str or file object.
        :param private_key_file: If provided, contains the filename of the
            private key file used for signing or an open
            file object containing the private key
            contents.  Only one of private_key_file or
            private_key_string can be provided.

        :type private_key_string: str
        :param private_key_string: If provided, contains the private key string
            used for signing. Only one of private_key_file or
            private_key_string can be provided.

        :rtype: str
        :return: The signed URL.
        )url
keypair_idexpire_timevalid_after_time
ip_address
policy_urlprivate_key_fileprivate_key_string?&)ExpiresPolicy	SignatureKey-Pair-Idz%s=%s)_create_signing_paramsr=   join)r   r   r   r   r   r   r   r   r   paramssepZsigned_url_paramsrt   paramZ
signed_urlr   r   r   create_signed_url  s(    8    zDistribution.create_signed_urlc	                 C   s   i }	|r.|s.|s.|s.|  ||}
t||	d< n0|dkr:|}| j||||d}
| |
}||	d< | |
||}| |}||	d< ||	d< |	S )zG
        Creates the required URL parameters for a signed URL.
        r   N)expiresvalid_afterr   r   r   r   )_canned_policyr   _custom_policy_url_base64_encode_sign_string)r   r   r   r   r   r   r   r   r   r   r}   Zencoded_policy	signatureZencoded_signaturer   r   r   r   G  s"    

z#Distribution._create_signing_paramsc                 C   s   dt   }|S )z1
        Creates a canned policy string.
        zf{"Statement":[{"Resource":"%(resource)s","Condition":{"DateLessThan":{"AWS:EpochTime":%(expires)s}}}]})locals)resourcer   r}   r   r   r   r   h  s    zDistribution._canned_policyc                 C   sr   i }|st t d }d|i|d< |r4d|i|d< |rTd|krH|d7 }d|i|d< d	| |d
gi}tj|ddS )zR
        Creates a custom policy string based on the supplied parameters.
        iQ zAWS:EpochTimeZDateLessThanZDateGreaterThanrv   z/32zAWS:SourceIpZ	IpAddressZ	Statement)Resource	Condition),:)
separators)ra   timer   dumps)r   r   r   r   	conditionr}   r   r   r   r   r  s    
zDistribution._custom_policyc              	   C   s   zddl }W n tk
r(   tdY nX |r:|r:td|sJ|sJtd|dkrt|tjr~t|d}| }W 5 Q R X n| }|j	
|}|t| |d}|S )zo
        Signs a string for use with Amazon CloudFront.
        Requires the rsa library be installed.
        r   NzMBoto depends on the python rsa library to generate signed URLs for CloudFrontzDOnly specify the private_key_file or the private_key_string not bothz>You must specify one of private_key_file or private_key_stringrzSHA-1)rsaImportErrorrq   
ValueErrorrn   r   string_typesopenreadZ
PrivateKeyZ
load_pkcs1signr   )messager   r   r   Zfile_handleZprivate_keyr   r   r   r   r     s     zDistribution._sign_stringc                 C   s2   t | }|dd}|dd}|dd}|S )zd
        Base64 encodes a string using the URL-safe characters specified by
        Amazon.
        +-=_rv   ~)base64	b64encodero   )msgZ
msg_base64r   r   r   r     s
    
zDistribution._url_base64_encode)NNr   r   Nr   )NNN)F)F)NT)NNNNNN)NNNNNN)NNN)NN)rC   rD   rE   r   r   r9   rB   rc   rf   rg   rh   rr   ru   r~   r   r   r   r   staticmethodr   r   r   r   r   r   r   r   rZ      sN         


)
 

"         
L         
!
	rZ   c                       s<   e Zd Zd fdd	Z fddZdddZd	d
 Z  ZS )StreamingDistributionNr   c                    s$   t t| |||||| t| _d S rX   )rG   r   r   r   r_   r`   rH   r   r   r     s       zStreamingDistribution.__init__c                    s.   |dkrt  | _| jS tt| |||S d S )NrF   )rF   r[   rG   r   r9   r6   rH   r   r   r9     s    z"StreamingDistribution.startElementc                 C   s~   t | j| jj| jj| jj| jj| jj| jj}|dk	r<||_|dk	rJ||_|dk	rX||_| j	| j
| j|| _|| _t| _dS )a  
        Update the configuration of the StreamingDistribution.  The only values
        of the StreamingDistributionConfig that can be directly updated are:

         * CNAMES
         * Comment
         * Whether the Distribution is enabled or not

        Any changes to the ``trusted_signers`` or ``origin`` properties of
        this distribution's current config object will also be included in
        the update. Therefore, to set the origin access identity for this
        distribution, set
        ``StreamingDistribution.config.origin.origin_access_identity``
        before calling this update method.

        :type enabled: bool
        :param enabled: Whether the StreamingDistribution is active or not.

        :type cnames: list of str
        :param cnames: The DNS CNAME's associated with this
                        Distribution.  Maximum of 10 values.

        :type comment: str or unicode
        :param comment: The comment associated with the Distribution.

        N)rF   r   r[   r   r   r   r   r   r   Z!set_streaming_distribution_configrM   rP   r   r_   rb   r   r   r   rc     s(    
zStreamingDistribution.updatec                 C   s   | j | j| j d S rX   )r   Zdelete_streaming_distributionrM   rP   r   r   r   r   rh     s    zStreamingDistribution.delete)NNr   r   Nr   )NNN)rC   rD   rE   r   r9   rc   rh   rJ   r   r   rH   r   r     s         
.r   )r   r   r   Zboto.compatr   r   Zboto.cloudfront.identityr   Zboto.cloudfront.objectr   r   Zboto.cloudfront.signersr   r   Zboto.cloudfront.loggingr	   Zboto.cloudfront.originr
   r   Zboto.s3.aclr   r|   r   rF   rK   rW   rZ   r   r   r   r   r   <module>   s&    +?   