a
    &ñ»jE  ã                   @  s¢  U d dl 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Zd dl	Z
d dl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mZ d dlmZ edƒZd	Zd
Zej eeƒjdd�j j d ¡Z!ej e!d¡Z"dZ#ejZ$dZ%ddddddddddddddœZ&dZ'eƒ  (¡ Z)e& *e)¡�p*e)Z+e$dk�r¬dZ'zZe,edƒ�r’e -¡ Z.dZ/de0d < d!e.v �rpe.d! Z/n
e. *d"¡Z/e/�r’d#e/ (¡ v �r’dZ%W n e1�y¨   Y n0 n"e$d$v �rÀd%Z$d&Z'ne$d'k�rÎd(Z'e 2d)e$e+e'f ej3¡Z4e 2d)d#e+e'f ej3¡Z5e 6d*¡Z7eG d+d,„ d,ƒƒZ8eG d-d.„ d.e8ƒƒZ9eG d/d0„ d0e8ƒƒZ:G d1d„ dƒZ;e<d2k�ržze; =¡  W n6 e1�yœ Z> ze ?d3e>› �¡ W Y dZ>[>n
dZ>[>0 0 dS )4é    )ÚannotationsN)Ú	dataclassÚfieldÚfields)ÚPath)Úmachine)ÚListÚOptionalÚTuple)Ú
get_loggerÚ
TLSLibrary)r   zv1.13.1T)ÚstrictÚbinzrelease.jsonz;https://api.github.com/repos/bogdanfinn/tls-client/releasesFÚamd64Ú386Úarm64zarm-5zarm-6zarm-7Úppc64leÚriscv64Ús390x)r   Úx86_64Úx86Úi686Úi386r   Úaarch64Zarmv5lZarmv6lÚarmv7lr   r   r   z.unkÚlinuxÚsoÚfreedesktop_os_releaseúOptional[str]Úcurr_systemZIDÚidÚubuntu)Úwin32ÚcygwinÚwindowsÚdllÚdarwinÚdylibz	%s-%s.*%sÚTLS_LIBRARY_PATHc                   @  s*   e Zd Zeddœdd„ƒZedd„ ƒZdS )ÚBaseReleaseÚset©Úreturnc                 C  s   dd„ t | ƒD ƒS )Nc                 S  s   h | ]
}|j ’qS © )Úname)Ú.0Zmodel_fieldr-   r-   úCE:\soccer\ml_env\Lib\site-packages\tls_requests/models/libraries.pyÚ	<setcomp>O   ó    z/BaseRelease.model_fields_set.<locals>.<setcomp>)r   ©Úclsr-   r-   r0   Úmodel_fields_setM   s    zBaseRelease.model_fields_setc                   s(   |   ¡ ‰ | f i ‡ fdd„| ¡ D ƒ¤ŽS )Nc                   s   i | ]\}}|ˆ v r||“qS r-   r-   ©r/   ÚkÚv©r5   r-   r0   Ú
<dictcomp>T   r2   z+BaseRelease.from_kwargs.<locals>.<dictcomp>)r5   Úitems)r4   Úkwargsr-   r9   r0   Úfrom_kwargsQ   s    zBaseRelease.from_kwargsN)Ú__name__Ú
__module__Ú__qualname__Úclassmethodr5   r=   r-   r-   r-   r0   r)   K   s   r)   c                   @  s"   e Zd ZU ded< dZded< dS )ÚReleaseAssetÚstrÚbrowser_download_urlNr   r.   )r>   r?   r@   Ú__annotations__r.   r-   r-   r-   r0   rB   W   s   
rB   c                   @  sD   e Zd ZU dZded< dZded< eed�Zded< e	dd	„ ƒZ
dS )
ÚReleaseNr   r.   Útag_name)Údefault_factoryzList[ReleaseAsset]Úassetsc                   sJ   |   ¡ ‰ | dg ¡pg }dd„ |D ƒ|d< | f i ‡ fdd„| ¡ D ƒ¤ŽS )NrI   c                 S  s   g | ]}t jf i |¤Ž‘qS r-   )rB   r=   )r/   Zasset_kwargsr-   r-   r0   Ú
<listcomp>g   r2   z'Release.from_kwargs.<locals>.<listcomp>c                   s   i | ]\}}|ˆ v r||“qS r-   r-   r6   r9   r-   r0   r:   h   r2   z'Release.from_kwargs.<locals>.<dictcomp>)r5   Úpopr;   )r4   r<   rI   r-   r9   r0   r=   c   s    zRelease.from_kwargs)r>   r?   r@   r.   rE   rG   r   ÚlistrI   rA   r=   r-   r-   r-   r0   rF   ]   s
   
rF   c                   @  s  e Zd ZU dZdZded< dZded< eddd	œd
d„ƒZedddœdd„ƒZ	e
d.ddœdd„ƒZe
ddœdd„ƒZe
ddœdd„ƒZe
d/dddœdd„ƒZe
ddœdd „ƒZe
d!dœd"d#„ƒZe
d$d%„ ƒZeZe
d0ddd&œd'd(„ƒZe
dd)œd*d+„ƒZe
d,d-„ ƒZdS )1r   a°  TLS Library

    A utility class for managing the TLS library, including discovery, validation,
    downloading, and loading. This class facilitates interaction with system-specific
    binaries, ensuring compatibility with the platform and machine architecture.

    Class Attributes:
        _PATH (str): The current path to the loaded TLS library.

    Methods:
        fetch_api(version: Optional[str] = None, retries: int = 3) -> Generator[str, None, None]:
            Fetches library download URLs from the GitHub API for the specified version.

        is_valid(fp: str) -> bool:
            Validates a file path against platform-specific patterns.

        find() -> str:
            Finds the first valid library binary in the binary directory.

        find_all() -> list[str]:
            Lists all library binaries in the binary directory.

        download(version: Optional[str] = None) -> str:
            Downloads the library binary for the specified version.

        set_path(fp: str):
            Sets the path to the currently loaded library.

        load() -> ctypes.CDLL:
            Loads the library, either from an existing path or by discovering and downloading it.
    Nr   Ú_PATHzOptional[ctypes.CDLL]Ú_LIBRARYrC   zTuple[int, ...])Úversion_stringr,   c              	   C  sB   z$t | ƒ d¡ d¡}ttt|ƒƒW S  ttfy<   Y dS 0 dS )zMConverts a version string (e.g., "v1.11.2") to a comparable tuple (1, 11, 2).r8   Ú.©r   r   r   N)rC   ÚlstripÚsplitÚtupleÚmapÚintÚ
ValueErrorÚAttributeError)rO   Úpartsr-   r-   r0   Ú_parse_version�   s
    zTLSLibrary._parse_version)Úfilenamer,   c                 C  s*   t  dt| ƒj¡}|r&t | d¡¡S dS )z8Extracts and parses the version from a library filename.zv?(\d+\.\d+\.\d+)é   rQ   )ÚreÚsearchr   r.   r   rZ   Úgroup)r[   Úmatchr-   r-   r0   Ú_parse_version_from_filename˜   s    z'TLSLibrary._parse_version_from_filename©Ú	keep_filec                 C  s�   |   ¡ D ]‚}d}|r,t|ƒjt|ƒjkr,d}|rzt |¡ t d|› �¡ W q tyˆ } z"t d|› d|› �¡ W Y d}~qd}~0 0 qdS )zDRemoves all library files in the BIN_DIR except for the one to keep.TFzRemoved old library file: z Error removing old library file ú: N)	Úfind_allr   r.   ÚosÚremoveÚloggerÚinfoÚOSErrorÚerror)r4   rc   Ú	file_pathZ	is_removeÚer-   r-   r0   Úcleanup_files    s    
zTLSLibrary.cleanup_fileszOptional[dict]r+   c              
   C  s„   t j t¡r€z>ttddd��}t |¡W  d  ƒ W S 1 s>0    Y  W n4 ty~ } zt 	d|› �¡ W Y d}~n
d}~0 0 dS )z#Loads release data from local disk.Úrúutf-8©ÚencodingNz$Error loading local release config: )
rf   ÚpathÚexistsÚRELEASE_CONFIG_PATHÚopenÚjsonÚloadÚ	Exceptionrh   rk   )r4   Úfrm   r-   r-   r0   Úimport_config¯   s    .&zTLSLibrary.import_configÚdict)Údatac              
   C  sš   z`t jtdd� ttddd�� }tj||dd� W d  ƒ n1 sD0    Y  t d	t› �¡ W n4 t	y” } zt 
d
|› �¡ W Y d}~n
d}~0 0 dS )z!Saves release data to local disk.T©Úexist_okÚwrp   rq   é   )ÚindentNzSaved release config to z#Error saving local release config: )rf   ÚmakedirsÚBIN_DIRrv   ru   rw   Údumprh   ri   ry   rk   )r4   r}   rz   rm   r-   r-   r0   Úexport_configº   s    .zTLSLibrary.export_configé   rV   )ÚversionÚretriesc                 #  s\  ‡ ‡‡fdd„}g ‰ g ‰d }t |ƒD ]ô}z®tjjtdd��Š}|jdkr¶| ¡  d¡}t 	|¡}t
|tƒr||r||  |d ¡ nt
|tƒr�|  |¡ ||ƒr¶t d¡ W d   ƒ W  �qW d   ƒ n1 sÊ0    Y  W q$ t�y } z&t d	|d
 › d|› �¡ W Y d }~q$d }~0 0 q$ˆ �s4ˆ�s4|  ¡ }	|	�rN||	ƒ t dt› �¡ næˆ�pVt}
|
 d¡�snd|
› �}
dddœ}tg}tdk�r¢t|v �r¢| d|t ¡ tg}t�rº| dd¡ |D ]^}|D ]R}|
|
 d¡fD ]<}d|› d|› d|› dt› �}d|
› d|› �}ˆ  |¡ �qØ�qÆ�q¾t dd ˆ ¡› �¡ ˆD ]}|V  �q8ˆ D ]}|V  �qJd S )Nc                   sº   t | tƒr| n| g}dd„ |D ƒ}ˆd urZtˆƒ d¡s@dˆ ntˆƒ‰ ‡ fdd„|D ƒ}d}|D ]R}|jD ]F}|jrltr–t |j¡r–ˆ 	|j
¡ d}t |j¡rlˆ 	|j
¡ d}qlqb|S )Nc                 S  s   g | ]}t jf i |¤Ž‘qS r-   )rF   r=   )r/   r<   r-   r-   r0   rJ   Ê   r2   z?TLSLibrary.fetch_api.<locals>._process_data.<locals>.<listcomp>r8   zv%sc                   s(   g | ] }t  ˆ |jp|jt j¡r|‘qS r-   )r]   r^   r.   rG   ÚI)r/   Úrelease©Zversion_r-   r0   rJ   Î   s   FT)Ú
isinstancerL   rC   Ú
startswithrI   r.   Ú	IS_UBUNTUÚPATTERN_UBUNTU_REr^   ÚappendrD   Ú
PATTERN_RE)r}   Zreleases_dataZreleasesZ
found_urlsr‹   Zasset©Z
asset_urlsZubuntu_urlsrˆ   rŒ   r0   Ú_process_dataÇ   s$    
ÿ
z+TLSLibrary.fetch_api.<locals>._process_dataé
   ©ÚtimeoutéÈ   rp   r   z%Fetched release data from GitHub API.z!GitHub API fetch failed (Attempt r\   z): z'Loaded release data from local config: r8   Ú64Ú32)r   r   r$   r!   ztls-client-ú-rP   z;https://github.com/bogdanfinn/tls-client/releases/download/ú/z*Fallback: generated direct download URLs: z, )ÚrangeÚurllibÚrequestÚurlopenÚGITHUB_API_URLÚstatusÚreadÚdecoderw   Úloadsr�   rL   r†   r|   rh   ri   ry   Údebugr{   ru   ÚLATEST_VERSION_TAG_NAMErŽ   ÚMACHINEÚPLATFORMÚinsertr�   rR   ÚFILE_EXTr‘   Újoin)r4   rˆ   r‰   r”   Zapi_dataÚ_ÚresponseÚcontentÚexZ
local_dataZv_tagZwin_arch_mapZtarget_archesÚ	platformsÚplatÚarchZv_strZdirect_filenameÚ
direct_urlÚurlr-   r“   r0   Ú	fetch_apiÅ   s\    




62


ÿ
zTLSLibrary.fetch_apic                 C  s$   |   ¡ D ]}t |¡r|  S qd S ©N)re   r’   r^   ©r4   Úfpr-   r-   r0   Úfind  s    

zTLSLibrary.findz	List[str]c                 C  s   dd„ t   tj td¡¡D ƒS )Nc                 S  s   g | ]}|  ¡  d ¡r|‘qS ))r   r%   r'   )ÚlowerÚendswith)r/   Úsrcr-   r-   r0   rJ   '  r2   z'TLSLibrary.find_all.<locals>.<listcomp>Ú*)Úglobrf   rs   r¬   r„   r3   r-   r-   r0   re   %  s    zTLSLibrary.find_allc                 C  sJ   t  dt› d�¡ | jtd�}|r<| j|d� t  d¡ |S t  d¡ dS )z0Forces a download of the latest library version.z Updating TLS library to version ú...©rˆ   rb   zUpdate complete.zUpdate failed.N)rh   ri   r§   Údownloadrn   rk   )r4   Údownloaded_fpr-   r-   r0   Úupdate)  s    

zTLSLibrary.update)rˆ   r,   c                 C  st  �z8t  dttrdt nttf ¡ d }|  |¡D �]ø}|s>q2|}t  d| ¡ �z„| d¡d }tj	 
t|¡}tjj|dd���@}|jdkr¶t  d	|› d
|j› �¡ W d   ƒ W q2tjtdd� t|j dd¡ƒ}d}t|dƒ�¦}	d}
| |¡}|sü�q||	 |¡ |
t|ƒ7 }
|dkrê|
| d }d}t||
 | ƒ}d| d||   }tj d|› d|› d|d›d�¡ tj ¡  qêW d   ƒ n1 �s’0    Y  tj d¡ |W  d   ƒ W   W S 1 �sÊ0    Y  W q2 tjjtjjf�y* } z.t  d|› d|› �¡ W Y d }~q2W Y d }~q2d }~0 0 q2t  d¡ W n4 t�yn } zt  d| ¡ W Y d }~n
d }~0 0 d S )Nz7System Info - Platform: %s, Machine: %s, File Ext : %s.z%s (Ubuntu)z#Trying to download library from: %srœ   éÿÿÿÿé   r–   r˜   z	Skipping z: HTTP Tr~   zcontent-lengthr   i    Úwbéd   é2   ú=r›   zDownloading z: [z] z.1fú%Ú
zFailed to download from rd   zAll download attempts failed.z0An unexpected error occurred during download: %s) rh   ri   r©   r�   r¨   r«   r¶   rS   rf   rs   r¬   r„   rž   rŸ   r    r¢   r¦   rƒ   rV   ÚheadersÚgetrv   r£   ÚwriteÚlenÚsysÚstdoutÚflushrk   ÚURLErrorÚ	HTTPErrorry   )r4   rˆ   Údownload_urlrµ   Zdestination_nameZdestinationr®   Z
total_sizeÚ
chunk_sizeÚfileZ
downloadedÚchunkÚpercentZ
bar_lengthZfilled_lengthÚbarr°   rm   r-   r-   r0   rÂ   7  s`    ýÿÿ


",0$$zTLSLibrary.download)r¹   c                 C  s
   || _ d S r·   )rM   r¸   r-   r-   r0   Úset_pathw  s    zTLSLibrary.set_pathc              
     s’  ˆ   t¡}ˆ jr0ˆ jr0ˆ  ˆ j¡}||kr0ˆ jS ‡ fdd„}trXt dt› �¡ |tƒS t dt› �¡ ˆ  	¡ }d}d}|rÆ|D ]}ˆ  |¡}||kr€|}|}q€t d|› dd	 
tt|ƒ¡› d
�¡ n
t d¡ ||k �rb|�rt dd	 
tt|ƒ¡› dt› d�¡ nt dt› d�¡ ˆ jtd�}	|	�rHˆ j|	d� ||	ƒ}
|
�rH|
S t dt› d�¡ tdƒ‚|�r†||ƒ}
|
�r†ˆ j|d� |
S tdƒ‚dS )z¬
        Loads the TLS library. It checks for the correct version, downloads it if
        the local version is outdated or missing, and then loads it into memory.
        c                   s˜   z2t j | ¡}ˆ  | ¡ |ˆ _t d| › �¡ |W S  ty’ } zHt d| › d|› �¡ zt	 
| ¡ W n ttfy|   Y n0 W Y d }~n
d }~0 0 d S )Nz!Successfully loaded TLS library: zUnable to load TLS library 'z', details: )ÚctypesÚcdllÚLoadLibraryrÜ   rN   rh   ri   ry   rk   rf   rg   ÚFileNotFoundErrorÚPermissionError)Zfp_Úlibr°   r3   r-   r0   Ú_load_libraryˆ  s    
z&TLSLibrary.load.<locals>._load_libraryz/Loading TLS library from environment variable: zRequired library version: rQ   NzFound newest local library: z
 (version rP   ú)zNo local library found.z"Local library is outdated (Found: z, Required: zZ). Auto-downloading... To manually upgrade, run: `python -m tls_requests.models.libraries`z%Downloading required library version rÀ   rÁ   rb   z,Failed to download the required TLS library zC. Please check your connection or download it manually from GitHub.z,Failed to download the required TLS library.z0Could not find or load a compatible TLS library.)rZ   r§   rN   rM   ra   r(   rh   ri   r¦   re   r¬   rU   rC   ÚwarningrÂ   rn   rk   rj   )r4   Ztarget_versionZcached_versionrã   Zlocal_filesZnewest_local_versionZnewest_local_filerl   Zfile_versionrÃ   Zlibraryr-   r3   r0   rx   {  s^    

ÿ

ÿÿ
ÿzTLSLibrary.load)N)Nr‡   )N)r>   r?   r@   Ú__doc__rM   rE   rN   ÚstaticmethodrZ   ra   rA   rn   r{   r†   r¶   rº   re   rÄ   ÚupgraderÂ   rÜ   rx   r-   r-   r-   r0   r   k   s8   
 

X
?Ú__main__zManual load test failed: )@Ú
__future__r   rÝ   r¿   rw   rf   Úplatformr]   rÑ   Úurllib.errorrž   Úurllib.requestÚdataclassesr   r   r   Úpathlibr   r   Útypingr   r	   r
   Ztls_requests.utilsr   rh   Ú__all__r§   rs   r¬   Ú__file__ÚresolveÚparentr„   ru   r¡   r©   r�   ZARCH_MAPPINGr«   r»   ZMACHINE_RAWrÎ   r¨   Úhasattrr   Zplatform_datar   rE   ry   ÚcompilerŠ   r’   r�   Úgetenvr(   r)   rB   rF   r   r>   rx   r°   rk   r-   r-   r-   r0   Ú<module>   s”    ó







  b
