
    iH                       d dl m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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mZ ddlmZm Z m!Z! ddl"m#Z# ddlm$Z$m%Z%m&Z& ddl'm(Z( ddl)m*Z* g dZ+ G d de(          Z, G d d          Z-	 	 dEddddddddddeddddddddFd@Z.	 dGdHdDZ/dS )I    )annotationsN)TracebackType)AnyCallableOptionalSequenceType)	CloseCode   )ServerExtensionFactory) enable_server_permessage_deflate)validate_subprotocols)
USER_AGENT)RequestResponse)
CONNECTINGOPENEvent)ServerProtocol)
LoggerLikeOriginSubprotocol   )
Connection)Deadline)serve
unix_serveServerConnectionWebSocketServerc                  T     e Zd ZdZddd fdZd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 server connection.

    :class:`ServerConnection` 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 client.
        protocol: Sans-I/O connection.
        close_timeout: Timeout for closing the connection in seconds.

    
   close_timeoutsocketsocket.socketprotocolr   r#   Optional[float]returnNonec                   |  t          j                    | _        t                                          |||           d S )Nr"   )	threadingr   request_rcvdsuper__init__)selfr$   r&   r#   	__class__s       \/var/www/html/crypto-bot/backend/venv/lib/python3.11/site-packages/websockets/sync/server.pyr.   zServerConnection.__init__7   sO     	%%O--' 	 	
 	
 	
 	
 	
    Nprocess_requestCOptional[Callable[[ServerConnection, Request], Optional[Response]]]process_responseMOptional[Callable[[ServerConnection, Request, Response], Optional[Response]]]server_headerOptional[str]timeoutc                   | j                             |          s<|                                  | j                                         t          d          | j        <|                                  | j                                         t          d          |                     t                    5  d| _
        |	  || | j                  | _
        nn# t          $ ra}|| j        _        | j                            dd           | j                            t"          j        j        d          | _
        Y d}~nd}~ww xY w| j
        $| j                            | j                  | _
        ||| j
        j        d	<   |	  || | j        | j
                  }||| _
        nn# t          $ ra}|| j        _        | j                            dd           | j                            t"          j        j        d          | _
        Y d}~nd}~ww xY w| j                            | j
                   ddd           n# 1 swxY w Y   | j        j        t0          urL| j                            | j                   |                                  | j                                         | j        j        | j        j        dS )
z1
        Perform the opening handshake.

        ztimed out during handshakeNz"connection closed during handshake)expected_statezopening handshake failedTexc_infozLFailed to open a WebSocket connection.
See server log for more information.
Server)r,   waitclose_socketrecv_events_threadjoinTimeoutErrorrequestConnectionErrorsend_contextr   response	Exceptionr&   handshake_excloggererrorrejecthttp
HTTPStatusINTERNAL_SERVER_ERRORacceptheaderssend_responsestater   r#   )r/   r3   r5   r7   r9   excrG   s          r1   	handshakezServerConnection.handshakeF   s   *  %%g.. 	=#((***;<<<<#((***!"FGGGj99 (	7 (	7 DM*$3OD$,$G$GDMM  	 	 	25DM/K%%&@4%PPP$(M$8$8=E% %DMMMMMM	 }$ $ 4 4T\ B B(2?%h/+1//dlDMRRH  +(0 ! 	 	 	25DM/K%%&@4%PPP$(M$8$8=E% %DMMMMMM	 M''666Q(	7 (	7 (	7 (	7 (	7 (	7 (	7 (	7 (	7 (	7 (	7 (	7 (	7 (	7 (	7T =d**#(();<<<#((***=&2--- 32si   5
H> CH>
E!AD=8H>=EAH>F%
H>%
H/AHH>H"H>>IIeventr   c                    | j         9t          |t                    sJ || _         | j                                         dS t                                          |           dS )z.
        Process one incoming event.

        N)rD   
isinstancer   r,   setr-   process_event)r/   rV   r0   s     r1   rZ   zServerConnection.process_event   se     <eW----- DL!!##### GG!!%(((((r2   c                    	 t                                                       | j                                         dS # | j                                         w xY w)zI
        Read incoming data from the socket and process events.

        N)r-   recv_eventsr,   rY   )r/   r0   s    r1   r\   zServerConnection.recv_events   sV    
	$GG!!! !!#####D!!####s	    > A)r$   r%   r&   r   r#   r'   r(   r)   )
r3   r4   r5   r6   r7   r8   r9   r'   r(   r)   )rV   r   r(   r)   r(   r)   )
__name__
__module____qualname____doc__r.   r   rU   rZ   r\   __classcell__)r0   s   @r1   r   r      s         8 *,
 
 
 
 
 
 
 
,  '1#'O. O. O. O. O.b) ) ) ) ) )	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$r2   r   c                  F    e 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   a  
    WebSocket server returned by :func:`serve`.

    This class mirrors the API of :class:`~socketserver.BaseServer`, notably the
    :meth:`~socketserver.BaseServer.serve_forever` and
    :meth:`~socketserver.BaseServer.shutdown` methods, as well as the context
    manager protocol.

    Args:
        socket: Server socket listening for new connections.
        handler: Handler for one connection. Receives the socket and address
            returned by :meth:`~socket.socket.accept`.
        logger: Logger for this server.

    Nr$   r%   handler$Callable[[socket.socket, Any], None]rJ   Optional[LoggerLike]c                    || _         || _        |t          j        d          }|| _        t
          j        dk    r"t          j                    \  | _	        | _
        d S d S )Nzwebsockets.serverwin32)r$   rd   logging	getLoggerrJ   sysplatformospipeshutdown_watchershutdown_notifier)r/   r$   rd   rJ   s       r1   r.   zWebSocketServer.__init__   s`     >&':;;F<7""<>GII9D!4#9#9#9 #"r2   r(   r)   c                   t          j                    }|                    | j        t           j                   t
          j        dk    r%|                    | j        t           j                   	 |                                 	 | j        	                                \  }}n# t          $ r Y dS w xY wt          j        | j        ||f          }|                                 u)a  
        See :meth:`socketserver.BaseServer.serve_forever`.

        This method doesn't return. Calling :meth:`shutdown` from another thread
        stops the server.

        Typical use::

            with serve(...) as server:
                server.serve_forever()

        rh   T)targetargsN)	selectorsDefaultSelectorregisterr$   
EVENT_READrk   rl   ro   selectrP   OSErrorr+   Threadrd   start)r/   pollersockaddrthreads        r1   serve_foreverzWebSocketServer.serve_forever   s     *,,Y%9:::<7""OOD193GHHH		MMOOO "[//11
dd   %T\tMMMFLLNNN		s   B! !
B/.B/c                    | j                                          t          j        dk    rt	          j        | j        d           dS dS )z@
        See :meth:`socketserver.BaseServer.shutdown`.

        rh      xN)r$   closerk   rl   rm   writerp   r/   s    r1   shutdownzWebSocketServer.shutdown   sH    
 	<7""HT+T22222 #"r2   intc                4    | j                                         S )z>
        See :meth:`socketserver.BaseServer.fileno`.

        )r$   filenor   s    r1   r   zWebSocketServer.fileno   s    
 {!!###r2   c                    | S N r   s    r1   	__enter__zWebSocketServer.__enter__   s    r2   exc_typeOptional[Type[BaseException]]	exc_valueOptional[BaseException]	tracebackOptional[TracebackType]c                .    |                                   d S r   )r   )r/   r   r   r   s       r1   __exit__zWebSocketServer.__exit__   s     	r2   r   )r$   r%   rd   re   rJ   rf   r]   )r(   r   )r(   r   )r   r   r   r   r   r   r(   r)   )
r^   r_   r`   ra   r.   r   r   r   r   r   r   r2   r1   r   r      s         ( (,	F F F F F   :3 3 3 3$ $ $ $        r2   r   Fdeflater!   i   )r}   ssl_contextunixpathorigins
extensionssubprotocolsselect_subprotocolr3   r5   r7   compressionopen_timeoutr#   max_sizerJ   create_connectionrd   "Callable[[ServerConnection], None]hostr8   portOptional[int]r}   Optional[socket.socket]r   Optional[ssl.SSLContext]r   boolr   r   $Optional[Sequence[Optional[Origin]]]r   *Optional[Sequence[ServerExtensionFactory]]r   Optional[Sequence[Subprotocol]]r   TOptional[Callable[[ServerConnection, Sequence[Subprotocol]], Optional[Subprotocol]]]r3   r4   r5   r6   r7   r   r   r'   r#   r   rJ   rf   r    Optional[Type[ServerConnection]]r(   c                  	
 	t          	           |dk    rt                    n|t          d|           t          |Kr2|t	          d          t          j        |t
          j                  }n(t          j        ||f          }n|t	          d                              |dd	          }d 
	fd}t          ||          S )aH  
    Create a WebSocket server listening on ``host`` and ``port``.

    Whenever a client connects, the server creates a :class:`ServerConnection`,
    performs the opening handshake, and delegates to the ``handler``.

    The handler receives a :class:`ServerConnection` instance, which you can use
    to send and receive messages.

    Once the handler completes, either normally or with an exception, the server
    performs the closing handshake and closes the connection.

    :class:`WebSocketServer` mirrors the API of
    :class:`~socketserver.BaseServer`. Treat it as a context manager to ensure
    that it will be closed and call the :meth:`~WebSocketServer.serve_forever`
    method to serve requests::

        def handler(websocket):
            ...

        with websockets.sync.server.serve(handler, ...) as server:
            server.serve_forever()

    Args:
        handler: Connection handler. It receives the WebSocket connection,
            which is a :class:`ServerConnection`, in argument.
        host: Network interfaces the server binds to.
            See :func:`~socket.create_server` for details.
        port: TCP port the server listens on.
            See :func:`~socket.create_server` for details.
        sock: Preexisting TCP socket. ``sock`` replaces ``host`` and ``port``.
            You may call :func:`socket.create_server` to create a suitable TCP
            socket.
        ssl_context: Configuration for enabling TLS on the connection.
        origins: Acceptable values of the ``Origin`` header, for defending
            against Cross-Site WebSocket Hijacking attacks. Include :obj:`None`
            in the list if the lack of an origin is acceptable.
        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.
        select_subprotocol: Callback for selecting a subprotocol among
            those supported by the client and the server. It receives a
            :class:`ServerConnection` (not a
            :class:`~websockets.server.ServerProtocol`!) instance and a list of
            subprotocols offered by the client. Other than the first argument,
            it has the same behavior as the
            :meth:`ServerProtocol.select_subprotocol
            <websockets.server.ServerProtocol.select_subprotocol>` method.
        process_request: Intercept the request during the opening handshake.
            Return an HTTP response to force the response or :obj:`None` to
            continue normally. When you force an HTTP 101 Continue response,
            the handshake is successful. Else, the connection is aborted.
        process_response: Intercept the response during the opening handshake.
            Return an HTTP response to force the response or :obj:`None` to
            continue normally. When you force an HTTP 101 Continue response,
            the handshake is successful. Else, the connection is aborted.
        server_header: Value of  the ``Server`` response 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 connections in seconds.
            :obj:`None` disables the timeout.
        close_timeout: Timeout for closing connections 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 server.
            It defaults to ``logging.getLogger("websockets.server")``. See the
            :doc:`logging guide <../../topics/logging>` for details.
        create_connection: Factory for the :class:`ServerConnection` managing
            the connection. Set it to a wrapper or a subclass to customize
            connection handling.
    Nr   zunsupported compression: zmissing path argument)familyz(path and sock arguments are incompatibleTF)server_sidedo_handshake_on_connectr}   r%   r~   r   r(   r)   c           	     H   t                    }	 s+|                     t          j        t          j        d           l|                     |                                           t          | t          j	                  sJ | 
                                 |                     d            d }dfd}t          |t          
	          }J  | |
                              |                                           n%# t          $ r |                                  Y d S w xY w	  	                                            d S # t          $ r? |j                            dd                               t$          j                   Y d S w xY w)NTr&   r   r   Sequence[Subprotocol]r(   Optional[Subprotocol]c                :    J | j         u sJ  |          S r   )r&   )r&   r   
connectionr   s     r1   protocol_select_subprotocolz@serve.<locals>.conn_handler.<locals>.protocol_select_subprotocol  s8    
 .999#z':::::--j,GGGr2   )r   r   r   r   rS   r   rJ   r"   zconnection handler failedr<   )r&   r   r   r   r(   r   )r   
setsockoptr$   IPPROTO_TCPTCP_NODELAY
settimeoutr9   rX   ssl	SSLSocketdo_handshaker   r   rU   rH   r   rJ   rK   r
   INTERNAL_ERROR)r}   r~   deadliner   r&   r   r#   r   r   rd   rJ   r   r   r   r3   r5   r   r7   r   r   r   s        @r1   conn_handlerzserve.<locals>.conn_handler  s'    L))B	  N 2F4FMMM & 0 0 2 2333!$66666!!###%%%  ( "-H H H H H H H &%)#> !  H %000**+  J      ""	     	 	 	JJLLLFF		GJ
 	  	7 	7 	7O!!"=!MMMY5666666	7s%   C=D D32D37E AF! F!)r}   r%   r~   r   r(   r)   )
r   r   
ValueErrorr   	TypeErrorr$   create_serverAF_UNIXwrap_socketr   )rd   r   r   r}   r   r   r   r   r   r   r   r3   r5   r7   r   r   r#   r   rJ   r   r   s   `   `` ``````` ````` r1   r   r   	  s   v l+++i5jAA

		 B[BBCCC , | 	6| 7888'V^DDDDD't55DDFGGG &&$)	 ' 
 
P P P P P P P P P P P P P P P P P P P Ph 4v666r2   !Callable[[ServerConnection], Any]kwargsr   c                "    t          | f|dd|S )a  
    Create a WebSocket server listening on a Unix socket.

    This function is identical to :func:`serve`, except the ``host`` and
    ``port`` arguments are replaced by ``path``. It's only available on Unix.

    It's useful for deploying a server behind a reverse proxy such as nginx.

    Args:
        handler: Connection handler. It receives the WebSocket connection,
            which is a :class:`ServerConnection`, in argument.
        path: File system path to the Unix socket.

    T)r   r   )r   )rd   r   r   s      r1   r   r     s!    & 9t$99&999r2   )NN)*rd   r   r   r8   r   r   r}   r   r   r   r   r   r   r8   r   r   r   r   r   r   r   r   r3   r4   r5   r6   r7   r8   r   r8   r   r'   r#   r'   r   r   rJ   rf   r   r   r(   r   r   )rd   r   r   r8   r   r   r(   r   )0
__future__r   rM   ri   rm   rt   r$   r   rk   r+   typesr   typingr   r   r   r   r	   websockets.framesr
   extensions.baser   extensions.permessage_deflater   rQ   r   r   http11r   r   r&   r   r   r   serverr   r   r   r   r   r   utilsr   __all__r   r   r   r   r   r2   r1   <module>r      s   " " " " " "   				      



 



           : : : : : : : : : : : : : : ' ' ' ' ' ' 4 4 4 4 4 4 L L L L L L + + + + + +       & & & & & & & & . . . . . . . . . . # # # # # # 4 4 4 4 4 4 4 4 4 4 " " " " " "       I
H
HO$ O$ O$ O$ O$z O$ O$ O$dU U U U U U U Ut s7 %),048=A48 	 	 	#-!*$&%'##':>Us7 s7 s7 s7 s7 s7p : : : : : : :r2   