
    2Bf,                       d dl mZ d dlZd dlZd dl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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$ g dZ% G d de"      Z&dddddddddeddddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ'	 	 d	 	 	 	 	 	 	 ddZ(y)    )annotationsN)AnyOptionalSequenceType   )ClientProtocol)HeadersLike)ClientExtensionFactory) enable_client_permessage_deflate)validate_subprotocols)
USER_AGENT)Response)
CONNECTINGOPENEvent)
LoggerLikeOriginSubprotocol)	parse_uri   )
Connection)Deadline)connectunix_connectClientConnectionc                  n     e Zd ZdZ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   a  
    Threaded 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.

    Args:
        socket: Socket connected to a WebSocket server.
        protocol: Sans-I/O connection.
        close_timeout: Timeout for closing the connection in seconds.

    
   close_timeoutc               `    |  t        j                         | _        t        |   |||       y )Nr   )	threadingr   response_rcvdsuper__init__)selfsocketprotocolr    	__class__s       V/var/www/highfloat_scraper/venv/lib/python3.12/site-packages/websockets/sync/client.pyr%   zClientConnection.__init__1   s2     	&__.' 	 	
    Nc                   | j                  t              5  | j                  j                         | _        |%| j                  j
                  j                  |       ||| j                  j
                  d<   | j                  j                  | j                         ddd       | j                  j                  |      s5| j                          | j                  j                          t        d      | j                  5| j                          | j                  j                          t        d      | j                  j                   t"        urO| j                  j                  | j$                         | j                          | j                  j                          | j                  j&                  | j                  j&                  y# 1 sw Y   3xY w)z1
        Perform the opening handshake.

        )expected_stateNz
User-Agentztimed out during handshakez"connection closed during handshake)send_contextr   r(   r   requestheadersupdatesend_requestr#   waitclose_socketrecv_events_threadjoinTimeoutErrorresponseConnectionErrorstater   r    handshake_exc)r&   additional_headersuser_agent_headertimeouts       r*   	handshakezClientConnection.handshake@   sp    j9 	5==002DL!-$$++,>? ,5F$$\2MM&&t||4	5 !!&&w/##((*;<<== ##((*!"FGG==d*##((););<##((*==&&2----- 3/	5 	5s   BGGc                    | j                   4t        |t              sJ || _         | j                  j	                          yt
        |   |       y)z.
        Process one incoming event.

        N)r8   
isinstancer   r#   setr$   process_event)r&   eventr)   s     r*   rC   zClientConnection.process_eventd   sG     == eX...!DM""$ G!%(r+   c                    	 t         |           | j                  j                          y# | j                  j                          w xY w)zI
        Read incoming data from the socket and process events.

        N)r$   recv_eventsr#   rB   )r&   r)   s    r*   rF   zClientConnection.recv_eventsr   s:    
	%G! ""$D""$s	   , A)r'   zsocket.socketr(   r	   r    Optional[float]returnNone)r<   Optional[HeadersLike]r=   Optional[str]r>   rG   rH   rI   )rD   r   rH   rI   )rH   rI   )
__name__
__module____qualname____doc__r%   r   r?   rC   rF   __classcell__)r)   s   @r*   r   r      s~    8 *,

 !

 '
 

" 59+5#'	".1". )". !	".
 
".H)	% 	%r+   r   Fdeflater   i   )sockssl_contextserver_hostnameunixpathorigin
extensionssubprotocolsr<   r=   compressionopen_timeoutr    max_sizeloggercreate_connectionc          	        t        |       }|j                  s|t        d      |r||t        d      ||t        d      |J |t        |       |dk(  rt	        |      }n|t        d|       t        |      }|t        }	 ||rgt        j                  t        j                  t        j                        }|j                  |j                                |J |j                  |       n:t        j                  |j                  |j                   f|j                               }|j                  d       |s/|j#                  t        j$                  t        j&                  d       |j                  rg|t)        j*                         }||j                  }|j                  |j                                |j-                  ||      }|j                  d       t/        ||||t0        ||	      } ||||
      }|j3                  |	|
|j                                |S # t4        $ r ||j7                           w xY w)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::

        async with websockets.sync.client.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_context: 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.
        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.
        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.
        open_timeout: Timeout for opening the connection in seconds.
            :obj:`None` disables the timeout.
        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.
        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.

    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.

    Nz5ssl_context argument is incompatible with a ws:// URIzmissing path argumentz(path and sock arguments are incompatiblerQ   zunsupported compression: T)rT   )rW   rX   rY   r:   r\   r]   r   )r   secure	TypeErrorr   r   
ValueErrorr   r   r'   AF_UNIXSOCK_STREAM
settimeoutr>   r   r^   hostport
setsockoptIPPROTO_TCPTCP_NODELAYsslcreate_default_contextwrap_socketr	   r   r?   	Exceptionclose)urirR   rS   rT   rU   rV   rW   rX   rY   r<   r=   rZ   r[   r    r\   r]   r^   wsurideadliner(   
connections                        r*   r   r   ~   sF   f cNE<<K3OPP<DL344$"2FGG||l+i5jA
		 4[MBCC
 %H ,= <}}V^^V5G5GH 0 0 23'''T"//ZZ,$$& OOD! OOF..0B0BDI <<"!88:&"'**OOH,,./**4*QDOOD! "!%
 ''

 		
   JJLs   FH) )Ic                P    ||j                  d      d}nd}t        d|d| d|S )a  
    Connect to a WebSocket server listening on a Unix socket.

    This function is identical to :func:`connect`, except for the additional
    ``path`` argument. 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_context`` is provided, to
            ``wss://localhost/``.

    rS   zws://localhost/zwss://localhost/T)rp   rU   rV    )getr   )rV   rp   kwargss      r*   r   r   /  s9    ( {::m$,#C$C;sD;F;;r+   )$rp   strrR   zOptional[socket.socket]rS   zOptional[ssl.SSLContext]rT   rK   rU   boolrV   rK   rW   zOptional[Origin]rX   z*Optional[Sequence[ClientExtensionFactory]]rY   zOptional[Sequence[Subprotocol]]r<   rJ   r=   rK   rZ   rK   r[   rG   r    rG   r\   zOptional[int]r]   zOptional[LoggerLike]r^   z Optional[Type[ClientConnection]]rH   r   )NN)rV   rK   rp   rK   rw   r   rH   r   ))
__future__r   r'   rk   r"   typingr   r   r   r   clientr	   datastructuresr
   extensions.baser   extensions.permessage_deflater   r0   r   httpr   http11r   r(   r   r   r   r   r   r   rp   r   rs   r   utilsr   __all__r   r   r   ru   r+   r*   <module>r      s   "  
  0 0 # ( 4 L +   . . 4 4  "  :b%z b%R %),0%)#=A4804'1!*$&%'##':>1n	n "	n
 *n #n n n n ;n 2n .n %n n" "#n$ #%n( )n, !-n0 81n2 3nd <
<	< < 	<r+   