U
    #FZhV                     @   sx  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
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eeejd ZdeZdZdZdZdZejdej dZ!dZ"dZ#dZ$dZ%dZ&dZ'dZ(dZ)dZ*dZ+dZ,dZ-dZ.G d d! d!e/Z0G d"d# d#e0Z1G d$d% d%e0Z2G d&d' d'e0Z3G d(d) d)e0Z4G d*d+ d+e0Z5d,d- Z6d.d/ Z7d0d1 Z8d2d3 Z9d4d5 Z:dS )6zVirtual bases classes for uploading media via Google APIs.

Supported here are:

* simple (media) uploads
* multipart uploads that contain both metadata and a small file as payload
* resumable uploads (with metadata as well)
    N)resumable_media)_helpers)common)ElementTreezcontent-typezbytes {:d}-{:d}/{:d}zbytes {:d}-{:d}/*zbytes */{:d}   z==============={{:0{:d}d}}==s   --s   
s3   
content-type: application/json; charset=UTF-8

s   multipart/related; boundary="zbytes=0-(?P<end_byte>\d+))flagszBytes stream is in unexpected state. The local stream has had {:d} bytes read from it while {:d} bytes have already been updated (they should match).zQ{:d} bytes have been read from the stream, which exceeds the expected total {:d}.DELETEPOSTPUTzjThe computed ``{}`` checksum, ``{}``, and the checksum reported by the remote host, ``{}``, did not match.zGResponse metadata had no ``{}`` value; checksum could not be validated.zFResponse headers had no ``{}`` value; checksum could not be validated.z?uploadsz'?partNumber={part}&uploadId={upload_id}z){http://s3.amazonaws.com/doc/2006-03-01/}ZUploadIdz?uploadId={upload_id}c                   @   sR   e Zd ZdZdddZedd Zdd Zed	d
 Z	edd Z
edd ZdS )
UploadBasea  Base class for upload helpers.

    Defines core shared behavior across different upload types.

    Args:
        upload_url (str): The URL where the content will be uploaded.
        headers (Optional[Mapping[str, str]]): Extra headers that should
            be sent with the request, e.g. headers for encrypted data.

    Attributes:
        upload_url (str): The URL where the content will be uploaded.
    Nc                 C   s,   || _ |d kri }|| _d| _t | _d S )NF)
upload_url_headers	_finishedr   ZRetryStrategyZ_retry_strategy)selfr   headers r   e/home/aprabhat/apps/x.techxrdev.in/venv/lib/python3.8/site-packages/google/resumable_media/_upload.py__init__]   s    zUploadBase.__init__c                 C   s   | j S )z2bool: Flag indicating if the upload has completed.)r   r   r   r   r   finishede   s    zUploadBase.finishedc                 C   s    d| _ t|tjjf| j dS )a  Process the response from an HTTP request.

        This is everything that must be done after a request that doesn't
        require network I/O (or other I/O). This is based on the `sans-I/O`_
        philosophy.

        Args:
            response (object): The HTTP response object.

        Raises:
            ~google.resumable_media.common.InvalidResponse: If the status
                code is not 200.

        .. _sans-I/O: https://sans-io.readthedocs.io/
        TN)r   r   require_status_codehttpclientOK_get_status_coder   responser   r   r   _process_responsej   s    zUploadBase._process_responsec                 C   s   t ddS )zAccess the status code from an HTTP response.

        Args:
            response (object): The HTTP response object.

        Raises:
            NotImplementedError: Always, since virtual.
        This implementation is virtual.NNotImplementedErrorr   r   r   r   r      s    
zUploadBase._get_status_codec                 C   s   t ddS )zAccess the headers from an HTTP response.

        Args:
            response (object): The HTTP response object.

        Raises:
            NotImplementedError: Always, since virtual.
        r   Nr   r!   r   r   r   _get_headers   s    
zUploadBase._get_headersc                 C   s   t ddS )zAccess the response body from an HTTP response.

        Args:
            response (object): The HTTP response object.

        Raises:
            NotImplementedError: Always, since virtual.
        r   Nr   r!   r   r   r   	_get_body   s    
zUploadBase._get_body)N)__name__
__module____qualname____doc__r   propertyr   r   staticmethodr   r"   r#   r   r   r   r   r   O   s   



r   c                   @   s"   e Zd ZdZdd ZdddZdS )SimpleUploada  Upload a resource to a Google API.

    A **simple** media upload sends no metadata and completes the upload
    in a single request.

    Args:
        upload_url (str): The URL where the content will be uploaded.
        headers (Optional[Mapping[str, str]]): Extra headers that should
            be sent with the request, e.g. headers for encrypted data.

    Attributes:
        upload_url (str): The URL where the content will be uploaded.
    c                 C   s@   | j rtdt|ts&tdt||| jt< t| j	|| jfS )a  Prepare the contents of an HTTP request.

        This is everything that must be done before a request that doesn't
        require network I/O (or other I/O). This is based on the `sans-I/O`_
        philosophy.

        .. note:

            This method will be used only once, so ``headers`` will be
            mutated by having a new key added to it.

        Args:
            data (bytes): The resource content to be uploaded.
            content_type (str): The content type for the request.

        Returns:
            Tuple[str, str, bytes, Mapping[str, str]]: The quadruple

              * HTTP verb for the request (always POST)
              * the URL for the request
              * the body of the request
              * headers for the request

        Raises:
            ValueError: If the current upload has already finished.
            TypeError: If ``data`` isn't bytes.

        .. _sans-I/O: https://sans-io.readthedocs.io/
         An upload can only be used once.`data` must be bytes, received)
r   
ValueError
isinstancebytes	TypeErrortyper   _CONTENT_TYPE_HEADER_POSTr   )r   datacontent_typer   r   r   _prepare_request   s    

zSimpleUpload._prepare_requestNc                 C   s   t ddS )a`  Transmit the resource to be uploaded.

        Args:
            transport (object): An object which can make authenticated
                requests.
            data (bytes): The resource content to be uploaded.
            content_type (str): The content type of the resource, e.g. a JPEG
                image has content type ``image/jpeg``.
            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.

        Raises:
            NotImplementedError: Always, since virtual.
        r   Nr   )r   	transportr4   r5   timeoutr   r   r   transmit   s    zSimpleUpload.transmit)N)r$   r%   r&   r'   r6   r9   r   r   r   r   r*      s   &r*   c                       s4   e Zd ZdZd	 fdd	Zdd Zd
ddZ  ZS )MultipartUploada5  Upload a resource with metadata to a Google API.

    A **multipart** upload sends both metadata and the resource in a single
    (multipart) request.

    Args:
        upload_url (str): The URL where the content will be uploaded.
        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 request metadata will be amended
            to include the computed value. Using this option will override a
            manually-set checksum value. Supported values are "md5", "crc32c"
            and None. The default is None.

    Attributes:
        upload_url (str): The URL where the content will be uploaded.
    Nc                    s   t t| j||d || _d S Nr   )superr:   r   _checksum_type)r   r   r   checksum	__class__r   r   r     s    zMultipartUpload.__init__c           
      C   s   | j rtdt|ts&tdt|t| j}|dk	rf|	| t
| }t| j}|||< t|||\}}t| d }	|	| jt< t| j|| jfS )aj  Prepare the contents of an HTTP request.

        This is everything that must be done before a request that doesn't
        require network I/O (or other I/O). This is based on the `sans-I/O`_
        philosophy.

        .. note:

            This method will be used only once, so ``headers`` will be
            mutated by having a new key added to it.

        Args:
            data (bytes): The resource content to be uploaded.
            metadata (Mapping[str, str]): The resource metadata, such as an
                ACL list.
            content_type (str): The content type of the resource, e.g. a JPEG
                image has content type ``image/jpeg``.

        Returns:
            Tuple[str, str, bytes, Mapping[str, str]]: The quadruple

              * HTTP verb for the request (always POST)
              * the URL for the request
              * the body of the request
              * headers for the request

        Raises:
            ValueError: If the current upload has already finished.
            TypeError: If ``data`` isn't bytes.

        .. _sans-I/O: https://sans-io.readthedocs.io/
        r+   r,   N   ")r   r-   r.   r/   r0   r1   r   _get_checksum_objectr>   updateprepare_checksum_digestdigest_get_metadata_keyconstruct_multipart_request_RELATED_HEADERr   r2   r3   r   )
r   r4   metadatar5   Zchecksum_objectZactual_checksummetadata_keycontentmultipart_boundaryZmultipart_content_typer   r   r   r6     s$    !

  
z MultipartUpload._prepare_requestc                 C   s   t ddS )a  Transmit the resource to be uploaded.

        Args:
            transport (object): An object which can make authenticated
                requests.
            data (bytes): The resource content to be uploaded.
            metadata (Mapping[str, str]): The resource metadata, such as an
                ACL list.
            content_type (str): The content type of the resource, e.g. a JPEG
                image has content type ``image/jpeg``.
            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.

        Raises:
            NotImplementedError: Always, since virtual.
        r   Nr   )r   r7   r4   rJ   r5   r8   r   r   r   r9   >  s    zMultipartUpload.transmit)NN)N)r$   r%   r&   r'   r   r6   r9   __classcell__r   r   r@   r   r:      s   6r:   c                       s   e Zd ZdZd( fdd	Zedd Zedd Zed	d
 Zedd Z	edd Z
d)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# Zd$d% Zd&d' Z  ZS ),ResumableUploada#  Initiate and fulfill a resumable upload to a Google API.

    A **resumable** upload sends an initial request with the resource metadata
    and then gets assigned an upload ID / upload URL to send bytes to.
    Using the upload URL, the upload is then done in chunks (determined by
    the user) until all bytes have been uploaded.

    Args:
        upload_url (str): The URL where the resumable upload will be initiated.
        chunk_size (int): The size of each chunk used to upload the resource.
        headers (Optional[Mapping[str, str]]): Extra headers that should
            be sent with every request.
        checksum (Optional([str])): The type of checksum to compute to verify
            the integrity of the object. After the upload is complete, the
            server-computed checksum of the resulting object will be read
            and google.resumable_media.common.DataCorruption will be raised on
            a mismatch. The corrupted file will not be deleted from the remote
            host automatically. Supported values are "md5", "crc32c" and None.
            The default is None.

    Attributes:
        upload_url (str): The URL where the content will be uploaded.

    Raises:
        ValueError: If ``chunk_size`` is not a multiple of
            :data:`.UPLOAD_CHUNK_SIZE`.
    Nc                    sv   t t| j||d |tj dkr6tdtjd || _d | _d | _	d| _
d| _|| _d | _d | _d | _d| _d S )Nr<   r   z{} KB must divide chunk sizei   F)r=   rO   r   r   ZUPLOAD_CHUNK_SIZEr-   format_chunk_size_stream_content_type_bytes_uploaded_bytes_checksummedr>   _checksum_object_total_bytes_resumable_url_invalid)r   r   
chunk_sizer?   r   r@   r   r   r   t  s"    zResumableUpload.__init__c                 C   s   | j S )zbool: Indicates if the upload is in an invalid state.

        This will occur if a call to :meth:`transmit_next_chunk` fails.
        To recover from such a failure, call :meth:`recover`.
        rY   r   r   r   r   invalid  s    zResumableUpload.invalidc                 C   s   | j S )z8int: The size of each chunk used to upload the resource.)rQ   r   r   r   r   rZ     s    zResumableUpload.chunk_sizec                 C   s   | j S )z;Optional[str]: The URL of the in-progress resumable upload.)rX   r   r   r   r   resumable_url  s    zResumableUpload.resumable_urlc                 C   s   | j S )z-int: Number of bytes that have been uploaded.)rT   r   r   r   r   bytes_uploaded  s    zResumableUpload.bytes_uploadedc                 C   s   | j S )a  Optional[int]: The total number of bytes to be uploaded.

        If this upload is initiated (via :meth:`initiate`) with
        ``stream_final=True``, this value will be populated based on the size
        of the ``stream`` being uploaded. (By default ``stream_final=True``.)

        If this upload is initiated with ``stream_final=False``,
        :attr:`total_bytes` will be :data:`None` since it cannot be
        determined from the stream.
        )rW   r   r   r   r   total_bytes  s    zResumableUpload.total_bytesTc                 C   s   | j dk	rtd| dkr&td|| _|| _tj| j}tj	|j
}d|ks^d|krn| jt|i}n| jtdd|i}|dk	r|| _n|rt|| _| jdk	rd	| j}	|	|d
< t|d}
t| j|
|fS )a  Prepare the contents of HTTP request to initiate upload.

        This is everything that must be done before a request that doesn't
        require network I/O (or other I/O). This is based on the `sans-I/O`_
        philosophy.

        Args:
            stream (IO[bytes]): The stream (i.e. file-like object) that will
                be uploaded. The stream **must** be at the beginning (i.e.
                ``stream.tell() == 0``).
            metadata (Mapping[str, str]): The resource metadata, such as an
                ACL list.
            content_type (str): The content type of the resource, e.g. a JPEG
                image has content type ``image/jpeg``.
            total_bytes (Optional[int]): The total number of bytes to be
                uploaded. If specified, the upload size **will not** be
                determined from the stream (even if ``stream_final=True``).
            stream_final (Optional[bool]): Indicates if the ``stream`` is
                "final" (i.e. no more bytes will be added to it). In this case
                we determine the upload size from the size of the stream. If
                ``total_bytes`` is passed, this argument will be ignored.

        Returns:
            Tuple[str, str, bytes, Mapping[str, str]]: The quadruple

              * HTTP verb for the request (always POST)
              * the URL for the request
              * the body of the request
              * headers for the request

        Raises:
            ValueError: If the current upload has already been initiated.
            ValueError: If ``stream`` is not at the beginning.

        .. _sans-I/O: https://sans-io.readthedocs.io/
        N'This upload has already been initiated.r   zStream must be at beginning.zx-goog-signaturezX-Goog-Signaturezapplication/json; charset=UTF-8zx-upload-content-typez{:d}zx-upload-content-lengthutf-8)r]   r-   tellrR   rS   urllibparseurlparser   parse_qsqueryr   r2   rW   get_total_bytesrP   jsondumpsencoder3   )r   streamrJ   r5   r_   stream_finalZparse_resultZparsed_queryr   content_lengthpayloadr   r   r   _prepare_initiate_request  s2    '
  

z)ResumableUpload._prepare_initiate_requestc                 C   s8   t j|tjjtjjf| j| jd t |d| j	| _
dS )aV  Process the response from an HTTP request that initiated upload.

        This is everything that must be done after a request that doesn't
        require network I/O (or other I/O). This is based on the `sans-I/O`_
        philosophy.

        This method takes the URL from the ``Location`` header and stores it
        for future use. Within that URL, we assume the ``upload_id`` query
        parameter has been included, but we do not check.

        Args:
            response (object): The HTTP response object (need headers).

        .. _sans-I/O: https://sans-io.readthedocs.io/
        callbacklocationN)r   r   r   r   r   CREATEDr   _make_invalidheader_requiredr"   rX   r   r   r   r   _process_initiate_response  s      z*ResumableUpload._process_initiate_responsec                 C   s   t ddS )a  Initiate a resumable upload.

        By default, this method assumes your ``stream`` is in a "final"
        state ready to transmit. However, ``stream_final=False`` can be used
        to indicate that the size of the resource is not known. This can happen
        if bytes are being dynamically fed into ``stream``, e.g. if the stream
        is attached to application logs.

        If ``stream_final=False`` is used, :attr:`chunk_size` bytes will be
        read from the stream every time :meth:`transmit_next_chunk` is called.
        If one of those reads produces strictly fewer bites than the chunk
        size, the upload will be concluded.

        Args:
            transport (object): An object which can make authenticated
                requests.
            stream (IO[bytes]): The stream (i.e. file-like object) that will
                be uploaded. The stream **must** be at the beginning (i.e.
                ``stream.tell() == 0``).
            metadata (Mapping[str, str]): The resource metadata, such as an
                ACL list.
            content_type (str): The content type of the resource, e.g. a JPEG
                image has content type ``image/jpeg``.
            total_bytes (Optional[int]): The total number of bytes to be
                uploaded. If specified, the upload size **will not** be
                determined from the stream (even if ``stream_final=True``).
            stream_final (Optional[bool]): Indicates if the ``stream`` is
                "final" (i.e. no more bytes will be added to it). In this case
                we determine the upload size from the size of the stream. If
                ``total_bytes`` is passed, this argument will be ignored.
            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.

        Raises:
            NotImplementedError: Always, since virtual.
        r   Nr   )r   r7   rl   rJ   r5   r_   rm   r8   r   r   r   initiate  s    3zResumableUpload.initiatec                 C   s   | j rtd| jrtd| jdkr.tdt| j| j| j\}}}|| jkrft	
|| j}t|| || | jt| jtj|i}t| j||fS )a  Prepare the contents of HTTP request to upload a chunk.

        This is everything that must be done before a request that doesn't
        require network I/O. This is based on the `sans-I/O`_ philosophy.

        For the time being, this **does require** some form of I/O to read
        a chunk from ``stream`` (via :func:`get_next_chunk`). However, this
        will (almost) certainly not be network I/O.

        Returns:
            Tuple[str, str, bytes, Mapping[str, str]]: The quadruple

              * HTTP verb for the request (always PUT)
              * the URL for the request
              * the body of the request
              * headers for the request

            The headers incorporate the ``_headers`` on the current instance.

        Raises:
            ValueError: If the current upload has finished.
            ValueError: If the current upload is in an invalid state.
            ValueError: If the current upload has not been initiated.
            ValueError: If the location in the stream (i.e. ``stream.tell()``)
                does not agree with ``bytes_uploaded``.

        .. _sans-I/O: https://sans-io.readthedocs.io/
        zUpload has finished.z;Upload is in an invalid state. To recover call `recover()`.Nz_This upload has not been initiated. Please call initiate() before beginning to transmit chunks.)r   r-   r\   r]   get_next_chunkrR   rQ   rW   r^   _STREAM_ERROR_TEMPLATErP   _update_checksumr   r2   rS   r   CONTENT_RANGE_HEADER_PUT)r   
start_bytero   content_rangemsgr   r   r   r   r6   E  s4    
  

  z ResumableUpload._prepare_requestc                 C   sf   | j s
dS | jst| j | _|| jk r@| j| }||d }n|}| j| |  jt|7  _dS )a%  Update the checksum with the payload if not already updated.

        Because error recovery can result in bytes being transmitted more than
        once, the checksum tracks the number of bytes checked in
        self._bytes_checksummed and skips bytes that have already been summed.
        N)r>   rV   r   rC   rU   rD   len)r   r~   ro   offsetr4   r   r   r   r{   ~  s    

z ResumableUpload._update_checksumc                 C   s
   d| _ dS )zSimple setter for ``invalid``.

        This is intended to be passed along as a callback to helpers that
        raise an exception so they can mark this instance as invalid before
        raising.
        TNr[   r   r   r   r   ru     s    zResumableUpload._make_invalidc                 C   s   t j|tjjtjjf| j| jd}|tjjkrL| j| | _d| _	| 
| nVt j|t j| j| jd}t|}|dkr|   t|d|dt|dd | _dS )a  Process the response from an HTTP request.

        This is everything that must be done after a request that doesn't
        require network I/O (or other I/O). This is based on the `sans-I/O`_
        philosophy.

        Args:
            response (object): The HTTP response object.
            bytes_sent (int): The number of bytes sent in the request that
                ``response`` was returned for.

        Raises:
            ~google.resumable_media.common.InvalidResponse: If the status
                code is 308 and the ``range`` header is not of the form
                ``bytes 0-{end}``.
            ~google.resumable_media.common.InvalidResponse: If the status
                code is not 200 or 308.

        .. _sans-I/O: https://sans-io.readthedocs.io/
        rq   TNUnexpected "range" header*Expected to be of the form "bytes=0-{end}"end_byter   )r   r   r   r   r   PERMANENT_REDIRECTr   ru   rT   r   _validate_checksumrv   RANGE_HEADERr"   _BYTES_RANGE_REmatchr   InvalidResponseintgroup)r   r   Z
bytes_sentstatus_codebytes_ranger   r   r   r   _process_resumable_response  s4    	
z+ResumableUpload._process_resumable_responsec                 C   s   | j dkrdS t| j }| }||}|dkrNt|t|| 	|t
| j }||krt|t| j  ||dS )aT  Check the computed checksum, if any, against the recieved metadata.

        Args:
            response (object): The HTTP response object.

        Raises:
            ~google.resumable_media.common.DataCorruption: If the checksum
            computed locally and the checksum reported by the remote host do
            not match.
        N)r>   r   rG   ri   getr   r   0_UPLOAD_METADATA_NO_APPROPRIATE_CHECKSUM_MESSAGErP   r"   rE   rV   rF   DataCorruption!_UPLOAD_CHECKSUM_MISMATCH_MESSAGEupper)r   r   rK   rJ   remote_checksumlocal_checksumr   r   r   r     s.    

  z"ResumableUpload._validate_checksumc                 C   s   t ddS )a  Transmit the next chunk of the resource to be uploaded.

        If the current upload was initiated with ``stream_final=False``,
        this method will dynamically determine if the upload has completed.
        The upload will be considered complete if the stream produces
        fewer than :attr:`chunk_size` bytes when a chunk is read from it.

        Args:
            transport (object): An 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.

        Raises:
            NotImplementedError: Always, since virtual.
        r   Nr   r   r7   r8   r   r   r   transmit_next_chunk  s    z#ResumableUpload.transmit_next_chunkc                 C   s   t jdi}t| jd|fS )a0  Prepare the contents of HTTP request to recover from failure.

        This is everything that must be done before a request that doesn't
        require network I/O. This is based on the `sans-I/O`_ philosophy.

        We assume that the :attr:`resumable_url` is set (i.e. the only way
        the upload can end up :attr:`invalid` is if it has been initiated.

        Returns:
            Tuple[str, str, NoneType, Mapping[str, str]]: The quadruple

              * HTTP verb for the request (always PUT)
              * the URL for the request
              * the body of the request (always :data:`None`)
              * headers for the request

            The headers **do not** incorporate the ``_headers`` on the
            current instance.

        .. _sans-I/O: https://sans-io.readthedocs.io/
        z	bytes */*N)r   r|   r}   r]   )r   r   r   r   r   _prepare_recover_request  s    
z(ResumableUpload._prepare_recover_requestc                 C   s   t |tjjf| j | |}t j|krl|t j }t	|}|dkrVt
|d|dt|dd | _nd| _| j| j d| _dS )a  Process the response from an HTTP request to recover from failure.

        This is everything that must be done after a request that doesn't
        require network I/O (or other I/O). This is based on the `sans-I/O`_
        philosophy.

        Args:
            response (object): The HTTP response object.

        Raises:
            ~google.resumable_media.common.InvalidResponse: If the status
                code is not 308.
            ~google.resumable_media.common.InvalidResponse: If the status
                code is 308 and the ``range`` header is not of the form
                ``bytes 0-{end}``.

        .. _sans-I/O: https://sans-io.readthedocs.io/
        Nr   r   r   r   r   F)r   r   r   r   r   r   r"   r   r   r   r   r   r   r   rT   rR   seekrY   )r   r   r   r   r   r   r   r   _process_recover_response*  s(      



z)ResumableUpload._process_recover_responsec                 C   s   t ddS )a!  Recover from a failure.

        This method should be used when a :class:`ResumableUpload` is in an
        :attr:`~ResumableUpload.invalid` state due to a request failure.

        This will verify the progress with the server and make sure the
        current upload is in a valid state before :meth:`transmit_next_chunk`
        can be used again.

        Args:
            transport (object): An object which can make authenticated
                requests.

        Raises:
            NotImplementedError: Always, since virtual.
        r   Nr   )r   r7   r   r   r   recoverS  s    zResumableUpload.recover)NN)NT)NTN)N)r$   r%   r&   r'   r   r(   r\   rZ   r]   r^   r_   rp   rw   rx   r6   r{   ru   r   r   r   r   r   r   rN   r   r   r@   r   rO   W  s:   




   
I    
59	;!
)rO   c                       s   e Zd ZdZd fdd	Zedd Zdd Zd	d
 Zdd Z	dddZ
dd Zdd ZdddZdd Zdd ZdddZ  ZS )XMLMPUContaineral  Initiate and close an upload using the XML MPU API.

    An XML MPU sends an initial request and then receives an upload ID.
    Using the upload ID, the upload is then done in numbered parts and the
    parts can be uploaded concurrently.

    In order to avoid concurrency issues with this container object, the
    uploading of individual parts is handled separately, by XMLMPUPart objects
    spawned from this container class. The XMLMPUPart objects are not
    necessarily in the same process as the container, so they do not update the
    container automatically.

    MPUs are sometimes referred to as "Multipart Uploads", which is ambiguous
    given the JSON multipart upload, so the abbreviation "MPU" will be used
    throughout.

    See: https://cloud.google.com/storage/docs/multipart-uploads

    Args:
        upload_url (str): The URL of the object (without query parameters). The
            initiate, PUT, and finalization requests will all use this URL, with
            varying query parameters.
        filename (str): The name (path) of the file to upload.
        headers (Optional[Mapping[str, str]]): Extra headers that should
            be sent with every request.

    Attributes:
        upload_url (str): The URL where the content will be uploaded.
        upload_id (Optional(str)): The ID of the upload from the initialization
            response.
    Nc                    s&   t  j||d || _|| _i | _d S r;   )r=   r   	_filename
_upload_id_parts)r   r   filenamer   	upload_idr@   r   r   r     s    zXMLMPUContainer.__init__c                 C   s   | j S Nr   r   r   r   r   r     s    zXMLMPUContainer.upload_idc                 C   s   || j |< dS )a  Register an uploaded part by part number and corresponding etag.

        XMLMPUPart objects represent individual parts, and their part number
        and etag can be registered to the container object with this method
        and therefore incorporated in the finalize() call to finish the upload.

        This method accepts part_number and etag, but not XMLMPUPart objects
        themselves, to reduce the complexity involved in running XMLMPUPart
        uploads in separate processes.

        Args:
            part_number (int): The part number. Parts are assembled into the
                final uploaded object with finalize() in order of their part
                numbers.
            etag (str): The etag included in the server response after upload.
        N)r   )r   part_numberetagr   r   r   register_part  s    zXMLMPUContainer.register_partc                 C   s6   | j dk	rtd| jt }| jt|i}t|d|fS )a  Prepare the contents of HTTP request to initiate upload.

        This is everything that must be done before a request that doesn't
        require network I/O (or other I/O). This is based on the `sans-I/O`_
        philosophy.

        Args:
            content_type (str): The content type of the resource, e.g. a JPEG
                image has content type ``image/jpeg``.

        Returns:
            Tuple[str, str, bytes, Mapping[str, str]]: The quadruple

              * HTTP verb for the request (always POST)
              * the URL for the request
              * the body of the request
              * headers for the request

        Raises:
            ValueError: If the current upload has already been initiated.

        .. _sans-I/O: https://sans-io.readthedocs.io/
        Nr`   )r   r-   r   _MPU_INITIATE_QUERYr   r2   r3   )r   r5   Zinitiate_urlr   r   r   r   rp     s    

 z)XMLMPUContainer._prepare_initiate_requestc                 C   s8   t |tjjf| j t|j}|	t
t j| _dS )a  Process the response from an HTTP request that initiated the upload.

        This is everything that must be done after a request that doesn't
        require network I/O (or other I/O). This is based on the `sans-I/O`_
        philosophy.

        This method takes the URL from the ``Location`` header and stores it
        for future use. Within that URL, we assume the ``upload_id`` query
        parameter has been included, but we do not check.

        Args:
            response (object): The HTTP response object.

        Raises:
            ~google.resumable_media.common.InvalidResponse: If the status
                code is not 200.

        .. _sans-I/O: https://sans-io.readthedocs.io/
        N)r   r   r   r   r   r   r   
fromstringtextfind_S3_COMPAT_XML_NAMESPACE_UPLOAD_ID_NODEr   )r   r   rootr   r   r   rw     s    z*XMLMPUContainer._process_initiate_responsec                 C   s   t ddS )a%  Initiate an MPU and record the upload ID.

        Args:
            transport (object): An object which can make authenticated
                requests.
            content_type (str): The content type of the resource, e.g. a JPEG
                image has content type ``image/jpeg``.
            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.

        Raises:
            NotImplementedError: Always, since virtual.
        r   Nr   )r   r7   r5   r8   r   r   r   rx     s    zXMLMPUContainer.initiatec                 C   s   | j dkrtdtj| jd}| j| }td}| j	 D ]4\}}t
|d}t|t
|d_|t
|d_q>t|}t||| jfS )a  Prepare the contents of an HTTP request to finalize the upload.

        All of the parts must be registered before calling this method.

        Returns:
            Tuple[str, str, bytes, Mapping[str, str]]: The quadruple

              * HTTP verb for the request (always POST)
              * the URL for the request
              * the body of the request
              * headers for the request

        Raises:
            ValueError: If the upload has not been initiated.
        N'This upload has not yet been initiated.r   ZCompleteMultipartUploadZPartZ
PartNumberETag)r   r-   _MPU_FINAL_QUERY_TEMPLATErP   r   r   r   ZElementr   itemsZ
SubElementstrr   tostringr3   r   )r   Zfinal_queryZfinalize_urlZfinal_xml_rootr   r   partro   r   r   r   _prepare_finalize_request  s    



z)XMLMPUContainer._prepare_finalize_requestc                 C   s    t |tjjf| j d| _dS )a  Process the response from an HTTP request that finalized the upload.

        This is everything that must be done after a request that doesn't
        require network I/O (or other I/O). This is based on the `sans-I/O`_
        philosophy.

        Args:
            response (object): The HTTP response object.

        Raises:
            ~google.resumable_media.common.InvalidResponse: If the status
                code is not 200.

        .. _sans-I/O: https://sans-io.readthedocs.io/
        TN)r   r   r   r   r   r   r   r   r   r   r   _process_finalize_response  s    z*XMLMPUContainer._process_finalize_responsec                 C   s   t ddS )a  Finalize an MPU request with all the parts.

        Args:
            transport (object): An 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.

        Raises:
            NotImplementedError: Always, since virtual.
        r   Nr   r   r   r   r   finalize+  s    zXMLMPUContainer.finalizec                 C   s8   | j dkrtdtj| jd}| j| }t|d| jfS )a  Prepare the contents of an HTTP request to cancel the upload.

        Returns:
            Tuple[str, str, bytes, Mapping[str, str]]: The quadruple

              * HTTP verb for the request (always DELETE)
              * the URL for the request
              * the body of the request
              * headers for the request

        Raises:
            ValueError: If the upload has not been initiated.
        Nr   r   )r   r-   r   rP   r   r   _DELETEr   )r   Zcancel_queryZ
cancel_urlr   r   r   _prepare_cancel_requestB  s
    

z'XMLMPUContainer._prepare_cancel_requestc                 C   s   t |tjjf| j dS )a  Process the response from an HTTP request that canceled the upload.

        This is everything that must be done after a request that doesn't
        require network I/O (or other I/O). This is based on the `sans-I/O`_
        philosophy.

        Args:
            response (object): The HTTP response object.

        Raises:
            ~google.resumable_media.common.InvalidResponse: If the status
                code is not 204.

        .. _sans-I/O: https://sans-io.readthedocs.io/
        N)r   r   r   r   
NO_CONTENTr   r   r   r   r   _process_cancel_responseW  s
      z(XMLMPUContainer._process_cancel_responsec                 C   s   t ddS )a  Cancel an MPU request and permanently delete any uploaded parts.

        This cannot be undone.

        Args:
            transport (object): An 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.

        Raises:
            NotImplementedError: Always, since virtual.
        r   Nr   r   r   r   r   cancell  s    zXMLMPUContainer.cancel)NN)N)N)N)r$   r%   r&   r'   r   r(   r   r   rp   rw   rx   r   r   r   r   r   r   rN   r   r   r@   r   r   g  s"    
# 
 
 r   c                       s   e Zd ZdZd fdd	Zedd Zedd Zed	d
 Zedd Z	edd Z
edd Zdd Zdd ZdddZdd Z  ZS )
XMLMPUParta  Upload a single part of an existing XML MPU container.

    An XML MPU sends an initial request and then receives an upload ID.
    Using the upload ID, the upload is then done in numbered parts and the
    parts can be uploaded concurrently.

    In order to avoid concurrency issues with the container object, the
    uploading of individual parts is handled separately by multiple objects
    of this class. Once a part is uploaded, it can be registered with the
    container with `container.register_part(part.part_number, part.etag)`.

    MPUs are sometimes referred to as "Multipart Uploads", which is ambiguous
    given the JSON multipart upload, so the abbreviation "MPU" will be used
    throughout.

    See: https://cloud.google.com/storage/docs/multipart-uploads

    Args:
        upload_url (str): The URL of the object (without query parameters).
        upload_id (str): The ID of the upload from the initialization response.
        filename (str): The name (path) of the file to upload.
        start (int): The byte index of the beginning of the part.
        end (int): The byte index of the end of the part.
        part_number (int): The part number. Part numbers will be assembled in
            sequential order when the container is finalized.
        headers (Optional[Mapping[str, str]]): Extra headers that should
            be sent with every request.
        checksum (Optional([str])): The type of checksum to compute to verify
            the integrity of the object. The request headers will be amended
            to include the computed value. Supported values are "md5", "crc32c"
            and None. The default is None.

    Attributes:
        upload_url (str): The URL of the object (without query parameters).
        upload_id (str): The ID of the upload from the initialization response.
        filename (str): The name (path) of the file to upload.
        start (int): The byte index of the beginning of the part.
        end (int): The byte index of the end of the part.
        part_number (int): The part number. Part numbers will be assembled in
            sequential order when the container is finalized.
        etag (Optional(str)): The etag returned by the service after upload.
    Nc	           	         sD   t  j||d || _|| _|| _|| _|| _d | _|| _d | _	d S r;   )
r=   r   r   _start_endr   _part_number_etagr>   rV   )	r   r   r   r   startendr   r   r?   r@   r   r   r     s    zXMLMPUPart.__init__c                 C   s   | j S r   )r   r   r   r   r   r     s    zXMLMPUPart.part_numberc                 C   s   | j S r   r   r   r   r   r   r     s    zXMLMPUPart.upload_idc                 C   s   | j S r   )r   r   r   r   r   r     s    zXMLMPUPart.filenamec                 C   s   | j S r   )r   r   r   r   r   r     s    zXMLMPUPart.etagc                 C   s   | j S r   )r   r   r   r   r   r     s    zXMLMPUPart.startc                 C   s   | j S r   )r   r   r   r   r   r     s    zXMLMPUPart.endc              	   C   s   | j rtdt| jd$}|| j || j| j }W 5 Q R X t	| j
| _| jdk	rh| j| tj| j| jd}| j| }t||| jfS )a|  Prepare the contents of HTTP request to upload a part.

        This is everything that must be done before a request that doesn't
        require network I/O. This is based on the `sans-I/O`_ philosophy.

        For the time being, this **does require** some form of I/O to read
        a part from ``stream`` (via :func:`get_part_payload`). However, this
        will (almost) certainly not be network I/O.

        Returns:
            Tuple[str, str, bytes, Mapping[str, str]]: The quadruple

              * HTTP verb for the request (always PUT)
              * the URL for the request
              * the body of the request
              * headers for the request

            The headers incorporate the ``_headers`` on the current instance.

        Raises:
            ValueError: If the current upload has finished.

        .. _sans-I/O: https://sans-io.readthedocs.io/
        z$This part has already been uploaded.brN)r   r   )r   r-   openr   r   r   readr   r   rC   r>   rV   rD   _MPU_PART_QUERY_TEMPLATErP   r   r   r   r}   r   )r   fro   Z
part_queryr   r   r   r   _prepare_upload_request  s    
 
z"XMLMPUPart._prepare_upload_requestc                 C   s@   t |tjjf| j | | t |d| j}|| _	d| _
dS )a  Process the response from an HTTP request.

        This is everything that must be done after a request that doesn't
        require network I/O (or other I/O). This is based on the `sans-I/O`_
        philosophy.

        Args:
            response (object): The HTTP response object.

        Raises:
            ~google.resumable_media.common.InvalidResponse: If the status
                code is not 200 or the response is missing data.

        .. _sans-I/O: https://sans-io.readthedocs.io/
        r   TN)r   r   r   r   r   r   r   rv   r"   r   r   )r   r   r   r   r   r   _process_upload_response	  s    
z#XMLMPUPart._process_upload_responsec                 C   s   t ddS )a  Upload the part.

        Args:
            transport (object): An 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.

        Raises:
            NotImplementedError: Always, since virtual.
        r   Nr   r   r   r   r   upload%  s    zXMLMPUPart.uploadc                 C   s   | j dkrdS t|| j| j }|dkrNt| j }t|t|| |t	| j
 }||krt|t| j  ||dS )aS  Check the computed checksum, if any, against the response headers.

        Args:
            response (object): The HTTP response object.

        Raises:
            ~google.resumable_media.common.DataCorruption: If the checksum
            computed locally and the checksum reported by the remote host do
            not match.
        N)r>   r   Z#_get_uploaded_checksum_from_headersr"   rG   r   r   r   rP   rE   rV   rF   r   r   r   )r   r   r   rK   r   r   r   r   r   <  s4    
    zXMLMPUPart._validate_checksum)NN)N)r$   r%   r&   r'   r   r(   r   r   r   r   r   r   r   r   r   r   rN   r   r   r@   r   r     s*   3  





* 
r   c                  C   s    t tj} t| }|dS )zGet a random boundary for a multipart request.

    Returns:
        bytes: The boundary used to separate parts of a multipart request.
    ra   )random	randrangesysmaxsize_BOUNDARY_FORMATrP   rk   )Z
random_intboundaryr   r   r   get_boundarya  s    
r   c                 C   sh   t  }t|d}|d}t| }|t | t | t d | t t |  t | t }||fS )a  Construct a multipart request body.

    Args:
        data (bytes): The resource content (UTF-8 encoded as bytes)
            to be uploaded.
        metadata (Mapping[str, str]): The resource metadata, such as an
            ACL list.
        content_type (str): The content type of the resource, e.g. a JPEG
            image has content type ``image/jpeg``.

    Returns:
        Tuple[bytes, bytes]: The multipart request body and the boundary used
        between each part.
    ra   s   content-type: )r   ri   rj   rk   _MULTIPART_SEP_MULTIPART_BEGIN_CRLF)r4   rJ   r5   rM   Z
json_bytesZboundary_seprL   r   r   r   rH   n  sB    
	
rH   c                 C   s,   |   }| dtj |   }| | |S )zDetermine the total number of bytes in a stream.

    Args:
       stream (IO[bytes]): The stream (i.e. file-like object).

    Returns:
        int: The number of bytes.
    r   )rb   r   osSEEK_END)rl   current_positionZend_positionr   r   r   rh     s
    	
rh   c                 C   s   |   }|dk	r<|| |  kr(dkr<n n| || }n
| |}|   d }t|}|dkrt||k r|d }n*|dkr|dkrtdn|dkrtdt|||}|||fS )a  Get a chunk from an I/O stream.

    The ``stream`` may have fewer bytes remaining than ``chunk_size``
    so it may not always be the case that
    ``end_byte == start_byte + chunk_size - 1``.

    Args:
        stream (IO[bytes]): The stream (i.e. file-like object).
        chunk_size (int): The size of the chunk to be read from the ``stream``.
        total_bytes (Optional[int]): The (expected) total number of bytes
            in the ``stream``.

    Returns:
        Tuple[int, bytes, str]: Triple of:

          * the start byte index
          * the content in between the start and end bytes (inclusive)
          * content range header for the chunk (slice) that has been read

    Raises:
        ValueError: If ``total_bytes == 0`` but ``stream.read()`` yields
            non-empty content.
        ValueError: If there is no data left to consume. This corresponds
            exactly to the case ``end_byte < start_byte``, which can only
            occur if ``end_byte == start_byte - 1``.
    Nr   r   z:Stream specified as empty, but produced non-empty content.z;Stream is already exhausted. There is no content remaining.)rb   r   r   r-   get_content_range)rl   rZ   r_   r~   ro   r   Znum_bytes_readr   r   r   r   ry     s(    $

ry   c                 C   s8   |dkrt | |S || k r&t|S t| ||S dS )a  Convert start, end and total into content range header.

    If ``total_bytes`` is not known, uses "bytes {start}-{end}/*".
    If we are dealing with an empty range (i.e. ``end_byte < start_byte``)
    then "bytes */{total}" is used.

    This function **ASSUMES** that if the size is not known, the caller will
    not also pass an empty range.

    Args:
        start_byte (int): The start (inclusive) of the byte range.
        end_byte (int): The end (inclusive) of the byte range.
        total_bytes (Optional[int]): The number of bytes in the byte
            range (if known).

    Returns:
        str: The content range header.
    N)_RANGE_UNKNOWN_TEMPLATErP   _EMPTY_RANGE_TEMPLATE_CONTENT_RANGE_TEMPLATE)r~   r   r_   r   r   r   r     s
    
r   );r'   http.clientr   ri   r   r   rer   urllib.parserc   Zgoogler   Zgoogle.resumable_mediar   r   Z	xml.etreer   r2   r   r   r   r   r   r   Z_BOUNDARY_WIDTHrP   r   r   r   r   rI   compile
IGNORECASEr   rz   Z_STREAM_READ_PAST_TEMPLATEr   r3   r}   r   r   Z._UPLOAD_HEADER_NO_APPROPRIATE_CHECKSUM_MESSAGEr   r   r   r   r   objectr   r*   r:   rO   r   r   r   rH   rh   ry   r   r   r   r   r   <module>   st   	
ULg      ! \)9