
    (phV                        S r SSKrSSKrSSKrSSKrSSKrSSKrSSKr	SSK
Jr  SSKJr  SSKJr  SSKJr  SrSrS	rS
r\" \" \R.                  S-
  5      5      rSR3                  \5      rSrSrSrSr\R>                  " S\R@                  S9r!Sr"Sr#Sr$Sr%Sr&Sr'Sr(Sr)Sr*Sr+Sr,Sr-Sr. " S  S!\/5      r0 " S" S#\05      r1 " S$ S%\05      r2 " S& S'\05      r3 " S( S)\05      r4 " S* S+\05      r5S, r6S- r7S. r8S/ r9S0 r:g)1zVirtual 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/}UploadIdz?uploadId={upload_id}c                   h    \ rS rSrSrSS jr\S 5       rS r\	S 5       r
\	S 5       r\	S	 5       rS
rg)
UploadBaseO   a|  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                 h    Xl         Uc  0 nX l        SU l        [        R                  " 5       U l        g )NF)
upload_url_headers	_finishedr   RetryStrategy_retry_strategy)selfr   headerss      Q/var/www/html/venv/lib/python3.13/site-packages/google/resumable_media/_upload.py__init__UploadBase.__init__]   s.    $?G%335    c                     U R                   $ )z2bool: Flag indicating if the upload has completed.)r   r   s    r   finishedUploadBase.finishede   s     ~~r   c                     SU l         [        R                  " U[        R                  R
                  4U R                  5        g)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   responses     r   _process_responseUploadBase._process_responsej   s.    $ $$X/@$BWBWXr   c                     [        S5      e)zAccess the status code from an HTTP response.

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

Raises:
    NotImplementedError: Always, since virtual.
This implementation is virtual.NotImplementedErrorr'   s    r   r%   UploadBase._get_status_code        ""CDDr   c                     [        S5      e)zAccess the headers from an HTTP response.

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

Raises:
    NotImplementedError: Always, since virtual.
r+   r,   r.   s    r   _get_headersUploadBase._get_headers   r0   r   c                     [        S5      e)zAccess the response body from an HTTP response.

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

Raises:
    NotImplementedError: Always, since virtual.
r+   r,   r.   s    r   	_get_bodyUploadBase._get_body   r0   r   )r   r   r   r   N)__name__
__module____qualname____firstlineno____doc__r   propertyr   r(   staticmethodr%   r2   r5   __static_attributes__ r   r   r   r   O   sh    6  Y* 	E 	E 	E 	E 	E 	Er   r   c                   (    \ rS rSrSrS rSS jrSrg)SimpleUpload   a  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                     U R                   (       a  [        S5      e[        U[        5      (       d  [	        S[        U5      5      eX R                  [        '   [        U R                  XR                  4$ )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_types      r   _prepare_requestSimpleUpload._prepare_request   sX    < ==?@@$&&<d4jII.:*+doot]]::r   Nc                     [        S5      e)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+   r,   )r   	transportrN   rO   timeouts        r   transmitSimpleUpload.transmit   s    ( ""CDDr   r@   r7   )r8   r9   r:   r;   r<   rP   rU   r?   r@   r   r   rB   rB      s    $;LEr   rB   c                   @   ^  \ rS rSrSrSU 4S jjrS rSS jrSrU =r	$ )	MultipartUpload   a  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.
c                 4   > [         [        U ]  XS9  X0l        g Nr   )superrX   r   _checksum_type)r   r   r   checksum	__class__s       r   r   MultipartUpload.__init__  s    ot-j-J&r   c                    U R                   (       a  [        S5      e[        U[        5      (       d  [	        S[        U5      5      e[        R                  " U R                  5      nUbY  UR                  U5        [        R                  " UR                  5       5      n[        R                  " U R                  5      nXRU'   [        XU5      u  px[        U-   S-   n	XR                  [         '   ["        U R$                  XpR                  4$ )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.
    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/
rE   rF      ")r   rG   rH   rI   rJ   rK   r   _get_checksum_objectr^   updateprepare_checksum_digestdigest_get_metadata_keyconstruct_multipart_request_RELATED_HEADERr   rL   rM   r   )
r   rN   metadatarO   checksum_objectactual_checksummetadata_keycontentmultipart_boundarymultipart_content_types
             r   rP    MultipartUpload._prepare_request  s    B ==?@@$&&<d4jII"778K8KL&""4(&>>?U?U?WXO#55d6I6IJL%4\"&AL'
# "13E!E!L.D*+doow==r   c                     [        S5      e)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+   r,   )r   rS   rN   rk   rO   rT   s         r   rU   MultipartUpload.transmit>      , ""CDDr   )r^   NNr7   )
r8   r9   r:   r;   r<   r   rP   rU   r?   __classcell__r`   s   @r   rX   rX      s    &'4>lE Er   rX   c                      ^  \ rS rSrSrSU 4S jjr\S 5       r\S 5       r\S 5       r	\S 5       r
\S 5       r SS	 jrS
 r   SS jrS rS rS rS rS rSS jrS rS rS rSrU =r$ )ResumableUploadiW  a  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`.
c                 4  > [         [        U ]  XS9  U[        R                  -  S:w  a+  [        SR                  [        R                  S-  5      5      eX l        S U l        S U l	        SU l
        SU l        X0l        S U l        S U l        S U l        SU l        g )Nr\   r   z{} KB must divide chunk sizei   F)r]   rz   r   r   UPLOAD_CHUNK_SIZErG   format_chunk_size_stream_content_type_bytes_uploaded_bytes_checksummedr^   _checksum_object_total_bytes_resumable_url_invalid)r   r   
chunk_sizer_   r   r`   s        r   r   ResumableUpload.__init__t  s    ot-j-J999Q>.55#55< 
 &! "#& $ "r   c                     U R                   $ )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`.
r   r   s    r   invalidResumableUpload.invalid  s     }}r   c                     U R                   $ )z8int: The size of each chunk used to upload the resource.)r~   r   s    r   r   ResumableUpload.chunk_size  s     r   c                     U R                   $ )z;Optional[str]: The URL of the in-progress resumable upload.)r   r   s    r   resumable_urlResumableUpload.resumable_url  s     """r   c                     U R                   $ )z-int: Number of bytes that have been uploaded.)r   r   s    r   bytes_uploadedResumableUpload.bytes_uploaded  s     ###r   c                     U R                   $ )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.
)r   r   s    r   total_bytesResumableUpload.total_bytes  s        r   c                    U R                   b  [        S5      eUR                  5       S:w  a  [        S5      eXl        X0l        [
        R                  R                  U R                  5      n[
        R                  R                  UR                  5      nSU;   d  SU;   a  0 U R                  E[        U0EnO0 U R                  E[        SSU0EnUb  X@l        OU(       a  [        U5      U l        U R                  b  SR                  U R                  5      n	XS	'   [         R"                  " U5      R%                  S
5      n
[&        U R                  X4$ )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/
'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   rG   tellr   r   urllibparseurlparser   parse_qsqueryr   rL   r   get_total_bytesr}   jsondumpsencoderM   )r   streamrk   rO   r   stream_finalparse_resultparsed_queryr   content_lengthpayloads              r   _prepare_initiate_request)ResumableUpload._prepare_initiate_request  s0   N )FGG;;=A;<<) ||,,T__=||,,\-?-?@-1C|1SKK(<lKG--$&G'G " + / 7D(#]]4+<+<=N1?-.**X&--g6doow77r   c                    [         R                  " U[        R                  R                  [        R                  R
                  4U R                  U R                  S9  [         R                  " USU R                  5      U l
        g)a  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_requiredr2   r   r&   s     r   _process_initiate_response*ResumableUpload._process_initiate_response  sc      	$$[[^^T[[001!!''		
 '66j$"3"3
r   c                     [        S5      e)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+   r,   )r   rS   r   rk   rO   r   r   rT   s           r   initiateResumableUpload.initiate  s    f ""CDDr   c                    U R                   (       a  [        S5      eU R                  (       a  [        S5      eU R                  c  [        S5      e[	        U R
                  U R                  U R                  5      u  pnXR                  :w  a*  [        R                  XR                  5      n[        U5      eU R                  X5        0 U R                  E[        U R                  [        R                   U0En["        U R                  X%4$ )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()`.z_This upload has not been initiated. Please call initiate() before beginning to transmit chunks.)r   rG   r   r   get_next_chunkr   r~   r   r   _STREAM_ERROR_TEMPLATEr}   _update_checksumr   rL   r   r   CONTENT_RANGE_HEADER_PUT)r   
start_byter   content_rangemsgr   s         r   rP    ResumableUpload._prepare_requestE  s    : ==344<<M  %B 
 .<LL$**D,=,=.
*
] ,,,(//
<O<OPCS/!j2
mm
 $"4"4))=

 T''99r   c                 P   U R                   (       d  gU R                  (       d%  [        R                  " U R                   5      U l        XR                  :  a  U R                  U-
  nX#S nOUnU R                  R                  U5        U =R                  [        U5      -  sl        g)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^   r   r   rd   r   re   len)r   r   r   offsetrN   s        r   r    ResumableUpload._update_checksum~  s     ""$$$,$A$A$BUBU$VD!///,,z9F7#DD$$T*3t9,r   c                     SU l         g)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   s    r   r   ResumableUpload._make_invalid  s     r   c                    [         R                  " U[        R                  R                  [        R                  R
                  4U R                  U R                  S9nU[        R                  R                  :X  a-  U R                  U-   U l        SU l	        U R                  U5        g[         R                  " U[         R                  U R                  U R                  S9n[        R                  U5      nUc)  U R                  5         [         R"                  " USUS5      e[%        UR'                  S5      5      S-   U l        g)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/
r   TNUnexpected "range" header*Expected to be of the form "bytes=0-{end}"end_byter   )r   r!   r"   r#   r$   PERMANENT_REDIRECTr%   r   r   r   _validate_checksumr   RANGE_HEADERr2   _BYTES_RANGE_REmatchr   InvalidResponseintgroup)r   r'   
bytes_sentstatus_codebytes_ranger   s         r   _process_resumable_response+ResumableUpload._process_resumable_response  s   * 22[[^^T[[;;<!!''	
 $++..( $(#7#7*#DD !DN##H-"22%%!!++	K $))+6E}""$,,/@	  $'u{{:'>#?!#CD r   c                    U R                   c  g[        R                  " U R                   5      nUR                  5       nUR	                  U5      nUc:  [
        R                  " U[        R                  U5      U R                  U5      5      e[        R                  " U R                  R                  5       5      nXT:w  aC  [
        R                  " U[        R                  U R                   R                  5       XT5      5      eg)a  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   rh   r   getr   r   0_UPLOAD_METADATA_NO_APPROPRIATE_CHECKSUM_MESSAGEr}   r2   rf   r   rg   DataCorruption!_UPLOAD_CHECKSUM_MISMATCH_MESSAGEupper)r   r'   rn   rk   remote_checksumlocal_checksums         r   r   "ResumableUpload._validate_checksum  s     &11$2E2EF==?",,|4"((@GGU!!(+ 
 "99!!((*
 ,''188''--/  -r   c                     [        S5      e)aT  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+   r,   r   rS   rT   s      r   transmit_next_chunk#ResumableUpload.transmit_next_chunk  ru   r   c                 N    [         R                  S0n[        U R                  SU4$ )a  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   s     r   _prepare_recover_request(ResumableUpload._prepare_recover_request  s)    , 00+>T''w66r   c                    [         R                  " U[        R                  R                  4U R
                  5        U R                  U5      n[         R                  U;   ag  U[         R                     n[        R                  U5      nUc  [        R                  " USUS5      e[        UR                  S5      5      S-   U l        OSU l        U R                  R!                  U R                  5        SU l        g)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%   r2   r   r   r   r   r   r   r   r   r   seekr   )r   r'   r   r   r   s        r   _process_recover_response)ResumableUpload._process_recover_response*  s    & 	$$t{{5579N9N	
 ##H-  G+!("7"78K#))+6E},,/@	  $'u{{:'>#?!#CD  $%D $../r   c                     [        S5      e)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+   r,   )r   rS   s     r   recoverResumableUpload.recoverS  s    " ""CDDr   )r   r   r   r^   r~   r   r   r   r   r   r   rv   )NT)NTNr7   )r8   r9   r:   r;   r<   r   r=   r   r   r   r   r   r   r   r   rP   r   r   r   r   r   r   r   r   r?   rw   rx   s   @r   rz   rz   W  s    8&       # # $ $ ! ! NRG8R
@ 3Ej7:r-,9DvBE072'RE Er   rz   c                      ^  \ rS rSrSrSU 4S jjr\S 5       rS rS r	S r
 SS jrS	 rS
 r SS jrS rS r SS jrSrU =r$ )XMLMPUContainerig  a  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.
c                 F   > [         TU ]  XS9  X l        X@l        0 U l        g r[   )r]   r   	_filename
_upload_id_parts)r   r   filenamer   	upload_idr`   s        r   r   XMLMPUContainer.__init__  s$    5!#r   c                     U R                   $ r7   r   r   s    r   r   XMLMPUContainer.upload_id      r   c                      X R                   U'   g)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etags      r   register_partXMLMPUContainer.register_part  s    " $(K r   c                     U R                   b  [        S5      eU R                  [        -   n0 U R                  E[
        U0En[        USU4$ )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   rG   r   _MPU_INITIATE_QUERYr   rL   rM   )r   rO   initiate_urlr   s       r   r   )XMLMPUContainer._prepare_initiate_request  sW    0 >>%FGG)<<
mm
 ,
 lD'11r   c                    [         R                  " U[        R                  R                  4U R
                  5        [        R                  " UR                  5      nUR                  [        [        -   5      R                  U l        g)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'   roots      r   r   *XMLMPUContainer._process_initiate_response  sW    ( 	$$X/@$BWBWX%%hmm4))$<$NOTTr   c                     [        S5      e)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+   r,   )r   rS   rO   rT   s       r   r   XMLMPUContainer.initiate  s    0 ""CDDr   c                    U R                   c  [        S5      e[        R                  U R                  S9nU R
                  U-   n[        R                  " S5      nU R                  R                  5        H]  u  pE[        R                  " US5      n[        U5      [        R                  " US5      l        U[        R                  " US5      l        M_     [        R                  " U5      n[        X'U R                  4$ )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.
'This upload has not yet been initiated.r   CompleteMultipartUploadPart
PartNumberETag)r   rG   _MPU_FINAL_QUERY_TEMPLATEr}   r   r   r   Elementr   items
SubElementstrr	  tostringrM   r   )r   final_queryfinalize_urlfinal_xml_rootr   r   partr   s           r   _prepare_finalize_request)XMLMPUContainer._prepare_finalize_request  s      >>!FGG/666Q4$,,-FG!%!2!2!4K)).&AD>A+>NK""46;8<K""405 "5 &&~6lT]]::r   c                     [         R                  " U[        R                  R                  4U R
                  5        SU l        g)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&   s     r   _process_finalize_response*XMLMPUContainer._process_finalize_response  s.    " 	$$X/@$BWBWXr   c                     [        S5      e)aB  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+   r,   r   s      r   finalizeXMLMPUContainer.finalize+      * ""CDDr   c                     U R                   c  [        S5      e[        R                  U R                  S9nU R
                  U-   n[        USU R                  4$ )aW  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   rG   r  r}   r   r   _DELETEr   )r   cancel_query
cancel_urls      r   _prepare_cancel_request'XMLMPUContainer._prepare_cancel_requestB  sR     >>!FGG077$//7R__|3

D$--77r   c                 z    [         R                  " U[        R                  R                  4U R
                  5        g)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&   s     r   _process_cancel_response(XMLMPUContainer._process_cancel_responseW  s,    " 	$$t{{--/1F1F	
r   c                     [        S5      e)ao  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+   r,   r   s      r   cancelXMLMPUContainer.cancell  s    . ""CDDr   )r   r   r   r   rv   r7   )r8   r9   r:   r;   r<   r   r=   r   r  r   r   r   r"  r%  r(  r/  r3  r6  r?   rw   rx   s   @r   r   r   g  sn    @  (&!2FU8 	E4;:. E.8*
0 E Er   r   c                      ^  \ rS rSrSr  SU 4S jjr\S 5       r\S 5       r\S 5       r	\S 5       r
\S 5       r\S	 5       rS
 rS r SS jrS rSrU =r$ )
XMLMPUParti  a8  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.
c	                    > [         T	U ]  XS9  X0l        X@l        XPl        X l        X`l        S U l        Xl        S U l	        g r[   )
r]   r   r   _start_endr   _part_number_etagr^   r   )
r   r   r   r   startendr   r   r_   r`   s
            r   r   XMLMPUPart.__init__  sD     	5!	#'
& $r   c                     U R                   $ r7   )r=  r   s    r   r   XMLMPUPart.part_number  s       r   c                     U R                   $ r7   r   r   s    r   r   XMLMPUPart.upload_id  r   r   c                     U R                   $ r7   )r   r   s    r   r   XMLMPUPart.filename  s    ~~r   c                     U R                   $ r7   )r>  r   s    r   r   XMLMPUPart.etag  s    zzr   c                     U R                   $ r7   )r;  r   s    r   r?  XMLMPUPart.start  s    {{r   c                     U R                   $ r7   )r<  r   s    r   r@  XMLMPUPart.end  s    yyr   c                 P   U R                   (       a  [        S5      e[        U R                  S5       nUR	                  U R
                  5        UR                  U R                  U R
                  -
  5      nSSS5        [        R                  " U R                  5      U l        U R                  b  U R                  R                  W5        [        R                  U R                  U R                   S9nU R"                  U-   n[$        UWU R&                  4$ ! , (       d  f       N= f)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   rG   openr   r   r;  readr<  r   rd   r^   r   re   _MPU_PART_QUERY_TEMPLATEr}   r=  r   r   r   r   )r   fr   
part_queryr   s        r   _prepare_upload_request"XMLMPUPart._prepare_upload_request  s    2 ==CDD$..$'1FF4;;ffTYY45G ( !) = =d>Q>Q R  ,!!((1-44""doo 5 

 __z1
Z$--77 ('s   AD
D%c                     [         R                  " U[        R                  R                  4U R
                  5        U R                  U5        [         R                  " USU R                  5      nX l	        SU l
        g)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   r   r2   r>  r   )r   r'   r   s      r   _process_upload_response#XMLMPUPart._process_upload_response	  sb      	$$[[^^!!	
 	)''&$:K:KL
r   c                     [        S5      e)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+   r,   r   s      r   uploadXMLMPUPart.upload%  r*  r   c                    U R                   c  g[        R                  " XR                  U R                   5      nUcZ  [        R                  " U R                   5      n[
        R                  " U[        R                  U5      U R                  U5      5      e[        R                  " U R                  R                  5       5      nXB:w  aC  [
        R                  " U[        R                  U R                   R                  5       XB5      5      eg)a  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   #_get_uploaded_checksum_from_headersr2   rh   r   r   r   r}   rf   r   rg   r   r   r   )r   r'   r   rn   r   s        r   r   XMLMPUPart._validate_checksum<  s     &"FF'')<)<
 "#55d6I6IJL((@GGU!!(+ 
 "99!!((*
 ,''188''--/  -r   )	r   r^   r<  r>  r   r   r=  r;  r   rv   r7   )r8   r9   r:   r;   r<   r   r=   r   r   r   r   r?  r@  rU  rX  r[  r   r?   rw   rx   s   @r   r9  r9    s    )f %* ! !          (8T> E." "r   r9  c                      [         R                  " [        R                  5      n [        R                  U 5      nUR                  S5      $ )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_FORMATr}   r   )
random_intboundarys     r   get_boundaryrh  a  s9     !!#++.J&&z2H ??7##r   c                 $   [        5       n[        R                  " U5      R                  S5      nUR                  S5      n[        U-   nU[
        -   U-   [        -   U-   [        -   S-   U-   [        -   [        -   U -   [        -   U-   [        -   nXc4$ )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: )rh  r   r   r   _MULTIPART_SEP_MULTIPART_BEGIN_CRLF)rN   rk   rO   rp   
json_bytesboundary_sepro   s          r   ri   ri   n  s     &H%,,W5J&&w/L "$66L
	
	 	 		
 	 	 	 	 		 
	 	 	 	 " &&r   c                     U R                  5       nU R                  S[        R                  5        U R                  5       nU R                  U5        U$ )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)r   current_positionend_positions      r   r   r     sB     {{} KK2;;;;=L
KK !r   c                 `   U R                  5       nUb&  X1-   Us=:  a  S:  a  O  OU R                  X#-
  5      nOU R                  U5      nU R                  5       S-
  n[        U5      nUc  Xa:  a  US-   nO)US:X  a  US:w  a  [        S5      eOUS:X  a  [        S5      e[	        X5U5      nX4U4$ )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``.
r   r   z:Stream specified as empty, but produced non-empty content.z;Stream is already exhausted. There is no content remaining.)r   rQ  r   rG   get_content_range)r   r   r   r   r   r   num_bytes_readr   s           r   r   r     s    6 J:#:k#MA#M++k67++j){{}q H\N&"Q,K		 QL  
 QM  &jKHM--r   c                     Uc  [         R                  X5      $ X:  a  [        R                  U5      $ [        R                  XU5      $ )aP  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.
)_RANGE_UNKNOWN_TEMPLATEr}   _EMPTY_RANGE_TEMPLATE_CONTENT_RANGE_TEMPLATE)r   r   r   s      r   ru  ru    sE    & &--jCC		$++K88&--jKPPr   );r<   http.clientr"   r   rp  ra  rerc  urllib.parser   googler   google.resumable_mediar   r   	xml.etreer   rL   rz  rx  ry  r   r  rd  _BOUNDARY_WIDTHr}   re  rj  rl  rk  rj   compile
IGNORECASEr   r   _STREAM_READ_PAST_TEMPLATEr,  rM   r   r   r   ._UPLOAD_HEADER_NO_APPROPRIATE_CHECKSUM_MESSAGEr  rR  r  r  r  objectr   rB   rX   rz   r   r9  rh  ri   r   r   ru  r@   r   r   <module>r     s~     	  	 
  " + ) ! & 0 - & c#++/*+188I O 2**9O@   * "
 N 1 M / ! D F 3 RE REjIE: IEXdEj dENMEj ME`\Ej \E~X Xv
$&'R(6.rQr   