
    gP                     8   d Z ddlZddlZddlmZ ddlmZ  ej                  dej                        Z	ej                  j                  ej                  j                  fZdZdZ G d	 d
e      Z G d de      Z G d de      Zd Zej*                  fdZd Zy)z=Virtual bases classes for downloading media from Google APIs.    N)_helpers)commonz@bytes (?P<start_byte>\d+)-(?P<end_byte>\d+)/(?P<total_bytes>\d+))flagsGETz	bytes */0c                   X    e Zd ZdZddZed        Zed        Zed        Z	ed        Z
y)	DownloadBasea:  Base class for download helpers.

    Defines core shared behavior across different download types.

    Args:
        media_url (str): The URL containing the media to be downloaded.
        stream (IO[bytes]): A write-able stream (i.e. file-like object) that
            the downloaded resource can be written to.
        start (int): The first byte in a range to be downloaded.
        end (int): The last byte in a range to be downloaded.
        headers (Optional[Mapping[str, str]]): Extra headers that should
            be sent with the request, e.g. headers for encrypted data.

    Attributes:
        media_url (str): The URL containing the media to be downloaded.
        start (Optional[int]): The first byte in a range to be downloaded.
        end (Optional[int]): The last byte in a range to be downloaded.
    Nc                     || _         || _        || _        || _        |i }|| _        d| _        t        j                         | _        y )NF)		media_url_streamstartend_headers	_finishedr   RetryStrategy_retry_strategy)selfr
   streamr   r   headerss         }/var/www/html/FastMealFinder_FlaskServer-InitialRelease/venv/lib/python3.12/site-packages/google/resumable_media/_download.py__init__zDownloadBase.__init__6   sG    "
?G%335    c                     | j                   S )z4bool: Flag indicating if the download has completed.)r   r   s    r   finishedzDownloadBase.finishedA   s     ~~r   c                     t        d      )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responses    r   _get_status_codezDownloadBase._get_status_codeF        ""CDDr   c                     t        d      )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_headerszDownloadBase._get_headersR   r"   r   c                     t        d      )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_bodyzDownloadBase._get_body^   r"   r   )NNNN)__name__
__module____qualname____doc__r   propertyr   staticmethodr!   r$   r&    r   r   r   r   "   sb    &	6   	E 	E 	E 	E 	E 	Er   r   c                   :     e Zd ZdZ	 d fd	Zd Zd ZddZ xZS )Downloada  Helper to manage downloading a resource from a Google API.

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

    Args:
        media_url (str): The URL containing the media to be downloaded.
        stream (IO[bytes]): A write-able stream (i.e. file-like object) that
            the downloaded resource can be written to.
        start (int): The first byte in a range to be downloaded. If not
            provided, but ``end`` is provided, will download from the
            beginning to ``end`` of the media.
        end (int): The last byte in a range to be downloaded. If not
            provided, but ``start`` is provided, will download from the
            ``start`` to the end of the media.
        headers (Optional[Mapping[str, str]]): Extra headers that should
            be sent with the request, e.g. headers for encrypted data.
        checksum Optional([str]): The type of checksum to compute to verify
            the integrity of the object. The response headers must contain
            a checksum of the requested type. If the headers lack an
            appropriate checksum (for instance in the case of transcoded or
            ranged downloads where the remote service does not know the
            correct checksum) an INFO-level log will be emitted. Supported
            values are "md5", "crc32c" and None.
    c                 |    t         t        |   |||||       || _        d| _        d | _        d | _        d | _        y )Nr   r   r   r   r   )superr/   r   checksum_bytes_downloaded_expected_checksum_checksum_object_object_generation)r   r
   r   r   r   r   r3   	__class__s          r   r   zDownload.__init__   sM     	h&fEsG 	' 	
 !!""& $"&r   c                     | j                   rt        d      t        | j                  | j                  | j
                         t        | j                  d| 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.

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

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

        Raises:
            ValueError: If the current :class:`Download` has already
                finished.

        .. _sans-I/O: https://sans-io.readthedocs.io/
        z!A download can only be used once.N)r   
ValueErroradd_bytes_ranger   r   r   _GETr
   r   s    r   _prepare_requestzDownload._prepare_request   sF    * ==@AA

DHHdmm<T^^T4==88r   c                 \    d| _         t        j                  |t        | j                         y)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.

        .. _sans-I/O: https://sans-io.readthedocs.io/
        TN)r   r   require_status_code_ACCEPTABLE_STATUS_CODESr!   )r   r    s     r   _process_responsezDownload._process_response   s'     $$.0E0E	
r   c                     t        d      )a  Consume the resource to be downloaded.

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

        Args:
            transport (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   	transporttimeouts      r   consumezDownload.consume   s    ( ""CDDr   )NNNNmd5N)	r'   r(   r)   r*   r   r=   rA   rF   __classcell__r8   s   @r   r/   r/   k   s$    8 TY
'96
$Er   r/   c                   t     e Zd ZdZd fd	Zed        Zed        Zed        Zd Z	d Z
d Zd	 Zdd
Z xZS )ChunkedDownloada  Download a resource in chunks from a Google API.

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

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

    Raises:
        ValueError: If ``start`` is negative.
    c                     |dk  rt        d      t        t        |   |||||       || _        d| _        d | _        d| _        y )Nr   z<On a chunked download the starting value cannot be negative.r1   F)r:   r2   rL   r   
chunk_sizer4   _total_bytes_invalid)r   r
   rN   r   r   r   r   r8   s          r   r   zChunkedDownload.__init__   s[    19Q  	ot-fEsG 	. 	
 %!" r   c                     | j                   S )z/int: Number of bytes that have been downloaded.)r4   r   s    r   bytes_downloadedz ChunkedDownload.bytes_downloaded   s     %%%r   c                     | j                   S )z:Optional[int]: The total number of bytes to be downloaded.)rO   r   s    r   total_byteszChunkedDownload.total_bytes  s        r   c                     | j                   S )zbool: Indicates if the download is in an invalid state.

        This will occur if a call to :meth:`consume_next_chunk` fails.
        rP   r   s    r   invalidzChunkedDownload.invalid
  s     }}r   c                     | j                   | j                  z   }|| j                  z   dz
  }| j                  t	        || j                        }| j
                  t	        || j
                  dz
        }||fS )zDetermines the byte range for the next request.

        Returns:
            Tuple[int, int]: The pair of begin and end byte for the next
            chunked request.
           )r   rR   rN   r   minrT   r   
curr_startcurr_ends      r   _get_byte_rangezChunkedDownload._get_byte_range  ss     ZZ$"7"77
/!3888TXX.H'8T%5%5%9:H8##r   c                     | j                   rt        d      | j                  rt        d      | j                         \  }}t	        ||| j
                         t        | j                  d| 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 multiple times, so ``headers`` will
            be mutated in between requests. However, we don't make a copy
            since the same keys are being updated.

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

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

        Raises:
            ValueError: If the current download has finished.
            ValueError: If the current download is invalid.

        .. _sans-I/O: https://sans-io.readthedocs.io/
        zDownload has finished.z*Download is invalid and cannot be re-used.N)r   r:   rW   r^   r;   r   r<   r
   r[   s      r   r=   z ChunkedDownload._prepare_request#  sd    6 ==566<<IJJ#335
H
Hdmm<T^^T4==88r   c                     d| _         y)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.
        TNrV   r   s    r   _make_invalidzChunkedDownload._make_invalidG  s     r   c           
      Z   t        || j                  | j                        rd| _        yt	        j
                  |t        | j                  | j                         | j                  |      }| j                  |      }t        || j                  | j                        \  }}}|j                  d      }|yt	        j                  |d| j                  | j                        }t        |      }	t        |      |	k7  r;| j                          t        j                  |dd|	dt        |            ||z
  d	z   }	| xj                   |	z  c_        | j"                  || j"                  k\  rd| _        n||d	z
  k\  rd| _        | j$                  || _        | j(                  j+                  |       y)
al  Process the response from an HTTP request.

        This is everything that must be done after 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 write
        a chunk to ``stream``. However, this will (almost) certainly not be
        network I/O.

        Updates the current state after consuming a chunk. First,
        increments ``bytes_downloaded`` by the number of bytes in the
        ``content-length`` header.

        If ``total_bytes`` is already set, this assumes (but does not check)
        that we already have the correct value and doesn't bother to check
        that it agrees with the headers.

        We expect the **total** length to be in the ``content-range`` header,
        but this header is only present on requests which sent the ``range``
        header. This response header should be of the form
        ``bytes {start}-{end}/{total}`` and ``{end} - {start} + 1``
        should be the same as the ``Content-Length``.

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

        Raises:
            ~google.resumable_media.common.InvalidResponse: If the number
                of bytes in the body doesn't match the content length header.

        .. _sans-I/O: https://sans-io.readthedocs.io/
        TNcallbackztransfer-encodingzcontent-lengthz.Response is different size than content-lengthExpectedReceivedrY   )_check_for_zero_content_ranger!   r$   r   r   r?   r@   ra   r&   get_range_infogetheader_requiredintlenr   InvalidResponser4   r   rT   rO   r   write)
r   r    r   response_body
start_byteend_byterT   transfer_encodingcontent_length	num_bytess
             r   rA   z!ChunkedDownload._process_responseP  s   D )d++T->->
 "DN$$$!!''		
 ##H-x0,:d''$2D2D-
)
Hk $KK(;<$%55 !!++	N N+I=!Y.""$,,D&  !:-1I 	)+88H$8!DNq(!DN# +D=)r   c                     t        d      )a  Consume the next chunk of the resource to be downloaded.

        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   rC   s      r   consume_next_chunkz"ChunkedDownload.consume_next_chunk  s    " ""CDDr   )r   NNrH   )r'   r(   r)   r*   r   r+   rR   rT   rW   r^   r=   ra   rA   rv   rI   rJ   s   @r   rL   rL      sf    6 & & ! !  $""9HX*tEr   rL   c                     | |ydj                  |      }n=|)| dk  rdj                  |       }n$dj                  |       }ndj                  | |      }d|z   |t        j                  <   y)a  Add a bytes range to a header dictionary.

    Some possible inputs and the corresponding bytes ranges::

       >>> headers = {}
       >>> add_bytes_range(None, None, headers)
       >>> headers
       {}
       >>> add_bytes_range(500, 999, headers)
       >>> headers['range']
       'bytes=500-999'
       >>> add_bytes_range(None, 499, headers)
       >>> headers['range']
       'bytes=0-499'
       >>> add_bytes_range(-500, None, headers)
       >>> headers['range']
       'bytes=-500'
       >>> add_bytes_range(9500, None, headers)
       >>> headers['range']
       'bytes=9500-'

    Args:
        start (Optional[int]): The first byte in a range. Can be zero,
            positive, negative or :data:`None`.
        end (Optional[int]): The last byte in a range. Assumed to be
            positive.
        headers (Mapping[str, str]): A headers mapping which can have the
            bytes range added if at least one of ``start`` or ``end``
            is not :data:`None`.
    Nz0-{:d}r   z{:d}z{:d}-z	{:d}-{:d}zbytes=)formatr   RANGE_HEADER)r   r   r   bytes_ranges       r   r;   r;     sr    > }; #//#.K;qy$mmE2%nnU3 &,,UC8K%-%;GH!!"r   c                 V   t        j                  | t         j                  ||      }t        j	                  |      }| |        t        j                  | d|d      t        |j                  d            t        |j                  d            t        |j                  d            fS )a  Get the start, end and total bytes from a content range header.

    Args:
        response (object): An HTTP response object.
        get_headers (Callable[Any, Mapping[str, str]]): Helper to get headers
            from an HTTP response.
        callback (Optional[Callable]): A callback that takes no arguments,
            to be executed when an exception is being raised.

    Returns:
        Tuple[int, int, int]: The start byte, end byte and total bytes.

    Raises:
        ~google.resumable_media.common.InvalidResponse: If the
            ``Content-Range`` header is not of the form
            ``bytes {start}-{end}/{total}``.
    rc   zUnexpected content-range headerz8Expected to be of the form "bytes {start}-{end}/{total}"rp   rq   rT   )	r   rj   CONTENT_RANGE_HEADER_CONTENT_RANGE_REmatchr   rm   rk   group)r    get_headersrd   content_ranger~   s        r   rh   rh     s    $ ,,(//xM ##M2E}
$$-F	
 	
 	EKK%&EKK
#$EKK&' r   c                      ||       t         j                  j                  k(  r?t        j                  | t        j
                  |t        j                        }|t        k(  ryy)a  Validate if response status code is 416 and content range is zero.

    This is the special case for handling zero bytes files.

    Args:
        response (object): An HTTP response object.
        get_status_code (Callable[Any, int]): Helper to get a status code
            from a response.
        get_headers (Callable[Any, Mapping[str, str]]): Helper to get headers
            from an HTTP response.

    Returns:
        bool: True if content range total bytes is zero, false otherwise.
    rc   TF)httpclientREQUESTED_RANGE_NOT_SATISFIABLEr   rj   r|   
do_nothing_ZERO_CONTENT_RANGE_HEADER)r    get_status_coder   r   s       r   rg   rg     sT     x DKK$O$OO 00))((	
 66r   )r*   http.clientr   regoogle.resumable_mediar   r   compile
IGNORECASEr}   r   OKPARTIAL_CONTENTr@   r<   r   objectr   r/   rL   r;   r   rh   rg   r-   r   r   <module>r      s    D  	 + ) BJJG
--  !KKNNDKK,G,GH ( FE6 FERiE| iEXdEl dEN0<f 4<3F3F #Lr   