
    ,hI                        U 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Zd dlmZ d dlmZ  ej2                  d      Z ed      ZdZdadad Z e j@                  d      a!e j@                  e"d<    e j@                  d      a#e j@                  e"d<   d Z$d Z%e
d        Z&e
d        Z'd Z(d Z) G d de*      Z+ G d de      Z, G d  d!e*      Z-e G d" d#             Z. G d$ d%      Z/ G d& d'e/      Z0 G d( d)e/ejb                  jd                        Z3e	d*ee3   fd+       Z4d*e3fd,Z5y)-    N)defaultdict)asynccontextmanager)contextmanager)	dataclass)Any)AsyncGenerator)AsyncIterator)	Generator)Type)TypeVar)ConnectionClosed)connect_websocket_urltrio_cdpTi   c                    | a d}	 t        j                  | |        at        S # t        $ r t        j                  t              j                  d   j                  d      }t        d |j                         D              }t        d |D              }t        j                  t              }|j!                  d|       t        j                  | |       at        cY S w xY w)z^Attempt to load the current latest available devtools into the module
    cache for use later.z$selenium.webdriver.common.devtools.v   devtoolsc              3   V   K   | ]!  }|j                         s|j                   # y wN)is_dirname).0fs     d/var/www/html/Resume-Scraper/venv/lib/python3.12/site-packages/selenium/webdriver/common/bidi/cdp.py	<genexpr>z"import_devtools.<locals>.<genexpr>F   s     OAAHHJOs   ))c              3   8   K   | ]  }t        |d d         yw)r   N)int)r   xs     r   r   z"import_devtools.<locals>.<genexpr>G   s     2AS12Z2s   z'Falling back to loading `devtools`: v%s)version	importlibimport_moduler   ModuleNotFoundErrorpathlibPath__file__parentsjoinpathtupleiterdirmaxlogging	getLogger__name__debug)verbasedevtools_pathversionslatestselenium_loggers         r   import_devtoolsr5   8   s    
 G1D**dVC5>: 	  X.66q9BB:NO)>)>)@OO222!++H5GP**dVF8+<=	s   % B:C"!C"connection_context_connection_contextsession_context_session_contextc                 b    	 t         j                         S # t        $ r t        |  d      w xY w)zLook up the current connection.

    If there is no current connection, raise a ``RuntimeError`` with a
    helpful message.
    z*() must be called in a connection context.)r7   getLookupErrorRuntimeErrorfn_names    r   get_connection_contextr@   R   s;    S"&&(( SgY&PQRRS    .c                 b    	 t         j                         S # t        $ r t        |  d      w xY w)z{Look up the current session.

    If there is no current session, raise a ``RuntimeError`` with a
    helpful message.
    z'() must be called in a session context.)r9   r;   r<   r=   r>   s    r   get_session_contextrC   ^   s;    P##%% PgY&MNOOPrA   c              #      K   t         j                  |       }	 d t         j                  |       y# t         j                  |       w xY ww)zbThis context manager installs ``connection`` as the session context for
    the current Trio task.N)r7   setreset)
connectiontokens     r   r6   r6   j   s=       ##J/E)!!%(!!%(   A3 AA

Ac              #      K   t         j                  |       }	 d t         j                  |       y# t         j                  |       w xY ww)z_This context manager installs ``session`` as the session context for the
    current Trio task.N)r9   rE   rF   )sessionrH   s     r   r8   r8   u   s=        )E&u%u%rI   c                 2    t        j                  d|       ay)zInstall ``connection`` in the root context so that it will become the
    default connection for all tasks.

    This is generally not recommended, except it may be necessary in
    certain use cases such as running inside Jupyter notebook.
    r7   defaultN)contextvars
ContextVarr7   )rG   s    r   set_global_connectionrQ      s     &001FPZ[    c                 2    t        j                  d|       ay)zInstall ``session`` in the root context so that it will become the
    default session for all tasks.

    This is generally not recommended, except it may be necessary in
    certain use cases such as running inside Jupyter notebook.
    r9   rM   N)rO   rP   r9   )rK   s    r   set_global_sessionrT      s     #--.@'RrR   c                       e Zd ZdZd Zd Zy)BrowserErrorzgThis exception is raised when the browser's response to a command
    indicates that an error occurred.c                     |j                  d      | _        |j                  d      | _        |j                  d      | _        y )Ncodemessagedata)r;   rX   rY   detail)selfobjs     r   __init__zBrowserError.__init__   s0    GGFO	wwy)ggforR   c                 T    d| j                    d| j                   d| j                   S )NzBrowserError<code=z	 message=z> )rX   rY   r[   r\   s    r   __str__zBrowserError.__str__   s'    #DII;i~R}UUrR   N)r-   
__module____qualname____doc__r^   ra    rR   r   rV   rV      s    )&
VrR   rV   c                       e Zd ZdZd Zd Zy)CdpConnectionClosedzARaised when a public method is called on a closed CDP connection.c                     || _         y)zfConstructor.

        :param reason:
        :type reason: wsproto.frame_protocol.CloseReason
        N)reason)r\   ri   s     r   r^   zCdpConnectionClosed.__init__   s     rR   c                 N    | j                   j                   d| j                   dS )zReturn representation.<>)	__class__r-   ri   r`   s    r   __repr__zCdpConnectionClosed.__repr__   s$    ..))*!DKK=::rR   N)r-   rb   rc   rd   r^   rn   re   rR   r   rg   rg      s    K;rR   rg   c                       e Zd ZdZy)InternalErrorzfThis exception is only raised when there is faulty logic in TrioCDP or
    the integration with PyCDP.N)r-   rb   rc   rd   re   rR   r   rp   rp      s    #rR   rp   c                        e Zd ZU dZdZeed<   y)CmEventProxyzA proxy object returned by :meth:`CdpBase.wait_for()``.

    After the context manager executes, this proxy object will have a
    value set that contains the returned event.
    Nvalue)r-   rb   rc   rd   rs   r   __annotations__re   rR   r   rr   rr      s     E3rR   rr   c                   x    e Zd Zd Zdeeeef   defdZdddZ	e
ddee   deed	f   fd
       Zd Zd Zd Zy	)CdpBasec                     || _         || _        || _        t        t              | _        t        j                         | _        i | _	        i | _
        y r   )ws
session_id	target_idr   rE   channels	itertoolscountid_iterinflight_cmdinflight_result)r\   rx   ry   rz   s       r   r^   zCdpBase.__init__   sA    $"#C( (!rR   cmdreturnc                   K   t        | j                        }t        j                         }||f| j                  |<   t        |      }||d<   | j
                  r| j
                  |d<   t        j                  |      }t        j                  t        j                        rt        j                  d| d| d|        	 | j                  j                  |       d{    |j%                          d{    | j&                  j)                  |      }t        j                  t        j                        rt        j                  d|        t+        |t,              rSt        j                  t        j                        r.t        j                  d| d	t/        |      j0                          ||S 7 # t        $ r}t!        |j"                        dd}~ww xY w7 w)
zExecute a command on the server and wait for the result.

        :param cmd: any CDP command
        :returns: a CDP result
        id	sessionIdzSending CDP message:  z: NzReceived CDP message: zException raised by z
 message: )nextr~   trioEventr   ry   jsondumpsloggerisEnabledForr+   DEBUGr.   rx   send_messageWsConnectionClosedrg   ri   waitr   pop
isinstance	Exceptiontyper-   )r\   r   cmd_id	cmd_eventrequestrequest_strwccresponses           r   executezCdpBase.execute   s{     dll#JJL	$'N&!s)??#'??GK jj)w}}-LL0)B{mTU	<''&&{333 nn''++F3w}}-LL1(<=h	*""7==13I;jhI`I`HabcN 4! 	<%cjj1t;	<sI   B<G ?F7 F5F7 "G 5G6B?G 5F7 7	G GGG 
   )buffer_sizec                    t        j                  |      \  }}|D ]   }| j                  |   j                  |       " |S )zXReturn an async iterator that iterates over events matching the
        indicated types.)r   open_memory_channelr{   add)r\   r   event_typessenderreceiver
event_types         r   listenzCdpBase.listen   sD      33K@% 	2JMM*%))&1	2rR   r   Nc                N  K   t        j                  |      \  }}| j                  |   j                  |       t	               }| |4 d{    |j                          d{   }ddd      d{    ||_        y7 47 7 # 1 d{  7  sw Y   |_        yxY ww)zWait for an event of the given type and return it.

        This is an async context manager, so you should open it inside
        an async with block. The block will not exit until the indicated
        event is received.
        N)r   r   r{   r   rr   receivers   )r\   r   r   r   r   proxyevents          r   wait_forzCdpBase.wait_for   s       33K@j!%%f- 	- 	-"**,,E	- 	-	-,	- 	- 	- 	-sZ   AB%BB%B	&B'B	+B%6B7B%B	B%	B"BB"B%c                 R    d|v r| j                  |       y| j                  |       y)zUHandle incoming WebSocket data.

        :param dict data: a JSON dictionary
        r   N)_handle_cmd_response_handle_event)r\   rZ   s     r   _handle_datazCdpBase._handle_data  s'    
 4<%%d+t$rR   c                    |d   }	 | j                   j                  |      \  }}d|v rt        |d         | j                  |<   n 	 |j                  |d         }t        d      |j                          y# t        $ r t        j	                  d|       Y yw xY w# t        $ r}|j                  }Y d}~nd}~ww xY w|| j                  |<   h)zHandle a response to a command. This will set an event flag that
        will return control to the task that called the command.

        :param dict data: response as a JSON dictionary
        r   z7Got a message with a command ID that does not exist: %sNerrorresultz<The command's generator function did not exit when expected!)r   r   KeyErrorr   warningrV   r   sendrp   StopIterationrs   rE   )r\   rZ   r   r   r   _exitreturn_s           r   r   zCdpBase._handle_cmd_response  s     d	**..v6JC d? ,8W+FD  (%HHT(^,#$bcc 			!  	NNTVZ[	 ! %**%+2D  (s)   A6 B 6BB	B:$B55B:c                    t         j                  j                  |      }t        j	                  d|       t               }| j                  t        |         D ]  }	 |j                  |        |r!| j                  t        |      xx   |z  cc<   yy# t        j                  $ r t        j                  d||       Y gt        j                  $ r |j                  |       Y w xY w)zOHandle an event.

        :param dict data: event as a JSON dictionary
        zReceived event: %sz0Unable to send event "%r" due to full channel %sN)r   utilparse_json_eventr   r.   rE   r{   r   send_nowaitr   
WouldBlockr   BrokenResourceErrorr   )r\   rZ   r   	to_remover   s        r   r   zCdpBase._handle_event*  s     ..t4)51E	mmDK0 	&F&""5)	& MM$u+&)3& 	 ?? `OQVX^_++ &f%&s   B*C%?#C%$C%)r   )r-   rb   rc   r^   r
   dictr   r   r   r   r   r   r   rr   r   r   r   r   re   rR   r   rv   rv      sp    "4C<!8 Q < 02  a ^T`bfTfEg  "%64rR   rv   c                   B     e Zd ZdZ fdZed        Zed        Z xZS )
CdpSessionzContains the state for a CDP session.

    Generally you should not instantiate this object yourself; you should call
    :meth:`CdpConnection.open_session`.
    c                     t         |   |||       d| _        t        j                         | _        d| _        t        j                         | _        y)zConstructor.

        :param trio_websocket.WebSocketConnection ws:
        :param devtools.target.SessionID session_id:
        :param devtools.target.TargetID target_id:
        r   N)superr^   _dom_enable_countr   Lock_dom_enable_lock_page_enable_count_page_enable_lock)r\   rx   ry   rz   rm   s       r   r^   zCdpSession.__init__E  sB     	Z3!" $		"#!%rR   c                z  K   | j                   4 d{    | xj                  dz  c_        | j                  dk(  r5| j                  t        j                  j                                d{    ddd      d{    d | j                   4 d{    | xj                  dz  c_        | j                  dk(  r5| j                  t        j                  j                                d{    ddd      d{    y7 7 7 # 1 d{  7  sw Y   xY w7 7 27 $# 1 d{  7  sw Y   yxY ww)zA context manager that executes ``dom.enable()`` when it enters and
        then calls ``dom.disable()``.

        This keeps track of concurrent callers and only disables DOM
        events when all callers have exited.
        Nr   r   )r   r   r   r   domenabledisabler`   s    r   
dom_enablezCdpSession.dom_enableS  s     (( 	: 	:""a'"%%*ll8<<#6#6#8999	: 	:
 	(( 	; 	;""a'"%%*ll8<<#7#7#9:::	; 	; 	;	: :	: 	: 	: 	:	; ;	; 	; 	; 	;   D;DD;AD,D-D1D;<D	=D;D D;AD&/D"0D&4D;?D$ D;D	D;DDDD;"D&$D;&D8,D/-D84D;c                z  K   | j                   4 d{    | xj                  dz  c_        | j                  dk(  r5| j                  t        j                  j                                d{    ddd      d{    d | j                   4 d{    | xj                  dz  c_        | j                  dk(  r5| j                  t        j                  j                                d{    ddd      d{    y7 7 7 # 1 d{  7  sw Y   xY w7 7 27 $# 1 d{  7  sw Y   yxY ww)zA context manager that executes ``page.enable()`` when it enters and
        then calls ``page.disable()`` when it exits.

        This keeps track of concurrent callers and only disables page
        events when all callers have exited.
        Nr   r   )r   r   r   r   pager   r   r`   s    r   page_enablezCdpSession.page_enableh  s     )) 	; 	;##q(#&&!+ll8==#7#7#9:::	; 	;
 	)) 	< 	<##q(#&&!+ll8==#8#8#:;;;	< 	< 	<	; ;	; 	; 	; 	;	< <	< 	< 	< 	<r   )	r-   rb   rc   rd   r^   r   r   r   __classcell__rm   s   @r   r   r   >  s5    - ; ;( < <rR   r   c                   R     e Zd ZdZ fdZd Zedee   fd       Z	ddZ
d Z xZS )	CdpConnectiona%  Contains the connection state for a Chrome DevTools Protocol server.

    CDP can multiplex multiple "sessions" over a single connection. This
    class corresponds to the "root" session, i.e. the implicitly created
    session that has no session ID. This class is responsible for
    reading incoming WebSocket messages and forwarding them to the
    corresponding session, as well as handling messages targeted at the
    root session itself. You should generally call the
    :func:`open_cdp()` instead of instantiating this class directly.
    c                 8    t         |   |dd       i | _        y)zLConstructor.

        :param trio_websocket.WebSocketConnection ws:
        N)ry   rz   )r   r^   sessions)r\   rx   rm   s     r   r^   zCdpConnection.__init__  s     
 	=rR   c                 T   K   | j                   j                          d{    y7 w)at  Close the underlying WebSocket connection.

        This will cause the reader task to gracefully exit when it tries
        to read the next message from the WebSocket. All of the public
        APIs (``execute()``, ``listen()``, etc.) will raise
        ``CdpConnectionClosed`` after the CDP connection is closed. It
        is safe to call this multiple times.
        N)rx   acloser`   s    r   r   zCdpConnection.aclose  s      ggnns   (&(r   c                   K   | j                  |       d{   }t        |      5  | ddd       y7 # 1 sw Y   yxY ww)a  This context manager opens a session and enables the "simple" style
        of calling CDP APIs.

        For example, inside a session context, you can call ``await
        dom.get_document()`` and it will execute on the current session
        automatically.
        N)connect_sessionr8   )r\   rz   rK   s      r   open_sessionzCdpConnection.open_session  sG      ,,Y77W% 	M	 	 8	 	s!   A6A8
AAAc                    K   | j                  t        j                  j                  |d             d{   }t	        | j
                  ||      }|| j                  |<   |S 7 ,w)zLReturns a new :class:`CdpSession` connected to the specified
        target.TN)r   r   targetattach_to_targetr   rx   r   )r\   rz   ry   rK   s       r   r   zCdpConnection.connect_session  sV       <<(H(HTX(YZZ
TWWj)<$+j! [s   3A$A"-A$c                   K   	 	 | j                   j                          d{   }	 t        j                  |      }t        j                  d|       d|v rDt        j                  j                  |d         }	 | j                  |   }|j                  |       n| j                  |       7 # t        $ r Y nGw xY w# t        j
                  $ r t        dd|d      w xY w# t        $ r t        dd|d      w xY w| j                  j                         D ]>  \  }}|j                   j                         D ]  \  }}|D ]  }|j#                            @ yw)zxRuns in the background and handles incoming messages: dispatching
        responses to commands and events to listeners.NiDzClient received invalid JSON)rX   rY   rZ   zReceived message %rr   z-Browser sent a message for an invalid session)rx   get_messager   r   loadsJSONDecodeErrorrV   r   r.   r   r   	SessionIDr   r   r   itemsr{   close)r\   rY   rZ   ry   rK   r   sendersr   s           r   _reader_taskzCdpConnection._reader_task  sm      $ 3 3 55qzz'* LL.5d"%__66tK7HI
	"mmJ7G $$T*!!$'9 5% 
  '' q"F?]gn#oppq   &$*'V'1n  ----/ 	#JAw%..446 #
7% #FLLN##	#sa   EB/ B-B/ B> <E:C$ 	$E-B/ /	B;8E:B;;E>#C!!E$C>>AE)r   r   )r-   rb   rc   rd   r^   r   r   r	   r   r   r   r   r   r   s   @r   r   r   ~  s<    		 
}Z/H 
 
%#rR   r   r   c                  K   t        j                         4 d{   }t        ||        d{   }	 t        |      5  | ddd       |j	                          d{    ddd      d{    y7 [7 I# 1 sw Y   6xY w7 %# |j	                          d{  7   w xY w7 5# 1 d{  7  sw Y   yxY ww)a  This async context manager opens a connection to the browser specified
    by ``url`` before entering the block, then closes the connection when the
    block exits.

    The context manager also sets the connection as the default
    connection for the current task, so that commands like ``await
    target.get_targets()`` will run on this connection automatically. If
    you want to use multiple connections concurrently, it is recommended
    to open each on in a separate task.
    N)r   open_nurseryconnect_cdpr6   r   )urlnurseryconns      r   open_cdpr     s        "    g #..	 #D) 
 ++-     .   $++-       s   B>A7B>B)A9B)B	 A;B	B)!B"B)&B>1B'2B>9B);B	 B	B)	B$B 
B$$B)'B>)B;/B20B;7B>c                    K   t        | |t               d{   }t        |      }| j                  |j                         |S 7 ,w)a  Connect to the browser specified by ``url`` and spawn a background task
    in the specified nursery.

    The ``open_cdp()`` context manager is preferred in most situations.
    You should only use this function if you need to specify a custom
    nursery. This connection is not automatically closed! You can either
    use the connection object as a context manager (``async with
    conn:``) or else call ``await conn.aclose()`` on it when you are
    done with it. If ``set_context`` is True, then the returned
    connection will be installed as the default connection for the
    current task. This argument is for unusual use cases, such as
    running inside of a notebook.
    )max_message_sizeN)r   MAX_WS_MESSAGE_SIZEr   
start_soonr   )r   r   rx   cdp_conns       r   r   r     sC      %WcDWX	XBR Hx,,-O 
Ys   AA-A)6rO   r    r|   r   r+   r#   collectionsr   
contextlibr   r   dataclassesr   typingr   r   r	   r
   r   r   r   trio_websocketr   r   r   r,   r   r   r   r   r   r5   rP   r7   rt   r9   r@   rC   r6   r8   rQ   rT   r   rV   rg   rp   rr   rv   r   abcAsyncResourcer   r   r   re   rR   r   <module>r      s  6       # * % !  !       A 0			:	&CL 
, /Ek.D.DEY.Z [++ Z+A;+A+ABS+T +(( T	S	P ) ) & &\S
V9 
V;, ; #I #
   x4 x4v=< =<@Z#GTXX33 Z#z  =7    *} rR   