
    i%                     H   d dl m Z mZ d dlZ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
 d dlmZmZmZmZm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 ddlmZ  ed	       G d
 de             Zej8                  e_         ed       G d de             Zej8                  e_        y)    )datetimetimezoneN)Path)IterableOptionalTupleUnionCallable)Clientregister_client_class)FileCacheMode   )HttpPathhttpc                   v    e Zd Zddej                  ddddfdeeeef      deeee	j                  f      dee   deej                  j                     deeegee   f      deeegef      d	ee   f fd
ZdedefdZdedee   fdZdedeee	j                  f   defdZdede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dedeeeef      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 dededeeeef      fd Z!d!ed"edee"jF                  jH                  e%f   fd#Z xZ&S )&
HttpClientNPUTfile_cache_modelocal_cache_dircontent_type_methodauthcustom_list_page_parsercustom_dir_matcherwrite_file_http_methodc                 &   t         |   |||       || _        | j                  $t        j                  j                         | _        n.t        j                  j                  | j                        | _        || _        ||nd | _        || _	        y)a  Class constructor. Creates an HTTP client that can be used to interact with HTTP servers
            using the cloudpathlib library.

        Args:
            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
                uploading files. Defaults to `mimetypes.guess_type`.
            auth (Optional[urllib.request.BaseHandler]): Authentication handler to use for the client. Defaults to None, which will use the default handler.
            custom_list_page_parser (Optional[Callable[[str], Iterable[str]]]): Function to call to parse pages that list directories. Defaults to looking for `<a>` tags with `href`.
            custom_dir_matcher (Optional[Callable[[str], bool]]): Function to call to identify a url that is a directory. Defaults to a lambda that checks if the path ends with a `/`.
            write_file_http_method (Optional[str]): HTTP method to use when writing files. Defaults to "PUT", but some servers may want "POST".
        Nc                 $    | j                  d      S )N/)endswith)xs    m/var/www/vps2.regionflexible.com/Desarrollo/venv/lib/python3.12/site-packages/cloudpathlib/http/httpclient.py<lambda>z%HttpClient.__init__.<locals>.<lambda><   s    PQPZPZ[^P_     )
super__init__r   urllibrequestbuild_openeropenerr   dir_matcherr   )	selfr   r   r   r   r   r   r   	__class__s	           r    r$   zHttpClient.__init__   s~    6 	/;NO	99 ..557DK ..55dii@DK'>$ #5"@F_ 	 '=#r"   
cloud_pathreturnc                    | j                   j                  |j                               5 }|j                  j	                  dd       }|6t        j                  |d      }|j                  t        j                        }t        |j                  j	                  dd            ||j                  j	                  dd       dcd d d        S # 1 sw Y   y xY w)NzLast-Modifiedz%a, %d %b %Y %H:%M:%S %Z)tzinfozContent-Lengthr   Content-Type)sizelast_modifiedcontent_type)r(   openas_urlheadersgetr   strptimereplacer   utcint)r*   r,   responser2   s       r    _get_metadatazHttpClient._get_metadataA   s    [[j//12 	h$,,00$GM( ( 1 1-A[ \ !. 5 5X\\ 5 J H,,001A1EF!. ( 0 0 4 4^T J	 	 	s   BCCc                 D    | j                  |j                               ryy)Ndirfile)r)   r5   r*   r,   s     r    _is_file_or_dirzHttpClient._is_file_or_dirR   s    J--/0r"   
local_pathc                 L   t        |      }| j                  j                  |j                               5 }|j                  j                  dd       |j                  d      5 }t        j                  ||       d d d        d d d        |S # 1 sw Y   xY w# 1 sw Y   |S xY w)NT)parentsexist_okwb)r   r(   r4   r5   parentmkdirshutilcopyfileobj)r*   r,   rC   r<   out_files        r    _download_filezHttpClient._download_fileX   s    *%
[[j//12 	7h##D4#@& 7(""8X67	7
 7 7	7
 s#   /B$B;BB	BB#c                    t         j                  j                  |j                         d      }	 | j                  j                  |      5 }|j                  dk(  cd d d        S # 1 sw Y   y xY w# t         j                  j                  t         j                  j                  f$ r>}t        |t         j                  j                        s|j                  dk(  rY d }~y d }~ww xY w)NHEADmethod     F)r%   r&   Requestr5   r(   r4   statuserror	HTTPErrorURLError
isinstancecode)r*   r,   r&   r<   es        r    _existszHttpClient._existsa   s    ..(():):)<V(L	!!'* .h#-. . .&&(=(=> 	!V\\223qvv}	s;   A1 A%	A1 %A.*A1 .A1 17C&(3C! C!!C&srcdst
remove_srcc           	          | j                  |j                  |       |r	 | j                  |       |S |S # t        $ r)}t	        j
                  d| d| d| t                d }~ww xY w)Nz"File was successfully uploaded to z but failed to remove original z: )_upload_filefspath_remove	ExceptionwarningswarnUserWarning)r*   r]   r^   r_   r[   s        r    
_move_filezHttpClient._move_filek   sw    #**c*S! 
s
  8=\]`\aacdecfg s   5 	A'$A""A'
missing_okc                    t         j                  j                  |j                         d      }	 | j                  j                  |      5 }|j                  dk7  rt        d| d      	 d d d        y # 1 sw Y   y xY w# t         j                  j                  $ r+}|j                  dk(  r|rnt        d| d      Y d }~y d }~ww xY w)NDELETErP      zFailed to delete .rS   )r%   r&   rT   r5   r(   r4   rU   rd   rV   rW   rZ   FileNotFoundError)r*   r,   ri   r&   r<   r[   s         r    rc   zHttpClient._removey   s    ..(():):)<X(N	K!!'* Gh??c)#&7
|1$EFF *G G G ||%% 	Kvv}'*;J<q(IJJ 	Ks5   B A5,B 5A>:B >B C	!CC		recursivec              #     K   	 | j                   j                  |j                               5 }| j                  |j	                         j                         t        |            D ],  \  }}||f |s|s| j                  |d      E d {    . 	 d d d        y 7 # 1 sw Y   y xY w# t        $ r}t        d|       d }~ww xY ww)N)base_urlT)ro   z{Unable to parse response as a listing of files; please provide a custom parser as `custom_list_page_parser`. Error raised: )
r(   r4   r5   _parse_list_dir_responsereaddecodestr	_list_dirrd   NotImplementedError)r*   r,   ro   r<   pathis_dirr[   s          r    rv   zHttpClient._list_dir   s     	!!*"3"3"56 	H($($A$AMMO**,s: %B % HLD& ,& !V#'>>$$>#GGGH	H 	H H	H 	H  	% N  OP  NQ  R 	sj   C)B- AB!5B!8B!BB!B- CB!!B*&B- )C*B- -	C	6CC		Cc           	         t        |      }| j                  | j                  |      \  }}dxs di}|j                  d      5 }t        j                  j                  |j                         |j                         | j                  |      }| j                  j                  |      5 }|j                  dk7  r!|j                  dk7  rt        d| d| d	      d d d        d d d        |S # 1 sw Y   xY w# 1 sw Y   |S xY w)
Nr0   zapplication/octet-streamrb)datarQ   r6      rR   zFailed to upload z to rm   )r   r   r4   r%   r&   rT   r5   rs   r   r(   rU   rd   )	r*   rC   r,   r3   _r6   	file_datar&   r<   s	            r    ra   zHttpClient._upload_file   s
   *%
##/"66zBOL!!<#M3MN__T" 		Winn,,!!#^^%22	 - G !!'* Wh??c)hoo.D#&7
|4
|ST$UVVW		W W W		W s%   A%C9*1C-C9-C6	2C99Dc                 "    |j                         S N)r5   rA   s     r    _get_public_urlzHttpClient._get_public_url   s      ""r"   expire_secondsc                     t        d      )Nz.Presigned URLs are not supported using urllib.)rw   )r*   r,   r   s      r    _generate_presigned_urlz"HttpClient._generate_presigned_url   s    !"RSSr"   r<   rq   c              #       K   j                  d      sdz  dt        dt        t           fd} j                   j                  n|} fd ||      D        E d {    y 7 w)Nr   htmlr-   c                 .    t        j                  d|       S )Nz<a\s+href="([^"]+)")refindall)r   s    r    _simple_linksz:HttpClient._parse_list_dir_response.<locals>._simple_links   s    ::4d;;r"   c              3      K   | ]D  }j                  t        j                  j                  |            j	                  |      f F y wr   )	CloudPathr%   parseurljoinr)   ).0matchrq   r*   s     r    	<genexpr>z6HttpClient._parse_list_dir_response.<locals>.<genexpr>   sD      
 ^^V\\11(EBDdFVFVW\F]^
s   A
A)r   ru   r   r   )r*   r<   rq   r   parsers   ` `  r    rr   z#HttpClient._parse_list_dir_response   st        %OH	< 	< 	<
 ++7 (( 	
)
 	
 	
s   AA)!A'"A)urlrQ   c                     t        j                  j                  |j                         fd|i|}| j                  j                  |      5 }||j                         fcd d d        S # 1 sw Y   y xY w)NrQ   )r%   r&   rT   r5   r(   r4   rs   )r*   r   rQ   kwargsr&   r<   s         r    r&   zHttpClient.request   sa     ..((OfOO[[g& 	-( X]]_,	- 	- 	-s   A((A1)T)i  )'__name__
__module____qualname__	mimetypes
guess_typer   r	   ru   r   osPathLiker
   r%   r&   BaseHandlerr   boolr$   r   dictr=   rB   r   rM   r\   rh   rc   r   rv   ra   r   r;   r   rr   r   clientHTTPResponsebytes__classcell__)r+   s   @r    r   r      sS    @D=A2;2F2F59LP>B05)=!%](:";<)= "%R[[(8"9:)= &h/	)=
 v~~112)= "*(C5(3-3G*H!I)= %XseTk%:;)= !))=V T "( x}  uS"++EU?V [_ ( t h X 4 S[ 
K( 
K 
K 
KH  (5QY[_Q_K`Ba $uS"++-='> H Ya &#( #s #T( TC T^a T

'*
	%$'	(
*--%(-	t{{''.	/-r"   r   httpsc                       e Zd Zy)HttpsClientN)r   r   r    r"   r    r   r      s    r"   r   )r   r   r   r   r   urllib.requestr%   urllib.parseurllib.errorpathlibr   typingr   r   r   r	   r
   rJ   r   re   cloudpathlib.clientr   r   cloudpathlib.enumsr   httppathr   r   r   r   	HttpsPathr   r"   r    <module>r      s    '  	 	     = =    = ,  vw- w- w-t !**
  w	* 	  	 $-- r"   