a
    یxd]                     @  s<  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 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 dej(Z)e)j*Z*e)j+Z+G dd dej(Z,e,j-Z-e,j.Z.e,j/Z/e,j0Z0dZ1G dd dZ2dS )    )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Frame)RequestResponse)StreamReader)
LoggerLikeOriginSubprotocol)ProtocolSideStateSEND_EOFc                   @  s   e Zd ZdZed\ZZdS )r    z6A WebSocket connection is either a server or a client.   N)__name__
__module____qualname____doc__rangeSERVERCLIENT r+   r+   K/var/www/html/Ranjet/env/lib/python3.9/site-packages/websockets/protocol.pyr    ,   s   r    c                   @  s    e Zd ZdZed\ZZZZdS )r!   z6A WebSocket connection is in one of these four states.   N)	r$   r%   r&   r'   r(   
CONNECTINGOPENCLOSINGCLOSEDr+   r+   r+   r,   r!   6   s   r!       c                   @  s  e Zd ZdZedddddddd	d
ddZeddddZejdd	dddZeddddZ	eddddZ
eddddZdd	dddZd	dddZdd d	d!d"d#ZdJdd d	d!d%d&ZdKdd d	d!d'd(ZdLdd*d	d+d,d-Zdd	dd.d/Zdd	dd0d1ZdMd2d*d	d+d3d4Zd5dd6d7Zd8dd9d:Zd dd;d<Zd=dd>d?Zd=dd@dAZdBd	dCdDdEZdBd	dCdFdGZd	ddHdIZdS )Nr   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loggerr    r!   zOptional[int]zOptional[LoggerLike]None)sider3   r4   r5   returnc                C  s   t  | _|d u r(td|j  }|| _|tj	| _
|| _|| _|| _d | _d| _d | _g | _d | _d | _d | _d | _d | _d| _t | _g | _g | _|  | _t| j d | _d S )Nzwebsockets.F) uuiduuid4idlogging	getLoggernamelowerr5   isEnabledForDEBUGdebugr7   r3   r4   cur_sizeexpect_continuation_frameorigin
extensionsZsubprotocol
close_rcvd
close_sentclose_rcvd_then_senthandshake_exceof_sentr   readereventswritesparseparsernext
parser_exc)selfr7   r3   r4   r5   r+   r+   r,   __init__V   s0    	
	

zProtocol.__init__)r8   c                 C  s   | j S )zm
        WebSocket connection state.

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

        )_staterS   r+   r+   r,   r3      s    zProtocol.state)r3   r8   c                 C  s    | j r| j d|j || _d S )Nz= connection is %s)rB   r5   r>   rU   )rS   r3   r+   r+   r,   r3      s    c                 C  s(   | j turdS | jdu rdS | jjS d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  )r3   r1   rG   coderV   r+   r+   r,   
close_code   s
    

zProtocol.close_codezOptional[str]c                 C  s(   | j turdS | jdu rdS | jjS d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 )r3   r1   rG   reasonrV   r+   r+   r,   close_reason   s
    

zProtocol.close_reasonr	   c                 C  sf   | j tu sJ d| jdurD| jdurD| jjtv rD| jjtv rDt}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 yetN)r3   r1   rG   rH   rX   r   r   r
   rI   rR   	__cause__)rS   exc_typeexcr+   r+   r,   	close_exc   s$    

zProtocol.close_excbytes)datar8   c                 C  s   | j | t| j dS )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)rL   	feed_datarQ   rP   rS   rb   r+   r+   r,   receive_data   s    zProtocol.receive_datac                 C  s   | j   t| j dS )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)rL   feed_eofrQ   rP   rV   r+   r+   r,   receive_eof  s    
zProtocol.receive_eofbool)rb   finr8   c                 C  s,   | j std| | _ | tt|| dS )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)rD   r   
send_framer   r   rS   rb   ri   r+   r+   r,   send_continuation  s    zProtocol.send_continuationTc                 C  s,   | j rtd| | _ | tt|| dS )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)rD   r   rk   r   r   rl   r+   r+   r,   	send_text.  s    zProtocol.send_textc                 C  s,   | j rtd| | _ | tt|| dS )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.

        rn   N)rD   r   rk   r   r   rl   r+   r+   r,   send_binaryC  s    zProtocol.send_binaryrZ   str)rX   r[   r8   c                 C  sh   | j rtd|du r6|dkr&tdtdd}d}nt||}| }| tt| || _t| _	dS )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

        rn   NrZ   z#cannot send a reason without a codei  r2   )
rD   r   r   	serializerk   r   r   rH   r0   r3   rS   rX   r[   closerb   r+   r+   r,   
send_closeX  s    

zProtocol.send_closec                 C  s   |  tt| dS )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)rk   r   r   rd   r+   r+   r,   	send_pingx  s    zProtocol.send_pingc                 C  s   |  tt| dS )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)rk   r   r   rd   r+   r+   r,   	send_pong  s    zProtocol.send_pongintc                 C  sp   | j tu r@|dkr@t||}| }| tt| || _t| _ | j	t
u rX| jsX|   |  | _t| j dS )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.
        rW   N)r3   r/   r   rr   rk   r   r   rH   r0   r7   r)   rK   send_eofdiscardrP   rQ   rs   r+   r+   r,   fail  s    


zProtocol.failzList[Event]c                 C  s   | j g  }| _ |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.
        )rM   )rS   rM   r+   r+   r,   events_received  s    zProtocol.events_receivedzList[bytes]c                 C  s   | j g  }| _ |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.

        )rN   )rS   rN   r+   r+   r,   data_to_send  s    zProtocol.data_to_sendc                 C  s   | j tu p| 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)r3   r0   rJ   rV   r+   r+   r,   close_expected  s    zProtocol.close_expectedzGenerator[None, None, None]c              
   c  s  z| j  E dH r,| jr$| jd td| jdu r<d}n| jdu rN| j}n| j| j }tj| j j	| j
tu || jdE dH }| jr| jd| | | qW n8 ty } z$| dt| || _W Y d}~nd}~0  ty } z"| dt| || _W Y d}~nd}~0  ty\ } z,| d|j d	|j  || _W Y d}~nd}~0  ty } z"| d
t| || _W Y d}~nNd}~0  ty } z,| jjddd | d || _W Y d}~n
d}~0 0 dV  tddS )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.

        N< EOFzunexpected end of stream)maskr4   rF   z< %si  rW   i  z at position i  zparser failedT)exc_infoi  z"parse() shouldn't step after error)rL   at_eofrB   r5   EOFErrorr4   rC   r   rO   Z
read_exactr7   r)   rF   
recv_framer   r{   rq   rR   UnicodeDecodeErrorr[   startr   	ExceptionerrorAssertionError)rS   r4   framer_   r+   r+   r,   rO     sJ    


zProtocol.parsec                 c  sl   | j tu | jksJ | j E dH s0| j  q| jrB| jd | j tu rT| 	  t
| _dV  tddS )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)r7   r)   rK   rL   r   rz   rB   r5   r*   ry   r1   r3   r   rV   r+   r+   r,   rz   B  s    
zProtocol.discardr   )r   r8   c                 C  sz  |j tu s|j tu rD| jdur&td|jr4d| _nt|j| _n&|j tu r| jdu r`td|jrnd| _n|  jt|j7  _n|j t	u rt
t|j}| | n|j tu rn|j tu rXt|j| _| jtu r| jdusJ d| _| jdurtd| jtu r.| t
t|j | j| _d| _t| _| jtu rB|   |  | _t| j ntd|j d| j| dS )	z-
        Process an incoming frame.

        Nrn   rj   Fzincomplete fragmented messageTzunexpected opcode: 02x)opcoder   r   rC   r   ri   lenrb   r   r   r   r   rk   r   r   rO   rG   r3   r0   rH   rI   r/   r7   r)   ry   rz   rP   rQ   r   rM   append)rS   r   Z
pong_framer+   r+   r,   r   `  sF    







zProtocol.recv_framec                 C  sT   | j turtd| j j d| jr2| jd| | j|j| j	t
u | jd d S )Nz#cannot write to a WebSocket in the z statez> %s)r   rF   )r3   r/   r   r>   rB   r5   rN   r   rr   r7   r*   rF   )rS   r   r+   r+   r,   rk     s    
zProtocol.send_framec                 C  s2   | j r
J d| _ | jr"| jd | jt d S )NTz> EOF)rK   rB   r5   rN   r   r"   rV   r+   r+   r,   ry     s
    
zProtocol.send_eof)T)T)NrZ   )rZ   )r$   r%   r&   r'   r/   rT   propertyr3   setterrY   r\   r`   re   rg   rm   ro   rp   ru   rv   rw   r{   r|   r}   r~   rO   rz   r   rk   ry   r+   r+   r+   r,   r   F   s@   D	% +GRr   )3
__future__r   enumr<   r9   typingr   r   r   r   r   
exceptionsr	   r
   r   r   r   r   rF   r   framesr   r   r   r   r   r   r   r   r   Zhttp11r   r   streamsr   r   r   r   __all__EventIntEnumr    r)   r*   r!   r.   r/   r0   r1   r"   r   r+   r+   r+   r,   <module>   s,    ,