a
    [r_2                     @   s>  d Z ddlZddlZddlZddlZddlZddlZddlZddlZ	ddl
mZ ddlmZ ddlmZmZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZmZmZmZ ddlm Z  ddl!m"Z" ddl#m$Z$ ddl%m&Z& ddl'm(Z( ddl'm)Z) ddl*m+Z+ e, Z-G dd deZ.dd Z/dd Z0dS )z9Client for interacting with the Google Cloud Storage API.    N)AnonymousCredentials)page_iterator)_LocalStack_NOW)ClientWithProject)NotFound)_get_storage_host)_bucket_bound_hostname_url)
Connection)get_expiration_seconds_v4get_v4_now_dtstampsensure_signed_credentials_sign_messageBatchBucket)Blob)HMACKeyMetadata)	BucketACL)DefaultObjectACL)_DEFAULT_TIMEOUTc                       sT  e Zd ZdZdZeddddf fdd	Zedd Ze	dd	 Z
e
jd
d	 Z
dd Zdd Zdd Ze	dd ZdefddZd0ddZdd ZeddfddZeddfddZddddddefddZd1dd Zddddddddd!defd"d#Zdddd!ddefd$d%Zddefd&d'Zdddddefd(d)Zddefd*d+Zd2d.d/Z  ZS )3Clienta  Client to bundle configuration needed for API requests.

    :type project: str or None
    :param project: the project which the client acts on behalf of. Will be
                    passed when creating a topic.  If not passed,
                    falls back to the default inferred from the environment.

    :type credentials: :class:`~google.auth.credentials.Credentials`
    :param credentials: (Optional) The OAuth2 Credentials to use for this
                        client. If not passed (and if no ``_http`` object is
                        passed), falls back to the default inferred from the
                        environment.

    :type _http: :class:`~requests.Session`
    :param _http: (Optional) HTTP object to make requests. Can be any object
                  that defines ``request()`` with the same interface as
                  :meth:`requests.Session.request`. If not passed, an
                  ``_http`` object is created that is bound to the
                  ``credentials`` for the current object.
                  This parameter should be considered private, and could
                  change in the future.

    :type client_info: :class:`~google.api_core.client_info.ClientInfo`
    :param client_info:
        The client info used to send a user-agent string along with API
        requests. If ``None``, then default info will be used. Generally,
        you only need to set this if you're developing your own library
        or partner tool.

    :type client_options: :class:`~google.api_core.client_options.ClientOptions` or :class:`dict`
    :param client_options: (Optional) Client options used to set user options on the client.
        API Endpoint should be set through client_options.
    )z7https://www.googleapis.com/auth/devstorage.full_controlz4https://www.googleapis.com/auth/devstorage.read_onlyz5https://www.googleapis.com/auth/devstorage.read_writeNc           	         s   d | _ |d u rd}d}nd}|tu r(d }tt| j||||d d|i}t |d< |rt|tkrptj	j
|}|jr|j}||d< |rd | _t| fi || _t | _d S )NT<none>F)projectcredentialsclient_options_httpclient_infoapi_endpoint)_base_connection_markersuperr   __init__r   typedictgoogleZapi_corer   Z	from_dictr   r   r
   _connectionr   _batch_stack)	selfr   r   r   r   r   Z
no_projectZkw_argsr   	__class__ :lib/python3.9/site-packages/google/cloud/storage/client.pyr#   _   s6    

zClient.__init__c                 C   s   | dt  d}d|_|S )aU  Factory: return client with anonymous credentials.

        .. note::

           Such a client has only limited access to "public" buckets:
           listing their contents and downloading their blobs.

        :rtype: :class:`google.cloud.storage.client.Client`
        :returns: Instance w/ anonymous credentials and no project.
        r   )r   r   N)r   r   )clsclientr,   r,   r-   create_anonymous_client   s    zClient.create_anonymous_clientc                 C   s   | j dur| j S | jS dS )zGet connection or batch on the client.

        :rtype: :class:`google.cloud.storage._http.Connection`
        :returns: The connection set on the client, or the batch
                  if one is set.
        N)current_batchr    r)   r,   r,   r-   r'      s    
zClient._connectionc                 C   s   | j durtd|| _ dS )a  Set connection on the client.

        Intended to be used by constructor (since the base class calls)
            self._connection = connection
        Will raise if the connection is set more than once.

        :type value: :class:`google.cloud.storage._http.Connection`
        :param value: The connection set on the client.

        :raises: :class:`ValueError` if connection has already been set.
        Nz Connection already set on client)r    
ValueError)r)   valuer,   r,   r-   r'      s    
c                 C   s   | j | dS )zPush a batch onto our stack.

        "Protected", intended for use by batch context mgrs.

        :type batch: :class:`google.cloud.storage.batch.Batch`
        :param batch: newly-active batch
        N)r(   push)r)   batchr,   r,   r-   _push_batch   s    zClient._push_batchc                 C   s
   | j  S )a  Pop a batch from our stack.

        "Protected", intended for use by batch context mgrs.

        :raises: IndexError if the stack is empty.
        :rtype: :class:`google.cloud.storage.batch.Batch`
        :returns: the top-most batch/transaction, after removing it.
        )r(   popr2   r,   r,   r-   
_pop_batch   s    	zClient._pop_batchc                 C   s    t |tr|}nt| |d}|S )a  Helper to return given bucket or create new by name.

        Args:
            bucket_or_name (Union[                 :class:`~google.cloud.storage.bucket.Bucket`,                  str,             ]):
                The bucket resource to pass or name to create.

        Returns:
            google.cloud.storage.bucket.Bucket
                The newly created bucket or the given one.
        )name)
isinstancer   )r)   bucket_or_namebucketr,   r,   r-   _bucket_arg_to_bucket   s    
zClient._bucket_arg_to_bucketc                 C   s   | j jS )zCurrently-active batch.

        :rtype: :class:`google.cloud.storage.batch.Batch` or ``NoneType`` (if
                no batch is active).
        :returns: The batch at the top of the batch stack.
        )r(   topr2   r,   r,   r-   r1      s    zClient.current_batchc                 C   s2   |du r| j }d|f }| jjd||d}|d S )at  Get the email address of the project's GCS service account

        :type project: str
        :param project:
            (Optional) Project ID to use for retreiving GCS service account
            email address.  Defaults to the client's project.
        :type timeout: float or tuple
        :param timeout: (Optional) The amount of time, in seconds, to wait
            for the server response.

            Can also be passed as a tuple (connect_timeout, read_timeout).
            See :meth:`requests.Session.request` documentation for details.

        :rtype: str
        :returns: service account email address
        Nz/projects/%s/serviceAccountZGET)methodpathtimeoutZemail_address)r   r    api_request)r)   r   rB   rA   api_responser,   r,   r-   get_service_account_email   s    
z Client.get_service_account_emailc                 C   s   t | ||dS )a0  Factory constructor for bucket object.

        .. note::
          This will not make an HTTP request; it simply instantiates
          a bucket object owned by this client.

        :type bucket_name: str
        :param bucket_name: The name of the bucket to be instantiated.

        :type user_project: str
        :param user_project: (Optional) The project ID to be billed for API
                             requests made via the bucket.

        :rtype: :class:`google.cloud.storage.bucket.Bucket`
        :returns: The bucket object created.
        )r/   r:   user_projectr   )r)   bucket_namerF   r,   r,   r-   r=     s    zClient.bucketc                 C   s
   t | dS )a  Factory constructor for batch object.

        .. note::
          This will not make an HTTP request; it simply instantiates
          a batch object owned by this client.

        :rtype: :class:`google.cloud.storage.batch.Batch`
        :returns: The batch object created.
        )r/   r   r2   r,   r,   r-   r6     s    
zClient.batchc                 C   s    |  |}|j| |||d |S )a  API call: retrieve a bucket via a GET request.

        See
        https://cloud.google.com/storage/docs/json_api/v1/buckets/get

        Args:
            bucket_or_name (Union[                 :class:`~google.cloud.storage.bucket.Bucket`,                  str,             ]):
                The bucket resource to pass or name to create.

            timeout (Optional[Union[float, Tuple[float, float]]]):
                The amount of time, in seconds, to wait for the server response.

                Can also be passed as a tuple (connect_timeout, read_timeout).
                See :meth:`requests.Session.request` documentation for details.

            if_metageneration_match (Optional[long]):
                Make the operation conditional on whether the
                blob's current metageneration matches the given value.

            if_metageneration_not_match (Optional[long]):
                Make the operation conditional on whether the blob's
                current metageneration does not match the given value.

        Returns:
            google.cloud.storage.bucket.Bucket
                The bucket matching the name provided.

        Raises:
            google.cloud.exceptions.NotFound
                If the bucket is not found.

        Examples:
            Retrieve a bucket using a string.

            .. literalinclude:: snippets.py
                :start-after: [START get_bucket]
                :end-before: [END get_bucket]
                :dedent: 4

            Get a bucket using a resource.

            >>> from google.cloud import storage
            >>> client = storage.Client()

            >>> # Set properties on a plain resource object.
            >>> bucket = client.get_bucket("my-bucket-name")

            >>> # Time passes. Another program may have modified the bucket
            ... # in the meantime, so you want to get the latest state.
            >>> bucket = client.get_bucket(bucket)  # API request.

        )r/   rB   if_metageneration_matchif_metageneration_not_match)r>   reload)r)   r<   rB   rH   rI   r=   r,   r,   r-   
get_bucket%  s    >
zClient.get_bucketc                 C   s.   z| j ||||dW S  ty(   Y dS 0 dS )aC  Get a bucket by name, returning None if not found.

        You can use this if you would rather check for a None value
        than catching an exception:

        .. literalinclude:: snippets.py
            :start-after: [START lookup_bucket]
            :end-before: [END lookup_bucket]
            :dedent: 4

        :type bucket_name: str
        :param bucket_name: The name of the bucket to get.

        :type timeout: float or tuple
        :param timeout: (Optional) The amount of time, in seconds, to wait
            for the server response.

            Can also be passed as a tuple (connect_timeout, read_timeout).
            See :meth:`requests.Session.request` documentation for details.

        :type if_metageneration_match: long
        :param if_metageneration_match: (Optional) Make the operation conditional on whether the
                                        blob's current metageneration matches the given value.

        :type if_metageneration_not_match: long
        :param if_metageneration_not_match: (Optional) Make the operation conditional on whether the
                                            blob's current metageneration does not match the given value.

        :rtype: :class:`google.cloud.storage.bucket.Bucket`
        :returns: The bucket matching the name provided or None if not found.
        )rB   rH   rI   N)rK   r   )r)   rG   rB   rH   rI   r,   r,   r-   lookup_bucketl  s    &zClient.lookup_bucketc	                    s   |  | |du r| j}|du r(td|durFtjdtdd | _d|i}	|durht|}||	d< |durt	|}||	d< |dur||	d	<  fd
d j
D }
 j|
d< |dur||
d< | jjdd|	|
 |d} |  S )a
  API call: create a new bucket via a POST request.

        See
        https://cloud.google.com/storage/docs/json_api/v1/buckets/insert

        Args:
            bucket_or_name (Union[                 :class:`~google.cloud.storage.bucket.Bucket`,                  str,             ]):
                The bucket resource to pass or name to create.
            requester_pays (bool):
                DEPRECATED. Use Bucket().requester_pays instead.
                (Optional) Whether requester pays for API requests for
                this bucket and its blobs.
            project (str):
                (Optional) The project under which the bucket is to be created.
                If not passed, uses the project set on the client.
            user_project (str):
                (Optional) The project ID to be billed for API requests
                made via created bucket.
            location (str):
                (Optional) The location of the bucket. If not passed,
                the default location, US, will be used. See
                https://cloud.google.com/storage/docs/bucket-locations
            predefined_acl (str):
                (Optional) Name of predefined ACL to apply to bucket. See:
                https://cloud.google.com/storage/docs/access-control/lists#predefined-acl
            predefined_default_object_acl (str):
                (Optional) Name of predefined ACL to apply to bucket's objects. See:
                https://cloud.google.com/storage/docs/access-control/lists#predefined-acl
            timeout (Optional[Union[float, Tuple[float, float]]]):
                The amount of time, in seconds, to wait for the server response.

                Can also be passed as a tuple (connect_timeout, read_timeout).
                See :meth:`requests.Session.request` documentation for details.

        Returns:
            google.cloud.storage.bucket.Bucket
                The newly created bucket.

        Raises:
            google.cloud.exceptions.Conflict
                If the bucket already exists.

        Examples:
            Create a bucket using a string.

            .. literalinclude:: snippets.py
                :start-after: [START create_bucket]
                :end-before: [END create_bucket]
                :dedent: 4

            Create a bucket using a resource.

            >>> from google.cloud import storage
            >>> client = storage.Client()

            >>> # Set properties on a plain resource object.
            >>> bucket = storage.Bucket("my-bucket-name")
            >>> bucket.location = "europe-west6"
            >>> bucket.storage_class = "COLDLINE"

            >>> # Pass that resource object to the client.
            >>> bucket = client.create_bucket(bucket)  # API request.

        N2Client project not set:  pass an explicit project.zFrequester_pays arg is deprecated. Use Bucket().requester_pays instead.   )
stacklevelr   ZpredefinedAclZpredefinedDefaultObjectAcluserProjectc                    s   i | ]}| j | qS r,   )_properties).0keyr=   r,   r-   
<dictcomp>	      z(Client.create_bucket.<locals>.<dictcomp>r:   locationPOST/b)r@   rA   query_paramsdataZ_target_objectrB   )r>   r   r3   warningswarnPendingDeprecationWarningrequester_paysr   Zvalidate_predefinedr   Z_changesr:   r'   rC   _set_properties)r)   r<   r_   r   rF   rW   Zpredefined_aclZpredefined_default_object_aclrB   rZ   Z
propertiesrD   r,   rT   r-   create_bucket  sJ    N


	
zClient.create_bucketc              	   C   sJ   z|j || ||d W n. tyD   t|}|j || ||d Y n0 dS )a  Download the contents of a blob object or blob URI into a file-like object.

        Args:
            blob_or_uri (Union[             :class:`~google.cloud.storage.blob.Blob`,              str,             ]):
                The blob resource to pass or URI to download.
            file_obj (file):
                A file handle to which to write the blob's data.
            start (int):
                (Optional) The first byte in a range to be downloaded.
            end (int):
                (Optional) The last byte in a range to be downloaded.

        Examples:
            Download a blob using a blob resource.

            >>> from google.cloud import storage
            >>> client = storage.Client()

            >>> bucket = client.get_bucket('my-bucket-name')
            >>> blob = storage.Blob('path/to/blob', bucket)

            >>> with open('file-to-download-to') as file_obj:
            >>>     client.download_blob_to_file(blob, file_obj)  # API request.


            Download a blob using a URI.

            >>> from google.cloud import storage
            >>> client = storage.Client()

            >>> with open('file-to-download-to') as file_obj:
            >>>     client.download_blob_to_file(
            >>>         'gs://bucket_name/path/to/blob', file_obj)


        )r/   startendN)Zdownload_to_fileAttributeErrorr   Zfrom_string)r)   Zblob_or_uriZfile_objrb   rc   Zblobr,   r,   r-   download_blob_to_file  s
    (
zClient.download_blob_to_fileZnoAclc                 C   s,   |  |}|j||||||||	|
|| |dS )a  Return an iterator used to find blobs in the bucket.

        If :attr:`user_project` is set, bills the API request to that project.

        Args:
            bucket_or_name (Union[                 :class:`~google.cloud.storage.bucket.Bucket`,                  str,             ]):
                The bucket resource to pass or name to create.

            max_results (int):
                (Optional) The maximum number of blobs to return.

            page_token (str):
                (Optional) If present, return the next batch of blobs, using the
                value, which must correspond to the ``nextPageToken`` value
                returned in the previous response.  Deprecated: use the ``pages``
                property of the returned iterator instead of manually passing the
                token.

            prefix (str):
                (Optional) Prefix used to filter blobs.

            delimiter (str):
                (Optional) Delimiter, used with ``prefix`` to
                emulate hierarchy.

            start_offset (str):
                (Optional) Filter results to objects whose names are
                lexicographically equal to or after ``startOffset``. If
                ``endOffset`` is also set, the objects listed will have names
                between ``startOffset`` (inclusive) and ``endOffset``
                (exclusive).

            end_offset (str):
                (Optional) Filter results to objects whose names are
                lexicographically before ``endOffset``. If ``startOffset`` is
                also set, the objects listed will have names between
                ``startOffset`` (inclusive) and ``endOffset`` (exclusive).

            include_trailing_delimiter (boolean):
                (Optional) If true, objects that end in exactly one instance of
                ``delimiter`` will have their metadata included in ``items`` in
                addition to ``prefixes``.

            versions (bool):
                (Optional) Whether object versions should be returned
                as separate blobs.

            projection (str):
                (Optional) If used, must be 'full' or 'noAcl'.
                Defaults to ``'noAcl'``. Specifies the set of
                properties to return.

            fields (str):
                (Optional) Selector specifying which fields to include
                in a partial response. Must be a list of fields. For
                example to get a partial response with just the next
                page token and the name and language of each blob returned:
                ``'items(name,contentLanguage),nextPageToken'``.
                See: https://cloud.google.com/storage/docs/json_api/v1/parameters#fields

            timeout (Optional[Union[float, Tuple[float, float]]]):
                The amount of time, in seconds, to wait for the server response.

                Can also be passed as a tuple (connect_timeout, read_timeout).
                See :meth:`requests.Session.request` documentation for details.

        Returns:
            Iterator of all :class:`~google.cloud.storage.blob.Blob`
            in this bucket matching the arguments.

        Example:
            List blobs in the bucket with user_project.

            >>> from google.cloud import storage
            >>> client = storage.Client()

            >>> bucket = storage.Bucket("my-bucket-name", user_project='my-project')
            >>> all_blobs = list(client.list_blobs(bucket))
        )max_results
page_tokenprefix	delimiterstart_offset
end_offsetinclude_trailing_delimiterversions
projectionfieldsr/   rB   )r>   
list_blobs)r)   r<   rf   rg   rh   ri   rj   rk   rl   rm   rn   ro   rB   r=   r,   r,   r-   rp   I  s    a
zClient.list_blobsc           
   	   C   sx   |du r| j }|du rtdd|i}|dur6||d< ||d< |durN||d< tj| jj|d}	tj| |	dt|||d	S )
a	  Get all buckets in the project associated to the client.

        This will not populate the list of blobs available in each
        bucket.

        .. literalinclude:: snippets.py
            :start-after: [START list_buckets]
            :end-before: [END list_buckets]
            :dedent: 4

        This implements "storage.buckets.list".

        :type max_results: int
        :param max_results: (Optional) The maximum number of buckets to return.

        :type page_token: str
        :param page_token:
            (Optional) If present, return the next batch of buckets, using the
            value, which must correspond to the ``nextPageToken`` value
            returned in the previous response.  Deprecated: use the ``pages``
            property of the returned iterator instead of manually passing the
            token.

        :type prefix: str
        :param prefix: (Optional) Filter results to buckets whose names begin
                       with this prefix.

        :type projection: str
        :param projection:
            (Optional) Specifies the set of properties to return. If used, must
            be 'full' or 'noAcl'. Defaults to 'noAcl'.

        :type fields: str
        :param fields:
            (Optional) Selector specifying which fields to include in a partial
            response. Must be a list of fields. For example to get a partial
            response with just the next page token and the language of each
            bucket returned: 'items/id,nextPageToken'

        :type project: str
        :param project: (Optional) The project whose buckets are to be listed.
                        If not passed, uses the project set on the client.

        :type timeout: float or tuple
        :param timeout: (Optional) The amount of time, in seconds, to wait
            for the server response.

            Can also be passed as a tuple (connect_timeout, read_timeout).
            See :meth:`requests.Session.request` documentation for details.

        :rtype: :class:`~google.api_core.page_iterator.Iterator`
        :raises ValueError: if both ``project`` is ``None`` and the client's
                            project is also ``None``.
        :returns: Iterator of all :class:`~google.cloud.storage.bucket.Bucket`
                  belonging to this project.
        NrM   r   rh   rn   ro   rB   rY   )r/   rC   rA   item_to_valuerg   rf   extra_params)	r   r3   	functoolspartialr'   rC   r   HTTPIterator_item_to_bucket)
r)   rf   rg   rh   rn   ro   r   rB   rs   rC   r,   r,   r-   list_buckets  s(    BzClient.list_bucketsc           
      C   sf   |du r| j }d|}d|i}|dur0||d< | jjd|||d}t| }|d |_|d }	||	fS )	a  Create an HMAC key for a service account.

        :type service_account_email: str
        :param service_account_email: e-mail address of the service account

        :type project_id: str
        :param project_id: (Optional) Explicit project ID for the key.
            Defaults to the client's project.

        :type user_project: str
        :param user_project: (Optional) This parameter is currently ignored.

        :type timeout: float or tuple
        :param timeout: (Optional) The amount of time, in seconds, to wait
            for the server response.

            Can also be passed as a tuple (connect_timeout, read_timeout).
            See :meth:`requests.Session.request` documentation for details.

        :rtype:
            Tuple[:class:`~google.cloud.storage.hmac_key.HMACKeyMetadata`, str]
        :returns: metadata for the created key, plus the bytes of the key's secret, which is an 40-character base64-encoded string.
        N/projects/{}/hmacKeysserviceAccountEmailrP   rX   )r@   rA   rZ   rB   metadatasecret)r   formatr'   rC   r   rQ   )
r)   service_account_email
project_idrF   rB   rA   Z	qs_paramsrD   r{   r|   r,   r,   r-   create_hmac_key  s    

zClient.create_hmac_keyc           
      C   st   |du r| j }d|}i }|dur,||d< |dur<||d< |durL||d< tj| jj|d}	tj| |	|t||dS )a	  List HMAC keys for a project.

        :type max_results: int
        :param max_results:
            (Optional) Max number of keys to return in a given page.

        :type service_account_email: str
        :param service_account_email:
            (Optional) Limit keys to those created by the given service account.

        :type show_deleted_keys: bool
        :param show_deleted_keys:
            (Optional) Included deleted keys in the list. Default is to
            exclude them.

        :type project_id: str
        :param project_id: (Optional) Explicit project ID for the key.
            Defaults to the client's project.

        :type user_project: str
        :param user_project: (Optional) This parameter is currently ignored.

        :type timeout: float or tuple
        :param timeout: (Optional) The amount of time, in seconds, to wait
            for the server response.

            Can also be passed as a tuple (connect_timeout, read_timeout).
            See :meth:`requests.Session.request` documentation for details.

        :rtype:
            Tuple[:class:`~google.cloud.storage.hmac_key.HMACKeyMetadata`, str]
        :returns: metadata for the created key, plus the bytes of the key's secret, which is an 40-character base64-encoded string.
        Nry   rz   ZshowDeletedKeysrP   rq   )r/   rC   rA   rr   rf   rs   )	r   r}   rt   ru   r'   rC   r   rv   _item_to_hmac_key_metadata)
r)   rf   r~   Zshow_deleted_keysr   rF   rB   rA   rs   rC   r,   r,   r-   list_hmac_keysG  s&    *
zClient.list_hmac_keysc                 C   s   t | |||}|j|d |S )a  Return a metadata instance for the given HMAC key.

        :type access_id: str
        :param access_id: Unique ID of an existing key.

        :type project_id: str
        :param project_id: (Optional) Project ID of an existing key.
            Defaults to client's project.

        :type timeout: float or tuple
        :param timeout: (Optional) The amount of time, in seconds, to wait
            for the server response.

            Can also be passed as a tuple (connect_timeout, read_timeout).
            See :meth:`requests.Session.request` documentation for details.

        :type user_project: str
        :param user_project: (Optional) This parameter is currently ignored.
        rq   )r   rJ   )r)   Z	access_idr   rF   rB   r{   r,   r,   r-   get_hmac_key_metadata  s    zClient.get_hmac_key_metadataFhttpc              	   C   s  |du r| j n|}t| t \}}dj|j|d}d|id|id|id|idd	ig}|p\g }i }t|pji  D ](\}}|d
sr|||< |||i qr||7 }t	 }|du r|t
jdd }|t
jt|d }tjtt|| d d dd}t|d}|r4|
r4t|||
}t|}n
||}t|d}||d	||||d |rxd|}n|rt||	}n
d|}||dS )a  Generate a V4 signed policy object.

        .. note::

            Assumes ``credentials`` implements the
            :class:`google.auth.credentials.Signing` interface. Also assumes
            ``credentials`` has a ``service_account_email`` property which
            identifies the credentials.

        Generated policy object allows user to upload objects with a POST request.

        :type bucket_name: str
        :param bucket_name: Bucket name.

        :type blob_name: str
        :param blob_name: Object name.

        :type expiration: Union[Integer, datetime.datetime, datetime.timedelta]
        :param expiration: Policy expiration time.

        :type conditions: list
        :param conditions: (Optional) List of POST policy conditions, which are
                           used to restrict what is allowed in the request.

        :type fields: dict
        :param fields: (Optional) Additional elements to include into request.

        :type credentials: :class:`google.auth.credentials.Signing`
        :param credentials: (Optional) Credentials object with an associated private
                            key to sign text.

        :type virtual_hosted_style: bool
        :param virtual_hosted_style: (Optional) If True, construct the URL relative to the bucket
                                     virtual hostname, e.g., '<bucket-name>.storage.googleapis.com'.

        :type bucket_bound_hostname: str
        :param bucket_bound_hostname:
            (Optional) If passed, construct the URL relative to the bucket-bound hostname.
            Value can be bare or with a scheme, e.g., 'example.com' or 'http://example.com'.
            See: https://cloud.google.com/storage/docs/request-endpoints#cname

        :type scheme: str
        :param scheme:
            (Optional) If ``bucket_bound_hostname`` is passed as a bare hostname, use
            this value as a scheme. ``https`` will work only when using a CDN.
            Defaults to ``"http"``.

        :type service_account_email: str
        :param service_account_email: (Optional) E-mail address of the service account.

        :type access_token: str
        :param access_token: (Optional) Access token for a service account.

        :rtype: dict
        :returns: Signed POST policy.

        Example:
            Generate signed POST policy and upload a file.

            >>> from google.cloud import storage
            >>> client = storage.Client()
            >>> policy = client.generate_signed_post_policy_v4(
                "bucket-name",
                "blob-name",
                expiration=datetime.datetime(2020, 3, 17),
                conditions=[
                    ["content-length-range", 0, 255]
                ],
                fields=[
                    "x-goog-meta-hello" => "world"
                ],
            )
            >>> with open("bucket-name", "rb") as f:
                files = {"file": ("bucket-name", f)}
                requests.post(policy["url"], data=policy["fields"], files=files)
        Nz.{email}/{datestamp}/auto/storage/goog4_request)Zemail	datestampr=   rS   x-goog-datex-goog-credentialx-goog-algorithmzGOOG4-RSA-SHA256z	x-ignore-rN   )Zhours)ZsecondsZ)
conditions
expiration),:)Z
separatorszutf-8)rS   r   r   r   zx-goog-signaturepolicyz"https://{}.storage.googleapis.com/z"https://storage.googleapis.com/{}/)urlro   )Z_credentialsr   r   r}   Zsigner_emailsorteditems
startswithappendr   datetimeZ	timedeltar   jsondumpscollectionsOrderedDictZ	isoformatbase64Z	b64encodeencoder   Z	b64decodeZ
sign_bytesbinasciiZhexlifydecodeupdater	   )r)   rG   Z	blob_namer   r   ro   r   Zvirtual_hosted_styleZbucket_bound_hostnameschemer~   Zaccess_tokenZ	timestampr   Zx_goog_credentialZrequired_conditionsZpolicy_fieldsrS   r4   ZnowZpolicy_expiresr   Zstr_to_signZ	signatureZsignature_bytesr   r,   r,   r-   generate_signed_post_policy_v4  sp    Z




z%Client.generate_signed_post_policy_v4)N)NN)NNNFNr   NN)__name__
__module____qualname____doc__ZSCOPEr!   r#   classmethodr0   propertyr'   setterr7   r9   r>   r1   r   rE   r=   r6   rK   rL   ra   re   rp   rx   r   r   r   r   __classcell__r,   r,   r*   r-   r   5   s   "	-




	

J
3

1
s
a
1
E
        r   c                 C   s$   | d}t| j|}|| |S )aJ  Convert a JSON bucket to the native object.

    :type iterator: :class:`~google.api_core.page_iterator.Iterator`
    :param iterator: The iterator that has retrieved the item.

    :type item: dict
    :param item: An item to be converted to a bucket.

    :rtype: :class:`.Bucket`
    :returns: The next bucket in the page.
    r:   )getr   r/   r`   )iteratoritemr:   r=   r,   r,   r-   rw   O  s    

rw   c                 C   s   t | j}||_|S )a  Convert a JSON key metadata resource to the native object.

    :type iterator: :class:`~google.api_core.page_iterator.Iterator`
    :param iterator: The iterator that has retrieved the item.

    :type item: dict
    :param item: An item to be converted to a key metadata instance.

    :rtype: :class:`~google.cloud.storage.hmac_key.HMACKeyMetadata`
    :returns: The next key metadata instance in the page.
    )r   r/   rQ   )r   r   r{   r,   r,   r-   r   a  s    
r   )1r   r   r   r   r   rt   r   r\   Zgoogle.api_core.client_optionsr&   Zgoogle.auth.credentialsr   Zgoogle.api_corer   Zgoogle.cloud._helpersr   r   Zgoogle.cloud.clientr   Zgoogle.cloud.exceptionsr   Zgoogle.cloud.storage._helpersr   r	   Zgoogle.cloud.storage._httpr
   Zgoogle.cloud.storage._signingr   r   r   r   Zgoogle.cloud.storage.batchr   Zgoogle.cloud.storage.bucketr   Zgoogle.cloud.storage.blobr   Zgoogle.cloud.storage.hmac_keyr   Zgoogle.cloud.storage.aclr   r   Zgoogle.cloud.storage.constantsr   objectr!   r   rw   r   r,   r,   r,   r-   <module>   sH           "