o
    5@Hh
W                  	   @   s  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 d dlm	Z	 d dl
mZ d dl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 eZi ejdejdejdejdejdejdej dej!dej"dej#dej$dej%dej&dej'dej(dej)dej*di ej+dej,dej-dej.d ej/d!ej0d"ej1d#ej2d$ej3d%ej4d&ej5d'ej6d(ej7d)ej8d*ej9d+ej:d,ej;d-i ej<d.ej=d/ej>d0ej?d1ej@d2ejAd3ejBd4ejCd5ejDd6ejEd7ejFd8ejGd9ejHd:ejId;ejJd<ejKd=ejLd>i ejMd?ejNd@ejOdAejPdBejQdCejRdDejSdEejTdFejUdGejVdHejWdIejXdJejYdKejZdLej[dMej\dNej]dOi ej^dPej_dQej`dRejadSejbdTejcdUejddVejedWejfdXejgdYejhdZejid[ejjd\ejkd]ejld^ejmd_ejnd`ejodaejpdbejqdcejrddiZsG dedf dfZtdS )g    N)	b64encode)Optional)parse)urlparse)__version__   )utils)ClientConfig)Command)	ErrorCode)POSTz/session)DELETEz/session/$sessionId)GET/session/$sessionId/window)r   z"/session/$sessionId/window/handles)r   /session/$sessionId/url)r   z/session/$sessionId/forward)r   z/session/$sessionId/back)r   z/session/$sessionId/refresh)r   z /session/$sessionId/execute/sync)r   z!/session/$sessionId/execute/async)r   r   )r   z/session/$sessionId/title)r   z/session/$sessionId/source)r   z/session/$sessionId/screenshot)r   z*/session/$sessionId/element/$id/screenshot)r   z/session/$sessionId/element)r   z/session/$sessionId/elements)r   z"/session/$sessionId/element/active)r   z'/session/$sessionId/element/$id/element)r   z(/session/$sessionId/element/$id/elements)r   z%/session/$sessionId/element/$id/click)r   z%/session/$sessionId/element/$id/clear)r   z$/session/$sessionId/element/$id/text)r   z%/session/$sessionId/element/$id/value)r   z$/session/$sessionId/element/$id/name)r   z(/session/$sessionId/element/$id/selected)r   z'/session/$sessionId/element/$id/enabled)r   z$/session/$sessionId/element/$id/rect)r   z//session/$sessionId/element/$id/attribute/$name)r   z./session/$sessionId/element/$id/property/$name)r   z,/session/$sessionId/element/$id/computedrole)r   z-/session/$sessionId/element/$id/computedlabel)r   z&/session/$sessionId/element/$id/shadow)r   z,/session/$sessionId/shadow/$shadowId/element)r   z-/session/$sessionId/shadow/$shadowId/elements)r   /session/$sessionId/cookie)r   r   )r    /session/$sessionId/cookie/$name)r   r   )r   r   )r   z/session/$sessionId/frame)r   z /session/$sessionId/frame/parent)r   r   )r   z/session/$sessionId/window/new)r   r   )r   z1/session/$sessionId/element/$id/css/$propertyName)r   z!/session/$sessionId/execute_async)r   /session/$sessionId/timeouts)r   r   )r   z!/session/$sessionId/alert/dismiss)r   z /session/$sessionId/alert/accept)r   /session/$sessionId/alert/text)r   r   )r   /session/$sessionId/actions)r   r   )r   /session/$sessionId/window/rect)r   r   )r   z#/session/$sessionId/window/maximize)r   /session/$sessionId/orientation)r   r   )r   &/session/$sessionId/network_connection)r   r   )r   z/session/$sessionId/se/log)r   z /session/$sessionId/se/log/types)r   /session/$sessionId/context)r   z/session/$sessionId/contexts)r   r   )r   z%/session/$sessionId/window/fullscreen)r   z#/session/$sessionId/window/minimize)r   z/session/$sessionId/print)r   z*/session/$sessionId/webauthn/authenticator)r   z;/session/$sessionId/webauthn/authenticator/$authenticatorId)r   zF/session/$sessionId/webauthn/authenticator/$authenticatorId/credential)r   G/session/$sessionId/webauthn/authenticator/$authenticatorId/credentials)r   zU/session/$sessionId/webauthn/authenticator/$authenticatorId/credentials/$credentialId)r   r   )r   z>/session/$sessionId/webauthn/authenticator/$authenticatorId/uv)r   z/session/$sessionId/se/file)r   /session/$sessionId/se/files)r   r   )r   r   )r   z"/session/$sessionId/fedcm/gettitle)r   z'/session/$sessionId/fedcm/getdialogtype)r   z%/session/$sessionId/fedcm/accountlist)r   z+/session/$sessionId/fedcm/clickdialogbutton)r   z&/session/$sessionId/fedcm/canceldialog)r   z'/session/$sessionId/fedcm/selectaccount)r   z)/session/$sessionId/fedcm/setdelayenabled)r   z'/session/$sessionId/fedcm/resetcooldownc                   @   s  e Zd ZU dZdZddlZddlZddlZe Z	dej
v r#edne ZdZee ed< e  Zedkr;dZdZde d	e d
Zedd Zedd Zedd Zedd Zedd Zedd Zed7ddZ dd Z!dd Z"dd Z#		 				d8d!ee$ d"ee% d#ee% d$ee% d%ee& d&ee fd'd(Z'i Z(d)d* Z)d+e$fd,d-Z*d.d/ Z+d9d0d1Z,d2d3 Z-d:d5d6Z.dS );RemoteConnectionzA connection with the Remote WebDriver server.

    Communicates with the server using the WebDriver wire protocol:
    https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol
    Nr   REQUESTS_CA_BUNDLE_client_configdarwinmacz	selenium/z	 (python )c                 C   s   | j S N)r   self r%   k/home/air/sanwanet/gpt-api/venv/lib/python3.10/site-packages/selenium/webdriver/remote/remote_connection.pyclient_config   s   zRemoteConnection.client_configc                 C      t jdtdd | jjS )zp:Returns:

        Timeout value in seconds for all http requests made to the
        Remote Connection
        zWget_timeout() in RemoteConnection is deprecated, get timeout from client_config instead   
stacklevelwarningswarnDeprecationWarningr   timeoutclsr%   r%   r&   get_timeout   s   zRemoteConnection.get_timeoutc                 C      t jdtdd || j_dS )zyOverride the default timeout.

        :Args:
            - timeout - timeout value for http requests in seconds
        zUset_timeout() in RemoteConnection is deprecated, set timeout in client_config insteadr)   r*   Nr,   )r2   r0   r%   r%   r&   set_timeout   s   zRemoteConnection.set_timeoutc                 C   s   t jdtdd | j  dS )zAReset the http request timeout to socket._GLOBAL_DEFAULT_TIMEOUT.z_reset_timeout() in RemoteConnection is deprecated, use reset_timeout() in client_config insteadr)   r*   N)r-   r.   r/   r   reset_timeoutr1   r%   r%   r&   r6      s   zRemoteConnection.reset_timeoutc                 C   r(   )z:Returns:

        Paths of the .pem encoded certificate to verify connection to
        command executor. Defaults to certifi.where() or
        REQUESTS_CA_BUNDLE env variable if set.
        zhget_certificate_bundle_path() in RemoteConnection is deprecated, get ca_certs from client_config insteadr)   r*   r-   r.   r/   r   ca_certsr1   r%   r%   r&   get_certificate_bundle_path   s   z,RemoteConnection.get_certificate_bundle_pathc                 C   r4   )zSet the path to the certificate bundle to verify connection to
        command executor. Can also be set to None to disable certificate
        validation.

        :Args:
            - path - path of a .pem encoded certificate chain.
        zfset_certificate_bundle_path() in RemoteConnection is deprecated, set ca_certs in client_config insteadr)   r*   Nr7   )r2   pathr%   r%   r&   set_certificate_bundle_path   s   	z,RemoteConnection.set_certificate_bundle_pathFc                 C   s|   dd| j d}|jr*tjddd t|j d|j  }|dd	|  i |r3|d
di | j	r<|| j	 |S )zGet headers for remote request.

        :Args:
         - parsed_url - The parsed url
         - keep_alive (Boolean) - Is this a keep-alive connection (default: False)
        zapplication/jsonzapplication/json;charset=UTF-8)AcceptContent-Typez
User-AgentzREmbedding username and password in URL could be insecure, use ClientConfig insteadr)   r*   :AuthorizationzBasic 
Connectionz
keep-alive)

user_agentusernamer-   r.   r   passwordencodeupdatedecodeextra_headers)r2   
parsed_url
keep_aliveheadersbase64stringr%   r%   r&   get_remote_connection_headers   s   
z.RemoteConnection.get_remote_connection_headersc                 C   s"   t | j}|jr|jrdS d S d S )NT)r   
_proxy_urlrB   rC   )r$   rH   r%   r%   r&   _identify_http_proxy_auth  s   
z*RemoteConnection._identify_http_proxy_authc                 C   s>   t | j}|j d|j d|j }|j d|j }||fS )Nz://r>   )r   rM   schemehostnameportrB   rC   )r$   rH   proxy_without_authauthr%   r%   r&   _separate_http_proxy_auth  s   
z*RemoteConnection._separate_http_proxy_authc                 C   s   d| j ji}|| j jdi  | j jr!d|d< ttjj	 n| j j
r/d|d< | j j
|d< | jrh| j drIdd	lm} || jfi |S |  r^|  \| _| _tj| jd
|d< tj| jfi |S tjdi |S )Nr0   init_args_for_pool_manager	CERT_NONE	cert_reqsCERT_REQUIREDr8   sockr   )SOCKSProxyManager)proxy_basic_authproxy_headersr%   )r   r0   rE   rU   getignore_certificatesurllib3disable_warnings
exceptionsInsecureRequestWarningr8   rM   lower
startswithurllib3.contrib.socksrZ   rN   rT   _basic_proxy_authmake_headersProxyManagerPoolManager)r$   pool_manager_init_argsrZ   r%   r%   r&   _get_connection_manager  s&   z(RemoteConnection._get_connection_managerTremote_server_addrrI   ignore_proxyr^   rU   r'   c                 C   s   |p	t ||||d| _| jjt_| jjt_| jt_| jjptjt_| jjp'tjt_|r3t	j
dtdd |s=t	j
dtdd |rGt	j
dtdd |rQt	j
dtdd |r_t	j
dtdd d | _n| j | _| jjrn|  | _t| _d S )	N)rl   rI   r^   rU   z\setting remote_server_addr in RemoteConnection() is deprecated, set in client_config insteadr)   r*   zTsetting keep_alive in RemoteConnection() is deprecated, set in client_config insteadz]setting ignore_certificates in RemoteConnection() is deprecated, set in client_config insteadzdsetting init_args_for_pool_manager in RemoteConnection() is deprecated, set in client_config insteadzVsetting ignore_proxy in RemoteConnection() is deprecated, set in client_config instead)r	   r   r0   r   _timeoutr8   	_ca_certsrG   rA   r-   r.   r/   rM   get_proxy_urlrI   rk   _connremote_commands	_commands)r$   rl   rI   rm   r^   rU   r'   r%   r%   r&   __init__2  s\   	



zRemoteConnection.__init__c                 C   s   ||f| j |< dS )zRegister a new command.N)rs   )r$   namemethodurlr%   r%   r&   add_commandu  s   zRemoteConnection.add_commandru   c                 C   s   | j |S )z Retrieve a command if it exists.)rs   r]   )r$   ru   r%   r%   r&   get_commandy  s   zRemoteConnection.get_commandc                 C   s   | j |p| j|}|dusJ d| |d }t||}dd |dD }t|tr<|r<|D ]}||= q6t	
|}| jj | }	| |}
td|d |	t|
 | j|d |	|d	S )
am  Send a command to the remote server.

        Any path substitutions required for the URL mapped to the command should be
        included in the command parameters.

        :Args:
         - command - A string specifying the command to execute.
         - params - A dictionary of named parameters to send with the command as
           its JSON payload.
        NzUnrecognised command r   c                 S   s"   h | ]}| d r|dd qS )$r   Nrd   ).0wordr%   r%   r&   	<setcomp>  s   " z+RemoteConnection.execute.<locals>.<setcomp>/z%s %s %sr   )body)rs   r]   extra_commandsstringTemplate
substitutesplit
isinstancedictr   	dump_jsonr   rl   _trim_large_entriesLOGGERdebugstr_request)r$   commandparamscommand_infopath_stringr:   substitute_paramsr}   datarw   trimmedr%   r%   r&   execute}  s   

zRemoteConnection.executec              	   C   s  t |}| || jj}| j }|r|| |r!|dvr!d}| jjr6| jj||||| jj	d}|j
}n%|  }	|	}
|
j||||| jj	d}W d   n1 sSw   Y  |j
}|jd}td|j
||j zd|  krvdk rn n| d|jd	dW td
 |  S d|  k rdkrn n*|dkr|ddW td
 |  S ||st|n| dW td
 |  S g }|jddr|jddd}tdd |D s.z	t| }W n/ ty   d|  k rdk rn ntj}ntj}|| d Y W td
 |  S w d|vr"d|d< |W td
 |  S d|d}|W td
 |  S td
 |  w )aq  Send an HTTP request to the remote server.

        :Args:
         - method - A string for the HTTP method to send the request with.
         - url - A string for the URL to send the request to.
         - body - A string for request body. Ignored unless method is POST or PUT.

        :Returns:
          A dictionary with the server's parsed JSON response.
        )r   PUTN)r   rJ   r0   zUTF-8z1Remote response: status=%s | data=%s | headers=%si,  i0  r   locationzFinished Requesti  i  i  zAuthorization Required)statusvaluer=   ;c                 S   s   g | ]}| d qS )z	image/pngr{   )r|   xr%   r%   r&   
<listcomp>  s    z-RemoteConnection._request.<locals>.<listcomp>   r   r   )r   r   rL   r   rI   get_auth_headerrE   rq   requestr0   r   rk   r   rF   r   r   rJ   r   r]   closer   stripr   anyr   	load_json
ValueErrorr   SUCCESSUNKNOWN_ERROR)r$   rv   rw   r   rH   rJ   auth_headerresponse
statuscodeconnhttpr   content_typer   r%   r%   r&   r     sn   













	






zRemoteConnection._requestc                 C   s   t | dr| j  dS dS )z<Clean up resources when finished with the remote_connection.rq   N)hasattrrq   clearr#   r%   r%   r&   r     s   
zRemoteConnection.closed   c                 C   sj   i }|  D ],\}}t|tr| ||||< qt|tr.t||kr.|d| d ||< q|||< q|S )a  Truncate string values in a dictionary if they exceed max_length.

        :param dict: Dictionary with potentially large values
        :param max_length: Maximum allowed length of string values
        :return: Dictionary with truncated string values
        Nz...)itemsr   r   r   r   len)r$   
input_dict
max_lengthoutput_dictionarykeyr   r%   r%   r&   r     s   

z$RemoteConnection._trim_large_entries)F)NTFFNNr"   )r   )/__name__
__module____qualname____doc__browser_nameossocketcertifigetdefaulttimeoutrn   environgetenvwherero   r   r   r	   __annotations__platformsystemrc   rG   r   rA   propertyr'   classmethodr3   r5   r6   r9   r;   rL   rN   rT   rk   r   boolr   rt   r   rx   ry   r   r   r   r   r%   r%   r%   r&   r      sr   
 



	


A
>r   )uloggingr   r   r-   base64r   typingr   urllibr   urllib.parser   r_   seleniumr    r   r'   r	   r   r
   errorhandlerr   	getLoggerr   r   NEW_SESSIONQUITW3C_GET_CURRENT_WINDOW_HANDLEW3C_GET_WINDOW_HANDLESr   
GO_FORWARDGO_BACKREFRESHW3C_EXECUTE_SCRIPTW3C_EXECUTE_SCRIPT_ASYNCGET_CURRENT_URL	GET_TITLEGET_PAGE_SOURCE
SCREENSHOTELEMENT_SCREENSHOTFIND_ELEMENTFIND_ELEMENTSW3C_GET_ACTIVE_ELEMENTFIND_CHILD_ELEMENTFIND_CHILD_ELEMENTSCLICK_ELEMENTCLEAR_ELEMENTGET_ELEMENT_TEXTSEND_KEYS_TO_ELEMENTGET_ELEMENT_TAG_NAMEIS_ELEMENT_SELECTEDIS_ELEMENT_ENABLEDGET_ELEMENT_RECTGET_ELEMENT_ATTRIBUTEGET_ELEMENT_PROPERTYGET_ELEMENT_ARIA_ROLEGET_ELEMENT_ARIA_LABELGET_SHADOW_ROOTFIND_ELEMENT_FROM_SHADOW_ROOTFIND_ELEMENTS_FROM_SHADOW_ROOTGET_ALL_COOKIES
ADD_COOKIE
GET_COOKIEDELETE_ALL_COOKIESDELETE_COOKIESWITCH_TO_FRAMESWITCH_TO_PARENT_FRAMESWITCH_TO_WINDOW
NEW_WINDOWCLOSE!GET_ELEMENT_VALUE_OF_CSS_PROPERTYEXECUTE_ASYNC_SCRIPTSET_TIMEOUTSGET_TIMEOUTSW3C_DISMISS_ALERTW3C_ACCEPT_ALERTW3C_SET_ALERT_VALUEW3C_GET_ALERT_TEXTW3C_ACTIONSW3C_CLEAR_ACTIONSSET_WINDOW_RECTGET_WINDOW_RECTW3C_MAXIMIZE_WINDOWSET_SCREEN_ORIENTATIONGET_SCREEN_ORIENTATIONGET_NETWORK_CONNECTIONSET_NETWORK_CONNECTIONGET_LOGGET_AVAILABLE_LOG_TYPESCURRENT_CONTEXT_HANDLECONTEXT_HANDLESSWITCH_TO_CONTEXTFULLSCREEN_WINDOWMINIMIZE_WINDOW
PRINT_PAGEADD_VIRTUAL_AUTHENTICATORREMOVE_VIRTUAL_AUTHENTICATORADD_CREDENTIALGET_CREDENTIALSREMOVE_CREDENTIALREMOVE_ALL_CREDENTIALSSET_USER_VERIFIEDUPLOAD_FILEGET_DOWNLOADABLE_FILESDOWNLOAD_FILEDELETE_DOWNLOADABLE_FILESGET_FEDCM_TITLEGET_FEDCM_DIALOG_TYPEGET_FEDCM_ACCOUNT_LISTCLICK_FEDCM_DIALOG_BUTTONCANCEL_FEDCM_DIALOGSELECT_FEDCM_ACCOUNTSET_FEDCM_DELAYRESET_FEDCM_COOLDOWNrr   r   r%   r%   r%   r&   <module>   s  
	
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHLMNRVWXYZ\]^_`g