
    i\7                     z   d dl m Z m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 d dlZddlmZmZ ddlmZ ddlmZ d	d
lmZ 	 er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$ 	 d dl#m'Z'  ed       G d de             Z)e)jT                  e)_        y# e%$ r ded   _&        Y @w xY w# e($ r dZ'Y Fw xY w)    )datetime	timedeltaN)PathPurePosixPath)AnyCallableDictIterableOptionalTYPE_CHECKINGTupleUnion   )Clientregister_client_class)implementation_registry)FileCacheMode   )GSPath)Credentials)Retry)default)DefaultCredentialsError)r   Fgs)transfer_managerc                   $    e Zd ZdZddddddej
                  dddf
deeee	j                  f      ded   dee   ded   d	eeeef      d
eeee	j                  f      dee   deeeef      dee   ded   f fdZdedeeeef      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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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 )&GSClienta  Client class for Google Cloud Storage which handles authentication with GCP for
    [`GSPath`](../gspath/) instances. See documentation for the
    [`__init__` method][cloudpathlib.gs.gsclient.GSClient.__init__] for detailed authentication
    options.
    Napplication_credentialscredentialsr   projectstorage_clientStorageClientfile_cache_modelocal_cache_dircontent_type_method#download_chunks_concurrently_kwargstimeoutretryr   c                    ||| _         nX|t        ||      | _         nC|t        j                  |      | _         n&	 t               \  }}|xs |}t        ||      | _         || _        i | _        |	 |	| _        | j                  | j                  d<   |
 |
| _	        | j                  | j                  d<   t        | -  |||       y# t        $ r t        j
                         | _         Y w xY w)a8  Class constructor. Sets up a [`Storage
        Client`](https://googleapis.dev/python/storage/latest/client.html).
        Supports, in this order, the following authentication methods of `Storage Client`.

        - Instantiated and already authenticated `Storage Client`.
        - OAuth2 Credentials object and a project name.
        - File path to a JSON credentials file for a Google service account.
        - Google Cloud SDK default credentials. See [How Application Default Credentials works](https://cloud.google.com/docs/authentication/application-default-credentials)

        If no authentication methods are used,
        then the client will be instantiated as anonymous, which will only have
        access to public buckets.

        Args:
            application_credentials (Optional[Union[str, os.PathLike]]): Path to Google service
                account credentials file.
            credentials (Optional[Credentials]): The OAuth2 Credentials to use for this client.
                See documentation for [`StorageClient`](
                https://googleapis.dev/python/storage/latest/client.html).
            project (Optional[str]): The project which the client acts on behalf of. See
                documentation for [`StorageClient`](
                https://googleapis.dev/python/storage/latest/client.html).
            storage_client (Optional[StorageClient]): Instantiated [`StorageClient`](
                https://googleapis.dev/python/storage/latest/client.html).
            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).
            download_chunks_concurrently_kwargs (Optional[Dict[str, Any]]): Keyword arguments to pass to
                [`download_chunks_concurrently`](https://cloud.google.com/python/docs/reference/storage/latest/google.cloud.storage.transfer_manager#google_cloud_storage_transfer_manager_download_chunks_concurrently)
                for sliced parallel downloads; Only available in `google-cloud-storage` version 2.7.0 or later, otherwise ignored and a warning is emitted.
            timeout (Optional[float]): Cloud Storage [timeout value](https://cloud.google.com/python/docs/reference/storage/1.39.0/retry_timeout)
            retry (Optional[google.api_core.retry.Retry]): Cloud Storage [retry configuration](https://cloud.google.com/python/docs/reference/storage/1.39.0/retry_timeout#configuring-retries)
        N)r   r    r'   r(   )r$   r%   r#   )clientr"   from_service_account_jsongoogle_default_authr   create_anonymous_clientr&   blob_kwargsr'   r(   super__init__)selfr   r   r    r!   r#   r$   r%   r&   r'   r(   default_project	__class__s               i/var/www/vps2.regionflexible.com/Desarrollo/venv/lib/python3.12/site-packages/cloudpathlib/gs/gsclient.pyr0   zGSClient.__init__(   s   j %(DK$'KQDK$0'AABYZDKF 0C/D,_!4_+WU 4W0+-")DL*.,,DY' %DJ(,

DW%+ 3+ 	 	
 + F+CCEFs   %C	 	"C.-C.
cloud_pathreturnc                     | j                   j                  |j                        }|j                  |j                        }|y |j                  |j
                  |j                  |j                  |j                  dS )N)etagsizeupdatedcontent_typemd5_hash)	r*   bucketget_blobblobr8   r9   r:   r;   r<   r1   r5   r=   r?   s       r4   _get_metadatazGSClient._get_metadata   sg    ##J$5$56z/< 				<< $ 1 1 MM     
local_pathc                    | j                   j                  |j                        }|j                  |j                        }t	        |      }t
        /| j                  #t        j                  ||fi | j                   |S t
        !| j                  t        j                  d        |j                  |fi | j                   |S )NzwIgnoring `download_chunks_concurrently_kwargs` for version of google-cloud-storage that does not support them (<2.7.0).)r*   r=   r>   r?   r   r   r&   download_chunks_concurrentlywarningswarndownload_to_filenamer.   )r1   r5   rC   r=   r?   s        r4   _download_filezGSClient._download_file   s    ##J$5$56z/*%
'D,T,T,`99j$($L$L   'D,T,T,` N &D%%jED4D4DErB   c                 <   |j                   sy| j                  j                  |j                        }|j                  |j                         }|y|j                   }|r|j	                  d      s|dz  }|j                  d|      }t        t        |            ryy )Ndirfile/r   )max_resultsprefix)r?   r*   r=   r>   endswith
list_blobsboollist)r1   r5   r=   r?   rO   fs         r4   _is_file_or_dirzGSClient._is_file_or_dir   s    ##J$5$56z/__Ffooc2# !!a!?A DG}rB   c                     |j                   s3| j                  j                  |j                        j                         S | j	                  |      dv S )N)rL   rK   )r?   r*   r=   existsrU   )r1   r5   s     r4   _existszGSClient._exists   sC    ;;%%j&7&78??AA##J/?BBrB   c           	   #   (   K   j                   s:|rt        d       fd j                  j                         D        E d {    y  j                  j                  j                         }j                  }|r|j                  d      s|dz  }|rt               }|j                  |      D ]  }t        |j                  t        |      d        j                  D ]Y  }||vst        |      dk7  s j                  j                   j                    d| |       df |j                  |       [  j                  j                   j                    d|j                         df  y |j                  d|      }|D ]<  }	 j                  j                   j                    d|	j                         df > |j                   D ]2  }
 j                  j                   j                    d|
       df 4 y 7 ʭw)	NztCannot recursively list all buckets and contents; you can get all the buckets then recursively list each separately.c              3   r   K   | ].  }j                  j                   t        |             d f 0 yw)TN)	CloudPathcloud_prefixstr).0br5   r1   s     r4   	<genexpr>z%GSClient._list_dir.<locals>.<genexpr>   s;       :#:#:";CF8 DEtLs   47rM   )rO   .TF)	delimiterrO   )r=   NotImplementedErrorr*   list_bucketsr?   rP   setrQ   r   namelenparentsr]   r[   r\   addprefixes)r1   r5   	recursiver=   rO   yielded_dirsoparentiteratorrL   	directorys   ``         r4   	_list_dirzGSClient._list_dir   s<      ) K 113   ##J$5$56&//#.cMF5L&&f&5 +AFF3v;=,ABJJ 	1F\1c&kS6H NN#-#:#:";J<M<M;NaPVxX^W_ ` !	  %((0	1 NNj&=&=%>z?P?P>QQRSTSYSYRZ#[\ " ((3v(FH ! NNj&=&=%>z?P?P>QQRSWS\S\R]#^_  &.. 	NNj&=&=%>z?P?P>QQRS\R]#^_ Qs    AHHB!H(H7DHsrcdst
remove_srcc                    ||k(  r| j                   j                  |j                        }|j                  |j                        }|j                  dt        j                         i|_        n!t        j                         |j                  d<   |j                          |S | j                   j                  |j                        }| j                   j                  |j                        }|j                  |j                        } |j                  |||j                  fi | j                   |r|j                          |S )Nr:   )r*   r=   r>   r?   metadatar   utcnowpatch	copy_blobr.   delete)	r1   rr   rs   rt   r=   r?   
src_bucket
dst_bucketsrc_blobs	            r4   
_move_filezGSClient._move_file   s    #:[[''

3F??388,D }}$!*HOO,= >+3??+<i(JJL 
 ++CJJ7J++CJJ7J!**3884H J  :sxxT4CSCST!
rB   
missing_okc                     | j                  |      }|dk(  r~| j                  |d      D cg c]  \  }}|r	|j                   }}}| j                  j	                  |j                        }|D ]!  }|j                  |      j                          # y |dk(  rO| j                  j	                  |j                        }|j                  |j                        j                          y |st        d|       y c c}}w )NrK   T)rk   rL   zFile does not exist: )rU   rq   r?   r*   r=   r>   rz   FileNotFoundError)	r1   r5   r   file_or_dirr_   is_dirblobsr=   r?   s	            r4   _removezGSClient._remove  s    **:6%(,zT(R$1fZ`E  [[''
(9(9:F /%,,./F"[[''
(9(9:FOOJOO,335 '*?
|(LMM s
   
C:C:c                 6   | j                   j                  |j                        }|j                  |j                        }i }| j                  "| j                  t	        |            \  }}||d<    |j
                  t	        |      fi || j                   |S )Nr;   )r*   r=   r?   r%   r]   upload_from_filenamer.   )r1   rC   r5   r=   r?   
extra_argsr;   _s           r4   _upload_filezGSClient._upload_file   s    ##J$5$56{{:??+
##/"66s:GOL!)5J~&!!!#j/TZT4CSCSTrB   c                     | j                   j                  |j                        }|j                  |j                        }|j                  S )N)r*   
get_bucketr=   r?   
public_urlr@   s       r4   _get_public_urlzGSClient._get_public_url,  s8    ''
(9(9:{{:??+rB   expire_secondsc                     | j                   j                  |j                        }|j                  |j                        }|j	                  dt        |      d      }|S )Nv4)secondsGET)version
expirationmethod)r*   r   r=   r?   generate_signed_urlr   )r1   r5   r   r=   r?   urls         r4   _generate_presigned_urlz GSClient._generate_presigned_url1  sV    ''
(9(9:{{:??+&&Y~%Fu ' 
 
rB   )F)T)i  )"__name__
__module____qualname____doc__	mimetypes
guess_typer   r   r]   osPathLiker   r   r	   r   floatr0   r   rA   r   rI   rU   rR   rX   r
   r   rq   r~   r   r   r   intr   __classcell__)r3   s   @r4   r   r       s0    FJ/3!%48?C=A2;2F2FHL#'#'U
!)%R[[0@*A!BU
 m,U
 #	U

 !1U
 "%](:";<U
 "%R[[(8"9:U
 &h/U
 .6d38n-EU
 %U
  U
n 8DcN3K  U3CS=T Y] && Xc] 0C& CT C4F 4vW[|I\@] 4lf 6 t v 2N& Nd Nd N"
uS"++-='> 
F 
W] 
& S 
& # \_ rB   r   )+r   r   r   r   pathlibr   r   typingr   r   r	   r
   r   r   r   r   rF   r*   r   r   	cloudpathr   enumsr   gspathr   google.auth.credentialsr   google.api_core.retryr   google.authr   r,   google.auth.exceptionsr   google.cloud.storager"   ModuleNotFoundErrordependencies_loadedr   ImportErrorr   r[    rB   r4   <module>r      s    (  	 ' W W W  2 / ! 
>7/:><5
 tVv V Vr $$I	  >8=D!5>  s$    B -B0 B-,B-0B:9B: