
    ^j.K                        d dl mZmZmZmZmZmZmZmZm	Z	m
Z
 d dlmZmZmZ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@mAZA d	dlBmCZC d	dlDmEZE d	dlFmGZG d	dlHmIZI d	d lJmKZK d	d!lLmMZM d	d"lNmOZO d	d#lPmQZQ d	d$lRmSZS d	d%lTmUZU d	d&lVmWZW d	d'lXmYZY d	d(lZm[Z d	d)l\m]Z] d	d*l^m_Z`  G d+ d,      Za	 d4d.e
ebef   d/ee!   d0eceee!   f   fd1Zd G d2 d3ee%e'e9e;e=e)e?e+eAeCe-eEeGeIeKeMeOe/e1e3eQeSeUeWe5e7      Zy-)5    )
TYPE_CHECKINGAnyCallableDictListOptionalSetTupleTypeUnion)InvalidArgumentExceptionSessionNotCreatedExceptionUnknownMethodExceptionWebDriverException)Command)RemoteConnection)	WebDriver)Self)logger)AppiumOptions   )AppiumConnection)AppiumClientConfig)MobileErrorHandler)ActionHelpers)
Activities)Common)Display)Gsm)Network)Performance)Power)Sms)
SystemBars)Applications)	Clipboard)Context)
DeviceTime)ExecuteDriver)ExecuteMobileCommand)HardwareActions)ImagesComparison)Keyboard)Location)LogEvent)Logs)RemoteFS)ScreenRecord)Session)Settings)AppiumLocatorConverter)MobileCommandMobileSwitchTo)
WebElementc                   |    e Zd ZdZdeeegeeef   f   fdZd
de	eeef   df   defdZ
defdZdeeef   fd	Zy)ExtensionBasea  
    Used to define an extension command as driver's methods.

    Example:
        When you want to add `example_command` which calls a get request to
        `session/$sessionId/path/to/your/custom/url`.

        #. Defines an extension as a subclass of `ExtensionBase`
            .. code-block:: python

                class YourCustomCommand(ExtensionBase):
                    def method_name(self):
                        return 'custom_method_name'

                    # Define a method with the name of `method_name`
                    def custom_method_name(self):
                        # Generally the response of Appium follows `{ 'value': { data } }`
                        # format.
                        return self.execute()['value']

                    # Used to register the command pair as "Appium command" in this driver.
                    def add_command(self):
                        return ('GET', 'session/$sessionId/path/to/your/custom/url')

        #. Creates a session with the extension.
            .. code-block:: python

                # Appium capabilities
                options = AppiumOptions()
                driver = webdriver.Remote('http://localhost:4723/wd/hub', options=options,
                    extensions=[YourCustomCommand])

        #. Calls the custom command
            .. code-block:: python

                # Then, the driver calls a get request against
                # `session/$sessionId/path/to/your/custom/url`. `$sessionId` will be
                # replaced properly in the driver. Then, the method returns
                # the `value` part of the response.
                driver.custom_method_name()

        #. Remove added commands (if needed)
            .. code-block:: python

                # New commands are added by `setattr`. They remain in the module,
                # so you should explicitly delete them to define the same name method
                # with different arguments or process in the method.
                driver.delete_extensions()


        You can give arbitrary arguments for the command like the below.

        .. code-block:: python

            class YourCustomCommand(ExtensionBase):
                def method_name(self):
                    return 'custom_method_name'

                def test_command(self, argument):
                    return self.execute(argument)['value']

                def add_command(self):
                    return ('post', 'session/$sessionId/path/to/your/custom/url')

            driver = webdriver.Remote('http://localhost:4723/wd/hub', options=options,
                extensions=[YourCustomCommand])

            # Then, the driver sends a post request to `session/$sessionId/path/to/your/custom/url`
            # with `{'dummy_arg': 'as a value'}` JSON body.
            driver.custom_method_name({'dummy_arg': 'as a value'})


        When you customize the URL dynamically with element id.

        .. code-block:: python

            class CustomURLCommand(ExtensionBase):
                def method_name(self):
                    return 'custom_method_name'

                def custom_method_name(self, element_id):
                    return self.execute({'id': element_id})['value']

                def add_command(self):
                    return ('GET', 'session/$sessionId/path/to/your/custom/$id/url')

            driver = webdriver.Remote('http://localhost:4723/wd/hub', options=options,
                extensions=[YourCustomCommand])
            element = driver.find_element(by=AppiumBy.ACCESSIBILITY_ID, value='id')

            # Then, the driver calls a get request to `session/$sessionId/path/to/your/custom/$id/url`
            # with replacing the `$id` with the given `element.id`
            driver.custom_method_name(element.id)

    executec                     || _         y N)_execute)selfr<   s     N/home/ubuntu/.local/lib/python3.12/site-packages/appium/webdriver/webdriver.py__init__zExtensionBase.__init__   s	        N
parametersreturnc                 N    i }|r|}| j                  | j                         |      S r>   )r?   method_name)r@   rD   params      rA   r<   zExtensionBase.execute   s)    E}}T--/77rC   c                     t               )z
        Expected to return a method name.
        This name will be available as a driver method.

        Returns:
            'str' The method name.
        NotImplementedErrorr@   s    rA   rG   zExtensionBase.method_name   s     "##rC   c                     t               )zI
        Expected to define the pair of HTTP method and its URL.
        rJ   rL   s    rA   add_commandzExtensionBase.add_command   s     "##rC   r>   )__name__
__module____qualname____doc__r   strr   r   rB   r   r<   rG   r
   rN    rC   rA   r;   r;   D   sp    ^@ #td38n)D E  8%S#X(<"= 8 8$S $$U38_ $rC   r;   Ncommand_executorclient_configrE   c                 f    t        | t              s| dfS |t        |       n|}t        |      |fS )a-  Return the pair of command executor and client config.
    If the given command executor is a custom one, returned client config will
    be None since the custom command executor has its own client config already.
    The custom command executor's one will be prior than the given client config.
    N)remote_server_addr)rV   )
isinstancerS   r   r   )rU   rV   new_client_configs      rA   (_get_remote_connection_and_client_configr[      sG     &, !$'' TaSh*>NOn{+<=?PQQrC   c            
           e Zd Z	 	 	 	 ddeeef   deeed         dee	ee	   df   dee
   f fdZer%dded	eeedf   d
dfdZdded	eeedf   d
ed   fdZd dZded
dfdZddeee	f   dee   d
dfdZd
efdZdeeef   d
efdZed
efd       Zed
efd       Zej8                  d	ed
dfd       Zded
efdZded
efdZd dZ  xZ!S )!r   NrU   
extensionsr;   optionsrV   c           	         t        ||      \  }}t        
| 	  ||t               t        |       |  | j                          t               | _        |r(|j                  r| j                  |j                         t               | _        |xs g | _        | j                  D ]  } || j                        }|j                         }t!        t"        |      rt%        j&                  d| d       t)        t"        |t+        ||             |j-                         \  }}	| j.                  j-                  ||j1                         |	        y )N)rU   rV   )rU   r^   locator_converterweb_element_clsrV   
keep_alivezOverriding the method '')r[   superrB   r5   MobileWebElement_add_commandsr   error_handlerdirect_connection_update_command_executorrc   set_absent_extensions_extensionsr<   rG   hasattrr   r   debugsetattrgetattrrN   rU   upper)r@   rU   r]   r^   rV   	extensioninstancerG   methodurl_cmd	__class__s             rA   rB   zWebDriver.__init__   s.    +S-]+
'- 	-46,' 	 	
 	/1]<<))]5M5M)N,/E%+)) 		TI .H"..0Ky+.6{m1EF I{GHk,JK&224OFG!!--k6<<>7S		TrC   byvaluerE   rf   c                      y r>   rT   r@   rx   ry   s      rA   find_elementzWebDriver.find_element      rC   c                      y r>   rT   r{   s      rA   find_elementszWebDriver.find_elements   r}   rC   c                     | j                   D ]E  } || j                        }|j                         }t        t        |      s6t        t        |       G y)z3Delete extensions added in the class with 'setattr'N)rm   r<   rG   rn   r   delattr)r@   rs   rt   rG   s       rA   delete_extensionszWebDriver.delete_extensions#  sG    )) 	0I .H"..0Ky+.	;/		0rC   rc   c                 |   d}d}d}d}| j                   st        d      ||||hj                  t        | j                               sHd}||||fD ]'  }|| d| j                   j	                  |d       d	z  }) t        j                  |       y
| j                   |   }| j                   |   }	| j                   |   }
| j                   |   }| d|	 d|
 | }t        j                  d|       t        | j                  t              rt        ||      | _        nt        ||      | _        | j                          y
)z7Update command executor following directConnect featuredirectConnectProtocoldirectConnectHostdirectConnectPortdirectConnectPathz#Driver capabilities must be definedz.Direct connect capabilities from server were:
z: ' z' Nz://:zUpdated request endpoint to %srb   )caps
ValueErrorissubsetrk   getr   ro   rY   rU   r   r   rg   )r@   rc   direct_protocoldirect_hostdirect_portdirect_pathmessagekeyprotocolhostnameportpathexecutors                rA   rj   z"WebDriver._update_command_executor+  s>   1)))yyBCCk;GPPQTUYU^U^Q_`GG'k;O AcU#diimmC&<%=R@@ALL!99_-99[)yy%yy%Zs8*AdVD6:5x@d++-=>$4X*$UD!$4X*$UD!rC   capabilitiesbrowser_profilec                    t        |t        t        f      st        d      t        |t              rt        j                  |      n|j                         }| j                  t        j                  |      t        t              st        d d      fd} |d      }|st        d d      || _
         |d      xs i | _        y)	a(  Creates a new session with the desired capabilities.

        Override for Appium

        Args:
            capabilities: Read https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/caps.md
             for more details.
            browser_profile: Browser profile
        z;Capabilities must be a dictionary or AppiumOptions instancezAA valid W3C session creation response must be a dictionary. Got "z	" insteadc                     j                  |       xs5 t        j                  d      t              rd   j                  |       S d S )Nry   )r   rY   dict)r   responses    rA   <lambda>z)WebDriver.start_session.<locals>.<lambda>b  sE    LLr
8<<X_K`bf@g(7"3"7"7"< mq rC   	sessionIdzWA valid W3C session creation response must contain a non-empty "sessionId" entry. Got "r   N)rY   r   r   r   as_w3cto_w3cr<   RemoteCommandNEW_SESSIONr   
session_idr   )r@   r   r   w3c_capsget_response_valuer   r   s         @rA   start_sessionzWebDriver.start_sessionK  s     ,}(=>*+hii9CLRV9W=''5]i]p]p]r<< 9 98D(D),ST\S]]fg >
 (4
,ijriss|}  %&~6<"	rC   c                 F    | j                  t        j                        d   S )z
        Get the Appium server status

        Usage:
            driver.get_status()

        Returns:
            dict: The status information

        ry   )r<   r   
GET_STATUSrL   s    rA   
get_statuszWebDriver.get_statusm  s     ||G../88rC   
element_idc                     t        | |      S )a#  Creates a web element with the specified element_id.

        Overrides method in Selenium WebDriver in order to always give them
        Appium WebElement

        Args:
            element_id: The element id to create a web element

        Returns:
            `MobileWebElement`
        )rf   )r@   r   s     rA   create_web_elementzWebDriver.create_web_elementz  s      j11rC   c                     t        |       S )zReturns an object containing all options to switch focus into

        Override for appium

        Returns:
            `appium.webdriver.switch_to.MobileSwitchTo`

        r7   rL   s    rA   	switch_tozWebDriver.switch_to  s     d##rC   c                 F    | j                  t        j                        d   S )z
        Gets the current orientation of the device

        Example:

            .. code-block:: python

                orientation = driver.orientation
        ry   )r<   r   GET_SCREEN_ORIENTATIONrL   s    rA   orientationzWebDriver.orientation  s     ||G::;GDDrC   c                     ddg}|j                         |v r#| j                  t        j                  d|i       yt	        d      )z
        Sets the current orientation of the device

        Args:
         - value: orientation to set it to.

        Example:
            .. code-block:: python

                driver.orientation = 'landscape'
        	LANDSCAPEPORTRAITr   z>You can only set the orientation to 'LANDSCAPE' and 'PORTRAIT'N)rr   r<   r   SET_SCREEN_ORIENTATIONr   )r@   ry   allowed_valuess      rA   r   zWebDriver.orientation  sA     &z2;;=N*LL77-9OP$%effrC   ext_namec                 6    || j                   v r
t               | S )a  
        Verifies if the given extension is not present in the list of absent extensions
        for the given driver instance.
        This API is designed for private usage.

        Args:
            ext_name: extension name

        Returns:
            self instance for chaining

        Raises:
            UnknownMethodException: If the extension has been marked as absent once
        )rl   r   r@   r   s     rA   assert_extension_existsz!WebDriver.assert_extension_exists  s      t...(**rC   c                 n    t        j                  d| d       | j                  j                  |       | S )z
        Marks the given extension as absent for the given driver instance.
        This API is designed for private usage.

        Args:
            ext_name: extension name

        Returns:
            self instance for chaining
        zMarking driver extension "z$" as absent for the current instance)r   ro   rl   addr   s     rA   mark_extension_absencez WebDriver.mark_extension_absence  s4     	1(;_`a##H-rC   c                 D   t        d | j                  j                        D ]O  }t        || j                  j
                        s$t        || j                  j
                  d       }|sH ||        Q | j                  j                  t        j                  dd       | j                  j                  t        j                  dd       | j                  j                  t        j                  dd       | j                  j                  t        j                  dd       | j                  j                  t        j                  dd       | j                  j                  t        j                  dd	       | j                  j                  t        j                   dd	       y )
Nc                 $    t        | t               S r>   )
issubclassr   )xs    rA   r   z)WebDriver._add_commands.<locals>.<lambda>  s    
1i0H,H rC   GETz/statusPOSTz%/session/$sessionId/element/$id/clearz0/session/$sessionId/element/$id/location_in_viewz)/session/$sessionId/element/$id/displayedz/session/$sessionIdz/session/$sessionId/orientation)filterrw   __mro__rn   rg   rO   rq   rU   rN   r   r   CLEARLOCATION_IN_VIEWIS_ELEMENT_DISPLAYEDGET_CAPABILITIESr   r   )r@   mixin_class	get_atters      rA   rg   zWebDriver._add_commands  s?    ""H$..J`J`a 	$K{D$6$6$?$?@#K1C1C1L1LdS	dO		$ 	))'*<*<eYO 	))'--Ahi))$$>	
 	))'*F*FOz{))'*B*BEK`a))'*H*H%Qrs))'*H*H&RstrC   )zhttp://127.0.0.1:4723NNNr>   )rE   N)"rO   rP   rQ   r   rS   r   r   r   r   r   r   rB   r   r   r|   r   r   boolrj   r   r   intrf   r   propertyr8   r   r   setterr   r   r   rg   __classcell__)rw   s   @rA   r   r      s   > :Q<@CG6:(T%5 56(T T$"789(T }d=&94?@	(T
   23(TT 	3 	uS$_/E 	Qc 		C 	c4o0F 	RVWiRj 	04 D @ =%m0C*D  =W_`cWd  =pt  =D9D 92U38_ 2AQ 2 
$> 
$ 
$ 
ES 
E 
E g g g g$  &s t urC   r   r>   )etypingr   r   r   r   r   r   r	   r
   r   r   selenium.common.exceptionsr   r   r   r   !selenium.webdriver.remote.commandr   r   +selenium.webdriver.remote.remote_connectionr   #selenium.webdriver.remote.webdriverr   Remotetyping_extensionsr   appium.common.loggerr   appium.options.common.baser   appium_connectionr   rV   r   errorhandlerr   extensions.action_helpersr   extensions.android.activitiesr   extensions.android.commonr   extensions.android.displayr   extensions.android.gsmr   extensions.android.networkr    extensions.android.performancer!   extensions.android.powerr"   extensions.android.smsr#   extensions.android.system_barsr$   extensions.applicationsr%   extensions.clipboardr&   extensions.contextr'   extensions.device_timer(   extensions.execute_driverr)   !extensions.execute_mobile_commandr*   extensions.hw_actionsr+   extensions.images_comparisonr,   extensions.keyboardr-   extensions.locationr.   extensions.log_eventr/   extensions.logsr0   extensions.remote_fsr1   extensions.screen_recordr2   extensions.sessionr3   extensions.settingsr4   r`   r5   mobilecommandr6   r   r8   
webelementr9   rf   r;   rS   tupler[   rT   rC   rA   <module>r      sL   _ ^ ^  G H D " ' 4 / - , 4 5 - / ' / 7 + ' 6 1 + ' . 4 C 2 : ) ) * ! * 2 ' ) 5 3 % 6x$ x$x cgRC!112RCKL^C_R
X&899:R*^u

	7^urC   