
    gw                       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	m
Z
 d dlmZmZmZmZ ddlmZmZmZmZ ddlmZmZmZmZmZ ddlmZmZ dd	lmZm Z 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gZ+ G d d      Z,y)    )annotationsN)TracebackType)AnyIterableIteratorMapping   )ConcurrencyErrorConnectionClosedConnectionClosedOKProtocolError)DATA_OPCODES	BytesLike	CloseCodeFrameOpcode)RequestResponse)CLOSEDOPENEventProtocolState)Data
LoggerLikeSubprotocol   )	Assembler)Deadline
Connectionc                  @   e Zd ZdZdZdd	 	 	 	 	 	 	 ddZedd       Zedd       Zedd       Z	dd	Z
	 	 	 	 	 	 	 	 d d
Zd!dZd"d#dZd!dZd$dZej"                  dfd%dZd"d&dZd'd(dZd)dZd*dZd+dZej2                  ed	 	 	 d,d       Zd+dZd-dZd+dZy).r    a?  
    :mod:`threading` implementation of a WebSocket connection.

    :class:`Connection` provides APIs shared between WebSocket servers and
    clients.

    You shouldn't use it directly. Instead, use
    :class:`~websockets.sync.client.ClientConnection` or
    :class:`~websockets.sync.server.ServerConnection`.

    i   
   )close_timeoutc               r   || _         || _        || _        t        j                  | j                  j
                  d| i      | j                  _        | j                  j                  | _        	 | j                  j
                  | _        	 | j                  j                  | _        d | _        	 d | _	        	 t        j                         | _        t               | _        d| _        d | _        i | _        t        j$                  | j&                  d      | _        | j(                  j+                          d | _        y )N	websocketFT)targetdaemon)socketprotocolr#   loggingLoggerAdapterloggeriddebugrequestresponse	threadingLockprotocol_mutexr   recv_messagessend_in_progressclose_deadlineping_waitersThreadrecv_eventsrecv_events_threadstartrecv_exc)selfr(   r)   r#   s       O/var/www/openai/venv/lib/python3.12/site-packages/websockets/sync/connection.py__init__zConnection.__init__-   s     *  '44MM  $ 
 "]]--B"&--"6"6)]]((
 (,()-) (nn. '[ !& 04 ;=
 #,"2"2###
 	%%' /3    c                6    | j                   j                         S )z
        Local address of the connection.

        For IPv4 connections, this is a ``(host, port)`` tuple.

        The format of the address depends on the address family.
        See :meth:`~socket.socket.getsockname`.

        )r(   getsocknamer=   s    r>   local_addresszConnection.local_addressi        {{&&((r@   c                6    | j                   j                         S )z
        Remote address of the connection.

        For IPv4 connections, this is a ``(host, port)`` tuple.

        The format of the address depends on the address family.
        See :meth:`~socket.socket.getpeername`.

        )r(   getpeernamerC   s    r>   remote_addresszConnection.remote_addressv   rE   r@   c                .    | j                   j                  S )z~
        Subprotocol negotiated during the opening handshake.

        :obj:`None` if no subprotocol was negotiated.

        )r)   subprotocolrC   s    r>   rJ   zConnection.subprotocol   s     }}(((r@   c                    | S N rC   s    r>   	__enter__zConnection.__enter__   s    r@   c                h    || j                          y | j                  t        j                         y rL   )closer   INTERNAL_ERROR)r=   exc_type	exc_value	tracebacks       r>   __exit__zConnection.__exit__   s%     JJLJJy//0r@   c              #  R   K   	 	 | j                          # t        $ r Y yw xY ww)aC  
        Iterate on incoming messages.

        The iterator calls :meth:`recv` and yields messages in an infinite loop.

        It exits when the connection is closed normally. It raises a
        :exc:`~websockets.exceptions.ConnectionClosedError` exception after a
        protocol error or a network failure.

        N)recvr   rC   s    r>   __iter__zConnection.__iter__   s0     	iik! ! 		s   ' 	$'$'Nc                    	 | j                   j                  |      S # t        $ r< | j                  j	                          | j
                  j                  | j                  t        $ r t        d      dw xY w)aB  
        Receive the next message.

        When the connection is closed, :meth:`recv` raises
        :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it raises
        :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal closure
        and :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol
        error or a network failure. This is how you detect the end of the
        message stream.

        If ``timeout`` is :obj:`None`, block until a message is received. If
        ``timeout`` is set and no message is received within ``timeout``
        seconds, raise :exc:`TimeoutError`. Set ``timeout`` to ``0`` to check if
        a message was already received.

        If the message is fragmented, wait until all fragments are received,
        reassemble them, and return the whole message.

        Returns:
            A string (:class:`str`) for a Text_ frame or a bytestring
            (:class:`bytes`) for a Binary_ frame.

            .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
            .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6

        Raises:
            ConnectionClosed: When the connection is closed.
            ConcurrencyError: If two threads call :meth:`recv` or
                :meth:`recv_streaming` concurrently.

        zOcannot call recv while another thread is already running recv or recv_streamingN)	r4   getEOFErrorr:   joinr)   	close_excr<   r
   )r=   timeouts     r>   rW   zConnection.recv   su    @
	%%))'22 	=##((*--))t}}< 	"< 	s
    AA6c              #    K   	 | j                   j                         D ]  }|  y# t        $ r< | j                  j	                          | j
                  j                  | j                  t        $ r t        d      dw xY ww)a6  
        Receive the next message frame by frame.

        If the message is fragmented, yield each fragment as it is received.
        The iterator must be fully consumed, or else the connection will become
        unusable.

        :meth:`recv_streaming` raises the same exceptions as :meth:`recv`.

        Returns:
            An iterator of strings (:class:`str`) for a Text_ frame or
            bytestrings (:class:`bytes`) for a Binary_ frame.

            .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
            .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6

        Raises:
            ConnectionClosed: When the connection is closed.
            ConcurrencyError: If two threads call :meth:`recv` or
                :meth:`recv_streaming` concurrently.

        zYcannot call recv_streaming while another thread is already running recv or recv_streamingN)	r4   get_iterr[   r:   r\   r)   r]   r<   r
   )r=   frames     r>   recv_streamingzConnection.recv_streaming   s~     .	++446 7 	=##((*--))t}}< 	"< 	s   B#( BABBc                   t        |t              rZ| j                         5  | j                  rt	        d      | j
                  j                  |j                                ddd       yt        |t              rL| j                         5  | j                  rt	        d      | j
                  j                  |       ddd       yt        |t              rt        d      t        |t              rt        |      }	 t        |      }	 t        |t              red}| j                         5  | j                  rt	        d      d| _        | j
                  j                  |j                         d       ddd       nrt        |t              rWd}| j                         5  | j                  rt	        d      d| _        | j
                  j                  |d       ddd       nt        d      |D ]  }t        |t              rU|rS| j                         5  | j                  sJ | j
                  j!                  |j                         d       ddd       ht        |t              rG|sE| j                         5  | j                  sJ | j
                  j!                  |d       ddd       t        d       | j                         5  | j
                  j!                  d	d       d| _        ddd       yyt        d      # 1 sw Y   yxY w# 1 sw Y   yxY w# t        $ r Y yw xY w# 1 sw Y   HxY w# 1 sw Y   UxY w# 1 sw Y   `xY w# 1 sw Y   mxY w# 1 sw Y   pxY w# t        $ r  t"        $ rQ | j                         5  | j
                  j%                  t&        j(                  d
       ddd        # 1 sw Y    xY ww xY w)a  
        Send a message.

        A string (:class:`str`) is sent as a Text_ frame. A bytestring or
        bytes-like object (:class:`bytes`, :class:`bytearray`, or
        :class:`memoryview`) is sent as a Binary_ frame.

        .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
        .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6

        :meth:`send` also accepts an iterable of strings, bytestrings, or
        bytes-like objects to enable fragmentation_. Each item is treated as a
        message fragment and sent in its own frame. All items must be of the
        same type, or else :meth:`send` will raise a :exc:`TypeError` and the
        connection will be closed.

        .. _fragmentation: https://datatracker.ietf.org/doc/html/rfc6455#section-5.4

        :meth:`send` rejects dict-like objects because this is often an error.
        (If you really want to send the keys of a dict-like object as fragments,
        call its :meth:`~dict.keys` method and pass the result to :meth:`send`.)

        When the connection is closed, :meth:`send` raises
        :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it
        raises :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal
        connection closure and
        :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol
        error or a network failure.

        Args:
            message: Message to send.

        Raises:
            ConnectionClosed: When the connection is closed.
            ConcurrencyError: If the connection is sending a fragmented message.
            TypeError: If ``message`` doesn't have a supported type.

        z=cannot call send while another thread is already running sendNzdata is a dict-like objectTF)finz'data iterable must contain bytes or strz(data iterable must contain uniform typesr@   zerror in fragmented messagez$data must be str, bytes, or iterable)
isinstancestrsend_contextr5   r
   r)   	send_textencoder   send_binaryr   	TypeErrorr   iternextStopIterationsend_continuation	Exceptionfailr   rQ   )r=   messagechunkschunktexts        r>   sendzConnection.send   sw   T gs#""$((*2  ''(89 %$ +""$((*2  ))'2 %$ )899 *']FVDeS)D**,00"2!:#  15-//!LLN % 0  -,  y1 D**,00"2!:#  15-11! % 2  -, $$MNN $E!%-$!..0#'#8#88#8 MM;; %$) <  10 $E95d!..0#'#8#88#8 MM;; %$) <  10 ((RSS! $& &&(MM33CT3B,1D) )(( BCCM %$ %$& !  -, -," 10 10 )( $    &&(MM&&!005 )
  )
 s   AL	3L?L! "M0 -A
L07+M0 "<L=;M0 :M
+M0 >,M*%M0 %M$4M0 	LL!	L-,L-0L:5M0 =MM0 
M	M0 M!	M0 $M-)M0 0"O+O=	OO	O c                   	 | j                         5  | j                  r+| j                  j                  t        j
                  d       n| j                  j                  ||       ddd       y# 1 sw Y   yxY w# t        $ r Y yw xY w)a  
        Perform the closing handshake.

        :meth:`close` waits for the other end to complete the handshake, for the
        TCP connection to terminate, and for all incoming messages to be read
        with :meth:`recv`.

        :meth:`close` is idempotent: it doesn't do anything once the
        connection is closed.

        Args:
            code: WebSocket close code.
            reason: WebSocket close reason.

        zclose during fragmented messageN)rg   r5   r)   rq   r   rQ   
send_closer   )r=   codereasons      r>   rP   zConnection.close  ss     	 ""$((MM&&!009
 MM,,T6: %$$   	 	s/   A; AA/&A; /A84A; 8A; ;	BBc                *   t        |t              rt        |      }n.t        |t              r|j	                         }n|t        d      | j                         5  || j                  v rt        d      ||| j                  v r;t        j                  dt        j                  d            }|,|| j                  v r;t        j                         }|| j                  |<   | j                  j!                  |       |cddd       S # 1 sw Y   yxY w)a  
        Send a Ping_.

        .. _Ping: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2

        A ping may serve as a keepalive or as a check that the remote endpoint
        received all messages up to this point

        Args:
            data: Payload of the ping. A :class:`str` will be encoded to UTF-8.
                If ``data`` is :obj:`None`, the payload is four random bytes.

        Returns:
            An event that will be set when the corresponding pong is received.
            You can ignore it if you don't intend to wait.

            ::

                pong_event = ws.ping()
                pong_event.wait()  # only if you want to wait for the pong

        Raises:
            ConnectionClosed: When the connection is closed.
            ConcurrencyError: If another ping was sent with the same data and
                the corresponding pong wasn't received yet.

        Ndata must be str or bytes-likez-already waiting for a pong with the same dataz!I    )re   r   bytesrf   ri   rk   rg   r7   r
   structpackrandomgetrandbitsr1   r   r)   	send_ping)r=   datapong_waiters      r>   pingzConnection.ping  s    8 dI&;Dc";;=D<== t(((&'VWW ,$$*;*;";{{4););B)?@ ,$$*;*;"; $//+K&1Dd#MM##D) !  s   AD	1D	 ?D		Dc                   t        |t              rt        |      }n,t        |t              r|j	                         }nt        d      | j                         5  | j                  j                  |       ddd       y# 1 sw Y   yxY w)ab  
        Send a Pong_.

        .. _Pong: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.3

        An unsolicited pong may serve as a unidirectional heartbeat.

        Args:
            data: Payload of the pong. A :class:`str` will be encoded to UTF-8.

        Raises:
            ConnectionClosed: When the connection is closed.

        r}   N)	re   r   r   rf   ri   rk   rg   r)   	send_pongr=   r   s     r>   pongzConnection.pong  sb     dI&;Dc";;=D<== MM##D) !  s   A>>Bc                   t        |t              sJ |j                  t        v r| j                  j                  |       |j                  t        j                  u r%| j                  t        |j                               yy)zx
        Process one incoming event.

        This method is overridden in subclasses to handle the handshake.

        N)re   r   opcoder   r4   putr   PONGacknowledge_pingsr   r   )r=   events     r>   process_eventzConnection.process_event  s`     %'''<<<'""5)<<6;;&""5#45 'r@   c                R   | j                   5  || j                  vr
	 ddd       yd}g }| j                  j                         D ]-  \  }}|j                  |       |j	                          ||k(  s- n t        d      |D ]  }| j                  |=  	 ddd       y# 1 sw Y   yxY w)z;
        Acknowledge pings when receiving a pong.

        Nz!solicited pong not found in pings)r3   r7   itemsappendsetAssertionError)r=   r   ping_idping_idsr   s        r>   r   zConnection.acknowledge_pings  s    
   4,,, !  GH!%!2!2!8!8!:(
d?	 "; %%HII#%%g. $! !  s   BA
B1"BB&c                   	 	 	 | j                   3| j                  j                  | j                   j                                | j                  j	                  | j
                        }|dk(  rn| j                  5  | j                  j                  |       | j                  j                         }	 | j                          | j                  j                         r&| j                   t!        | j"                        | _         ddd       	 D ]  }| j%                  |        	 "| j                  5  | j                  j)                          | j                  j                         rJ | j                          ddd       | j-                          y# t        $ rf}| j                  r| j                  j                  dd       | j                  5  | j                  |       ddd       n# 1 sw Y   nxY wY d}~d}~ww xY w# t        $ rM}| j                  r| j                  j                  dd       | j                  |       Y d}~ddd       /d}~ww xY w# 1 sw Y   ]xY w# t&        $ r Y Pw xY w# 1 sw Y   xY w# t        $ r[}| j                  j+                  dd       | j                  5  | j                  |       ddd       n# 1 sw Y   nxY wY d}~ed}~ww xY w# | j-                          w xY w)z
        Read incoming data from the socket and process events.

        Run this method in a thread as long as the connection is alive.

        ``recv_events()`` exits immediately when the ``self.socket`` is closed.

        TNzerror while receiving dataexc_infor@   error while sending dataunexpected internal error)r6   r(   
settimeoutr^   rW   recv_bufsizerp   r.   r,   r3   set_recv_excr)   receive_dataevents_received	send_dataclose_expectedr   r#   r   r[   receive_eoferrorclose_socket)r=   r   exceventsr   s        r>   r9   zConnection.recv_events#  s|   R	 **6..t/B/B/J/J/LM;;++D,=,=>D 3; ((MM..t4 "]]::<F
( }}335  ..62:4;M;M2ND/1 )B!' **51 "(m ~ $$))+  ==88:::   %$ Y ! 	zz))*FQU)V
 ,,))#. -,,	2 % :: KK--.HSW-X
 ))#.% )( )(L   
 %$  	'KK9DI$$!!#& %$$	' s	  J A$F (J :6I1HA IJ 
I) "J 1AI98J 	H 5G;G*!	G;*G3	/G;6J ;H  J 	I:II

J III&!J )	I62J 5I66J 9J>J 	K*)K%8K
	K%K	K%K- %K**K- -K?)expected_statec             #  L  K   d}d}d}| j                   5  | j                  j                  |u r[	 d | j                  j                         r*d}| j                  J t        | j                        | _        	 | j                          nd}d}ddd       |r| j                  | j                  }n| j                  j                  d      }| j                  j!                  |       | j                  j#                         r7|J t%        d      }d}| j                   5  | j'                  |       ddd       |rA| j)                          | j                  j!                          | j                  j*                  |y# t        $ r:}| j                  r| j                  j                  dd       d}d}|}Y d}~-d}~ww xY w# t        t        f$ r  t        $ r.}| j                  j                  dd       d}d}|}Y d}~vd}~ww xY w# 1 sw Y   xY w# 1 sw Y   xY ww)	a  
        Create a context for writing to the connection from user code.

        On entry, :meth:`send_context` acquires the connection lock and checks
        that the connection is open; on exit, it writes outgoing data to the
        socket::

            with self.send_context():
                self.protocol.send_text(message.encode())

        When the connection isn't open on entry, when the connection is expected
        to close on exit, or when an unexpected error happens, terminating the
        connection, :meth:`send_context` waits until the connection is closed
        then raises :exc:`~websockets.exceptions.ConnectionClosed`.

        FNTr   r   r   )raise_if_elapsedz"timed out while closing connection)r3   r)   stater   r6   r   r#   r   rp   r.   r,   r   r
   r   r^   r:   r\   is_aliveTimeoutErrorr   r   r]   )r=   r   wait_for_closeraise_close_excoriginal_excr   r^   s          r>   rg   zConnection.send_context  s    . -1   }}""n4"+ }}335)-  $22:::.6t7I7I.J+	+( "&"&W !d ""*,, --55u5M##((1&&//1 $++++,PQ #'((%%l3 )
 ##((*--))|;	 S % +:: KK--.HSW-X */*.'*+3 &'78   'KK%%&AD%Q &+N&*O#&L' ! D )(s   H$HGAH8E<HBH$H0AH$<	F?/F:4H:F??HH#H=HHHHH$H!H$c                   | j                   j                         sJ | j                  j                         D ]  }|r[| j                  3| j
                  j                  | j                  j                                | j
                  j                  |       `	 | j
                  j                  t
        j                          y# t        $ r Y w xY w)z
        Send outgoing data.

        This method requires holding protocol_mutex.

        Raises:
            OSError: When a socket operations fails.

        N)r3   lockedr)   data_to_sendr6   r(   r   r^   sendallshutdownSHUT_WROSErrorr   s     r>   r   zConnection.send_data  s     ""))+++MM..0D&&2KK**4+>+>+F+F+HI##D)KK((8 1  s   )C	CCc                d    | j                   j                         sJ | j                  || _        yy)zf
        Set recv_exc, if not set yet.

        This method requires holding protocol_mutex.

        N)r3   r   r<   )r=   r   s     r>   r   zConnection.set_recv_exc  s2     ""))+++== DM !r@   c                N   	 | j                   j                  t         j                         | j                   j	                          | j
                  j                          | j
                  j                  t        u sJ | j                  j	                          y# t        $ r Y xw xY w)z
        Shutdown and close socket. Close message assembler.

        Calling close_socket() guarantees that recv_events() terminates. Indeed,
        recv_events() may block only on socket.recv() or on recv_messages.put().

        N)
r(   r   	SHUT_RDWRr   rP   r)   r   r   r   r4   rC   s    r>   r   zConnection.close_socket  s    	KK  !1!12 	 	!!#}}""f,,, 	  "  		s   )B 	B$#B$)r(   zsocket.socketr)   r   r#   float | NonereturnNone)r   r   )r   zSubprotocol | None)r   r    )rR   ztype[BaseException] | NonerS   BaseException | NonerT   zTracebackType | Noner   r   )r   zIterator[Data]rL   )r^   r   r   r   )rr   zData | Iterable[Data]r   r   )rz   intr{   rf   r   r   )r   zData | Noner   zthreading.Event)r@   )r   r   r   r   )r   r   r   r   )r   r   r   r   )r   r   )r   r   r   zIterator[None])r   r   r   r   )__name__
__module____qualname____doc__r   r?   propertyrD   rH   rJ   rN   rU   rX   rW   rb   rv   r   NORMAL_CLOSURErP   r   r   r   r   r9   
contextlibcontextmanagerr   rg   r   r   r   rM   r@   r>   r    r       s:   
 L ')8383 83
 $83 
83x 
) 
) 
) 
) ) )	1,	1 (	1 (		1
 
	1"*X"HQDf !* 8 8 @/b*66/0[ z  !%h< h< 
	h< h<T,	 #r@   )-
__future__r   r   r*   r   r(   r   r1   uuidtypesr   typingr   r   r   r   
exceptionsr
   r   r   r   framesr   r   r   r   r   http11r   r   r)   r   r   r   r   r   r   r   r   messagesr   utilsr   __all__r    rM   r@   r>   <module>r      sc    "         3 3  G F & ; ; 2 2   .C# C#r@   