o
    i                     @   s  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mZ d dlm	Z	m
Z
mZmZmZmZmZmZmZmZmZmZmZmZmZ d dlmZmZmZ d dlmZ ddlmZ ddl m!Z!m"Z" dd	l#m$Z$m%Z% dd
l&m'Z'm(Z(m)Z)m*Z*m+Z+ erd dl m,Z, ddl&m-Z- ddl.m/Z/ ddl0m1Z1 ddl2m3Z3 ddl4m5Z5 ede6e7Z8de9de9dee9 dee7e	f ded deee9e9f ee9e9f f fddZ:de	de9de9dee7e	f de6f
dd Z;G d!d" d"e<Z=G d#d$ d$e<Z>G d%d& d&ee8 Z?dS )'    N)BytesIOStringIO)AnyCallablecastDict	GeneratorGenericIOIteratorListOptionaloverloadTupleTypeVarUnionTYPE_CHECKING)DecodeErrorHttpResponseErrorIncompleteReadError)with_current_context   )!validate_and_format_range_headers)parse_length_from_content_rangeprocess_storage_error)deserialize_blob_propertiesget_page_ranges_result)adjust_blob_size_for_encryptiondecrypt_blob&get_adjusted_download_range_and_offsetis_encryption_v2parse_encryption_data)IncrementalDecoder)_EncryptionData)AzureBlobStorage)BlobOperations)BlobProperties)StorageConfigurationTstart_range	end_rangelengthencryption_optionsencryption_datar#   returnc                 C   sB   d\}}| dd us| dd urt| |||S | |f||ffS )N)r   r   keyresolver)getr   )r)   r*   r+   r,   r-   start_offset
end_offset r4   S/home/app/Keep/.python/lib/python3.10/site-packages/azure/storage/blob/_download.pyprocess_range_and_offset,   s   r6   datar2   r3   
encryptionc              
   C   s   | d u rt ddt| }|r|dd us|dd urMzt|dp'd|d|d|||| jjW S  tyL } z	td| j|d|d }~ww |S )	NzResponse cannot be None.    r/   r0   requiredFzDecryption failed.)messageresponseerror)	
ValueErrorjoinlistr1   r   r<   headers	Exceptionr   )r7   r2   r3   r8   contentr=   r4   r4   r5   process_content>   s&    	rD   c                   @   sL  e Zd Z					d+dddededededed	ed
eeef ded dedee dee	eeef   dee
eee gdf  deddfddZdedeeef fddZdeeddf fddZdeddfddZdedeeef fddZdeddfdd Zd!ededdfd"d#Zd$ed%edefd&d'Zded(edeeef fd)d*ZdS ),_ChunkDownloaderNclientr%   
total_size
chunk_sizecurrent_progressr)   r*   validate_contentr,   r-   r#   streamparallelnon_empty_rangesprogress_hookkwargsr.   c                 K   s   || _ || _|| _|| _|| _|| _|
| _|rt nd | _	|r$t nd | _
|| _|r0|
 nd| _|| _|| _|	| _|| _|| _d S Nr   )rF   rM   rH   rG   start_index	end_indexrK   	threadingLockstream_lockprogress_lockrN   tellstream_startprogress_totalr,   r-   rJ   request_options)selfrF   rG   rH   rI   r)   r*   rJ   r,   r-   rK   rL   rM   rN   rO   r4   r4   r5   __init__U   s    
z_ChunkDownloader.__init__chunk_startc                 C   s0   || j  | jkr| j}||fS || j  }||fS N)rH   rR   r[   r]   	chunk_endr4   r4   r5   _calculate_range   s
   
z!_ChunkDownloader._calculate_rangec                 c   s4    | j }|| jk r|V  || j7 }|| jk s	d S d S r^   )rQ   rR   rH   )r[   indexr4   r4   r5   get_chunk_offsets   s   

z"_ChunkDownloader.get_chunk_offsetsc                 C   sP   |  |\}}| ||d \}}|| }|dkr&| || | | d S d S )Nr   r   )ra   _download_chunk_write_to_stream_update_progress)r[   r]   r`   
chunk_data_r+   r4   r4   r5   process_chunk   s   z_ChunkDownloader.process_chunkc                 C   s   |  |\}}| ||d S )Nr   )ra   rd   r_   r4   r4   r5   yield_chunk   s   z_ChunkDownloader.yield_chunkr+   c                 C   sh   | j r| j  |  j|7  _W d    n1 sw   Y  n|  j|7  _| jr2| | j| j d S d S r^   )rV   rY   rN   rG   )r[   r+   r4   r4   r5   rf      s   z!_ChunkDownloader._update_progressrg   c                 C   sf   | j r+| j  | j| j|| j   | j| W d    d S 1 s$w   Y  d S | j| d S r^   )rU   rK   seekrX   rQ   write)r[   rg   r]   r4   r4   r5   re      s   "z!_ChunkDownloader._write_to_streamgiven_range_startgiven_range_endc                 C   sB   | j d u rdS | j D ]}||d k r dS |d |k rq
 dS dS )NFstartTend)rM   )r[   rm   rn   Zsource_ranger4   r4   r5   _do_optimize   s   

z_ChunkDownloader._do_optimizer`   c              
   C   s  | j d u r	tdt|||| j | j\}}| |d |d r1|d |d  d }d| }||fS t|d |d | jd\}}d}	d}
|	rd }z| jjd||| j| j	| j
d| j\}}W n tyt } z
t| W Y d }~nd }~ww zt||d |d | j }d	}	W n) tttfy } z|
d8 }
|
dkrt||d
|td W Y d }~nd }~ww |	sE|j}| jdr|jj| jd _||fS )Nz0Required argument is missing: encryption_optionsr   r       )check_content_md5T   rangeZrange_get_content_md5rJ   data_stream_totaldownload_stream_currentFr=   modified_access_conditionsr4   )r,   r>   r6   r-   rq   r   rJ   rF   downloadrG   rY   rZ   r   r   rD   r   r   timesleepcontent_lengthr1   
propertiesetagif_match)r[   r]   r`   Zdownload_rangeoffsetr~   rg   range_headerrange_validationretry_activeretry_totalr<   rh   r=   r4   r4   r5   rd      s^   
'
z _ChunkDownloader._download_chunk)NNNNN)__name__
__module____qualname__intboolr   strr   r   r   r   r\   r   ra   r   rc   ri   bytesrj   rf   re   rq   rd   r4   r4   r4   r5   rE   T   sZ    
	

/
"rE   c                
   @   sr   e Zd ZdZdededee deddf
dd	Zdefd
dZ	de
e fddZdefddZeZdefddZdS )_ChunkIteratorz,Iterator for chunks in blob download stream.sizerC   
downloaderrH   r.   Nc                 C   s,   || _ || _|| _|| _d | _|dk| _d S rP   )r   _chunk_size_current_content_iter_downloader_iter_chunks	_complete)r[   r   rC   r   rH   r4   r4   r5   r\      s   z_ChunkIterator.__init__c                 C      | j S r^   r   r[   r4   r4   r5   __len__     z_ChunkIterator.__len__c                 C   s   | S r^   r4   r   r4   r4   r5   __iter__  s   z_ChunkIterator.__iter__c              
   C   s   | j rtd| jst| j| jkr|  S d| _ | jS | js%| j | _t| j| jkr1|  S zt	| j}|  j| j
|d 7  _W |  S  tye } zd| _ | jr_| jW  Y d }~S |d }~ww )NzDownload completeTr   )r   StopIterationr   lenr   r   _get_chunk_datar   rc   nextrj   )r[   
next_chunker4   r4   r5   __next__  s,   
	z_ChunkIterator.__next__c                 C   s&   | j d | j }| j | jd  | _ |S r^   )r   r   )r[   rg   r4   r4   r5   r   /  s   z_ChunkIterator._get_chunk_data)r   r   r   __doc__r   r   r   rE   r\   r   r   r   r   r   r   r4   r4   r4   r5   r      s    "r   c                   @   s  e Zd ZU dZeed< 	 eed< 	 ded< 	 eed< 	 											d9d	d
dddee dee dede	ee
f dedededee dee de
ddfddZdd Zd:ddZedd Zdd Zdee fd d!Zed;dedefd#d$Zedd%d&ee defd'd$Zd;dd%ded&ee defd(d$Zdefd)d*Zd+ee defd,d-Zd.d/ Zd0d1 Zd<d2d3Zd=d5d6Zd<d7d8ZdS )>StorageStreamDownloaderz<
    A streaming object to download from Azure Storage.
    name	containerr&   r   r   Nr   clientsr$   configr'   r)   r*   rJ   r,   max_concurrencyencodingdownload_clsrO   r.   c                 K   s  || _ |	| _d| _|| _|| _|| _|| _|| _|
| _|| _	|p!i | _
|dd | _|| _d | _d | _d| _d| _d | _d | _d| _d| _d| _d| _d | _d | _d| _| jpXd| _|| jd< | j
dd uso| j
dd urs|   | j	sz| jjn| jj}| j}| jd ur| j| |k r| j}n|| d }t ||| j| j
| j\| _!| _"| # | _t$d	| jj%| _%| j | j%_ | j| j%_| j| j%_d
| j d| jd ur| jn| jd  d| j | j%_&d | j%_'d S )Nr   rN   r9   Tclsr/   r0   r   r&   zbytes -/)(r   r   r   _clients_config_start_range
_end_range_max_concurrency	_encoding_validate_content_encryption_optionspop_progress_hook_request_options	_response_location_moder   
_file_size_non_empty_ranges_encryption_data_download_offset_raw_download_offset_read_offset_current_content_offset
_text_mode_decoder_first_chunk_download_startr1   _get_encryption_data_requestZmax_single_get_sizemax_chunk_get_sizer6   _initial_range_initial_offset_initial_requestr   r   content_rangeZcontent_md5)r[   r   r   r)   r*   rJ   r,   r   r   r   r   r   rO   Zfirst_get_sizeZinitial_request_startZinitial_request_endr4   r4   r5   r\   E  sl   

 





z StorageStreamDownloader.__init__c                 C   r   r^   r   r   r4   r4   r5   r     r   zStorageStreamDownloader.__len__c                 C   sr   | j dd }| j dd }t| j d< td| jjjdi | j }t|j| _	|| j d< |d ur7|| j d< d S d S )Nr   
decompressr&   r4   )
r   r   r   r   r   blobZget_propertiesr!   metadatar   )r[   r   r   r   r4   r4   r5   r     s   

z4StorageStreamDownloader._get_encryption_data_requestc                 C   s"   t | jr| j| jkS | j| jkS r^   )r    r   r   r   r   r   r4   r4   r5   _download_complete  s   
z*StorageStreamDownloader._download_completec                 C   s  t | jd | jd dd| jd\}}d}d}|r zftttt tf | jj	j
d||| jd dd| j\}}|| _t|jj| _| jd u rJtdt| j| j| _| jd urm| jd urmt| j| j | j| j d | _n| jd urz| j| j | _n| j| _W nV ty } zJ| jd u r|jr|jjd	krz| jj	j
d| jddd
| j\}}W n ty }	 z
t|	 W Y d }	~	nd }	~	ww d| _d| _nt| W Y d }~nd }~ww z| jdkrd| _nt|| jd | jd | j| _d}W n+ t tt!fy } z|d8 }|dkrt||d|t"#d W Y d }~nd }~ww |s|  j$t%| j7  _$|  j&|j'7  _&|jj(dkrSz| jj)* }
t+|
d | _,W n
 tyR   Y nw | j-sf| j.drf|jj/| jd _0|S )Nr   r   F)Zstart_range_requiredZend_range_requiredrs   Trt   ru   z?Required Content-Range response header is missing or malformed.i  )rJ   rw   rx   r9   ry   ZPageBlobrz   r4   )1r   r   r   r   r   r   r   r   r   r   r{   r   r   r   r   r   r   r>   r   r   r   r   minr   r   r<   status_coder   r   rD   r   r   r   r   r|   r}   r   r   r   r~   Z	blob_typeZ	page_blobZget_page_rangesr   r   r   r1   r   r   )r[   r   r   r   r   Zlocation_moder<   r=   rh   r   Zpage_rangesr4   r4   r5   r     s   

"



Dz(StorageStreamDownloader._initial_requestc                 C   s   | j rtd| jrtd d}| jr| jsQ| jr(| jt| j	 }t| j	}n| j}d}| j| j
 }td| jj| j| j
| jj|||| j| j| j| jd| j}| jrW| j	nd}t| j
tt||| jjdS )	a  
        Iterate over chunks in the download stream. Note, the iterator returned will
        iterate over the entire download content, regardless of any data that was
        previously read.

        NOTE: If the stream has been partially read, some data may be re-downloaded by the iterator.

        :return: An iterator of the chunks in the download stream.
        :rtype: Iterator[bytes]

        .. admonition:: Example:

            .. literalinclude:: ../samples/blob_samples_hello_world.py
                :start-after: [START download_a_blob_in_chunk]
                :end-before: [END download_a_blob_in_chunk]
                :language: python
                :dedent: 12
                :caption: Download a blob using chunks().
        zRStream has been partially read in text mode. chunks is not supported in text mode.z<Encoding is ignored with chunks as only bytes are supported.Nr   )rF   rM   rG   rH   rI   r)   r*   rJ   r,   r-   use_locationr9   )r   rC   r   rH   r4   )r   r>   r   warningswarnr   r   r   r   r   r   rE   r   r   r   r   r   r   r   r   r   r   r   r   r   )r[   Ziter_downloaderro   rI   rp   Zinitial_contentr4   r4   r5   chunks&  sD   
zStorageStreamDownloader.chunksc                 C      d S r^   r4   )r[   r   r4   r4   r5   reada     zStorageStreamDownloader.read)charsr   c                C   r   r^   r4   )r[   r   r4   r4   r5   r   e  r   c                C   s*  |dkr| j rtd |dkr|durtd| j s#|dur#td| jr.|dkr.td| jdu r;|dur;td|d	ksN|d	ksN| jrU| jt| jkrU| j sSd
S dS | js||dur|| j dur|d| _t	
| j d| _| jjtt| j| jd| _n| jdu rd| _| jrt }|du s|d	krtjn|}nt }|d	kr|ntj}|tjk}d	}| j}tt| j| j || }|| j|||  }||7 }|  j|7  _|  j|7  _|   || }	|	d	kr| js| j| j }| j| j }
| jdk}td| jj| j| j| jj | j||
||| j!| j"| j#| j$| j%d| j&}d| _'|( }|rt| jst|rd| j| j | jj krdd	dl)}|j*+| j}t,|-t.|j/|(  W d   n	1 s^w   Y  n|D ]}|/| qf| 0  nxt1|d }dur|	d	kr|2|\}}|  jt|7  _|  j3|7  _3| jr| jdur| jj|| jd| _n|| _|	t| jk r|| jd|	 }n|| j}|| _|  j|7  _|	|8 }	|   t1|d }dur|	d	ks|4 }| js| j rztt|| j }W |S  t5y   td  w |S )a  
        Read the specified bytes or chars from the stream. If `encoding`
        was specified on `download_blob`, it is recommended to use the
        chars parameter to read a specific number of chars to avoid decoding
        errors. If size/chars is unspecified or negative all bytes will be read.

        :param int size:
            The number of bytes to download from the stream. Leave unspecified
            or set negative to download all bytes.
        :keyword Optional[int] chars:
            The number of chars to download from the stream. Leave unspecified
            or set negative to download all chars. Note, this can only be used
            when encoding is specified on `download_blob`.
        :return:
            The requested data as bytes or a string if encoding was specified. If
            the return value is empty, there is no more data to read.
        :rtype: T
        r   zSize parameter specified with text encoding enabled. It is recommended to use chars to read a specific number of characters instead.Nz#Cannot specify both size and chars.z$Must specify encoding to read chars.z>Stream has been partially read in text mode. Please use chars.Fz>Stream has been partially read in bytes mode. Please use size.r   r9    Tstrict)finalr   rF   rM   rG   rH   rI   r)   r*   rK   rL   rJ   r,   r-   r   rN   zEncountered a decoding error while decoding blob data from a partial read. Try using the `chars` keyword instead to read in text mode.r4   )6r   r   r   r>   r   r   r   r   r   codecsgetincrementaldecoderr   decoder   r   r   sysmaxsizer   r   rl   r   _check_and_report_progressr   r   r   r   rE   r   r   r   r   r   r   r   r   r   r   r   r   rc   concurrent.futuresfuturesThreadPoolExecutorr@   mapr   ri   _complete_readr   rj   r   getvalueUnicodeDecodeError)r[   r   r   Zoutput_streamreadallcountro   r+   r   	remainingrp   rL   r   Zchunks_iter
concurrentexecutorr   chunkrg   r~   r7   r4   r4   r5   r   j  s   




c                 C   s   |   S )z
        Read the entire contents of this blob.
        This operation is blocking until all data is downloaded.

        :return: The requested data as bytes or a string if encoding was specified.
        :rtype: T
        )r   r   r4   r4   r5   r     s   zStorageStreamDownloader.readallrK   c                 C   s  | j rtd| jrtd | jdk}|rBd}tjdkr%| s%t|z	|	|
  W n ttfyA } zt||d}~ww | j| j }|dkrNdS t| j| j }| j}|tt| j|||  }|  j|7  _|  j|7  _| jr| | j| j | jr|S | j| j }	| j| j }
td	| jj| j| j| jj| j|	|
||| j| j| j | j!| jd| j"}|rddl#}|j$%| j}t&|'t(|j)|*  W d   n1 sw   Y  n|* D ]}|)| q| +  |S )
ae  Download the contents of this file to a stream.

        :param IO[bytes] stream:
            The stream to download to. This can be an open file-handle,
            or any writable stream. The stream must be seekable if the download
            uses more than one parallel connection.
        :return: The number of bytes read.
        :rtype: int
        zTStream has been partially read in text mode. readinto is not supported in text mode.zEEncoding is ignored with readinto as only byte streams are supported.r   z&Target stream handle must be seekable.)rt   Nr   r   r4   ),r   r>   r   r   r   r   r   version_infoseekablerk   rW   NotImplementedErrorAttributeErrorr   r   r   r   r   rl   r   r   r   r   r   rE   r   r   r   r   r   r   r   r   r   r   r   r   r   r@   r   r   ri   rc   r   )r[   rK   rL   error_messageexcZremaining_sizeZcurrent_remainingro   r   Z
data_startZdata_endr   r   r   r   r4   r4   r5   readinto  sx   



z StorageStreamDownloader.readintoc                 C   s(   | j | _| j | _| j | _t| j| _dS )z/Adjusts all offsets to the end of the download.N)r   r   r   r   r   r   r   r   r4   r4   r5   r   V  s   z&StorageStreamDownloader._complete_readc                 C   s2   | j r| jt| jkr|  | j| j dS dS dS )zReports progress if necessary.N)r   r   r   r   r   r   r   r4   r4   r5   r   ]  s   z2StorageStreamDownloader._check_and_report_progressc                 C   s(   t dt | jrtd|| _|  S )ap  DEPRECATED: Download the contents of this file.

        This operation is blocking until all data is downloaded.

        This method is deprecated, use func:`readall` instead.

        :param int max_concurrency:
            The number of parallel connections with which to download.
        :return: The contents of the file as bytes.
        :rtype: bytes
        z3content_as_bytes is deprecated, use readall insteadz\Stream has been partially read in text mode. content_as_bytes is not supported in text mode.)r   r   DeprecationWarningr   r>   r   r   )r[   r   r4   r4   r5   content_as_bytesd  s   z(StorageStreamDownloader.content_as_bytesUTF-8c                 C   s.   t dt | jrtd|| _|| _|  S )a  DEPRECATED: Download the contents of this blob, and decode as text.

        This operation is blocking until all data is downloaded.

        This method is deprecated, use func:`readall` instead.

        :param int max_concurrency:
            The number of parallel connections with which to download.
        :param str encoding:
            Test encoding to decode the downloaded bytes. Default is UTF-8.
        :return: The content of the file as a str.
        :rtype: str
        z2content_as_text is deprecated, use readall insteadz[Stream has been partially read in text mode. content_as_text is not supported in text mode.)r   r   r   r   r>   r   r   r   )r[   r   r   r4   r4   r5   content_as_text{  s   z'StorageStreamDownloader.content_as_textc                 C   s0   t dt | jrtd|| _| | | jS )a&  DEPRECATED: Download the contents of this blob to a stream.

        This method is deprecated, use func:`readinto` instead.

        :param IO[T] stream:
            The stream to download to. This can be an open file-handle,
            or any writable stream. The stream must be seekable if the download
            uses more than one parallel connection.
        :param int max_concurrency:
            The number of parallel connections with which to download.
        :return: The properties of the downloaded blob.
        :rtype: Any
        z6download_to_stream is deprecated, use readinto insteadz^Stream has been partially read in text mode. download_to_stream is not supported in text mode.)r   r   r   r   r>   r   r   r   )r[   rK   r   r4   r4   r5   download_to_stream  s   
z*StorageStreamDownloader.download_to_stream)NNNNNNr   NNNN)r.   N)r   )r   )r   r   ) r   r   r   r   r   __annotations__r   r   r   r   r   r   r\   r   r   propertyr   r   r   r   r   r   r(   r   r   r
   r   r   r   r   r   r   r4   r4   r4   r5   r   5  s   
 
	

^

c;" 
Q

r   )@r   r   rS   r|   r   ior   r   typingr   r   r   r   r   r	   r
   r   r   r   r   r   r   r   r   Zazure.core.exceptionsr   r   r   Zazure.core.tracing.commonr   Z_shared.request_handlersr   Z_shared.response_handlersr   r   Z_deserializer   r   Z_encryptionr   r   r   r    r!   r"   r#   Z
_generatedr$   Z_generated.operationsr%   Z_modelsr&   Z_shared.modelsr'   r   r   r(   r   r6   rD   objectrE   r   r   r4   r4   r4   r5   <module>   sN   D

& *8