
    gxX                       d dl m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
mZmZmZmZ ddlmZ ddlmZmZ ddlmZmZmZ dd	lmZ dd
lmZ ddlmZmZmZ ddl m!Z!m"Z" ddl#m$Z$m%Z% ddl&m'Z' ddl	m(Z(m)Z)m*Z* ddl+m,Z,m-Z-m.Z.m/Z/m0Z0 ddl1m2Z2 ddl3m4Z4 g dZ5 G d de2          Z6dddddddde!ddddddddddddd_dDZ7	 	 d`dadFZ8	 d dGl9m:Z: d dHl;m,Z< e:j=        e:j=        e:j>        e:j>        dIZ?ddJddJdIZ@dbdQZAn# eB$ r dbdRZAY nw xY w	 dcdddTZCdedVZDddddWdfdXZE edY          ZF edZed[eFf         \          ZG G d] d^          ZHdS )g    )annotationsN)Sequence)AnyCallableLiteralTypeVarcast   )ClientProtocol)HeadersHeadersLike)InvalidProxyMessageInvalidProxyStatus
ProxyError)ClientExtensionFactory) enable_client_permessage_deflate)build_authorization_basic
build_hostvalidate_subprotocols)
USER_AGENTResponse)
CONNECTINGEvent)StreamReader)
LoggerLikeOriginSubprotocol)ProxyWebSocketURI	get_proxyparse_proxy	parse_uri   )
Connection)Deadline)connectunix_connectClientConnectionc                  X     e Zd ZdZdddddd fdZdedfddZd  fdZd! fdZ xZ	S )"r(   a1  
    :mod:`threading` implementation of a WebSocket client connection.

    :class:`ClientConnection` provides :meth:`recv` and :meth:`send` methods for
    receiving and sending messages.

    It supports iteration to receive messages::

        for message in websocket:
            process(message)

    The iterator exits normally when the connection is closed with close code
    1000 (OK) or 1001 (going away) or without a close code. It raises a
    :exc:`~websockets.exceptions.ConnectionClosedError` when the connection is
    closed with any other code.

    The ``ping_interval``, ``ping_timeout``, ``close_timeout``, and
    ``max_queue`` arguments have the same meaning as in :func:`connect`.

    Args:
        socket: Socket connected to a WebSocket server.
        protocol: Sans-I/O connection.

       
      ping_intervalping_timeoutclose_timeout	max_queuesocketsocket.socketprotocolr   r.   float | Noner/   r0   r1   *int | None | tuple[int | None, int | None]returnNonec                   |  t          j                    | _        t                                          ||||||           d S )Nr-   )	threadingr   response_rcvdsuper__init__)selfr2   r4   r.   r/   r0   r1   	__class__s          b/var/www/html/nodeJS/PythonScripts/venv3.11/lib/python3.11/site-packages/websockets/sync/client.pyr=   zClientConnection.__init__6   sX     	%&_..'%' 	 	
 	
 	
 	
 	
    Nadditional_headersHeadersLike | Noneuser_agent_header
str | Nonetimeoutc                   |                      t                    5  | j                                        | _        || j        j                            |           | | j        j                            d|           | j                            | j                   ddd           n# 1 swxY w Y   | j	        
                    |          st          d          | j        j        | j        j        dS )z1
        Perform the opening handshake.

        )expected_stateN
User-Agentz.timed out while waiting for handshake response)send_contextr   r4   r&   requestheadersupdate
setdefaultsend_requestr;   waitTimeoutErrorhandshake_exc)r>   rB   rD   rF   s       r@   	handshakezClientConnection.handshakeK   s*    j99 	5 	5=0022DL!-$++,>??? ,$//>OPPPM&&t|444	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 !&&w// 	QOPPP =&2--- 32s   BB))B-0B-eventr   c                    | j         9t          |t                    sJ || _         | j                                         dS t                                          |           dS )z.
        Process one incoming event.

        N)response
isinstancer   r;   setr<   process_event)r>   rT   r?   s     r@   rY   zClientConnection.process_eventg   se     = eX.....!DM""$$$$$ GG!!%(((((rA   c                    	 t                                                       | j                                         dS # | j                                         w xY w)zI
        Read incoming data from the socket and process events.

        N)r<   recv_eventsr;   rX   )r>   r?   s    r@   r[   zClientConnection.recv_eventsu   sV    
	%GG!!! ""$$$$$D""$$$$s	    > A)r2   r3   r4   r   r.   r5   r/   r5   r0   r5   r1   r6   r7   r8   )rB   rC   rD   rE   rF   r5   r7   r8   )rT   r   r7   r8   )r7   r8   )
__name__
__module____qualname____doc__r=   r   rS   rY   r[   __classcell__)r?   s   @r@   r(   r(      s         < ')%'&(@B
 
 
 
 
 
 
 
. 26(2 $	. . . . .8) ) ) ) ) )	% 	% 	% 	% 	% 	% 	% 	% 	% 	%rA   r(   deflateTr+   r*   i   r,   )socksslserver_hostnameorigin
extensionssubprotocolscompressionrB   rD   proxy	proxy_sslproxy_server_hostnameopen_timeoutr.   r/   r0   max_sizer1   loggercreate_connectionuristrrb   socket.socket | Nonerc   ssl_module.SSLContext | Nonerd   rE   re   Origin | Nonerf   'Sequence[ClientExtensionFactory] | Nonerg   Sequence[Subprotocol] | Nonerh   rB   rC   rD   ri   str | Literal[True] | Nonerj   rk   rl   r5   r.   r/   r0   rm   
int | Noner1   r6   rn   LoggerLike | Nonero   type[ClientConnection] | Nonekwargsr   r7   c          	     J   |3d|v r/|                     d          }t          j        dt                     t	          |           }|j        s|t          d          |                     dd          }|                     dd          }|r&||t          d          ||t          d	          |t          |           |d
k    rt          |          }n|t          d|           |rd}
|d}
|
du rt          |          }
t          |          }|t          }	 |e|rjt          j        t          j        t          j                  }|                    |                                           |J |                    |           n|
t%          |
          }|j        dd         dk    r(t)          ||||                     dd                    }n|j        dd         dk    r0|j        dk    r|t          d          t+          |||f|	||d|}nUt-          d          |                    d|                                           t          j        |j        |j        ffi |}|                    d           |s+|                    t          j        t          j        d           |j        r|t=          j                    }||j        }|                    |                                           ||                     ||          }n,tC          |||          }tE          t          j        |          }|                    d           tG          ||||||          } |||||||          }n%# tH          $ r ||%                                  w xY w	 |&                    ||	|                                           n<# tH          $ r/ |'                                 |j(        )                                  w xY w|*                                 |S )a  
    Connect to the WebSocket server at ``uri``.

    This function returns a :class:`ClientConnection` instance, which you can
    use to send and receive messages.

    :func:`connect` may be used as a context manager::

        from websockets.sync.client import connect

        with connect(...) as websocket:
            ...

    The connection is closed automatically when exiting the context.

    Args:
        uri: URI of the WebSocket server.
        sock: Preexisting TCP socket. ``sock`` overrides the host and port
            from ``uri``. You may call :func:`socket.create_connection` to
            create a suitable TCP socket.
        ssl: Configuration for enabling TLS on the connection.
        server_hostname: Host name for the TLS handshake. ``server_hostname``
            overrides the host name from ``uri``.
        origin: Value of the ``Origin`` header, for servers that require it.
        extensions: List of supported extensions, in order in which they
            should be negotiated and run.
        subprotocols: List of supported subprotocols, in order of decreasing
            preference.
        compression: The "permessage-deflate" extension is enabled by default.
            Set ``compression`` to :obj:`None` to disable it. See the
            :doc:`compression guide <../../topics/compression>` for details.
        additional_headers (HeadersLike | None): Arbitrary HTTP headers to add
            to the handshake request.
        user_agent_header: Value of  the ``User-Agent`` request header.
            It defaults to ``"Python/x.y.z websockets/X.Y"``.
            Setting it to :obj:`None` removes the header.
        proxy: If a proxy is configured, it is used by default. Set ``proxy``
            to :obj:`None` to disable the proxy or to the address of a proxy
            to override the system configuration. See the :doc:`proxy docs
            <../../topics/proxies>` for details.
        proxy_ssl: Configuration for enabling TLS on the proxy connection.
        proxy_server_hostname: Host name for the TLS handshake with the proxy.
            ``proxy_server_hostname`` overrides the host name from ``proxy``.
        open_timeout: Timeout for opening the connection in seconds.
            :obj:`None` disables the timeout.
        ping_interval: Interval between keepalive pings in seconds.
            :obj:`None` disables keepalive.
        ping_timeout: Timeout for keepalive pings in seconds.
            :obj:`None` disables timeouts.
        close_timeout: Timeout for closing the connection in seconds.
            :obj:`None` disables the timeout.
        max_size: Maximum size of incoming messages in bytes.
            :obj:`None` disables the limit.
        max_queue: High-water mark of the buffer where frames are received.
            It defaults to 16 frames. The low-water mark defaults to ``max_queue
            // 4``. You may pass a ``(high, low)`` tuple to set the high-water
            and low-water marks. If you want to disable flow control entirely,
            you may set it to ``None``, although that's a bad idea.
        logger: Logger for this client.
            It defaults to ``logging.getLogger("websockets.client")``.
            See the :doc:`logging guide <../../topics/logging>` for details.
        create_connection: Factory for the :class:`ClientConnection` managing
            the connection. Set it to a wrapper or a subclass to customize
            connection handling.

    Any other keyword arguments are passed to :func:`~socket.create_connection`.

    Raises:
        InvalidURI: If ``uri`` isn't a valid WebSocket URI.
        OSError: If the TCP connection fails.
        InvalidHandshake: If the opening handshake fails.
        TimeoutError: If the opening handshake times out.

    Nssl_contextzssl_context was renamed to sslz-ssl argument is incompatible with a ws:// URIunixFpathzmissing path argumentz(path and sock arguments are incompatiblera   zunsupported compression: T   sockssource_address)
local_addr   httphttpsz8proxy_ssl argument is incompatible with an http:// proxyrD   rc   rd   zunsupported proxyrF   rd   )re   rf   rg   rm   rn   r-   )+popwarningswarnDeprecationWarningr"   secure
ValueErrorr   r   r    r%   r(   r2   AF_UNIXSOCK_STREAM
settimeoutrF   r&   r!   schemeconnect_socks_proxyconnect_http_proxyAssertionErrorrN   ro   hostport
setsockoptIPPROTO_TCPTCP_NODELAY
ssl_modulecreate_default_contextwrap_socketSSLSSLSocketr	   r   	ExceptioncloserS   close_socketrecv_events_threadjoinstart_keepalive)rp   rb   rc   rd   re   rf   rg   rh   rB   rD   ri   rj   rk   rl   r.   r/   r0   rm   r1   rn   ro   r{   ws_urir~   r   deadlineproxy_parsedsock_2r4   
connections                                 r@   r&   r&      s   \ {}..jj'',	
 	
 	

 s^^F= JS_HIII FE**Dzz&$//D I<DL4555$"2GHHHl+++i5jAA

		 B[BBCCC }}&!!
 %%H ,\ < (}V^V5GHH 0 0 2 2333'''T"""""*511&rr*g55.$  $*::.>#E#E  DD "(!,66#*g55):O(V   .$  +<%(=  ! DD ))<===!!)X-=-=-?-?@@@/[&+.   OOD!!!  	JOOF.0BDIII = 	"{ 799&"(+OOH,,../// t_MM%dCQQQFM622OOD!!! "!%
 
 
 '&'%'
 
 


    JJLLL
		
 	
 	
 	

    !!!%**,,,
    s    I"N "N%))O 9Pr   c                    |/|                     d          |                     d          d}nd}t          d|d| d|S )	a  
    Connect to a WebSocket server listening on a Unix socket.

    This function accepts the same keyword arguments as :func:`connect`.

    It's only available on Unix.

    It's mainly useful for debugging servers listening on Unix sockets.

    Args:
        path: File system path to the Unix socket.
        uri: URI of the WebSocket server. ``uri`` defaults to
            ``ws://localhost/`` or, when a ``ssl`` is provided, to
            ``wss://localhost/``.

    Nrc   r}   zws://localhost/zwss://localhost/T)rp   r~   r    )getr&   )r   rp   r{   s      r@   r'   r'     sU    * {::e$M)B)B)J#CC$C;sD;;F;;;rA   )	ProxyType)r   )socks5hsocks5socks4asocks4Fr   r   r   r   r%   r3   c           	        t          t          | j                 | j        | j        | j        | j        t          | j                           }|                    d|	                                           	  |j
        |j        |j        fi |S # t          t          t          j	        f$ r  t          $ r}t          d          |d}~ww xY w)z0Connect via a SOCKS proxy and return the socket.rF   z failed to connect to SOCKS proxyN)
SocksProxySOCKS_PROXY_TYPESr   r   r   usernamepasswordSOCKS_PROXY_RDNSrN   rF   r&   OSErrorrQ   r2   r   r   )ri   r   r   r{   socks_proxyexcs         r@   r   r     s     !el+JJNNU\*
 
 	)X%5%5%7%7888	J&;&v{FKJJ6JJJv~6 	 	 	 	J 	J 	J?@@cI	Js   2B &C1CCc                     t          d          )Nz-python-socks is required to use a SOCKS proxy)ImportError)ri   r   r   r{   s       r@   r   r     s     IJJJrA   bytesc                j   t          |j        |j        |j        d          }t	                      }t          |j        |j        |j                  |d<   |||d<   | j        &| j        J t          | j        | j                  |d<   d| d                                |	                                z   S )NT)always_include_portHostrI   zProxy-AuthorizationzCONNECT z HTTP/1.1
)
r   r   r   r   r   r   r   r   encode	serialize)ri   r   rD   r   rL   s        r@   prepare_connect_requestr     s    
 fk6;SWXXXDiiG fk6=IIGFO$ 1~!~))))BNEN*
 *
%& *d)))0022W5F5F5H5HHHrA   r   c                   t                      }t          j        |j        |j        |j        d          }	 	 |                     |                                           |                     d          }|r|	                    |           n|
                                 t          |           x# t          $ rh}t          |j        t                    sJ |j        }d|j        cxk    rdk     rn n|cY d }~|                     d            S t!          |          d }~wt"          j        $ r t%          d          t&          $ r}t)          d          |d }~ww xY w# |                     d            w xY w)	NF)include_bodyTi      i,  z(timed out while connecting to HTTP proxyz0did not receive a valid HTTP response from proxy)r   r   parse	read_line
read_exactread_to_eofr   rF   recv	feed_datafeed_eofnextStopIterationrW   valuestatus_coder   r2   rQ   r   r   )rb   r   readerparserdatar   rV   s          r@   read_connect_responser     s   ^^F^	  F	OOH,,..///99T??D "  &&&&!!!LLL	  / / /#)X.....9(&,,,,,,,,,OOOOO 	 %X...> G G GEFFF   !>
 
	
 	sB   A9B0 0
E:9D3E4E D*EEEE E6r   c               <   |                     d|                                           t          j        | j        | j        ffi |}| j        dk    rq|t          j                    }|| j        }|	                    |                                           |
                    ||          }|	                    d            |                    t          | ||                     	 t          ||           n## t          $ r |                                  w xY w|S )NrF   r   r   )rN   rF   r2   ro   r   r   r   r   r   r   r   sendallr   r   r   r   )ri   r   r   rD   rc   rd   r{   rb   s           r@   r   r     s'    i!1!1!3!3444#UZ$<GGGGD |w;355C"#jO((**+++t_EE 	LL(8IJJKKKdH----   

 Ks   (C9 9 DTF.)boundc                  J    e Zd ZdZdZ	 dddZddZd dZd!dZd"dZ	d#dZ
dS )$r   zr
    Socket-like object providing TLS-in-TLS.

    Only methods that are used by websockets are implemented.

    i   Nrb   r3   r}   ssl_module.SSLContextrd   rE   r7   r8   c                    t          j                    | _        t          j                    | _        || _        |                    | j        | j        |          | _        |                     | j        j                   d S )Nr   )	r   	MemoryBIOincomingoutgoing
ssl_socketwrap_bio
ssl_objectrun_iodo_handshake)r>   rb   r}   rd   s       r@   r=   zSSLSSLSocket.__init__E  ss     #,..",..%..MM+ / 
 

 	DO011111rA   funcCallable[..., T]argsr   r   c                   	 d}d}	  || }n)# t           j        $ r d}Y nt           j        $ r d}Y nw xY w| j                                        }|r| j                            |           |rV| j                            | j                  }|r| j	        
                    |           n| j	                                         |r|S )NTF)r   SSLWantReadErrorSSLWantWriteErrorr   readr   r   r   recv_bufsizer   write	write_eof)r>   r   r   	want_read
want_writeresultr   s          r@   r   zSSLSSLSocket.run_ioU  s   	IJ"t. ! ! ! 			/ " " "!


" =%%''D .''---  ++D,=>> .M''----M++--- Ms    333buflenintr   c                p    	 |                      | j        j        |          S # t          j        $ r Y dS w xY w)NrA   )r   r   r   r   SSLEOFError)r>   r   s     r@   r   zSSLSSLSocket.recvs  sE    	;;t3V<<<% 	 	 	33	s   " 55r   c                B    |                      | j        j        |          S N)r   r   r   )r>   r   s     r@   sendzSSLSSLSocket.sendy  s    {{4?0$777rA   c                *   d}t          |          5 }|                    d          5 }t          |          }||k     r&||                     ||d                    z  }||k     &d d d            n# 1 swxY w Y   d d d            d S # 1 swxY w Y   d S )Nr   B)
memoryviewr	   lenr   )r>   r   countview	byte_viewamounts         r@   r   zSSLSSLSocket.sendall|  s    	6tyy~~ 	6^^F&..9UVV#4555 &..	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6s4   B<A0$B0A4	4B7A4	8BBBnamerq   c                ,    t          | j        |          S r   )getattrr   )r>   r  s     r@   __getattr__zSSLSSLSocket.__getattr__  s    t---rA   r   )rb   r3   r}   r   rd   rE   r7   r8   )r   r   r   r   r7   r   )r   r   r7   r   )r   r   r7   r   )r   r   r7   r8   )r  rq   r7   r   )r\   r]   r^   r_   r   r=   r   r   r   r   r  r   rA   r@   r   r   ;  s          L '+	2 2 2 2 2    <   8 8 8 86 6 6 6. . . . . .rA   r   ).rp   rq   rb   rr   rc   rs   rd   rE   re   rt   rf   ru   rg   rv   rh   rE   rB   rC   rD   rE   ri   rw   rj   rs   rk   rE   rl   r5   r.   r5   r/   r5   r0   r5   rm   rx   r1   r6   rn   ry   ro   rz   r{   r   r7   r(   )NN)r   rE   rp   rE   r{   r   r7   r(   )
ri   r   r   r   r   r%   r{   r   r7   r3   r   )ri   r   r   r   rD   rE   r7   r   )rb   r3   r   r%   r7   r   )ri   r   r   r   r   r%   rD   rE   rc   rs   rd   rE   r{   r   r7   r3   )I
__future__r   r2   rc   r   r:   r   collections.abcr   typingr   r   r   r   r	   clientr   datastructuresr   r   
exceptionsr   r   r   extensions.baser   extensions.permessage_deflater   rL   r   r   r   http11r   r   r4   r   r   streamsr   r   r   r   rp   r   r   r    r!   r"   r   r$   utilsr%   __all__r(   r&   r'   python_socksr   python_socks.syncr   SOCKS5SOCKS4r   r   r   r   r   r   r   r   r   r   r   rA   r@   <module>r     s   " " " " " "           $ $ $ $ $ $ 8 8 8 8 8 8 8 8 8 8 8 8 8 8 # # # # # # 1 1 1 1 1 1 1 1 L L L L L L L L L L 4 4 4 4 4 4 L L L L L L R R R R R R R R R R ) ) ) ) ) ) ) ) ( ( ( ( ( ( ( ( " " " " " " 4 4 4 4 4 4 4 4 4 4 H H H H H H H H H H H H H H " " " " " "       :
9
9b% b% b% b% b%z b% b% b%R "&(,"& :>15'-1$.(,.2(,!#"$!#"$ <> $7;;D D D D D DP < < < < <<3K&&&&&&555555 #"#"	  	 J J J J J2  K K KK K K K K KK %)I I I I I&   N %)(,"&# # # # # #L GCLLGCxQ'(((M. M. M. M. M. M. M. M. M. M.s   2C: :	DD