o
    )=jq\  ã                   @   s~  d Z ddlZddlZddlm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 ddlmZ ddlmZ dd	lmZ dd
lmZ dZ	 dZ	 dZ	 dZdZejed�ZdZe ed¡Z	 dZdZejj Z!ej"j#Z$dd„ Z%dd„ Z&dd„ Z'd:dd„Z(dd„ Z)d d!„ Z*G d"d#„ d#e+ƒZ,d$d%„ Z-d;d'd(„Z.d)d*„ Z/d+d,„ Z0d-d.„ Z1d/d0„ Z2d<d1d2„Z3d3d4„ Z4	5		d=d6d7„Z5d8d9„ Z6dS )>zVHelper functions for Cloud Storage utility classes.

These are *not* part of the API.
é    N)Úmd5)Úurlsplit)Ú
urlunsplit)Úuuid4)Úenvironment_vars)Ú_DEFAULT_TIMEOUT)ÚDEFAULT_RETRY)Ú)DEFAULT_RETRY_IF_METAGENERATION_SPECIFIEDZSTORAGE_EMULATOR_HOSTZAPI_ENDPOINT_OVERRIDEZAPI_VERSION_OVERRIDEzgoogleapis.comzstorage.{universe_domain})Zuniverse_domainzhttps://Zv1))Úif_etag_matchzIf-Match)Úif_etag_not_matchzIf-None-Match))Úif_generation_matchZifGenerationMatch)Úif_generation_not_matchZifGenerationNotMatch)Úif_metageneration_matchZifMetagenerationMatch)Úif_metageneration_not_matchZifMetagenerationNotMatch)Zif_source_generation_matchZifSourceGenerationMatch)Zif_source_generation_not_matchZifSourceGenerationNotMatch)Zif_source_metageneration_matchZifSourceMetagenerationMatch)Z"if_source_metageneration_not_matchZifSourceMetagenerationNotMatchc                   C   s   t j td ¡S ©N)ÚosÚenvironÚgetÚSTORAGE_EMULATOR_ENV_VAR© r   r   úgC:\Users\psant\Downloads\Anu Raj Backend\school\venv\Lib\site-packages\google/cloud/storage/_helpers.pyÚ_get_storage_emulator_overrideS   ó   r   c                   C   s   t  ttt ¡S r   )r   ÚgetenvÚ_API_ENDPOINT_OVERRIDE_ENV_VARÚ_DEFAULT_SCHEMEÚ_TRUE_DEFAULT_STORAGE_HOSTr   r   r   r   Ú_get_default_storage_base_urlW   s   ÿr   c                   C   s   t ƒ tt kr
t ƒ S dS )zIThis is an experimental configuration variable. Use api_endpoint instead.N)r   r   r   r   r   r   r   Ú_get_api_endpoint_override]   s   r   Fc                 C   s8   t | ƒ}|› d|j› �}t|j||rdndddfƒ}|S )z²Returns the scheme and netloc sections of the url, with the bucket
    prepended to the netloc.

    Not intended for use with netlocs which include a username and password.
    Ú.ú/Ú N)r   Únetlocr   Úscheme)ÚurlZbucketZtrailing_slashÚ
parsed_urlZ
new_netlocÚbase_urlr   r   r   Ú_virtual_hosted_style_base_urld   s   ÿr'   c                   C   s   t  tjt  tj¡¡S r   )r   r   r   ZPROJECTZLEGACY_PROJECTr   r   r   r   Ú_get_environ_projectr   s   
þr(   c                 C   s4   | du rdS t | d  ¡ | d  ¡ gƒstdƒ‚| S )zÁPre-flight ``Bucket`` name validation.

    :type name: str or :data:`NoneType`
    :param name: Proposed bucket name.

    :rtype: str or :data:`NoneType`
    :returns: ``name`` if valid.
    Nr   éÿÿÿÿz8Bucket names must start and end with a number or letter.)ÚallÚisalnumÚ
ValueError)Únamer   r   r   Ú_validate_namey   s
   	r.   c                   @   s¾   e Zd ZdZddd„Zedd„ ƒZedd„ ƒZed	d
„ ƒZdd„ Z	dd„ Z
edd„ ƒZddddddddeedfdd„Zdd„ Zdd„ Zdddddeedfdd„Zdddddeedfdd„ZdS )Ú_PropertyMixina1  Abstract mixin for cloud storage classes with associated properties.

    Non-abstract subclasses should implement:
      - path
      - client
      - user_project

    :type name: str
    :param name: The name of the object. Bucket names must start and end with a
                 number or letter.
    Nc                 C   s   || _ i | _tƒ | _d S r   )r-   Ú_propertiesÚsetÚ_changes)Úselfr-   r   r   r   Ú__init__˜   s   z_PropertyMixin.__init__c                 C   ó   t ‚)z$Abstract getter for the object path.N©ÚNotImplementedError©r3   r   r   r   Úpath�   ó   z_PropertyMixin.pathc                 C   r5   )z&Abstract getter for the object client.Nr6   r8   r   r   r   Úclient¢   r:   z_PropertyMixin.clientc                 C   r5   )z,Abstract getter for the object user_project.Nr6   r8   r   r   r   Úuser_project§   r:   z_PropertyMixin.user_projectc                 C   s   |du r| j }|S )a£  Check client or verify over-ride.

        :type client: :class:`~google.cloud.storage.client.Client` or
                      ``NoneType``
        :param client: the client to use.  If not passed, falls back to the
                       ``client`` stored on the current object.

        :rtype: :class:`google.cloud.storage.client.Client`
        :returns: The client passed in or the currently bound client.
        N)r;   )r3   r;   r   r   r   Ú_require_client¬   s   z_PropertyMixin._require_clientc                 C   s   i S )a@  Return any encryption headers needed to fetch the object.

        .. note::
           Defined here because :meth:`reload` calls it, but this method is
           really only relevant for :class:`~google.cloud.storage.blob.Blob`.

        :rtype: dict
        :returns: a mapping of encryption-related headers.
        Nr   r8   r   r   r   Ú_encryption_headers»   s   
z"_PropertyMixin._encryption_headersc                 C   s   i }| j dur| j |d< |S )zDefault query parameters.NZuserProject)r<   )r3   Úparamsr   r   r   Ú_query_paramsÇ   s   

z_PropertyMixin._query_paramsZnoAclc                 C   s€   |   |¡}| j}||d< t|||||d� |dur"||d< | j|d< |  ¡ }t|||d� |j| j|||	|
| d�}|  |¡ dS )aÊ  Reload properties from Cloud Storage.

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

        :type client: :class:`~google.cloud.storage.client.Client` or
                      ``NoneType``
        :param client: the client to use. If not passed, falls back to the
                       ``client`` stored on the current object.

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

        :type if_etag_match: Union[str, Set[str]]
        :param if_etag_match: (Optional) See :ref:`using-if-etag-match`

        :type if_etag_not_match: Union[str, Set[str]])
        :param if_etag_not_match: (Optional) See :ref:`using-if-etag-not-match`

        :type if_generation_match: long
        :param if_generation_match:
            (Optional) See :ref:`using-if-generation-match`

        :type if_generation_not_match: long
        :param if_generation_not_match:
            (Optional) See :ref:`using-if-generation-not-match`

        :type if_metageneration_match: long
        :param if_metageneration_match:
            (Optional) See :ref:`using-if-metageneration-match`

        :type if_metageneration_not_match: long
        :param if_metageneration_not_match:
            (Optional) See :ref:`using-if-metageneration-not-match`

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

        :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy
        :param retry:
            (Optional) How to retry the RPC. See: :ref:`configuring_retries`

        :type soft_deleted: bool
        :param soft_deleted:
            (Optional) If True, looks for a soft-deleted object. Will only return
            the object metadata if the object exists and is in a soft-deleted state.
            :attr:`generation` is required to be set on the blob if ``soft_deleted`` is set to True.
            See: https://cloud.google.com/storage/docs/soft-delete
        Ú
projection©r   r   r   r   NZsoftDeletedÚ
generation)r
   r   )Úquery_paramsÚheadersÚtimeoutÚretryÚ_target_object)	r=   r@   Ú _add_generation_match_parametersrC   r>   Ú_add_etag_match_headersZ_get_resourcer9   Ú_set_properties)r3   r;   rA   r
   r   r   r   r   r   rF   rG   Zsoft_deletedrD   rE   Úapi_responser   r   r   ÚreloadÏ   s4   
Bû
ÿúz_PropertyMixin.reloadc                 C   s   | j  |¡ || j|< dS )aµ  Update field of this object's properties.

        This method will only update the field provided and will not
        touch the other fields.

        It **will not** reload the properties from the server. The behavior is
        local only and syncing occurs via :meth:`patch`.

        :type name: str
        :param name: The field name to update.

        :type value: object
        :param value: The value being updated.
        N)r2   Úaddr0   )r3   r-   Úvaluer   r   r   Ú_patch_property0  s   z_PropertyMixin._patch_propertyc                 C   s   || _ tƒ | _dS )z±Set the properties for the current object.

        :type value: dict or :class:`google.cloud.storage.batch._FutureDict`
        :param value: The properties to be set.
        N)r0   r1   r2   ©r3   rO   r   r   r   rK   B  s   z_PropertyMixin._set_propertiesFc	                    sp   ˆ   |¡}ˆ j}	d|	d< |r||	d< t|	||||d� ‡ fdd„ˆ jD ƒ}
|jˆ j|
|	ˆ ||d�}ˆ  |¡ dS )	aj  Sends all changed properties in a PATCH request.

        Updates the ``_properties`` with the response from the backend.

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

        :type client: :class:`~google.cloud.storage.client.Client` or
                      ``NoneType``
        :param client: the client to use. If not passed, falls back to the
                       ``client`` stored on the current object.

        :type if_generation_match: long
        :param if_generation_match:
            (Optional) See :ref:`using-if-generation-match`

        :type if_generation_not_match: long
        :param if_generation_not_match:
            (Optional) See :ref:`using-if-generation-not-match`

        :type if_metageneration_match: long
        :param if_metageneration_match:
            (Optional) See :ref:`using-if-metageneration-match`

        :type if_metageneration_not_match: long
        :param if_metageneration_not_match:
            (Optional) See :ref:`using-if-metageneration-not-match`

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

        :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy
        :param retry:
            (Optional) How to retry the RPC. See: :ref:`configuring_retries`

        :type override_unlocked_retention: bool
        :param override_unlocked_retention:
            (Optional) override_unlocked_retention must be set to True if the operation includes
            a retention property that changes the mode from Unlocked to Locked, reduces the
            retainUntilTime, or removes the retention configuration from the object. See:
            https://cloud.google.com/storage/docs/json_api/v1/objects/patch
        ÚfullrA   ÚoverrideUnlockedRetentionrB   c                    s   i | ]}|ˆ j | “qS r   )r0   )Ú.0Úkeyr8   r   r   Ú
<dictcomp>�  ó    z(_PropertyMixin.patch.<locals>.<dictcomp>)rD   rH   rF   rG   N)r=   r@   rI   r2   Z_patch_resourcer9   rK   )r3   r;   r   r   r   r   rF   rG   Úoverride_unlocked_retentionrD   Zupdate_propertiesrL   r   r8   r   ÚpatchL  s,   
6ûúz_PropertyMixin.patchc	                 C   s^   |   |¡}| j}	d|	d< |r||	d< t|	||||d� |j| j| j|	||| d�}
|  |
¡ dS )a`  Sends all properties in a PUT request.

        Updates the ``_properties`` with the response from the backend.

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

        :type client: :class:`~google.cloud.storage.client.Client` or
                      ``NoneType``
        :param client: the client to use. If not passed, falls back to the
                       ``client`` stored on the current object.

        :type if_generation_match: long
        :param if_generation_match:
            (Optional) See :ref:`using-if-generation-match`

        :type if_generation_not_match: long
        :param if_generation_not_match:
            (Optional) See :ref:`using-if-generation-not-match`

        :type if_metageneration_match: long
        :param if_metageneration_match:
            (Optional) See :ref:`using-if-metageneration-match`

        :type if_metageneration_not_match: long
        :param if_metageneration_not_match:
            (Optional) See :ref:`using-if-metageneration-not-match`

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

        :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy
        :param retry:
            (Optional) How to retry the RPC. See: :ref:`configuring_retries`

        :type override_unlocked_retention: bool
        :param override_unlocked_retention:
            (Optional) override_unlocked_retention must be set to True if the operation includes
            a retention property that changes the mode from Unlocked to Locked, reduces the
            retainUntilTime, or removes the retention configuration from the object. See:
            https://cloud.google.com/storage/docs/json_api/v1/objects/patch
        rR   rA   rS   rB   )rD   rF   rG   rH   N)r=   r@   rI   Z_put_resourcer9   r0   rK   )r3   r;   r   r   r   r   rF   rG   rX   rD   rL   r   r   r   Úupdate�  s*   
6ûúz_PropertyMixin.updater   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r4   Úpropertyr9   r;   r<   r=   r>   r@   r   r   rM   rP   rK   rY   r	   rZ   r   r   r   r   r/   ‹   sZ    




	
ôa
÷S÷r/   c                    s"   ‡ fdd„}‡ fdd„}t ||ƒS )zHCreate a property descriptor around the :class:`_PropertyMixin` helpers.c                    s   | j  ˆ ¡S )zScalar property getter.N)r0   r   r8   ©Ú	fieldnamer   r   Ú_getterï  s   z!_scalar_property.<locals>._getterc                    s   |   ˆ |¡ dS )zScalar property setter.N)rP   rQ   r`   r   r   Ú_setteró  s   z!_scalar_property.<locals>._setterN)r_   )ra   rb   rc   r   r`   r   Ú_scalar_propertyì  s   
rd   é    c                 C   s>   |   |¡}t|ƒdkr| |¡ |   |¡}t|ƒdksdS dS )a¯  Read blocks from a buffer and update a hash with them.

    :type buffer_object: bytes buffer
    :param buffer_object: Buffer containing bytes used to update a hash object.

    :type hash_obj: object that implements update
    :param hash_obj: A hash object (MD5 or CRC32-C).

    :type digest_block_size: int
    :param digest_block_size: The block size to write to the hash.
                              Defaults to 8192.
    r   N)ÚreadÚlenrZ   )Úbuffer_objectÚhash_objZdigest_block_sizeÚblockr   r   r   Ú_write_buffer_to_hashú  s
   


ýrk   c                 C   s8   t jdkrtdd�}ntƒ }t| |ƒ | ¡ }t |¡S )a  Get MD5 hash of bytes (as base64).

    :type buffer_object: bytes buffer
    :param buffer_object: Buffer containing bytes used to compute an MD5
                          hash (as base64).

    :rtype: str
    :returns: A base64 encoded digest of the MD5 hash.
    )é   é	   F)ÚusedforsecurityN)ÚsysÚversion_infor   rk   ÚdigestÚbase64Ú	b64encode)rh   ri   Zdigest_bytesr   r   r   Ú_base64_md5hash  s   



rt   c                 K   sB   t D ]\}}| |¡}|durt|tƒr|g}d |¡| |< qdS )zßAdd generation match parameters into the given parameters list.

    :type headers: dict
    :param headers: Headers dict.

    :type match_parameters: dict
    :param match_parameters: if*etag*match parameters to add.
    Nú, )Ú_ETAG_MATCH_PARAMETERSr   Ú
isinstanceÚstrÚjoin)rE   Úmatch_parametersÚsnakecase_nameÚheader_namerO   r   r   r   rJ   "  s   	

€úrJ   c                 K   sZ   t D ](\}}| |¡}|dur*t| tƒr|  ||f¡ qt| tƒr&|| |< qtdƒ‚qdS )ab  Add generation match parameters into the given parameters list.

    :type parameters: list or dict
    :param parameters: Parameters list or dict.

    :type match_parameters: dict
    :param match_parameters: if*generation*match parameters to add.

    :raises: :exc:`ValueError` if ``parameters`` is not a ``list()``
             or a ``dict()``.
    Nz5`parameters` argument should be a dict() or a list().)Ú_GENERATION_MATCH_PARAMETERSr   rw   ÚlistÚappendÚdictr,   )Ú
parametersrz   r{   Zcamelcase_namerO   r   r   r   rI   4  s   



ÿøýrI   c                  K   sb   t dd„ |  ¡ D ƒƒdkr/dd„ |  ¡ D ƒ}d |dd… ¡}|d }d	|› d
|› �}t|ƒ‚dS )zéRaise ``ValueError`` exception if more than one parameter was set.

    :type error: :exc:`ValueError`
    :param error: Description of which fields were set

    :raises: :class:`~ValueError` containing the fields that were set
    c                 s   s   � | ]}|d uV  qd S r   r   )rT   Úargr   r   r   Ú	<genexpr>X  s   € z._raise_if_more_than_one_set.<locals>.<genexpr>é   c                 S   s   g | ]}d |› d �‘qS )ú'r   )rT   r-   r   r   r   Ú
<listcomp>Y  rW   z/_raise_if_more_than_one_set.<locals>.<listcomp>ru   Nr)   zPass at most one of z and )ÚsumÚvaluesÚkeysry   r,   )ÚkwargsZescaped_keysZkeys_but_lastÚlast_keyÚmsgr   r   r   Ú_raise_if_more_than_one_setP  s   ør�   c                 C   s&   t | ƒ}|jr|jr| S |› d| › �S )a!  Helper to build bucket bound hostname URL.

    :type host: str
    :param host: Host name.

    :type scheme: str
    :param scheme: (Optional) Web scheme. If passed, use it
                   as a scheme in the result URL.

    :rtype: str
    :returns: A bucket bound hostname URL.
    z://N)r   r#   r"   )Úhostr#   Z	url_partsr   r   r   Ú_bucket_bound_hostname_urlc  s   r�   c                   C   s   dt tƒ ƒ S )Nzgccl-invocation-id/)rx   r   r   r   r   r   Ú_get_invocation_idw  r   r�   úapplication/json; charset=UTF-8c                 C   s8   | › dt ƒ › �}|r|d|› �7 }dd| |||p|dœS )a§  Get the headers for a request.

    :type user_agent: str
    :param user_agent: The user-agent for requests.

    :type command: str
    :param command:
        (Optional) Information about which interface for the operation was
        used, to be included in the X-Goog-API-Client header. Please leave
        as None unless otherwise directed.

    :rtype: dict
    :returns: The headers to be used for the request.
    ú z gccl-gcs-cmd/zapplication/jsonzgzip, deflate)ÚAcceptzAccept-Encodingz
User-AgentzX-Goog-API-Clientzcontent-typezx-upload-content-typeN)r�   )Ú
user_agentÚcontent_typeZx_upload_content_typeÚcommandZx_goog_api_clientr   r   r   Ú_get_default_headers{  s   úr—   c                  C   s   t  d¡} t | d¡S )a  Generates a secure 56 bit random integer.


    If 64 bit int is used, sometimes the random int generated is greater than
    max positive value of signed 64 bit int which is 2^63 -1 causing overflow
    issues.

    :rtype: int
    :returns: A secure random 56 bit integer.
    é   ÚbigN)ÚsecretsZtoken_bytesÚintÚ
from_bytes)Zrandom_bytesr   r   r   Úgenerate_random_56_bit_integerž  s   
r�   )F)re   r   )r‘   NN)7r^   rr   ÚdatetimeÚhashlibr   r   ro   rš   Úurllib.parser   r   Úuuidr   Zgoogle.authr   Zgoogle.cloud.storage.constantsr   Zgoogle.cloud.storage.retryr   r	   r   r   Z_API_VERSION_OVERRIDE_ENV_VARZ_DEFAULT_UNIVERSE_DOMAINZ_STORAGE_HOST_TEMPLATEÚformatr   r   r   Z_API_VERSIONrv   r}   ÚnowZ_NOWÚtimezoneÚutcZ_UTCr   r   r   r'   r(   r.   Úobjectr/   rd   rk   rt   rJ   rI   r�   r�   r�   r—   r�   r   r   r   r   Ú<module>   sl   ÿ
  c


ü#