o
    "{g~                     @   s  d 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
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 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 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  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* ddl(m+Z+ ddl,m-Z- ddl.m/Z/ ddl0m1Z1 dd l2m3Z3 dd!l4m5Z5 dd"l6m7Z7 dd#l8m9Z9 dd$l:m;Z; dd%l:m<Z< dd&l=m>Z> dd'l?m@Z@ dd(lAmBZB dd)lCmDZD dd*lEmFZF dd+lGmHZH dd,lImJZJ dd-lKmLZL daMdaNd.d/ ZOd0d1 ZP	dBd2eQd3eeReBf d4eSd5eSd6ee3 d7eBfd8d9ZTd:ee# d7efd;d<ZUG d=d> d>ed?ZVG d@dA dAeVZWdS )CzThe WebDriver implementation.    N)ABCMeta)	b64decode)urlsafe_b64encode)asynccontextmanager)contextmanager)import_module)Dict)List)Optional)Union)InvalidArgumentException)JavascriptException)NoSuchCookieException)NoSuchElementException)WebDriverException)Script)By)
ArgOptions)BaseOptions)PrintOptions)Timeouts)
Credential)VirtualAuthenticatorOptions)required_virtual_authenticator)
RelativeBy   )Dialog   )BidiConnection)ClientConfig)Command)ErrorHandler)FedCM)FileDetector)LocalFileDetector)LocatorConverter)Mobile)RemoteConnection)	ScriptKey)
ShadowRoot)SwitchTo)
WebElement)WebSocketConnectionc                   C   s   t stda d S d S )Nz"selenium.webdriver.common.bidi.cdp)cdpr    r.   r.   /var/www/bot.gig.net.ua/public_html/telegram/P1/HellBot/venv/lib/python3.10/site-packages/selenium/webdriver/remote/webdriver.py
import_cdpN   s   r0   c                 C   s8   t | } i }|  D ]\}}|||< qdi g|diS )a  Makes a W3C alwaysMatch capabilities object.

    Filters out capability names that are not in the W3C spec. Spec-compliant
    drivers will reject requests containing unknown capability names.

    Moves the Firefox profile, if present, from the old location to the new Firefox
    options object.

    :Args:
     - caps - A dictionary of capabilities requested by the caller.
    capabilities)
firstMatchalwaysMatch)copydeepcopyitems)capsalways_matchkvr.   r.   r/   _create_capsT   s
   

r;   r1   command_executor
keep_aliveignore_local_proxyclient_configreturnc                    s   t |tr|pt|d}||_t|d}ddlm} ddlm} ddl	m
} ddlm} ||||g}	t fdd	|	D t}
|
||||d
S )N)remote_server_addr)r?   r   )ChromeRemoteConnection)EdgeRemoteConnection)FirefoxRemoteConnection)SafariRemoteConnectionc                 3   s$    | ]}|j  d kr|V  qdS )browserNameN)browser_nameget).0cr1   r.   r/   	<genexpr>x   s   " z(get_remote_connection.<locals>.<genexpr>)rA   r=   ignore_proxyr?   )
isinstancestrr   rA   r'   +selenium.webdriver.chrome.remote_connectionrB   )selenium.webdriver.edge.remote_connectionrC   ,selenium.webdriver.firefox.remote_connectionrD   +selenium.webdriver.safari.remote_connectionrE   next)r1   r<   r=   r>   r?   rB   rC   rD   rE   
candidateshandlerr.   rK   r/   get_remote_connectiong   s    

rW   optionsc                 C   s   di i}g }| D ]	}| |  qt|}i }t|D ]8}|}|d |k rT||  }|D ]%}	|	||d   v rS|| |	 ||d  |	 krS||	|| |	 i q.qi }
| D ]\}}||
|< q[|D ]
}|
D ]}||= qjqf|
|d d< ||d d< |S )Nr1   r   r3   r2   )appendto_capabilitieslenrangekeysupdater6   )rX   r1   optsopt	opts_sizesamesiesi	min_index
first_keyskysalwaysr9   r:   r.   r.   r/   create_matches   s2   
rh   c                   @   s   e Zd ZdZdS )BaseWebDriverzAbstract Base Class for all Webdriver subtypes.

    ABC's allow custom implementations of Webdriver to be registered so
    that isinstance type checks will succeed.
    N)__name__
__module____qualname____doc__r.   r.   r.   r/   ri      s    ri   )	metaclassc                   @   s  e Zd ZdZeZeZ							ddee	e
f dedee deeeee f  d	ee d
ee dee ddfddZdd Zdd Zdejeje  deje dejej fddZedd ZedefddZ ede	fddZ!dd Z"d d! Z#d"e$ddfd#d$Z%d%d& Z&d'e	defd(d)Z'd*d+ Z(dd,e	d-e$de$fd.d/Z)d0e	ddfd1d2Z*ede	fd3d4Z+dd5e	de,fd6d7Z-d8e,ddfd9d:Z.dee	 fd;d<Z/d=d> Z0d5e	fd?d@Z1ede	fdAdBZ2ede	fdCdDZ3ddEdFZ4ddGdHZ5ede	fdIdJZ6edee	 fdKdLZ7ddMdNZ8ddOdPZ9ddQdRZ:ddSee; de	fdTdUZ<ede=fdVdWZ>ddXdYZ?ddZd[Z@dd\d]ZAdee$ fd^d_ZBdejejC fd`daZDddbdcZEddddeZFddfdgZGdheHddfdidjZIdheHddfdkdlZJdheHddfdmdnZKedeLfdodpZMeMjNddqdpZMeOjPdfdree	 defdsdtZQeOjPdfdree	 dee fdudvZRede$fdwdxZSdefdydzZTdefd{d|ZUdeVfd}d~ZWde	fddZXdde	ddfddZYdde	de$fddZZddeHdeHde	de$fddZ[dde$fddZ\de	ddfddZ]de$fddZ^dde$fddZ_edefddZ`e`jNdddZ`edd ZaeajNdddZaedd Zbdd Zcdd Zdeedd Zfedd Zgdd Zhdd ZidejddfddZkede	fddZlemdddZnemdeoddfddZpemdeeo fddZqemdee	erf ddfddZsemdddZtemdeddfddZude$fddZvde	de	ddfddZwdddZxedeyfddÄZzedefddńZ{ddǄ Z|eddɄ Z}ddd̈́Z~dS )	WebDrivera  Controls a browser by sending commands to a remote server. This server
    is expected to be running the WebDriver wire protocol as defined at
    https://www.selenium.dev/documentation/legacy/json_wire_protocol/.

    :Attributes:
     - session_id - String ID of the browser session started and controlled by this WebDriver.
     - capabilities - Dictionary of effective capabilities of this browser session as returned
         by the remote server. See https://www.selenium.dev/documentation/legacy/desired_capabilities/
     - command_executor - remote_connection.RemoteConnection object used to execute commands.
     - error_handler - errorhandler.ErrorHandler object used to handle errors.
    http://127.0.0.1:4444TNr<   r=   file_detectorrX   locator_converterweb_element_clsr?   r@   c           
      C   s   t |trt|}d}	n| }|j}	|| _t | jttfr(t||||	|d| _d| _	d| _
i | _i | _t | _t| | _t| | _|pFt | _|pLt | _|pR| j| _d| _|   | | t| | _d| _d| _dS )a  Create a new driver that will issue commands using the wire
        protocol.

        :Args:
         - command_executor - Either a string representing URL of the remote server or a custom
             remote_connection.RemoteConnection object. Defaults to 'http://127.0.0.1:4444/wd/hub'.
         - keep_alive - (Deprecated) Whether to configure remote_connection.RemoteConnection to use
             HTTP keep-alive. Defaults to True.
         - file_detector - Pass custom file detector object during instantiation. If None,
             then default LocalFileDetector() will be used.
         - options - instance of a driver options.Options class
         - locator_converter - Custom locator converter to use. Defaults to None.
         - web_element_cls - Custom class to use for web elements. Defaults to WebElement.
         - client_config - Custom client configuration to use. Defaults to None.
        F)r<   r=   r>   r?   TN)rN   listrh   rZ   _ignore_local_proxyr<   rO   bytesrW   
_is_remote
session_idr7   pinned_scriptsr!   error_handlerr*   
_switch_tor&   _mobiler$   rq   r%   rr   _web_element_cls_authenticator_idstart_clientstart_sessionr"   _fedcm_websocket_connection_script)
selfr<   r=   rq   rX   rr   rs   r?   r1   ru   r.   r.   r/   __init__   s<   





zWebDriver.__init__c                 C   s&   dt | j dt | j d| j dS )N<.z (session="z")>)typerk   rj   rx   r   r.   r.   r/   __repr__   s   &zWebDriver.__repr__c                 C   s   | S Nr.   r   r.   r.   r/   	__enter__   s   zWebDriver.__enter__exc_typeexc	tracebackc                 C   s   |    d S r   )quit)r   r   r   r   r.   r.   r/   __exit__   s   zWebDriver.__exit__c                 o   sP    d}t | j|s| j}||i || _zdV  W |r || _dS dS |r'|| _w )a  Overrides the current file detector (if necessary) in limited
        context. Ensures the original file detector is set afterwards.

        Example::

            with webdriver.file_detector_context(UselessFileDetector):
                someinput.send_keys('/etc/hosts')

        :Args:
         - file_detector_class - Class of the desired file detector. If the class is different
             from the current file_detector, then the class is instantiated with args and kwargs
             and used as a file detector during the duration of the context manager.
         - args - Optional arguments that get passed to the file detector class during
             instantiation.
         - kwargs - Keyword arguments, passed the same way as args.
        N)rN   rq   )r   file_detector_classargskwargslast_detectorr.   r.   r/   file_detector_context  s   
zWebDriver.file_detector_contextc                 C      | j S r   )r|   r   r.   r.   r/   mobile!     zWebDriver.mobilec                 C   s   d| j v r
| j d S td)zReturns the name of the underlying browser for this instance.

        :Usage:
            ::

                name = driver.name
        rF   z1browserName not specified in session capabilities)r7   KeyErrorr   r.   r.   r/   name%  s   
	
zWebDriver.namec                 C      dS )zxCalled before starting a new session.

        This method may be overridden to define custom startup behavior.
        Nr.   r   r.   r.   r/   r   2  s   zWebDriver.start_clientc                 C   r   )zCalled after executing a quit command.

        This method may be overridden to define custom shutdown
        behavior.
        Nr.   r   r.   r.   r/   stop_client9  s   zWebDriver.stop_clientr1   c                 C   s6   t |}| tj|d }|d| _|d| _dS )zCreates a new session with the desired capabilities.

        :Args:
         - capabilities - a capabilities dict to start the session with.
        value	sessionIdr1   N)r;   executer    NEW_SESSIONrH   rx   r7   )r   r1   r7   responser.   r.   r/   r   A  s   zWebDriver.start_sessionc                    s   t |tri }| D ]\}} |||< q|S t | jr$d|jiS t | jr/d|jiS t |tr?t fdd|D S |S )N#element-6066-11e4-a52e-4f735466cecf"shadow-6066-11e4-a52e-4f735466cecfc                 3       | ]}  |V  qd S r   )_wrap_valuerI   itemr   r.   r/   rL   X      z(WebDriver._wrap_value.<locals>.<genexpr>)rN   dictr6   r   r}   id_shadowroot_clsrt   )r   r   	convertedkeyvalr.   r   r/   r   M  s   



zWebDriver._wrap_value
element_idc                 C   s   |  | |S )z6Creates a web element with the specified `element_id`.)r}   )r   r   r.   r.   r/   create_web_element[  s   zWebDriver.create_web_elementc                    s   t |tr.d|v r |d S d|v r  |d S | D ]\}} |||< q |S t |tr>t fdd|D S |S )Nr   r   c                 3   r   r   )_unwrap_valuer   r   r.   r/   rL   i  r   z*WebDriver._unwrap_value.<locals>.<genexpr>)rN   r   r   r   r6   r   rt   )r   r   r   r   r.   r   r/   r   _  s   

zWebDriver._unwrap_valuedriver_commandparamsc                 C   sx   |  |}| jr|sd| ji}n	d|vr| j|d< | j||}|r5| j| | |dd|d< |S dd| jdS )aH  Sends a command to be executed by a command.CommandExecutor.

        :Args:
         - driver_command: The name of the command to execute as a string.
         - params: A dictionary of named parameters to send with the command.

        :Returns:
          The command's JSON response loaded into a dictionary object.
        r   r   Nr   )successr   r   )r   rx   r<   r   rz   check_responser   rH   )r   r   r   r   r.   r.   r/   r   l  s   


zWebDriver.executeurlc                 C      |  tjd|i dS )z0Loads a web page in the current browser session.r   N)r   r    GET)r   r   r.   r.   r/   rH     s   zWebDriver.getc                 C   s   |  tjddS )zuReturns the title of the current page.

        :Usage:
            ::

                title = driver.title
        r    )r   r    	GET_TITLErH   r   r.   r.   r/   title  s   	zWebDriver.titlescriptc                 C   s   t |}|| j|j< |S )zUStore common javascript scripts to be executed later by a unique
        hashable ID.)r(   ry   r   )r   r   
script_keyscript_key_instancer.   r.   r/   
pin_script  s   zWebDriver.pin_scriptr   c                 C   s<   z
| j |j W dS  ty   td| d| j  dw )z$Remove a pinned script from storage.zNo script with key: z existed in N)ry   popr   r   )r   r   r.   r.   r/   unpin  s
   zWebDriver.unpinc                 C   s
   t | jS r   )rt   ry   r   r.   r.   r/   get_pinned_scripts  s   
zWebDriver.get_pinned_scriptsc                 G   sV   t |trz| j|j }W n ty   tdw t|}tj}| 	|||dd S )a'  Synchronously Executes JavaScript in the current window/frame.

        :Args:
         - script: The JavaScript to execute.
         - \*args: Any applicable arguments for your JavaScript.

        :Usage:
            ::

                driver.execute_script('return document.title;')
        z Pinned script could not be foundr   r   r   )
rN   r(   ry   r   r   r   rt   r    W3C_EXECUTE_SCRIPTr   r   r   r   converted_argscommandr.   r.   r/   execute_script  s   
zWebDriver.execute_scriptc                 G   s$   t |}tj}| |||dd S )a  Asynchronously Executes JavaScript in the current window/frame.

        :Args:
         - script: The JavaScript to execute.
         - \*args: Any applicable arguments for your JavaScript.

        :Usage:
            ::

                script = "var callback = arguments[arguments.length - 1]; " \
                         "window.setTimeout(function(){ callback('timeout') }, 3000);"
                driver.execute_async_script(script)
        r   r   )rt   r    W3C_EXECUTE_SCRIPT_ASYNCr   r   r.   r.   r/   execute_async_script  s   zWebDriver.execute_async_scriptc                 C      |  tjd S )znGets the URL of the current page.

        :Usage:
            ::

                driver.current_url
        r   )r   r    GET_CURRENT_URLr   r.   r.   r/   current_url     	zWebDriver.current_urlc                 C   r   )zqGets the source of the current page.

        :Usage:
            ::

                driver.page_source
        r   )r   r    GET_PAGE_SOURCEr   r.   r.   r/   page_source  r   zWebDriver.page_sourcec                 C      |  tj dS )zcCloses the current window.

        :Usage:
            ::

                driver.close()
        N)r   r    CLOSEr   r.   r.   r/   close     zWebDriver.closec                 C   s:   z|  tj W |   | j  dS |   | j  w )z|Quits the driver and closes every associated window.

        :Usage:
            ::

                driver.quit()
        N)r   r    QUITr   r<   r   r   r.   r.   r/   r     s   zWebDriver.quitc                 C   r   )zReturns the handle of the current window.

        :Usage:
            ::

                driver.current_window_handle
        r   )r   r    W3C_GET_CURRENT_WINDOW_HANDLEr   r.   r.   r/   current_window_handle  r   zWebDriver.current_window_handlec                 C   r   )zReturns the handles of all windows within the current session.

        :Usage:
            ::

                driver.window_handles
        r   )r   r    W3C_GET_WINDOW_HANDLESr   r.   r.   r/   window_handles
  r   zWebDriver.window_handlesc                 C   s   t j}| |d dS )z5Maximizes the current window that webdriver is using.N)r    W3C_MAXIMIZE_WINDOWr   )r   r   r.   r.   r/   maximize_window  s   zWebDriver.maximize_windowc                 C   r   )z<Invokes the window manager-specific 'full screen' operation.N)r   r    FULLSCREEN_WINDOWr   r.   r.   r/   fullscreen_window     zWebDriver.fullscreen_windowc                 C   r   )z9Invokes the window manager-specific 'minimize' operation.N)r   r    MINIMIZE_WINDOWr   r.   r.   r/   minimize_window  r   zWebDriver.minimize_windowprint_optionsc                 C   s"   i }|r|  }| tj|d S )zTakes PDF of the current page.

        The driver makes a best effort to return a PDF based on the
        provided parameters.
        r   )to_dictr   r    
PRINT_PAGE)r   r   rX   r.   r.   r/   
print_page"  s   zWebDriver.print_pagec                 C   r   )a<  
        :Returns:
            - SwitchTo: an object containing all options to switch focus into

        :Usage:
            ::

                element = driver.switch_to.active_element
                alert = driver.switch_to.alert
                driver.switch_to.default_content()
                driver.switch_to.frame('frame_name')
                driver.switch_to.frame(1)
                driver.switch_to.frame(driver.find_elements(By.TAG_NAME, "iframe")[0])
                driver.switch_to.parent_frame()
                driver.switch_to.window('main')
        )r{   r   r.   r.   r/   	switch_to.  s   zWebDriver.switch_toc                 C   r   )zvGoes one step backward in the browser history.

        :Usage:
            ::

                driver.back()
        N)r   r    GO_BACKr   r.   r.   r/   backC  r   zWebDriver.backc                 C   r   )zxGoes one step forward in the browser history.

        :Usage:
            ::

                driver.forward()
        N)r   r    
GO_FORWARDr   r.   r.   r/   forwardM  r   zWebDriver.forwardc                 C   r   )zfRefreshes the current page.

        :Usage:
            ::

                driver.refresh()
        N)r   r    REFRESHr   r.   r.   r/   refreshW  r   zWebDriver.refreshc                 C   r   )zReturns a set of dictionaries, corresponding to cookies visible in
        the current session.

        :Usage:
            ::

                driver.get_cookies()
        r   )r   r    GET_ALL_COOKIESr   r.   r.   r/   get_cookiesb  r   zWebDriver.get_cookiesc                 C   sD   t t | tjd|id W  d   S 1 sw   Y  dS )zGet a single cookie by name. Returns the cookie if found, None if
        not.

        :Usage:
            ::

                driver.get_cookie('my_cookie')
        r   r   N)
contextlibsuppressr   r   r    
GET_COOKIEr   r   r.   r.   r/   
get_cookiem  s   	 zWebDriver.get_cookiec                 C   r   )zDeletes a single cookie with the given name.

        :Usage:
            ::

                driver.delete_cookie('my_cookie')
        r   N)r   r    DELETE_COOKIEr   r.   r.   r/   delete_cookiez  s   zWebDriver.delete_cookiec                 C   r   )zDelete all cookies in the scope of the session.

        :Usage:
            ::

                driver.delete_all_cookies()
        N)r   r    DELETE_ALL_COOKIESr   r.   r.   r/   delete_all_cookies  r   zWebDriver.delete_all_cookiesc                 C   sD   d|v r|d dv sJ |  tjd|i dS |  tjd|i dS )ag  Adds a cookie to your current session.

        :Args:
         - cookie_dict: A dictionary object, with required keys - "name" and "value";
            optional keys - "path", "domain", "secure", "httpOnly", "expiry", "sameSite"

        :Usage:
            ::

                driver.add_cookie({'name' : 'foo', 'value' : 'bar'})
                driver.add_cookie({'name' : 'foo', 'value' : 'bar', 'path' : '/'})
                driver.add_cookie({'name' : 'foo', 'value' : 'bar', 'path' : '/', 'secure' : True})
                driver.add_cookie({'name' : 'foo', 'value' : 'bar', 'sameSite' : 'Strict'})
        sameSite)StrictLaxNonecookieN)r   r    
ADD_COOKIE)r   cookie_dictr.   r.   r/   
add_cookie  s   zWebDriver.add_cookietime_to_waitc                 C   "   |  tjdtt|d i dS )a  Sets a sticky timeout to implicitly wait for an element to be found,
        or a command to complete. This method only needs to be called one time
        per session. To set the timeout for calls to execute_async_script, see
        set_script_timeout.

        :Args:
         - time_to_wait: Amount of time to wait (in seconds)

        :Usage:
            ::

                driver.implicitly_wait(30)
        implicit  Nr   r    SET_TIMEOUTSintfloatr   r   r.   r.   r/   implicitly_wait  s   "zWebDriver.implicitly_waitc                 C   r  )a!  Set the amount of time that the script should wait during an
        execute_async_script call before throwing an error.

        :Args:
         - time_to_wait: The amount of time to wait (in seconds)

        :Usage:
            ::

                driver.set_script_timeout(30)
        r   r  Nr  r  r.   r.   r/   set_script_timeout  s   "zWebDriver.set_script_timeoutc              	   C   sV   z|  tjdtt|d i W dS  ty*   |  tjt|d dd Y dS w )zSet the amount of time to wait for a page load to complete before
        throwing an error.

        :Args:
         - time_to_wait: The amount of time to wait

        :Usage:
            ::

                driver.set_page_load_timeout(30)
        pageLoadr  z	page load)msr   N)r   r    r  r  r  r   r  r.   r.   r/   set_page_load_timeout  s
   $"zWebDriver.set_page_load_timeoutc                 C   sT   |  tjd }|dd |d< |dd |d< |dd |d< td	i |S )
zGet all the timeouts that have been set on the current session.

        :Usage:
            ::

                driver.timeouts
        :rtype: Timeout
        r   r  r  implicit_waitr  	page_loadr   Nr.   )r   r    GET_TIMEOUTSr   r   )r   timeoutsr.   r.   r/   r    s
   
zWebDriver.timeoutsc                 C   s   |  tj| d }dS )a  Set all timeouts for the session. This will override any previously
        set timeouts.

        :Usage:
            ::
                my_timeouts = Timeouts()
                my_timeouts.implicit_wait = 10
                driver.timeouts = my_timeouts
        r   N)r   r    r  _to_json)r   r  _r.   r.   r/   r    s   r   c                 C   s^   | j ||\}}t|tr#| j||d}|std|j |d S | tj	||dd S )zFind an element given a By strategy and locator.

        :Usage:
            ::

                element = driver.find_element(By.ID, 'foo')

        :rtype: WebElement
        )byr   z%Cannot locate relative element with: r   usingr   r   )
rr   convertrN   r   find_elementsr   rootr   r    FIND_ELEMENT)r   r  r   elementsr.   r.   r/   find_element  s   

zWebDriver.find_elementc                 C   s~   | j ||\}}t|tr1dtddd }t|d	d}d| d}| 
|| S | tj||dd	 p>g S )
zFind elements given a By strategy and locator.

        :Usage:
            ::

                elements = driver.find_elements(By.CLASS_NAME, 'foo')

        :rtype: list of WebElement
        r   NzfindElements.jsutf8z/* findElements */return (z).apply(null, arguments);r  r   )rr   r  rN   r   joinrj   splitpkgutilget_datadecoder   r   r   r    FIND_ELEMENTS)r   r  r   _pkgraw_functionfind_element_jsr.   r.   r/   r    s   

zWebDriver.find_elementsc                 C   r   )z4Returns the drivers current capabilities being used.)r7   r   r.   r.   r/   r1        zWebDriver.capabilitiesc                 C   s   t | dstjdtdd |  }z1z$t|d}|| W d   n1 s,w   Y  W W ~dS W W ~dS  t	yF   Y W ~dS w ~w )	a  Saves a screenshot of the current window to a PNG image file.
        Returns False if there is any IOError, else returns True. Use full
        paths in your filename.

        :Args:
         - filename: The full path you wish to save your screenshot to. This
           should end with a `.png` extension.

        :Usage:
            ::

                driver.get_screenshot_as_file('/Screenshots/foo.png')
        z.pngz^name used for saved screenshot does not match file type. It should end with a `.png` extensionr   
stacklevelwbNFT)
rO   lowerendswithwarningswarnUserWarningget_screenshot_as_pngopenwriteOSError)r   filenamepngfr.   r.   r/   get_screenshot_as_file  s*    z WebDriver.get_screenshot_as_filec                 C   s
   |  |S )a  Saves a screenshot of the current window to a PNG image file.
        Returns False if there is any IOError, else returns True. Use full
        paths in your filename.

        :Args:
         - filename: The full path you wish to save your screenshot to. This
           should end with a `.png` extension.

        :Usage:
            ::

                driver.save_screenshot('/Screenshots/foo.png')
        )r8  )r   r5  r.   r.   r/   save_screenshot=  s   
zWebDriver.save_screenshotc                 C   s   t |  dS )zGets the screenshot of the current window as a binary data.

        :Usage:
            ::

                driver.get_screenshot_as_png()
        ascii)r   get_screenshot_as_base64encoder   r.   r.   r/   r1  M  s   zWebDriver.get_screenshot_as_pngc                 C   r   )zGets the screenshot of the current window as a base64 encoded string
        which is useful in embedded images in HTML.

        :Usage:
            ::

                driver.get_screenshot_as_base64()
        r   )r   r    
SCREENSHOTr   r.   r.   r/   r;  W  r   z"WebDriver.get_screenshot_as_base64currentwindowHandlec                 C   s$   |  | | jt|t|d dS )a$  Sets the width and height of the current window. (window.resizeTo)

        :Args:
         - width: the width in pixels to set the window to
         - height: the height in pixels to set the window to

        :Usage:
            ::

                driver.set_window_size(800,600)
        widthheightN"_check_if_window_handle_is_currentset_window_rectr  )r   rA  rB  r?  r.   r.   r/   set_window_sizeb  s   
zWebDriver.set_window_sizec                    s8   |  | |    ddr d   fdddD S )zGets the width and height of the current window.

        :Usage:
            ::

                driver.get_window_size()
        r   Nc                       i | ]}| | qS r.   r.   rI   r9   sizer.   r/   
<dictcomp>      z-WebDriver.get_window_size.<locals>.<dictcomp>r@  )rD  get_window_rectrH   r   r?  r.   rI  r/   get_window_sizeq  s
   
	zWebDriver.get_window_sizexyc                 C   s    |  | | jt|t|dS )a.  Sets the x,y position of the current window. (window.moveTo)

        :Args:
         - x: the x-coordinate in pixels to set the window position
         - y: the y-coordinate in pixels to set the window position

        :Usage:
            ::

                driver.set_window_position(0,0)
        rP  rQ  rC  )r   rP  rQ  r?  r.   r.   r/   set_window_position  s   
zWebDriver.set_window_positionc                    s$   |  | |    fdddD S )zGets the x,y position of the current window.

        :Usage:
            ::

                driver.get_window_position()
        c                    rG  r.   r.   rH  positionr.   r/   rK    rL  z1WebDriver.get_window_position.<locals>.<dictcomp>rR  )rD  rM  rN  r.   rT  r/   get_window_position  s   
	zWebDriver.get_window_positionc                 C   s   |dkrt jddd dS dS )z5Warns if the window handle is not equal to `current`.r>  z?Only 'current' window is supported for W3C compatible browsers.r   r)  N)r.  r/  rN  r.   r.   r/   rD    s   z,WebDriver._check_if_window_handle_is_currentc                 C   r   )zGets the x, y coordinates of the window as well as height and width
        of the current window.

        :Usage:
            ::

                driver.get_window_rect()
        r   )r   r    GET_WINDOW_RECTr   r.   r.   r/   rM    r   zWebDriver.get_window_rectc                 C   s<   |du r|du r|s|st d| tj||||dd S )a  Sets the x, y coordinates of the window as well as height and width
        of the current window. This method is only supported for W3C compatible
        browsers; other browsers should use `set_window_position` and
        `set_window_size`.

        :Usage:
            ::

                driver.set_window_rect(x=10, y=10)
                driver.set_window_rect(width=100, height=200)
                driver.set_window_rect(x=10, y=10, width=100, height=200)
        Nz'x and y or height and width need values)rP  rQ  rA  rB  r   )r   r   r    SET_WINDOW_RECT)r   rP  rQ  rA  rB  r.   r.   r/   rE    s   zWebDriver.set_window_rectc                 C   r   r   )_file_detectorr   r.   r.   r/   rq     r   zWebDriver.file_detectorc                 C   s(   |st dt|tst d|| _dS )a0  Set the file detector to be used when sending keyboard input. By
        default, this is set to a file detector that does nothing.

        see FileDetector
        see LocalFileDetector
        see UselessFileDetector

        :Args:
         - detector: The detector to use. Must not be None.
        z,You may not set a file detector that is nullz+Detector has to be instance of FileDetectorN)r   rN   r#   rY  )r   detectorr.   r.   r/   rq     s
   

c                 C   r   )zGets the current orientation of the device.

        :Usage:
            ::

                orientation = driver.orientation
        r   )r   r    GET_SCREEN_ORIENTATIONr   r.   r.   r/   orientation  r   zWebDriver.orientationc                 C   s2   ddg}|  |v r| tjd|i dS td)zSets the current orientation of the device.

        :Args:
         - value: orientation to set it to.

        :Usage:
            ::

                driver.orientation = 'landscape'
        	LANDSCAPEPORTRAITr\  z>You can only set the orientation to 'LANDSCAPE' and 'PORTRAIT'N)upperr   r    SET_SCREEN_ORIENTATIONr   )r   r   allowed_valuesr.   r.   r/   r\    s   c                 C   r   )zGets a list of the available log types. This only works with w3c
        compliant browsers.

        :Usage:
            ::

                driver.log_types
        r   )r   r    GET_AVAILABLE_LOG_TYPESr   r.   r.   r/   	log_types  s   
zWebDriver.log_typesc                 C   s   |  tjd|id S )a>  Gets the log for a given log type.

        :Args:
         - log_type: type of log that which will be returned

        :Usage:
            ::

                driver.get_log('browser')
                driver.get_log('driver')
                driver.get_log('client')
                driver.get_log('server')
        r   r   )r   r    GET_LOG)r   log_typer.   r.   r/   get_log  s   zWebDriver.get_logc                 C   s   | j rt| j fS t  tsG| jdr%| jd}| jddd }n|  \}}|s1tdt	|a| jd 
 dkrGtjdtd	d
 t|| _ | j tj }|d j}| j tj|d}|| j _t| j fS )Nse:cdpse:cdpVersionr   r   2Unable to find url to connect to from capabilitiesrF   firefoxznCDP support for Firefox is deprecated and will be removed in future versions. Please switch to WebDriver BiDi.r   r)  T)r   devtoolsr0   r7   rH   r   _get_cdp_detailsr   r-   import_devtoolsr,  r.  r/  DeprecationWarningr,   r   targetget_targets	target_idattach_to_targetrx   )r   ws_urlversiontargetsrq  sessionr.   r.   r/   start_devtools  s.   




zWebDriver.start_devtoolsc              
   C  s
  t   | jdr| jd}| jddd }n|  \}}|s(tdt|}t|4 I d H B}|	|j
 I d H }|d j}||4 I d H }t|t|V  W d   I d H  n1 I d H shw   Y  W d   I d H  d S 1 I d H s~w   Y  d S )Nrg  rh  r   r   ri  )r0   r7   rH   r   rl  r   r-   rm  open_cdpr   ro  rp  rq  open_sessionr   )r   rs  rt  rk  connru  rq  rv  r.   r.   r/   bidi_connection1  s    

*.zWebDriver.bidi_connectionc                 C   s&   | j s|   | jst| j | _| jS r   )r   _start_bidir   r   r   r.   r.   r/   r   E  s
   zWebDriver.scriptc                 C   s0   | j dr| j d}ntdt|| _d S )NwebSocketUrlri  )r7   rH   r   r,   r   )r   rs  r.   r.   r/   r|  O  s   zWebDriver._start_bidic                 C   s   dd l }dd l}| }d}| jddkr | jdd}n| jddkr2| jdd}nd	}| jd
}|dd| d}||j}|d}|d}	dd l}
|r`d}||	fS |
	d|
d}||	fS )Nr   FrF   chromezgoog:chromeOptionsdebuggerAddressMicrosoftEdgezms:edgeOptionsTzmoz:debuggerAddressr   zhttp://z/json/versionBrowserwebSocketDebuggerUrlU   z
.*/(\d+)\.r   )jsonurllib3PoolManagerr7   rH   requestloadsdataresearchgroup)r   r  r  http_firefoxdebugger_addressresr  browser_versionwebsocket_urlr  rt  r.   r.   r/   rl  W  s(   

zWebDriver._get_cdp_detailsc                 C   s   |  tj| d | _dS )z4Adds a virtual authenticator with the given options.r   N)r   r    ADD_VIRTUAL_AUTHENTICATORr   r~   )r   rX   r.   r.   r/   add_virtual_authenticatorw  s   z#WebDriver.add_virtual_authenticatorc                 C   r   )z,Returns the id of the virtual authenticator.)r~   r   r.   r.   r/   virtual_authenticator_id{  r(  z"WebDriver.virtual_authenticator_idc                 C   s   |  tjd| ji d| _dS )zRemoves a previously added virtual authenticator.

        The authenticator is no longer valid after removal, so no
        methods may be called.
        authenticatorIdN)r   r    REMOVE_VIRTUAL_AUTHENTICATORr~   r   r.   r.   r/   remove_virtual_authenticator  s   
z&WebDriver.remove_virtual_authenticator
credentialc                 C   s$   |  tji | d| ji dS )z,Injects a credential into the authenticator.r  N)r   r    ADD_CREDENTIALr   r~   )r   r  r.   r.   r/   add_credential  s   $zWebDriver.add_credentialc                 C   s&   |  tjd| ji}dd |d D S )z;Returns the list of credentials owned by the authenticator.r  c                 S   s   g | ]}t |qS r.   )r   	from_dict)rI   r  r.   r.   r/   
<listcomp>  rL  z-WebDriver.get_credentials.<locals>.<listcomp>r   )r   r    GET_CREDENTIALSr~   )r   credential_datar.   r.   r/   get_credentials  s   zWebDriver.get_credentialscredential_idc                 C   s0   t |trt| }| tj|| jd dS )z,Removes a credential from the authenticator.)credentialIdr  N)rN   	bytearrayr   r#  r   r    REMOVE_CREDENTIALr~   )r   r  r.   r.   r/   remove_credential  s
   
zWebDriver.remove_credentialc                 C   s   |  tjd| ji dS )z/Removes all credentials from the authenticator.r  N)r   r    REMOVE_ALL_CREDENTIALSr~   r   r.   r.   r/   remove_all_credentials  s   z WebDriver.remove_all_credentialsverifiedc                 C   s   |  tj| j|d dS )zSets whether the authenticator will simulate success or fail on user
        verification.

        verified: True if the authenticator will pass user verification, False otherwise.
        )r  isUserVerifiedN)r   r    SET_USER_VERIFIEDr~   )r   r  r.   r.   r/   set_user_verified  s   zWebDriver.set_user_verifiedc                 C   s&   d| j vr	td| tjd d S )z]Retrieves the downloadable files as a map of file names and their
        corresponding URLs.se:downloadsEnabledCYou must enable downloads in order to work with downloadable files.r   names)r1   r   r   r    GET_DOWNLOADABLE_FILESr   r.   r.   r/   get_downloadable_files  s   
z WebDriver.get_downloadable_files	file_nametarget_directoryc              	   C   s  d| j vr	tdtj|st| | tjd|id d }t	
 R}tj||d }t|d}|t| W d   n1 sGw   Y  t|d	}|| W d   n1 sbw   Y  W d   dS W d   dS 1 szw   Y  dS )
zDownloads a file with the specified file name to the target
        directory.

        file_name: The name of the file to download.
        target_directory: The path to the directory to save the downloaded file.
        r  r  r   r   contentsz.zipr+  Nr)r1   r   ospathexistsmakedirsr   r    DOWNLOAD_FILEtempfileTemporaryDirectoryr  r2  r3  base64r   zipfileZipFile
extractall)r   r  r  r  tmp_dirzip_filefilezip_refr.   r.   r/   download_file  s    


"zWebDriver.download_filec                 C   s"   d| j vr	td| tj dS )zDeletes all downloadable files.r  r  N)r1   r   r   r    DELETE_DOWNLOADABLE_FILESr   r.   r.   r/   delete_downloadable_files  s   
z#WebDriver.delete_downloadable_filesc                 C   r   )aw  
        :Returns:
            - FedCM: an object providing access to all Federated Credential Management (FedCM) dialog commands.

        :Usage:
            ::

                title = driver.fedcm.title
                subtitle = driver.fedcm.subtitle
                dialog_type = driver.fedcm.dialog_type
                accounts = driver.fedcm.account_list
                driver.fedcm.select_account(0)
                driver.fedcm.accept()
                driver.fedcm.dismiss()
                driver.fedcm.enable_delay()
                driver.fedcm.disable_delay()
                driver.fedcm.reset_cooldown()
        )r   r   r.   r.   r/   fedcm  s   zWebDriver.fedcmc                 C   s   | j tjdS )z8Returns whether the browser supports FedCM capabilities.F)r1   rH   r   FEDCM_CAPABILITYr   r.   r.   r/   supports_fedcm  s   zWebDriver.supports_fedcmc                 C   s   | j stddS )z.Raises an exception if FedCM is not supported.znThis browser does not support Federated Credential Management. Please ensure you're using a supported browser.N)r  r   r   r.   r.   r/   _require_fedcm_support  s
   z WebDriver._require_fedcm_supportc                 C   s   |    t| S )z0Returns the FedCM dialog object for interaction.)r  r   r   r.   r.   r/   dialog  s   zWebDriver.dialog         ?c                    s^   ddl m  ddlm}   |du r f} fdd||||d}|fdd	S )
a  Waits for and returns the FedCM dialog.

        Args:
            timeout: How long to wait for the dialog
            poll_frequency: How frequently to poll
            ignored_exceptions: Exceptions to ignore while waiting

        Returns:
            The FedCM dialog object if found

        Raises:
            TimeoutException if dialog doesn't appear
            WebDriverException if FedCM not supported
        r   )NoAlertPresentException)WebDriverWaitNc                     s0   zt } | jr| W S d W S   y   Y d S w r   )r   r   )r  )r  r   r.   r/   _check_fedcm  s   z,WebDriver.fedcm_dialog.<locals>._check_fedcm)poll_frequencyignored_exceptionsc                    s     S r   r.   )r  )r  r.   r/   <lambda>  s    z(WebDriver.fedcm_dialog.<locals>.<lambda>)selenium.common.exceptionsr  selenium.webdriver.support.waitr  r  until)r   timeoutr  r  r  waitr.   )r  r  r   r/   fedcm_dialog  s   zWebDriver.fedcm_dialog)rp   TNNNNNr   )r@   N)r>  )NNNN)r  r  N)rj   rk   rl   rm   r+   r}   r)   r   r   rO   r'   boolr
   r#   r   r	   r%   r   r   r   r   r   typingTypeBaseExceptiontypesTracebackTyper   r   r   propertyr&   r   r   r   r   r   r   r   r   r   r   rH   r   r(   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r*   r   r   r   r   r   r   r   r   r   r   r  r	  r
  r  r   r  setterr   IDr  r  r1   r8  r9  rv   r1  r;  rF  rO  rS  rV  rD  rM  rE  rq   r\  rc  rf  rw  r   r{  r   r|  rl  r   r  r  r   r  r   r  r  r  r  r  r  r  r  r  r"   r  r  r  r  r  r.   r.   r.   r/   ro      s(   
	
;























"



 

	 	


ro   r   )Xrm   r  r   r4   r  r!  r  r  r  r.  r  abcr   r   r   r   r   	importlibr   r   r	   r
   r   r  r   r   r   r   r   %selenium.webdriver.common.bidi.scriptr   selenium.webdriver.common.byr   !selenium.webdriver.common.optionsr   r   ,selenium.webdriver.common.print_page_optionsr   "selenium.webdriver.common.timeoutsr   /selenium.webdriver.common.virtual_authenticatorr   r   r   +selenium.webdriver.support.relative_locatorr   common.fedcm.dialogr   r{  r   r?   r   r   r    errorhandlerr!   r  r"   rq   r#   r$   rr   r%   r   r&   remote_connectionr'   r   r(   
shadowrootr)   r   r*   
webelementr+   websocket_connectionr,   r-   rk  r0   r;   r   rO   r  rW   rh   ri   ro   r.   r.   r.   r/   <module>   s   

"