U
    gW                     @   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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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-ej<d.ej=d/ej>d0ej?d1ej@d2ejAd3ejBd4ejCd5ejDd6ejEd7ejFd8ejGd9ejHd:ejId;ejJd<ejKd=ejLd>ejMd?ejNd@ejOdAejPdBejQdCejRdDejSdEejTdFejUdGejVdHejWdIejXdJejYdKejZdLej[dMej\dNej]dOej^dPej_dQej`dRejadSejbdTejcdUejddVejedWejfdXejgdYejhdZejid[ejjd\ejkd]ejld^ejmd_ejnd`ejodaejpdbejqdcejrddiYZsG 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ddk	rPe	ede
e ne Zdejkrledne ZdZeed< e  Zedkrd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d1ddZdd Z dd Z!dd Z"d2e#e
 e#e$ e#e$ e#e$ e#e% e#e d d!d"Z&i Z'd#d$ Z(e
d%d&d'Z)d(d) Z*d3d*d+Z+d,d- Z,d4d/d0Z-dS )5RemoteConnectionzA connection with the Remote WebDriver server.

    Communicates with the server using the WebDriver wire protocol:
    https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol
    Nr   ZGLOBAL_DEFAULT_TIMEOUTREQUESTS_CA_BUNDLE_client_configdarwinmacz	selenium/z	 (python )c                 C   s   t jdtdd | jjS )zp:Returns:

        Timeout value in seconds for all http requests made to the
        Remote Connection
        z_get_timeout() in RemoteConnection is deprecated, get timeout from ClientConfig instance instead   
stacklevelwarningswarnDeprecationWarningr   timeoutcls r,   O/tmp/pip-unpacked-wheel-3ysq0mf8/selenium/webdriver/remote/remote_connection.pyget_timeout   s    zRemoteConnection.get_timeoutc                 C   s   t jdtdd || j_dS )zyOverride the default timeout.

        :Args:
            - timeout - timeout value for http requests in seconds
        zlset_timeout() in RemoteConnection is deprecated, set timeout to ClientConfig instance in constructor insteadr"   r#   Nr%   )r+   r)   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.zgreset_timeout() in RemoteConnection is deprecated, use reset_timeout() in ClientConfig instance insteadr"   r#   N)r&   r'   r(   r   reset_timeoutr*   r,   r,   r-   r0      s    zRemoteConnection.reset_timeoutc                 C   s   t jdtdd | jjS )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.
        zpget_certificate_bundle_path() in RemoteConnection is deprecated, get ca_certs from ClientConfig instance insteadr"   r#   r&   r'   r(   r   ca_certsr*   r,   r,   r-   get_certificate_bundle_path   s    z,RemoteConnection.get_certificate_bundle_pathc                 C   s   t jdtdd || j_dS )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.
        z}set_certificate_bundle_path() in RemoteConnection is deprecated, set ca_certs to ClientConfig instance in constructor insteadr"   r#   Nr1   )r+   pathr,   r,   r-   set_certificate_bundle_path   s    	z,RemoteConnection.set_certificate_bundle_pathFc                 C   s|   dd| j d}|jrTtjddd t|j d|j  }|dd	|  i |rf|d
di | j	rx|| 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)r+   
parsed_url
keep_aliveheadersZ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 )NT)r   
_proxy_urlr<   r=   )selfrB   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://r8   )r   rF   schemehostnameportr<   r=   )rG   rB   Z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rBd|d< ttjj	 n| j j
r^d|d< | j j
|d< | jr| j drdd	lm} || jf|S |  r|  \| _| _tj| jd
|d< tj| jf|S tjf |S )Nr)   init_args_for_pool_manager	CERT_NONE	cert_reqsCERT_REQUIREDr2   sockr   )SOCKSProxyManager)proxy_basic_authproxy_headers)r   r)   r?   rN   getignore_certificatesurllib3disable_warnings
exceptionsInsecureRequestWarningr2   rF   lower
startswithZurllib3.contrib.socksrS   rH   rM   Z_basic_proxy_authmake_headersProxyManagerPoolManager)rG   Zpool_manager_init_argsrS   r,   r,   r-   _get_connection_manager  s&    z(RemoteConnection._get_connection_managerT)remote_server_addrrC   ignore_proxyrW   rN   client_configc                 C   s   |pt ||||d| _| jjt_| jjt_| jt_| jjp>tjt_| jjpNtjt_|rft	j
dtdd |szt	j
dtdd |rt	j
dtdd |rt	j
dtdd |rt	j
dtdd d | _n| j | _| jjr|  | _t| _d S )	N)rb   rC   rW   rN   zdsetting remote_server_addr in RemoteConnection() is deprecated, set in ClientConfig instance insteadr"   r#   z\setting keep_alive in RemoteConnection() is deprecated, set in ClientConfig instance insteadzesetting ignore_certificates in RemoteConnection() is deprecated, set in ClientConfig instance insteadzlsetting init_args_for_pool_manager in RemoteConnection() is deprecated, set in ClientConfig instance insteadz^setting ignore_proxy in RemoteConnection() is deprecated, set in ClientConfig instance instead)r	   r   r)   r   _timeoutr2   	_ca_certsrA   r;   r&   r'   r(   rF   Zget_proxy_urlrC   ra   _connremote_commands	_commands)rG   rb   rC   rc   rW   rN   rd   r,   r,   r-   __init__2  s\    	


zRemoteConnection.__init__c                 C   s   ||f| j |< dS )zRegister a new command.N)ri   )rG   namemethodurlr,   r,   r-   add_commandu  s    zRemoteConnection.add_command)rk   c                 C   s   | j |S )z Retrieve a command if it exists.)ri   rV   )rG   rk   r,   r,   r-   get_commandy  s    zRemoteConnection.get_commandc                 C   s   | j |p| j|}|dk	s.td| |d }t||}dd |dD }t|t	rx|rx|D ]
}||= qlt
|}| 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r]   ).0wordr,   r,   r-   	<setcomp>  s     
 z+RemoteConnection.execute.<locals>.<setcomp>/z%s %s %sr   )body)ri   rV   extra_commandsAssertionErrorstringTemplate
substitutesplit
isinstancedictr   Z	dump_jsonr   rb   _trim_large_entriesLOGGERdebugstr_request)rG   commandparamscommand_infoZpath_stringr4   Zsubstitute_paramsrs   datarm   Ztrimmedr,   r,   r-   execute}  s    

zRemoteConnection.executec              	   C   s4  t |}| || jj}| j }|r2|| |rB|dkrBd}| jjrl| jj||||| jj	d}|j
}n6|  }	|	}
|
j||||| jj	d}W 5 Q R X |j
}|jd}td|j
||j zVd|  krdk rn n| d	|jd
dW $S d|  k rdkrNn n8|dkr.|ddW S ||s>t|n| dW S g }|jddrv|jddd}tdd |D s
zt| }W nR tk
r   d|  k rdk rn ntj}ntj}|| d Y W 0S X d|krd|d< |W S d|d}|W S td |  X dS )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)rv   rD   r)   zUTF-8z1Remote response: status=%s | data=%s | headers=%szFinished Requesti,  i0  r   locationi  i  i  zAuthorization Required)statusvaluer7   ;c                 S   s   g | ]}| d qS )z	image/pngrq   )rr   xr,   r,   r-   
<listcomp>  s     z-RemoteConnection._request.<locals>.<listcomp>   r   r   )r   r   rE   r   rC   Zget_auth_headerr?   rg   requestr)   r   ra   r   r@   r   r   rD   closer   rV   r   stripr|   anyr   Z	load_json
ValueErrorr   SUCCESSUNKNOWN_ERROR)rG   rl   rm   rv   rB   rD   auth_headerresponseZ
statuscodeconnhttpr   content_typer   r,   r,   r-   r     sR    


"
 


zRemoteConnection._requestc                 C   s   t | dr| j  dS )z<Clean up resources when finished with the remote_connection.rg   N)hasattrrg   clear)rG   r,   r,   r-   r     s    
zRemoteConnection.closed   c                 C   sj   i }|  D ]X\}}t|tr0| ||||< 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)rG   Z
input_dict
max_lengthZoutput_dictionarykeyr   r,   r,   r-   r     s    

z$RemoteConnection._trim_large_entries)F)NTFFNN)N)r   ).__name__
__module____qualname____doc__Zbrowser_nameossocketcertifigetenvfloatr   getdefaulttimeoutre   environwhererf   r   r	   __annotations__platformsystemr\   rA   r   r;   classmethodr.   r/   r0   r3   r5   rE   rH   rM   ra   r   boolr~   rj   rw   rn   ro   r   r   r   r   r,   r,   r,   r-   r      sh   



	

      A
>r   )uloggingr   ry   r&   base64r   typingr   urllibr   urllib.parser   rX   Zseleniumr    r   rd   r	   r   r
   Zerrorhandlerr   	getLoggerr   r   ZNEW_SESSIONZQUITZW3C_GET_CURRENT_WINDOW_HANDLEZW3C_GET_WINDOW_HANDLESr   Z
GO_FORWARDZGO_BACKZREFRESHZW3C_EXECUTE_SCRIPTZW3C_EXECUTE_SCRIPT_ASYNCZGET_CURRENT_URLZ	GET_TITLEZGET_PAGE_SOURCEZ
SCREENSHOTZELEMENT_SCREENSHOTZFIND_ELEMENTZFIND_ELEMENTSZW3C_GET_ACTIVE_ELEMENTZFIND_CHILD_ELEMENTZFIND_CHILD_ELEMENTSZCLICK_ELEMENTZCLEAR_ELEMENTZGET_ELEMENT_TEXTZSEND_KEYS_TO_ELEMENTZGET_ELEMENT_TAG_NAMEZIS_ELEMENT_SELECTEDZIS_ELEMENT_ENABLEDZGET_ELEMENT_RECTZGET_ELEMENT_ATTRIBUTEZGET_ELEMENT_PROPERTYZGET_ELEMENT_ARIA_ROLEZGET_ELEMENT_ARIA_LABELZGET_SHADOW_ROOTZFIND_ELEMENT_FROM_SHADOW_ROOTZFIND_ELEMENTS_FROM_SHADOW_ROOTZGET_ALL_COOKIESZ
ADD_COOKIEZ
GET_COOKIEZDELETE_ALL_COOKIESZDELETE_COOKIEZSWITCH_TO_FRAMEZSWITCH_TO_PARENT_FRAMEZSWITCH_TO_WINDOWZ
NEW_WINDOWZCLOSEZ!GET_ELEMENT_VALUE_OF_CSS_PROPERTYZEXECUTE_ASYNC_SCRIPTZSET_TIMEOUTSZGET_TIMEOUTSZW3C_DISMISS_ALERTZW3C_ACCEPT_ALERTZW3C_SET_ALERT_VALUEZW3C_GET_ALERT_TEXTZW3C_ACTIONSZW3C_CLEAR_ACTIONSZSET_WINDOW_RECTZGET_WINDOW_RECTZW3C_MAXIMIZE_WINDOWZSET_SCREEN_ORIENTATIONZGET_SCREEN_ORIENTATIONZGET_NETWORK_CONNECTIONZSET_NETWORK_CONNECTIONZGET_LOGZGET_AVAILABLE_LOG_TYPESZCURRENT_CONTEXT_HANDLEZCONTEXT_HANDLESZSWITCH_TO_CONTEXTZFULLSCREEN_WINDOWZMINIMIZE_WINDOWZ
PRINT_PAGEZADD_VIRTUAL_AUTHENTICATORZREMOVE_VIRTUAL_AUTHENTICATORZADD_CREDENTIALZGET_CREDENTIALSZREMOVE_CREDENTIALZREMOVE_ALL_CREDENTIALSZSET_USER_VERIFIEDZUPLOAD_FILEZGET_DOWNLOADABLE_FILESZDOWNLOAD_FILEZDELETE_DOWNLOADABLE_FILESZGET_FEDCM_TITLEZGET_FEDCM_DIALOG_TYPEZGET_FEDCM_ACCOUNT_LISTZCLICK_FEDCM_DIALOG_BUTTONZCANCEL_FEDCM_DIALOGZSELECT_FEDCM_ACCOUNTZSET_FEDCM_DELAYZRESET_FEDCM_COOLDOWNrh   r   r,   r,   r,   r-   <module>   s  
                                                                                         g