
    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	m
Z
 ddlmZmZmZmZmZmZ ddlmZ ddlmZmZmZmZmZmZmZmZ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& g dZ'e
e e!ef   Z(	  G d dejR                        Z*e*jV                  Z+e*jX                  Z, G d dejR                        Z-e-j\                  Z.e-j^                  Z/e-j`                  Z0e-jb                  Z1dZ2	  G d d      Z3y)    )annotationsN)	GeneratorListOptionalTypeUnion   )ConnectionClosedConnectionClosedErrorConnectionClosedOKInvalidStatePayloadTooBigProtocolError)	Extension)
OK_CLOSE_CODES	OP_BINARYOP_CLOSEOP_CONTOP_PINGOP_PONGOP_TEXTClose	CloseCodeFrame)RequestResponse)StreamReader)
LoggerLikeOriginSubprotocol)ProtocolSideStateSEND_EOFc                  &    e Zd ZdZ ed      \  ZZy)r"   z6A WebSocket connection is either a server or a client.   N)__name__
__module____qualname____doc__rangeSERVERCLIENT     S/var/www/highfloat_scraper/venv/lib/python3.12/site-packages/websockets/protocol.pyr"   r"   -   s    @1XNFFr/   r"   c                  *    e Zd ZdZ ed      \  ZZZZy)r#   z6A WebSocket connection is in one of these four states.   N)	r'   r(   r)   r*   r+   
CONNECTINGOPENCLOSINGCLOSEDr.   r/   r0   r#   r#   7   s    @(-a%Jgvr/   r#   r/   c                  2   e Zd ZdZeddd	 	 	 	 	 	 	 	 	 ddZedd       Zej                  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$dZd&d'dZd"dZd"dZd(d)dZd*dZd+dZd,dZd-dZd-dZd.dZd.dZd#dZy)/r!   a6  
    Sans-I/O implementation of a WebSocket connection.

    Args:
        side: :attr:`~Side.CLIENT` or :attr:`~Side.SERVER`.
        state: initial state of the WebSocket connection.
        max_size: maximum size of incoming messages in bytes;
            :obj:`None` disables the limit.
        logger: logger for this connection; depending on ``side``,
            defaults to ``logging.getLogger("websockets.client")``
            or ``logging.getLogger("websockets.server")``;
            see the :doc:`logging guide <../../topics/logging>` for details.

    i   N)statemax_sizeloggerc               H   t        j                         | _        	 |0t        j                  d|j
                  j                                }|| _        	 |j                  t        j                        | _
        || _        || _        || _        d | _        d| _        d | _        g | _        d | _        d | _        d | _        d | _        d | _        	 d| _        t1               | _        g | _        g | _        | j9                         | _        t=        | j:                         d | _        y )Nzwebsockets.F) uuiduuid4idlogging	getLoggernamelowerr:   isEnabledForDEBUGdebugsider8   r9   cur_sizeexpect_continuation_frameorigin
extensionssubprotocol
close_rcvd
close_sentclose_rcvd_then_senthandshake_exceof_sentr   readereventswritesparseparsernext
parser_exc)selfrF   r8   r9   r:   s        r0   __init__zProtocol.__init__W   s    "ZZ\B >&&TYY__5F4G'HIF"() ((7
 	 
 ! (, */& )-+-26 ,0+/48! 37	  #n#%#%jjlT[[/3r/   c                    | j                   S )zm
        WebSocket connection state.

        Defined in 4.1, 4.2, 7.1.3, and 7.1.4 of :rfc:`6455`.

        )_staterX   s    r0   r8   zProtocol.state   s     {{r/   c                v    | j                   r&| j                  j                  d|j                         || _        y )Nz= connection is %s)rE   r:   rA   r[   )rX   r8   s     r0   r8   zProtocol.state   s)    ::KK2EJJ?r/   c                    | j                   t        ury| j                  t        j                  S | j                  j
                  S )z
        `WebSocket close code`_.

        .. _WebSocket close code:
            https://www.rfc-editor.org/rfc/rfc6455.html#section-7.1.5

        :obj:`None` if the connection isn't closed yet.

        N)r8   r6   rL   r   ABNORMAL_CLOSUREcoder\   s    r0   
close_codezProtocol.close_code   s9     ::V#__$---??'''r/   c                n    | j                   t        ury| j                  y| j                  j                  S )z
        `WebSocket close reason`_.

        .. _WebSocket close reason:
            https://www.rfc-editor.org/rfc/rfc6455.html#section-7.1.6

        :obj:`None` if the connection isn't closed yet.

        N )r8   r6   rL   reasonr\   s    r0   close_reasonzProtocol.close_reason   s0     ::V#__$??)))r/   c                d   | j                   t        u sJ d       | j                  K| j                  ?| j                  j                  t
        v r#| j                  j                  t
        v rt        }nt        } || j                  | j                  | j                        }| j                  |_
        |S )a  
        Exception to raise when trying to interact with a closed connection.

        Don't raise this exception while the connection :attr:`state`
        is :attr:`~websockets.protocol.State.CLOSING`; wait until
        it's :attr:`~websockets.protocol.State.CLOSED`.

        Indeed, the exception includes the close code and reason, which are
        known only once the connection is closed.

        Raises:
            AssertionError: if the connection isn't closed yet.

        zconnection isn't closed yet)r8   r6   rL   rM   r`   r   r   r   rN   rW   	__cause__)rX   exc_typeexcs      r0   	close_exczProtocol.close_exc   s      zzV#B%BB# OO'+$$6$$6)H,H (OOOO%%!
 
r/   c                d    | j                   j                  |       t        | j                         y)aH  
        Receive data from the network.

        After calling this method:

        - You must call :meth:`data_to_send` and send this data to the network.
        - You should call :meth:`events_received` and process resulting events.

        Raises:
            EOFError: if :meth:`receive_eof` was called earlier.

        N)rQ   	feed_datarV   rU   rX   datas     r0   receive_datazProtocol.receive_data   s"     	d#T[[r/   c                b    | j                   j                          t        | j                         y)a  
        Receive the end of the data stream from the network.

        After calling this method:

        - You must call :meth:`data_to_send` and send this data to the network;
          it will return ``[b""]``, signaling the end of the stream, or ``[]``.
        - You aren't expected to call :meth:`events_received`; it won't return
          any new events.

        Raises:
            EOFError: if :meth:`receive_eof` was called earlier.

        N)rQ   feed_eofrV   rU   r\   s    r0   receive_eofzProtocol.receive_eof  s      	T[[r/   c                    | j                   st        d      | | _         | j                  t        t        ||             y)a  
        Send a `Continuation frame`_.

        .. _Continuation frame:
            https://datatracker.ietf.org/doc/html/rfc6455#section-5.6

        Parameters:
            data: payload containing the same kind of data
                as the initial frame.
            fin: FIN bit; set it to :obj:`True` if this is the last frame
                of a fragmented message and to :obj:`False` otherwise.

        Raises:
            ProtocolError: if a fragmented message isn't in progress.

        unexpected continuation frameN)rH   r   
send_framer   r   rX   rn   fins      r0   send_continuationzProtocol.send_continuation  s8    " -- ?@@-0&gtS12r/   c                    | j                   rt        d      | | _         | j                  t        t        ||             y)a  
        Send a `Text frame`_.

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

        Parameters:
            data: payload containing text encoded with UTF-8.
            fin: FIN bit; set it to :obj:`False` if this is the first frame of
                a fragmented message.

        Raises:
            ProtocolError: if a fragmented message is in progress.

        expected a continuation frameN)rH   r   ru   r   r   rv   s      r0   	send_textzProtocol.send_text/  s8      )) ?@@-0&gtS12r/   c                    | j                   rt        d      | | _         | j                  t        t        ||             y)a  
        Send a `Binary frame`_.

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

        Parameters:
            data: payload containing arbitrary binary data.
            fin: FIN bit; set it to :obj:`False` if this is the first frame of
                a fragmented message.

        Raises:
            ProtocolError: if a fragmented message is in progress.

        rz   N)rH   r   ru   r   r   rv   s      r0   send_binaryzProtocol.send_binaryD  s8      )) ?@@-0&is34r/   c                *   | j                   rt        d      |-|dk7  rt        d      t        t        j                  d      }d}nt        ||      }|j                         }| j                  t        t        |             || _	        t        | _        y)a  
        Send a `Close frame`_.

        .. _Close frame:
            https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.1

        Parameters:
            code: close code.
            reason: close reason.

        Raises:
            ProtocolError: if a fragmented message is being sent, if the code
                isn't valid, or if a reason is provided without a code

        rz   Nrc   z#cannot send a reason without a coder/   )rH   r   r   r   NO_STATUS_RCVD	serializeru   r   r   rM   r5   r8   rX   r`   rd   closern   s        r0   
send_closezProtocol.send_closeY  s      )) ?@@<|#$IJJ)22B7ED$'E??$D 	h-.
r/   c                B    | j                  t        t        |             y)z
        Send a `Ping frame`_.

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

        Parameters:
            data: payload containing arbitrary binary data.

        N)ru   r   r   rm   s     r0   	send_pingzProtocol.send_pingy       	gt,-r/   c                B    | j                  t        t        |             y)z
        Send a `Pong frame`_.

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

        Parameters:
            data: payload containing arbitrary binary data.

        N)ru   r   r   rm   s     r0   	send_pongzProtocol.send_pong  r   r/   c                   | j                   t        u r`|t        j                  k7  rMt	        ||      }|j                         }| j                  t        t        |             || _	        t        | _         | j                  t        u r| j                  s| j                          | j                         | _        t#        | j                          y)a?  
        `Fail the WebSocket connection`_.

        .. _Fail the WebSocket connection:
            https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.7

        Parameters:
            code: close code
            reason: close reason

        Raises:
            ProtocolError: if the code isn't valid.
        N)r8   r4   r   r_   r   r   ru   r   r   rM   r5   rF   r,   rP   send_eofdiscardrU   rV   r   s        r0   failzProtocol.fail  s    & ::y111dF+(h 56"'$
 99t}}MMO llnT[[r/   c                .    | j                   g c}| _         |S )a7  
        Fetch events generated from data received from the network.

        Call this method immediately after any of the ``receive_*()`` methods.

        Process resulting events, likely by passing them to the application.

        Returns:
            List[Event]: Events read from the connection.
        )rR   )rX   rR   s     r0   events_receivedzProtocol.events_received  s     #kk2r/   c                .    | j                   g c}| _         |S )a  
        Obtain data to send to the network.

        Call this method immediately after any of the ``receive_*()``,
        ``send_*()``, or :meth:`fail` methods.

        Write resulting data to the connection.

        The empty bytestring :data:`~websockets.protocol.SEND_EOF` signals
        the end of the data stream. When you receive it, half-close the TCP
        connection.

        Returns:
            List[bytes]: Data to write to the connection.

        )rS   )rX   rS   s     r0   data_to_sendzProtocol.data_to_send  s    " #kk2r/   c                F    | j                   t        u xs | j                  duS )a  
        Tell if the TCP connection is expected to close soon.

        Call this method immediately after any of the ``receive_*()``,
        ``send_close()``, or :meth:`fail` methods.

        If it returns :obj:`True`, schedule closing the TCP connection after a
        short timeout if the other side hasn't already closed it.

        Returns:
            bool: Whether the TCP connection is expected to close soon.

        N)r8   r5   rO   r\   s    r0   close_expectedzProtocol.close_expected  s#    , zzW$F(:(:$(FFr/   c              #  P  K   	 	 | j                   j                         E d{   r2| j                  r| j                  j                  d       t	        d      | j
                  d}n2| j                  | j
                  }n| j
                  | j                  z
  }t        j                  | j                   j                  | j                  t        u || j                        E d{   }| j                  r| j                  j                  d|       | j                  |       7 7 B# t        $ r;}| j                  t         j"                  t%        |             || _        Y d}~n/d}~wt        $ r:}| j                  t         j(                  t%        |             || _        Y d}~nd}~wt*        $ rJ}| j                  t         j,                  |j.                   d|j0                          || _        Y d}~nd}~wt2        $ r:}| j                  t         j4                  t%        |             || _        Y d}~n\d}~wt6        $ rM}| j                  j9                  dd	       | j                  t         j:                         || _        Y d}~nd}~ww xY wd t=        d
      w)a-  
        Parse incoming data into frames.

        :meth:`receive_data` and :meth:`receive_eof` run this generator
        coroutine until it needs more data or reaches EOF.

        :meth:`parse` never raises an exception. Instead, it sets the
        :attr:`parser_exc` and yields control.

        TN< EOFzunexpected end of stream)maskr9   rJ   z< %sz at position zparser failed)exc_infoz"parse() shouldn't step after error)rQ   at_eofrE   r:   EOFErrorr9   rG   r   rT   
read_exactrF   r,   rJ   
recv_framer   r   r   PROTOCOL_ERRORstrrW   r_   UnicodeDecodeErrorINVALID_DATArd   startr   MESSAGE_TOO_BIG	ExceptionerrorINTERNAL_ERRORAssertionError)rX   r9   frameri   s       r0   rT   zProtocol.parse  s    5	"#{{11333zz))'2
 ##=>>==(#H]]*#}}H#}}t}}<H
 $);;KK**f,%#	$  ::KK%%fe4&= 3&  	"IIi..C9!DOO 	"IIi00#c(;!DOO! 	"IIi,,M#)).UV!DOO 	"IIi//S:!DOO 	"KKo=IIi../!DOO		" 	ABBs   J&D) D$CD) $D'%A D) 'D) )	J20E("J&(J40F)$J&)J5A G:5J&:J0H;6J&;JAJ
J&JJ&c              #    K   | j                   t        u | j                  k(  sJ | j                  j	                         E d{   s=| j                  j                          | j                  j	                         E d{   s=| j                  r| j                  j                  d       | j                   t        u r| j                          t        | _        d t        d      7 7 jw)z
        Discard incoming data.

        This coroutine replaces :meth:`parse`:

        - after receiving a close frame, during a normal closure (1.4);
        - after sending a close frame, during an abnormal closure (7.1.7).

        Nr   z"discard() shouldn't step after EOF)rF   r,   rP   rQ   r   r   rE   r:   r-   r   r6   r8   r   r\   s    r0   r   zProtocol.discardC  s      		V#777"kk00222KK! #kk00222::KKg& 99MMO
 ABB 32s*   ?C*C&;C*=C(>C*A$C*(C*c                   |j                   t        u s|j                   t        u rH| j                  t	        d      |j
                  r	d| _        nt        |j                        | _        n|j                   t        u rV| j                  t	        d      |j
                  r	d| _        n| xj                  t        |j                        z  c_        n|j                   t        u r-t        t        |j                        }| j                  |       nM|j                   t        u rn9|j                   t        u rt        j                  |j                        | _        | j"                  t$        u r| j&                  J d| _        | j                  t	        d      | j"                  t*        u rL| j                  t        t        |j                               | j                   | _        d| _        t$        | _        | j,                  t.        u r| j1                          | j3                         | _        t7        | j4                         nt9        d|j                   d      | j:                  j=                  |       y)	z-
        Process an incoming frame.

        Nrz   rt   Fzincomplete fragmented messageTzunexpected opcode: 02x)opcoder   r   rG   r   rw   lenrn   r   r   r   r   ru   r   r   rT   rL   r8   r5   rM   rN   r4   rF   r,   r   r   rU   rV   r   rR   append)rX   r   
pong_frames      r0   r   zProtocol.recv_framea  s   
 <<7"elli&?}}(#$CDDyy $ #EJJ\\W$}}$#$CDDyy $UZZ0\\W$ w

3JOOJ'\\W$ \\X% $kk%**5DOzzW$222,1)}}(#$CDD zzT!
 h

 ;<"&//,0)$
 yyF"
 ,,.DK !#6u||C6H!IJJ5!r/   c                J   | j                   t        ur#t        d| j                   j                   d      | j                  r| j
                  j	                  d|       | j                  j                  |j                  | j                  t        u | j                               y )Nz#cannot write to a WebSocket in the z statez> %s)r   rJ   )r8   r4   r   rA   rE   r:   rS   r   r   rF   r-   rJ   )rX   r   s     r0   ru   zProtocol.send_frame  s|    ::T!5djjoo5FfM  ::KKfe,OOf!4OQ	
r/   c                    | j                   rJ d| _         | j                  r| j                  j                  d       | j                  j	                  t
               y )NTz> EOF)rP   rE   r:   rS   r   r$   r\   s    r0   r   zProtocol.send_eof  sA    ==  ::KKg&8$r/   )
rF   r"   r8   r#   r9   Optional[int]r:   zOptional[LoggerLike]returnNone)r   r#   )r8   r#   r   r   )r   r   )r   zOptional[str])r   r
   )rn   bytesr   r   )r   r   )rn   r   rw   boolr   r   )T)Nrc   )r`   r   rd   r   r   r   )rc   )r`   intrd   r   r   r   )r   zList[Event])r   zList[bytes])r   r   )r   zGenerator[None, None, None])r   r   r   r   )r'   r(   r)   r*   r4   rY   propertyr8   setterra   re   rj   ro   rr   rx   r{   r}   r   r   r   r   r   r   r   rT   r   r   ru   r   r.   r/   r0   r!   r!   G   s   & "''+B4B4 	B4
  B4 %B4 
B4H   \\ 
 ( (" * *" ! !J (3,3*5*@..'V (G4ECNC<N"d

%r/   r!   )4
__future__r   enumr?   r<   typingr   r   r   r   r   
exceptionsr
   r   r   r   r   r   rJ   r   framesr   r   r   r   r   r   r   r   r   r   http11r   r   streamsr   r   r   r    __all__EventIntEnumr"   r,   r-   r#   r3   r4   r5   r6   r$   r!   r.   r/   r0   <module>r      s    "    9 9  "   & ! 3 3 	gx&' ?4<<  
	1DLL 1 
zz
--	  E}	% }	%r/   