U
    #FZhv                     @   s   d 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Z
dZd	ZG d
d de	jejZG dd de	jejZG dd de	jejZG dd de	jejZdd ZG dd dejjZeejdrG dd dZndZdS )z/Support for downloading media from Google APIs.    N)	_download)common)_helpers)_request_helperszChecksum mismatch while downloading:

  {}

The X-Goog-Hash header indicated an {checksum_type} checksum of:

  {}

but the actual {checksum_type} checksum of the downloaded contents was:

  {}
zIncomplete download for:
{}
Error writing to stream while handling a gzip-compressed file download.
Please restart the download.
z
The X-Goog-Stored-Content-Length is {}. The X-Goog-Stored-Content-Encoding is {}.

The download request read {} bytes of data.
If the download was incomplete, please check the network connection and restart the download.
c                   @   s,   e Zd ZdZdd ZejejffddZdS )Downloada  Helper to manage downloading a resource from a Google API.

    "Slices" of the resource can be retrieved by specifying a range
    with ``start`` and / or ``end``. However, in typical usage, neither
    ``start`` nor ``end`` is expected to be provided.

    Args:
        media_url (str): The URL containing the media to be downloaded.
        stream (IO[bytes]): A write-able stream (i.e. file-like object) that
            the downloaded resource can be written to.
        start (int): The first byte in a range to be downloaded. If not
            provided, but ``end`` is provided, will download from the
            beginning to ``end`` of the media.
        end (int): The last byte in a range to be downloaded. If not
            provided, but ``start`` is provided, will download from the
            ``start`` to the end of the media.
        headers (Optional[Mapping[str, str]]): Extra headers that should
            be sent with the request, e.g. headers for encrypted data.
        checksum Optional([str]): The type of checksum to compute to verify
            the integrity of the object. The response headers must contain
            a checksum of the requested type. If the headers lack an
            appropriate checksum (for instance in the case of transcoded or
            ranged downloads where the remote service does not know the
            correct checksum) an INFO-level log will be emitted. Supported
            values are "md5", "crc32c" and None. The default is "md5".

    Attributes:
        media_url (str): The URL containing the media to be downloaded.
        start (Optional[int]): The first byte in a range to be downloaded.
        end (Optional[int]): The last byte in a range to be downloaded.
    c              	   C   sd  | j dkr>| jdkr>tj|| j| j| jd\}}|| _ || _n| j }| j}|T t|j|}|j	t
jdd}|D ],}| j| |  jt|7  _|| qpW 5 Q R X |dk	r`|jtjjkr`t| }||kr`| |}|d}	|d}
t|
|	| j}|
r2| jt|
k r2|	dkr2t|n.tj| j||| j d}||7 }t||dS )  Write response body to a write-able stream.

        .. note:

            This method assumes that the ``_stream`` attribute is set on the
            current download.

        Args:
            response (~requests.Response): The HTTP response object.

        Raises:
            ~google.resumable_media.common.DataCorruption: If the download's
                checksum doesn't agree with server-computed checksum.
        NZchecksum_typeF)
chunk_sizedecode_unicodex-goog-stored-content-encodingx-goog-stored-content-lengthgzip) _expected_checksum_checksum_objectr   _get_expected_checksum_get_headers	media_urlchecksum_add_decoderrawiter_contentr   _SINGLE_GET_CHUNK_SIZE_streamwrite_bytes_downloadedlenupdatestatus_codehttpclientPARTIAL_CONTENTprepare_checksum_digestdigestget_RESPONSE_HEADERS_INFOformatintConnectionError_CHECKSUM_MISMATCHupperr   DataCorruption)selfresponseexpected_checksumchecksum_objectZlocal_checksum_object	body_iterchunkactual_checksumheadersx_goog_encodingx_goog_lengthcontent_length_msgmsg r7   o/home/aprabhat/apps/x.techxrdev.in/venv/lib/python3.8/site-packages/google/resumable_media/requests/download.py_write_to_streamY   sd       
 



  
zDownload._write_to_streamc                    sj     \ }}}|||djdk	r.dd< jdkrFtj_ fdd}t|jj	S )H  Consume the resource to be downloaded.

        If a ``stream`` is attached to this download, then the downloaded
        resource will be written to the stream.

        Args:
            transport (~requests.Session): A ``requests`` object which can
                make authenticated requests.
            timeout (Optional[Union[float, Tuple[float, float]]]):
                The number of seconds to wait for the server response.
                Depending on the retry strategy, a request may be repeated
                several times using the same timeout each time.

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

        Returns:
            ~requests.Response: The HTTP response returned by ``transport``.

        Raises:
            ~google.resumable_media.common.DataCorruption: If the download's
                checksum doesn't agree with server-computed checksum.
            ValueError: If the current :class:`Download` has already
                finished.
        datar2   timeoutNTstreamc               
      s  j } jdkrjtjpdj jj jd< jd k	rjt	j d krjdji}t
j |} j | f}jd krt|j_| jd k	rt|jr
zjd W n8 tk
r } zt| }t||W 5 d }~X Y nX d_| |S Nr   r2   Z
generationr   r   r   Zadd_bytes_rangestartend_headers_object_generationr   _get_generation_from_urlZadd_query_parametersrequestZ_parse_generation_headerr   _process_responser   Z_is_decompressive_transcodingseek	Exception_STREAM_SEEK_ERRORr%   r9   urlZquery_paramresultexcr6   methodZrequest_kwargsr+   	transportr7   r8   retriable_request   s>    
  


 


z+Download.consume.<locals>.retriable_request)
_prepare_requestr   rD   r   rE   r   r   wait_and_retry_get_status_code_retry_strategyr+   rQ   r=   _payloadr2   rR   r7   rO   r8   consume   s    !

.  zDownload.consumeN	__name__
__module____qualname____doc__r9   r   _DEFAULT_CONNECT_TIMEOUT_DEFAULT_READ_TIMEOUTrZ   r7   r7   r7   r8   r   8   s    Tr   c                   @   s,   e Zd ZdZdd ZejejffddZdS )RawDownloada  Helper to manage downloading a raw resource from a Google API.

    "Slices" of the resource can be retrieved by specifying a range
    with ``start`` and / or ``end``. However, in typical usage, neither
    ``start`` nor ``end`` is expected to be provided.

    Args:
        media_url (str): The URL containing the media to be downloaded.
        stream (IO[bytes]): A write-able stream (i.e. file-like object) that
            the downloaded resource can be written to.
        start (int): The first byte in a range to be downloaded. If not
            provided, but ``end`` is provided, will download from the
            beginning to ``end`` of the media.
        end (int): The last byte in a range to be downloaded. If not
            provided, but ``start`` is provided, will download from the
            ``start`` to the end of the media.
        headers (Optional[Mapping[str, str]]): Extra headers that should
            be sent with the request, e.g. headers for encrypted data.
        checksum Optional([str]): The type of checksum to compute to verify
            the integrity of the object. The response headers must contain
            a checksum of the requested type. If the headers lack an
            appropriate checksum (for instance in the case of transcoded or
            ranged downloads where the remote service does not know the
            correct checksum) an INFO-level log will be emitted. Supported
            values are "md5", "crc32c" and None. The default is "md5".
    Attributes:
        media_url (str): The URL containing the media to be downloaded.
        start (Optional[int]): The first byte in a range to be downloaded.
        end (Optional[int]): The last byte in a range to be downloaded.
    c              	   C   s`  | j dkr>| jdkr>tj|| j| j| jd\}}|| _ || _n| j }| j}|P |jjt	j
dd}|D ],}| j| |  jt|7  _|| qfd|_W 5 Q R X |dk	r\|jtjjkr\t| }||kr\| |}|d}|d}	t|	|| j}
|	r.| jt|	k r.|dkr.t|
n.tj| j||| j d}||
7 }t||dS )	r   Nr   F)decode_contentTr   r   r   ) r   r   r   r   r   r   r   r   r>   r   r   r   r   r   r   r   _content_consumedr   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r   r*   )r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r7   r8   r9   ,  sd       
 



  
zRawDownload._write_to_streamc                    sZ     \ }}}|||ddjdkr6tj_ fdd}t|jjS )r:   T)r<   r2   r=   r>   Nc               
      s  j } jdkrjtjpdj jj jd< jd k	rjt	j d krjdji}t
j |} j | f}jd krt|j_| jd k	rt|jr
zjd W n8 tk
r } zt| }t||W 5 d }~X Y nX d_| |S r?   r@   rK   rO   r7   r8   rR     s>    
  


 


z.RawDownload.consume.<locals>.retriable_request)	rS   rD   r   rE   r   r   rT   rU   rV   rW   r7   rO   r8   rZ   w  s    !
.  zRawDownload.consumeNr[   r7   r7   r7   r8   rb     s   Orb   c                   @   s$   e Zd ZdZejejffddZdS )ChunkedDownloada  Download a resource in chunks from a Google API.

    Args:
        media_url (str): The URL containing the media to be downloaded.
        chunk_size (int): The number of bytes to be retrieved in each
            request.
        stream (IO[bytes]): A write-able stream (i.e. file-like object) that
            will be used to concatenate chunks of the resource as they are
            downloaded.
        start (int): The first byte in a range to be downloaded. If not
            provided, defaults to ``0``.
        end (int): The last byte in a range to be downloaded. If not
            provided, will download to the end of the media.
        headers (Optional[Mapping[str, str]]): Extra headers that should
            be sent with each request, e.g. headers for data encryption
            key headers.

    Attributes:
        media_url (str): The URL containing the media to be downloaded.
        start (Optional[int]): The first byte in a range to be downloaded.
        end (Optional[int]): The last byte in a range to be downloaded.
        chunk_size (int): The number of bytes to be retrieved in each request.

    Raises:
        ValueError: If ``start`` is negative.
    c                    s:     \  fdd}t|jjS )+  Consume the next chunk of the resource to be downloaded.

        Args:
            transport (~requests.Session): A ``requests`` object which can
                make authenticated requests.
            timeout (Optional[Union[float, Tuple[float, float]]]):
                The number of seconds to wait for the server response.
                Depending on the retry strategy, a request may be repeated
                several times using the same timeout each time.

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

        Returns:
            ~requests.Response: The HTTP response returned by ``transport``.

        Raises:
            ValueError: If the current download has finished.
        c                     s"   j  d} |  | S )Nr;   rF   rG   rM   r2   rP   rY   r+   r=   rQ   rL   r7   r8   rR     s    
z=ChunkedDownload.consume_next_chunk.<locals>.retriable_requestrS   r   rT   rU   rV   r+   rQ   r=   rR   r7   ri   r8   consume_next_chunk  s      z"ChunkedDownload.consume_next_chunkNr\   r]   r^   r_   r   r`   ra   rl   r7   r7   r7   r8   re     s
   re   c                   @   s$   e Zd ZdZejejffddZdS )RawChunkedDownloada  Download a raw resource in chunks from a Google API.

    Args:
        media_url (str): The URL containing the media to be downloaded.
        chunk_size (int): The number of bytes to be retrieved in each
            request.
        stream (IO[bytes]): A write-able stream (i.e. file-like object) that
            will be used to concatenate chunks of the resource as they are
            downloaded.
        start (int): The first byte in a range to be downloaded. If not
            provided, defaults to ``0``.
        end (int): The last byte in a range to be downloaded. If not
            provided, will download to the end of the media.
        headers (Optional[Mapping[str, str]]): Extra headers that should
            be sent with each request, e.g. headers for data encryption
            key headers.

    Attributes:
        media_url (str): The URL containing the media to be downloaded.
        start (Optional[int]): The first byte in a range to be downloaded.
        end (Optional[int]): The last byte in a range to be downloaded.
        chunk_size (int): The number of bytes to be retrieved in each request.

    Raises:
        ValueError: If ``start`` is negative.
    c                    s:     \  fdd}t|jjS )rf   c                     s$   j  dd} |  | S )NT)r<   r2   r>   r=   rg   rh   ri   r7   r8   rR   ^  s    
z@RawChunkedDownload.consume_next_chunk.<locals>.retriable_requestrj   rk   r7   ri   r8   rl   @  s      z%RawChunkedDownload.consume_next_chunkNrm   r7   r7   r7   r8   rn   $  s
   rn   c                 C   sR   | j dd }|dkr,t|| _t S |dkrJtrJt|| _t S |S dS )a  Patch the ``_decoder`` on a ``urllib3`` response.

    This is so that we can intercept the compressed bytes before they are
    decoded.

    Only patches if the content encoding is ``gzip`` or ``br``.

    Args:
        response_raw (urllib3.response.HTTPResponse): The raw response for
            an HTTP request.
        checksum (object):
            A checksum which will be updated with compressed bytes.

    Returns:
        object: Either the original ``checksum`` if ``_decoder`` is not
        patched, or a ``_DoNothingHash`` if the decoder is patched, since the
        caller will no longer need to hash to decoded bytes.
    zcontent-encoding r   brN)r2   r#   lower_GzipDecoder_decoderr   Z_DoNothingHash_BrotliDecoder)Zresponse_rawr   encodingr7   r7   r8   r   p  s    

r   c                       s,   e Zd ZdZ fddZ fddZ  ZS )rr   aD  Custom subclass of ``urllib3`` decoder for ``gzip``-ed bytes.

    Allows a checksum function to see the compressed bytes before they are
    decoded. This way the checksum of the compressed value can be computed.

    Args:
        checksum (object):
            A checksum which will be updated with compressed bytes.
    c                    s   t    || _d S N)super__init__	_checksumr+   r   	__class__r7   r8   rx     s    
z_GzipDecoder.__init__c                    s   | j | t |S )zDecompress the bytes.

        Args:
            data (bytes): The compressed bytes to be decompressed.

        Returns:
            bytes: The decompressed bytes from ``data``.
        )ry   r   rw   
decompressr+   r<   r{   r7   r8   r}     s    	z_GzipDecoder.decompress)r\   r]   r^   r_   rx   r}   __classcell__r7   r7   r{   r8   rr     s   
rr   BrotliDecoderc                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	rt   a*  Handler for ``brotli`` encoded bytes.

        Allows a checksum function to see the compressed bytes before they are
        decoded. This way the checksum of the compressed value can be computed.

        Because BrotliDecoder's decompress method is dynamically created in
        urllib3, a subclass is not practical. Instead, this class creates a
        captive urllib3.requests.BrotliDecoder instance and acts as a proxy.

        Args:
            checksum (object):
                A checksum which will be updated with compressed bytes.
        c                 C   s   t j | _|| _d S rv   )urllib3r,   r   rs   ry   rz   r7   r7   r8   rx     s    z_BrotliDecoder.__init__c                 C   s   | j | | j|S )zDecompress the bytes.

            Args:
                data (bytes): The compressed bytes to be decompressed.

            Returns:
                bytes: The decompressed bytes from ``data``.
            )ry   r   rs   r}   r~   r7   r7   r8   r}     s    	z_BrotliDecoder.decompressc                 C   s
   | j  S rv   )rs   flush)r+   r7   r7   r8   r     s    z_BrotliDecoder.flushN)r\   r]   r^   r_   rx   r}   r   r7   r7   r7   r8   rt     s   rt   )r_   Zurllib3.responser   r   Zgoogle.resumable_mediar   r   r   Zgoogle.resumable_media.requestsr   r(   rJ   r$   ZRequestsMixinr   ZRawRequestsMixinrb   re   rn   r   r,   GzipDecoderrr   hasattrrt   r7   r7   r7   r8   <module>   s(   	 U NKL#