a
    !f)                     @   s0  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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%G dd de&Z'G dd de'Z(G dd de'Z)G dd de'Z*d d! Z+d"d# Z,d$d% Z-d&d' Z.d(d) Z/dS )*zVirtual 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)commonz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}.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.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 u ri }|| _d| _t | _d S )NF)
upload_url_headers	_finishedr   ZRetryStrategyZ_retry_strategy)selfr
   headers r   _/var/www/html/python-backend/venv/lib/python3.9/site-packages/google/resumable_media/_upload.py__init__R   s    zUploadBase.__init__c                 C   s   | j S )z2bool: Flag indicating if the upload has completed.)r   r   r   r   r   finishedZ   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_response_   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   t   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	   D   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   	transportr2   r3   timeoutr   r   r   transmit   s    zSimpleUpload.transmit)N)r"   r#   r$   r%   r4   r7   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 )MultipartUploada3  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   )superr8   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u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-   r.   r/   r   _get_checksum_objectr;   updateprepare_checksum_digestdigest_get_metadata_keyconstruct_multipart_request_RELATED_HEADERr   r0   r1   r
   )
r   r2   metadatar3   Zchecksum_objectZactual_checksummetadata_keycontentmultipart_boundaryZmultipart_content_typer   r   r   r4      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   r5   r2   rG   r3   r6   r   r   r   r7   3  s    zMultipartUpload.transmit)NN)N)r"   r#   r$   r%   r   r4   r7   __classcell__r   r   r=   r   r8      s   6r8   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 the :meth:`initiate` request, e.g. headers for
            encrypted data. These **will not** be sent with
            :meth:`transmit_next_chunk` or :meth:`recover` requests.
        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 )Nr9   r   z{} KB must divide chunk sizei   F)r:   rL   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   k  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`.
        rV   r   r   r   r   invalid~  s    zResumableUpload.invalidc                 C   s   | j S )z8int: The size of each chunk used to upload the resource.)rN   r   r   r   r   rW     s    zResumableUpload.chunk_sizec                 C   s   | j S )z;Optional[str]: The URL of the in-progress resumable upload.)rU   r   r   r   r   resumable_url  s    zResumableUpload.resumable_urlc                 C   s   | j S )z-int: Number of bytes that have been uploaded.)rQ   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.
        )rT   r   r   r   r   total_bytes  s    zResumableUpload.total_bytesTc                 C   s   | j durtd| dkr&td|| _|| _tj| j}tj	|j
}d|v s^d|v rri | jt|i}ni | jtdd|i}|dur|| _n|rt|| _| jdu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/
        Nz'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)rZ   r+   tellrO   rP   urllibparseurlparser
   parse_qsqueryr   r0   rT   get_total_bytesrM   jsondumpsencoder1   )r   streamrG   r3   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    rU   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   r5   rh   rG   r3   r\   ri   r6   r   r   r   initiate  s    3zResumableUpload.initiatec                 C   s   | j rtd| jrtd| jdu r.tdt| j| j| j\}}}|| jkrft	
|| j}t|| || i | 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 **do not** 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+   rY   rZ   get_next_chunkrO   rN   rT   r[   _STREAM_ERROR_TEMPLATErM   _update_checksumr   r0   rP   r   CONTENT_RANGE_HEADER_PUT)r   
start_byterk   content_rangemsgr   r   r   r   r4   <  s0    


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;   rS   r   r@   rR   rA   len)r   rz   rk   offsetr2   r   r   r   rw   v  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.
        TNrX   r   r   r   r   rq     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u 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/
        rm   TNUnexpected "range" header*Expected to be of the form "bytes=0-{end}"end_byter   )r   r   r   r   r   PERMANENT_REDIRECTr   rq   rQ   r   _validate_checksumrr   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u rdS t| j }| }||}|du rNt|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   rD   re   getr   r   0_UPLOAD_METADATA_NO_APPROPRIATE_CHECKSUM_MESSAGErM   r    rB   rS   rC   ZDataCorruption!_UPLOAD_CHECKSUM_MISMATCH_MESSAGEupper)r   r   rH   rG   Zremote_checksumZ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   r5   r6   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   rx   ry   rZ   )r   r   r   r   r   _prepare_recover_request	  s    
z(ResumableUpload._prepare_recover_requestc                 C   s   t |tjjf| j | |}t j|v rl|t j }t	|}|du 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   rQ   rO   seekrV   )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   r5   r   r   r   recoverK  s    zResumableUpload.recover)NN)NT)NTN)N)r"   r#   r$   r%   r   r&   rY   rW   rZ   r[   r\   rl   rs   rt   r4   rw   rq   r   r   r   r   r   r   rK   r   r   r=   r   rL   L  s8   




 
I    
5:	;!
)rL   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.
    r]   )random	randrangesysmaxsize_BOUNDARY_FORMATrM   rg   )Z
random_intboundaryr   r   r   get_boundary_  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.
    r]   s   content-type: )r   re   rf   rg   _MULTIPART_SEP_MULTIPART_BEGIN_CRLF)r2   rG   r3   rJ   Z
json_bytesZboundary_seprI   r   r   r   rE   l  sB    
	
rE   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   )r^   r   osSEEK_END)rh   current_positionZend_positionr   r   r   rd     s
    	
rd   c                 C   s   |   }|dur<|| |  kr(dkr<n n| || }n
| |}|   d }t|}|du 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.)r^   readr}   r+   get_content_range)rh   rW   r\   rz   rk   r   Znum_bytes_readr{   r   r   r   ru     s(    $

ru   c                 C   s8   |du 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_TEMPLATErM   _EMPTY_RANGE_TEMPLATE_CONTENT_RANGE_TEMPLATE)rz   r   r\   r   r   r   r     s
    
r   )0r%   http.clientr   re   r   r   rer   urllib.parser_   Zgoogler   Zgoogle.resumable_mediar   r   r0   r   r   r   r}   strr   Z_BOUNDARY_WIDTHrM   r   r   r   r   rF   compile
IGNORECASEr   rv   Z_STREAM_READ_PAST_TEMPLATEr1   ry   r   r   objectr	   r(   r8   rL   r   rE   rd   ru   r   r   r   r   r   <module>   sX   	
ULg    )9