
    iX                        d dl m Z mZ d dlZd dlZd dlmZ d dlmZ d dlm	Z	m
Z
mZmZ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 ddlmZ ddlmZ ddlmZ 	 d dl m!Z!m"Z" d dl#m$Z$ d dl%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+ d dl,m-Z. d dl/m0Z0m1Z1 d dl2m-Z3  ed       G d de             Z6d Z7e6jp                  e6_        y# e$ r	 d dlmZ Y w xY w# e4$ r ded   _5        Y Mw xY w)    )datetime	timedeltaN)
HTTPStatus)Path)AnyCallableDictIterableOptionalTupleUnion)islice)cast   )Clientregister_client_class)implementation_registry)FileCacheMode)MissingCredentialsError   )AzureBlobPath)HttpResponseErrorResourceNotFoundError)AzureNamedKeyCredential)
BlobPrefixBlobSasPermissionsBlobServiceClientBlobPropertiesContentSettingsgenerate_blob_sas)SharedKeyCredentialPolicy)DataLakeServiceClientFilePropertiesFazurec                   L    e Zd ZdZdddddddej
                  fdee   dee   dee   ded   ded	   d
ee	ee
f      dee	eej                  f      dee   f fdZdedee   fdZdedefdZdede	ddeeef   f   fdZedefd       Zdede	eej                  f   defdZdedee   fdZdedefdZ	 d)dededeeeef      fdZ	 d*dedededefdZ	 d+ded ed!eddfd"Zd*ded#eddfd$Z de	eej                  f   dedefd%Z!dedefd&Z"	 d,ded'e#defd(Z$ xZ%S )-AzureBlobClienta  Client class for Azure Blob Storage which handles authentication with Azure for
    [`AzureBlobPath`](../azblobpath/) instances. See documentation for the
    [`__init__` method][cloudpathlib.azure.azblobclient.AzureBlobClient.__init__] for detailed
    authentication options.
    Naccount_url
credentialconnection_stringblob_service_clientr   data_lake_clientr"   file_cache_modelocal_cache_dircontent_type_methodc	                    t         	|   |||       |t        j                  dd      }d| _        ||| _        |t        |j                  t              s|j                  n3t        |j                  j                  |j                  j                        }t        | j
                  j                  j                  ddd      |      | _        d| _        y|| _        d| _        y||| _        |t        |j                  t              s|j                  n3t        |j                  j                  |j                  j                        }t!        | j                  j                  j                  ddd      |      | _        d| _        y|@t!        j"                  ||      | _        t        j"                  ||      | _        d| _        y|d|v r<t!        |j                  dd      |      | _        t        ||      | _        d| _        yd|v r<t!        ||      | _        t        |j                  dd      |      | _        d| _        yt!        ||      | _        d| _        yt%        d	      d| _        y)
a  Class constructor. Sets up a [`BlobServiceClient`](
        https://docs.microsoft.com/en-us/python/api/azure-storage-blob/azure.storage.blob.blobserviceclient?view=azure-python).
        Supports the following authentication methods of `BlobServiceClient`.

        - Environment variable `""AZURE_STORAGE_CONNECTION_STRING"` containing connecting string
        with account credentials. See [Azure Storage SDK documentation](
        https://docs.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-python#copy-your-credentials-from-the-azure-portal).
        - Connection string via `connection_string`, authenticated either with an embedded SAS
        token or with credentials passed to `credentials`.
        - Account URL via `account_url`, authenticated either with an embedded SAS token, or with
        credentials passed to `credentials`.
        - Instantiated and already authenticated [`BlobServiceClient`](
        https://docs.microsoft.com/en-us/python/api/azure-storage-blob/azure.storage.blob.blobserviceclient?view=azure-python) or
        [`DataLakeServiceClient`](https://learn.microsoft.com/en-us/python/api/azure-storage-file-datalake/azure.storage.filedatalake.datalakeserviceclient).

        If multiple methods are used, priority order is reverse of list above (later in list takes
        priority). If no methods are used, a [`MissingCredentialsError`][cloudpathlib.exceptions.MissingCredentialsError]
        exception will be raised raised.

        Args:
            account_url (Optional[str]): The URL to the blob storage account, optionally
                authenticated with a SAS token. See documentation for [`BlobServiceClient`](
                https://docs.microsoft.com/en-us/python/api/azure-storage-blob/azure.storage.blob.blobserviceclient?view=azure-python).
            credential (Optional[Any]): Credentials with which to authenticate. Can be used with
                `account_url` or `connection_string`, but is unnecessary if the other already has
                an SAS token. See documentation for [`BlobServiceClient`](
                https://docs.microsoft.com/en-us/python/api/azure-storage-blob/azure.storage.blob.blobserviceclient?view=azure-python)
                or [`BlobServiceClient.from_connection_string`](
                https://docs.microsoft.com/en-us/python/api/azure-storage-blob/azure.storage.blob.blobserviceclient?view=azure-python#from-connection-string-conn-str--credential-none----kwargs-).
            connection_string (Optional[str]): A connection string to an Azure Storage account. See
                [Azure Storage SDK documentation](
                https://docs.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-python#copy-your-credentials-from-the-azure-portal).
            blob_service_client (Optional[BlobServiceClient]): Instantiated [`BlobServiceClient`](
                https://docs.microsoft.com/en-us/python/api/azure-storage-blob/azure.storage.blob.blobserviceclient?view=azure-python).
            data_lake_client (Optional[DataLakeServiceClient]): Instantiated [`DataLakeServiceClient`](
                https://learn.microsoft.com/en-us/python/api/azure-storage-file-datalake/azure.storage.filedatalake.datalakeserviceclient).
                If None and `blob_service_client` is passed, we will create based on that.
                Otherwise, will create based on passed credential, account_url, connection_string, or AZURE_STORAGE_CONNECTION_STRING env var
            file_cache_mode (Optional[Union[str, FileCacheMode]]): How often to clear the file cache; see
                [the caching docs](https://cloudpathlib.drivendata.org/stable/caching/) for more information
                about the options in cloudpathlib.eums.FileCacheMode.
            local_cache_dir (Optional[Union[str, os.PathLike]]): Path to directory to use as cache
                for downloaded files. If None, will use a temporary directory. Default can be set with
                the `CLOUDPATHLIB_LOCAL_CACHE_DIR` environment variable.
            content_type_method (Optional[Callable]): Function to call to guess media type (mimetype) when
                writing a file to the cloud. Defaults to `mimetypes.guess_type`. Must return a tuple (content type, content encoding).
        )r-   r.   r,   NAZURE_STORAGE_CONNECTION_STRINGz.blob.z.dfs.r   )r'   r(   )conn_strr(   ziAzureBlobClient does not support anonymous instantiation. Credentials are required; see docs for options.)super__init__osgetenvr+   service_client
isinstancer(   BlobSharedKeyCredentialPolicyr   account_nameaccount_keyr"   urlreplace!DataLakeSharedKeyCredentialPolicyr   from_connection_stringr   _hns_enabled)
selfr'   r(   r)   r*   r+   r,   r-   r.   	__class__s
            p/var/www/vps2.regionflexible.com/Desarrollo/venv/lib/python3.12/site-packages/cloudpathlib/azure/azblobclient.pyr3   zAzureBlobClient.__init__7   s   t 	+ 3+ 	 	
 $ "		*KT R  	 *"5D  ' &+668U (22 1+66CC+66BB  )> $ 3 3 7 7 ? ?'ST U))%| -1s )9%r -1o )$4D!"* &(335V %// 1(33@@(33??  '8 $ 5 5 9 9 A A'8UV W)'#N -1E *"3"J"J*z#D %:$P$P*z%D!< -17 $+%&7 + 3 3GX FS]'# )> +
)%, -1' [(&7 +
'# )> + 3 3Hg FS])% -1 '8 +
'# -1 *B 
 -1    
cloud_pathreturnc                 n   | j                   >	 | j                  j                         }|j                  dd      | _         | j                   S | j                   S # t        $ r | j                  |      cY S t        $ r9}|j                  t        j                  k(  r| j                  |      cY d }~S  d }~ww xY w)Nis_hns_enabledF)
r?   r6   get_account_informationgetr   _check_hns_root_metadatar   status_coder   	FORBIDDEN)r@   rD   account_infoerrors       rB   
_check_hnszAzureBlobClient._check_hns   s    $#22JJL$0$4$45Eu$M!    t    ) A44Z@@$ $$
(<(<<88DD	s)   1A B43B4;-B/(B4.B//B4c                    | j                   j                  |j                  d      }|j                         xr- |j	                         j
                  j                  dd      dk(  | _        t        t        | j                        S )N/	containerblobhdi_isfolderFtrue)
r6   get_blob_clientrS   existsget_blob_propertiesmetadatarI   r?   r   bool)r@   rD   root_dirs      rB   rJ   z(AzureBlobClient._check_hns_root_metadata   sx    &&66AUAU\_6` OO ],,.77;;NERV\\ 	
 D$++,,rC   r   r#   c                    | j                  |      rx| j                  j                  |j                        }|)|j	                  |j
                        j                         }j                  ddd i      j                  d      |d<   |S | j                  j                  |j                  |j
                        }|j                         }|j                  j                  |d<   |S )Ncontent_settingscontent_typerR   )rO   r+   get_file_system_clientrS   get_file_clientrT   get_file_propertiesrI   r6   rW   rY   r^   r_   )r@   rD   fsc
propertiesrT   s        rB   _get_metadatazAzureBlobClient._get_metadata   s     ??:& ''>>z?S?STC 00AUUW
 *4"^T$:*c.! ~&  &&66$..Z__ 7 D 113J)3)D)D)Q)QJ~&rC   c                 0    t        t        |       dz         S )Nz.part)r   str)
local_paths    rB   _partial_filenamez!AzureBlobClient._partial_filename  s    C
Og-..rC   rh   c                    | j                   j                  |j                  |j                        }|j	                         }t        |      }|j                  j                  dd       	 | j                  |      }|j                  d      5 }|j                  |       d d d        |j                  |       |S # 1 sw Y   xY w#  j                         r|j                           xY w)NrR   T)exist_okparentswb)r6   rW   rS   rT   download_blobr   parentmkdirri   openreadintor<   rX   unlink)r@   rD   rh   rT   download_streampartial_local_pathdatas          rB   _download_filezAzureBlobClient._download_file  s     ""22 ** 3 
 ,,.*%
t<
	!%!7!7
!C#((. /$((./ &&z2 / /	!((*"))+s$   +"C B:C :C?C #C)c                    |j                   sy	 | j                  |      }|j                  dd      s"|j                  di       j                  dd      rdS dS # t        $ rx |j                   }|r|j	                  d      s|dz  }| j
                  j                  |j                        }	 t        |j                  |             Y y# t        $ r Y Y y w xY ww xY w)	Ndiris_directoryFrZ   rU   filerQ   name_starts_with)rT   re   rI   r   endswithr6   get_container_clientrS   next
list_blobsStopIteration)r@   rD   metaprefixcontainer_clients        rB   _is_file_or_dirzAzureBlobClient._is_file_or_dir#  s    	%%j1D
 88NE288J+//F  	 % 	__Ffooc2#  $22GG
H\H\]%00&0IJ  	s1   AA A AC+C	CCCCc                     |j                   s3| j                  j                  |j                        j	                         S | j                  |      dv S )N)r{   ry   )rT   r6   r   rS   rX   r   )r@   rD   s     rB   _existszAzureBlobClient._existsB  sE    &&;;J<P<PQXXZZ##J/?BBrC   	recursivec              #   8  K   |j                   s| j                  j                         D ]t  }| j                  |j                   |j
                         df |s3| j                  | j                  |j                   |j
                         d      E d {    v y | j                  j                  |j                         }|j                  }|r|j                  d      s|dz  }| j                  |      r| j                  j                  |j                         }|j                  |j                  |      }|D ]F  }| j                  |j                   |j                    d|j
                         |j                  f H y |s|j                  |      }	n|j!                  |      }	|	D ]a  }
|
j
                  j#                  d      }| j                  |j                   |j                    d|       }||st%        |
t&              ndf c y 7 ~w)NTr   rQ   )pathr   r|   F)rS   r6   list_containers	CloudPathcloud_prefixname	_list_dirr   rT   r~   rO   r+   r`   	get_pathsrz   
walk_blobsr   rstripr7   r   )r@   rD   r   rS   r   r   file_system_clientpathsr   blobsrT   	blob_pathblob_cloud_paths                rB   r   zAzureBlobClient._list_dirI  s     ##!00@@B 	nn
(?(?'@@P%QRTXXX >>NNj&=&=%>y~~>N#OP\` *    ..CCJDXDXY&//#.cMF??:&!%!6!6!M!MjNbNb!c&00jooQZ0[E %nn!../
0D0D/EQtyykR$$% %% (33V3L(33V3L  II,,S1	"&..!../
0D0D/EQykR# &$ tZ0 5s   BHHE>Hsrcdst
remove_srcc                 0   ||k(  rx| j                   j                  |j                  |j                        }|j	                  t        t        t        j                         j                                            |S |r|j                  |j                  u r| j                  |      r| j                  j                  |j                        }|j                         rE|j                  |j                        j!                  |j                   d|j                          |S |j"                  j%                  dd       |j'                  |j                        j)                  |j                   d|j                          |S | j                   j                  |j                  |j                        }| j                   j                  |j                  |j                        }|j+                  |j,                         |r| j/                  |       |S )NrR   )last_modified)rZ   rQ   T)rl   rk   )r6   rW   rS   rT   set_blob_metadatadictrg   r   utcnow	timestampclientrO   r+   r`   is_dirget_directory_clientrename_directoryro   rp   ra   rename_filestart_copy_from_urlr;   _remove)r@   r   r   r   blob_clientrc   targetsources           rB   
_move_filezAzureBlobClient._move_filez  s    #:--==--chh > K ))C0A0K0K0M,NO * 0 
' SZZ3::54??3;O''>>s}}MCzz|((2CCs}}oUVWZW_W_V`Dab 
 

   =##CHH-99S]]O1SXXJ:WX 
 ((883==WZW_W_8`F((883==WZW_W_8`F&&vzz2S!
rC   rl   rk   c                 t   | j                  |      r| j                  j                  |j                        }|j	                  |j
                        }|s|j                         rt        d|       |s4| j                  |j                        st        d|j                   d      |j                          y y )NzDirectory already exists: z!Parent directory does not exist (z4). To create parent directories, use `parents=True`.)rO   r+   r`   rS   r   rT   rX   FileExistsErrorr   ro   FileNotFoundErrorcreate_directory)r@   rD   rl   rk   r   directory_clients         rB   _mkdirzAzureBlobClient._mkdir  s     ??:&!%!6!6!M!MjNbNb!c1FFzW 0 7 7 9%(B:,&OPP||J$5$56+;J<M<M;N  OC  D  --/ rC   
missing_okc                 V   | j                  |      }|dk(  r| j                  |      r,t        | j                  |j                  |j
                         y d | j                  |d      D        }| j                  j                  |j                        }t        t        |d            x}r( |j                  |  t        t        |d            x}r'y y |dk(  rB| j                  j                  |j                  |j
                        }|j                          y |st        d|       y )	Nry   c              3   @   K   | ]  \  }}|r	|j                     y w)N)rT   ).0br   s      rB   	<genexpr>z*AzureBlobClient._remove.<locals>.<genexpr>  s       $1fZ`s   
Tr      r{   rR   zFile does not exist: )r   rO   _hns_rmtreer+   rS   rT   r   r6   r   tupler   delete_blobsrW   delete_blobr   )r@   rD   r   file_or_dirr   r   batchrT   s           rB   r   zAzureBlobClient._remove  s   **:6%z*D11:3G3GY(,zT(RE  $22GG
H\H\] s!344%4- --u5 !s!344%4F"&&66$..Z__ 7 D  '*?
|(LMM rC   c                 x   | j                   j                  |j                  |j                        }i }| j                  +| j	                  t        |            \  }}|||d<   |||d<   t        di |}t        |      j                  d      5 }|j                  |d|       d d d        |S # 1 sw Y   |S xY w)NrR   r_   content_encodingrbT)	overwriter^    )
r6   rW   rS   rT   r.   rg   r   r   rq   upload_blob)	r@   rh   rD   rT   
extra_argsr_   r   r^   rv   s	            rB   _upload_filezAzureBlobClient._upload_file  s     ""22 ** 3 
 
##/-1-E-Ec*o-V*L*'-9
>*+1A
-.*8Z8*""4( 	VDTTDTU	V 	V s   B//B9c                 |    | j                   j                  |j                  |j                        }|j                  S )NrR   )r6   rW   rS   rT   r;   )r@   rD   r   s      rB   _get_public_urlzAzureBlobClient._get_public_url  s8    ))99 ** : 
 rC   expire_secondsc                 2   t        | j                  j                  |j                  |j                  | j                  j
                  j                  t        d      t        j                         t        |      z         }| j                  |       d| }|S )NT)read)seconds)container_name	blob_namer:   
permissionexpiry?)r    r6   r9   rS   rT   r(   r:   r   r   r   r   r   )r@   rD   r   	sas_tokenr;   s        rB   _generate_presigned_urlz'AzureBlobClient._generate_presigned_url  s     &,,%// oo++66BB)t4??$y'HH
	 %%j12!I;?
rC   )F)T)FF)i  )&__name__
__module____qualname____doc__	mimetypes
guess_typer   rg   r   r   r   r4   PathLiker   r3   r   r[   rO   rJ   r	   re   staticmethodr   ri   rw   r   r   r
   r   r   r   r   r   r   r   intr   __classcell__)rA   s   @rB   r&   r&   /   s    &*$(+/=A>B?C=A2;2F2FU1c]U1 SMU1 $C=	U1
 &&9:U1 ##:;U1 "%](:";<U1 "%R[[(8"9:U1 &h/U1n!] !x~ !$-= -T -'	!14S>A	B4 / / /'5:3;K5L	6- HSM >C- CD C <A/'/48/	%t+,	-/d JN! !'4!BF!	!H RW'26JN	*N- NT NT N0R[[ 01?L	.- C  @G'9<	rC   r&   c                 h    | j                  |      }|j                  |      }|j                          y)zStateless implementation so can be used in test suite cleanup as well.

    If hierarchical namespace is enabled, delete the directory and all its contents.
    (The non-HNS version is implemented in `_remove`, but will leave empty folders in HNS).
    N)r`   r   delete_directory)r+   rS   	directoryr   r   s        rB   r   r     s2     *@@K)>>yI%%'rC   )9r   r   r   r4   httpr   pathlibr   typingr   r   r	   r
   r   r   r   	itertoolsr   r   ImportErrortyping_extensionsr   r   r   	cloudpathr   enumsr   
exceptionsr   
azblobpathr   azure.core.exceptionsr   r   azure.core.credentialsr   azure.storage.blobr   r   r   r   r   r    )azure.storage.blob._shared.authenticationr!   r8   azure.storage.filedatalaker"   r#   1azure.storage.filedatalake._shared.authenticationr=   ModuleNotFoundErrordependencies_loadedr&   r   r   r   rC   rB   <module>r      s    (  	   H H H ' 3 / ! 0 %AN>  Q wCf C  CL( !0 9 9 m  '&'@  A;@G$8As#   B: 2C :CCCC