o
    ¨ÝjY  ã                   @   sÒ   d dl Z d dlZd dl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mZ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mZ G dd„ dƒZG dd„ deƒZG dd„ deƒZdS )é    N)Útime)Úurlsplit)ÚConnectionTypeÚWSConnection)	ÚAcceptConnectionÚRejectConnectionÚCloseConnectionÚMessageÚRequestÚPingÚPongÚTextMessageÚBytesMessage)ÚPerMessageDeflate)ÚCloseReason)ÚLocalProtocolErroré   )ÚConnectionErrorÚConnectionClosedc                   @   sX   e Zd Z			ddd„Zdd„ Zdd„ Zdd	d
„Zddd„Zdd„ Zdd„ Z	dd„ Z
dS )ÚBaseNé   c	           
      C   sì   d | _ || _|| _|| _|| _d| _g | _d | _d| _d| _	|t
jk| _tj| _d | _|d u r6dd l}	|	j}|d u rAdd l}	|	j}|d u rHtj}|| _|ƒ | _t|ƒ| _|  ¡  | j	s^tƒ ‚|| jd�| _| jj dd¡| j_| j  ¡  d S )NTr   F)Útargetz	(_thread)z(simple_websocket.Base._thread))!ÚsubprotocolÚsockÚreceive_bytesÚping_intervalÚmax_message_sizeÚpong_receivedÚinput_bufferÚincoming_messageÚincoming_message_lenÚ	connectedr   ÚSERVERÚ	is_serverr   ZNO_STATUS_RCVDÚclose_reasonÚclose_messageÚ	threadingÚThreadÚEventÚ	selectorsÚDefaultSelectorÚselector_classÚeventr   ÚwsÚ	handshaker   Ú_threadÚthreadÚnameÚreplaceÚstart)
Úselfr   Úconnection_typer   r   r   Úthread_classÚevent_classr+   r&   © r8   úN/var/www/html/chatgpt/venv/lib/python3.10/site-packages/simple_websocket/ws.pyÚ__init__   s@   
ÿzBase.__init__c                 C   ó   d S ©Nr8   )r4   r8   r8   r9   r.   B   s   zBase.handshakec                 C   sX   | j s
t| j| jƒ‚t|tƒr| j t|d�¡}n| j t	t
|ƒd�¡}| j |¡ dS )zîSend data over the WebSocket connection.

        :param data: The data to send. If ``data`` is of type ``bytes``, then
                     a binary message is sent. Else, the message is sent in
                     text format.
        )ÚdataN)r!   r   r$   r%   Ú
isinstanceÚbytesr-   Úsendr	   r   Ústrr   )r4   r=   Úout_datar8   r8   r9   r@   F   s   
z	Base.sendc                 C   sn   | j r| js| jj|d�sdS | j ¡  | j r| jrz| j d¡W S  ty*   Y nw | j s5t| j| j	ƒ‚dS )a}  Receive data over the WebSocket connection.

        :param timeout: Amount of time to wait for the data, in seconds. Set
                        to ``None`` (the default) to wait indefinitely. Set
                        to 0 to read without blocking.

        The data received is returned, as ``bytes`` or ``str``, depending on
        the type of the incoming message.
        )ÚtimeoutNr   )
r!   r   r,   ÚwaitÚclearÚpopÚ
IndexErrorr   r$   r%   )r4   rC   r8   r8   r9   ÚreceiveU   s   

ýÿÿzBase.receivec                 C   sZ   | j s
t| j| jƒ‚| j t|ptj|ƒ¡}z| j	 |¡ W n	 t
y'   Y nw d| _ dS )a@  Close the WebSocket connection.

        :param reason: A numeric status code indicating the reason of the
                       closure, as defined by the WebSocket specification. The
                       default is 1000 (normal closure).
        :param message: A text message to be sent to the other side.
        FN)r!   r   r$   r%   r-   r@   r   r   ZNORMAL_CLOSUREr   ÚBrokenPipeError)r4   ÚreasonÚmessagerB   r8   r8   r9   Úclosej   s   
ÿÿ
z
Base.closec                 C   r;   r<   r8   )r4   Úrequestr8   r8   r9   Úchoose_subprotocol|   s   zBase.choose_subprotocolc              
   C   s`  d }| j r'tƒ | j  }|  ¡ }z| | jtjd¡ W n ty&   d| _Y nw | jr™zW|retƒ }||ks;| 	|| ¡se| j
sM| jtjdd� | j ¡  W nLd| _
| j | j tƒ ¡¡ t||ƒ| j  }W q'| j | j¡}t|ƒdkrutƒ ‚| j |¡ |  ¡ | _W n tttfy•   d| _| j ¡  Y nw | js*|rŸ| ¡ n	d  | j ¡  d S  | j ¡  d S )NTFzPing/Pong timeout©rJ   rK   r   )r   r   r+   Úregisterr   r)   Ú
EVENT_READÚ
ValueErrorr!   Úselectr   rL   r   ZPOLICY_VIOLATIONr,   Úsetr@   r-   r   ÚmaxÚrecvr   ÚlenÚOSErrorÚreceive_dataÚ_handle_eventsÚConnectionResetErrorr   )r4   ÚselZ	next_pingÚnowÚin_datar8   r8   r9   r/   ‚   sR   
ÿÿ

ÿ
üìÿzBase._threadc              	   C   sn  d}d}| j  ¡ D �]!}�zt|tƒr)|  |¡| _|| j  t| jtƒ gd�¡7 }nît|t	ƒrN| j
r;|| j  | ¡ ¡7 }|j| _|j| _d| _| j ¡  d}nÉt|tƒr^|| j  | ¡ ¡7 }n¹t|tƒrgd| _n°t|ttfƒ�r|  jt|jƒ7  _| jr˜| j| jkr˜|| j  t	tjdƒ¡7 }| j ¡  d}W  n”| jd u r¢|j| _n:t|tƒrÄt| jtƒs¹t| j|j   ¡ ƒ| _n#|  j|j  ¡ 7  _nt| jtƒsÔt| j|j ƒ| _n|  j|j7  _|j!sáW q	t| jt"t#fƒrñ| j$ %| j¡ nt|tƒ�r| j$ %| j &¡ ¡ n	| j$ %t#| jƒ¡ d | _d| _| j ¡  n	 W q	 t'�y+   d}| j ¡  d}Y q	w |�r5| j( |¡ |S )NTó    )r   Ú
extensionsFzMessage is too bigr   ))r-   Úeventsr>   r
   rN   r   r@   r   r   r   r#   ÚresponseÚcoder$   rJ   r%   r!   r,   rT   r   r   r   r   r   r    rW   r=   r   r   ZMESSAGE_TOO_BIGr   Ú	bytearrayÚencodeZmessage_finishedrA   r?   r   ÚappendÚdecoder   r   )r4   Z
keep_goingrB   r,   r8   r8   r9   rZ   ¨   s†   

þ




ÿ



ÿ
ÿÿ€
ýzBase._handle_events©NNr   NNNNNr<   ©NN)Ú__name__Ú
__module__Ú__qualname__r:   r.   r@   rH   rL   rN   r/   rZ   r8   r8   r8   r9   r      s    
þ(

&r   c                       sL   e Zd ZdZ			d‡ fdd„	Ze			ddd„ƒZdd	„ Zd
d„ Z‡  Z	S )ÚServerzãThis class implements a WebSocket server.

    Instead of creating an instance of this class directly, use the
    ``accept()`` class method to create individual instances of the server,
    each bound to a client request.
    Nr   c	              
      s   || _ |pg | _t| jtƒr| jg| _d| _d }	d|v r%| d¡}	d| _nRd|v r2| d¡}	d| _nEd|v rA| d¡ ¡ }	d| _n6| dd	¡ d
¡rw|d }
t|
dƒs[t|
dƒr[|
j	}
t|
dƒrw|
j
j}	z|	 ¡ }	W n	 tys   Y nw d
| _|	d u rtdƒ‚tƒ j|	tj||||||d� d S )NÚunknownzwerkzeug.socketZwerkzeugzgunicorn.socketZgunicornzeventlet.inputZeventletZSERVER_SOFTWAREÚ Zgeventz
wsgi.inputÚrawÚrfilez+Cannot obtain socket from WSGI environment.)r5   r   r   r   r6   r7   r+   )ÚenvironÚsubprotocolsr>   rA   ÚmodeÚgetZ
get_socketÚ
startswithÚhasattrrq   rp   Ú_sockÚdupÚNotImplementedErrorÚRuntimeErrorÚsuperr:   r   r"   )r4   rr   rs   r   r   r   r6   r7   r+   r   Z
wsgi_input©Ú	__class__r8   r9   r:   ÿ   sL   



ÿ
ÿ
ûzServer.__init__c	           	   
   C   s   | ||||||||d�S )aS	  Accept a WebSocket connection from a client.

        :param environ: A WSGI ``environ`` dictionary with the request details.
                        Among other things, this class expects to find the
                        low-level network socket for the connection somewhere
                        in this dictionary. Since the WSGI specification does
                        not cover where or how to store this socket, each web
                        server does this in its own different way. Werkzeug,
                        Gunicorn, Eventlet and Gevent are the only web servers
                        that are currently supported.
        :param subprotocols: A list of supported subprotocols, or ``None`` (the
                             default) to disable subprotocol negotiation.
        :param receive_bytes: The size of the receive buffer, in bytes. The
                              default is 4096.
        :param ping_interval: Send ping packets to clients at the requested
                              interval in seconds. Set to ``None`` (the
                              default) to disable ping/pong logic. Enable to
                              prevent disconnections when the line is idle for
                              a certain amount of time, or to detect
                              unresponsive clients and disconnect them. A
                              recommended interval is 25 seconds.
        :param max_message_size: The maximum size allowed for a message, in
                                 bytes, or ``None`` for no limit. The default
                                 is ``None``.
        :param thread_class: The ``Thread`` class to use when creating
                             background threads. The default is the
                             ``threading.Thread`` class from the Python
                             standard library.
        :param event_class: The ``Event`` class to use when creating event
                            objects. The default is the `threading.Event``
                            class from the Python standard library.
        :param selector_class: The ``Selector`` class to use when creating
                               selectors. The default is the
                               ``selectors.DefaultSelector`` class from the
                               Python standard library.
        )rs   r   r   r   r6   r7   r+   r8   )	Úclsrr   rs   r   r   r   r6   r7   r+   r8   r8   r9   Úaccept*  s   (üzServer.acceptc                 C   s~   d}| j  ¡ D ]&\}}| d¡r-d dd„ |dd …  d¡D ƒ¡}||› d|› d	� ¡ 7 }q|d
7 }| j |¡ |  ¡ | _	d S )Ns   GET / HTTP/1.1
ZHTTP_ú-c                 S   s   g | ]}|  ¡ ‘qS r8   )Ú
capitalize)Ú.0Úpr8   r8   r9   Ú
<listcomp>\  s    z$Server.handshake.<locals>.<listcomp>é   Ú_z: z
s   
)
rr   Úitemsrv   ÚjoinÚsplitre   r-   rY   rZ   r!   )r4   r^   ÚkeyÚvalueÚheaderr8   r8   r9   r.   X  s   
"€zServer.handshakec                 C   s"   |j D ]}|| j v r|  S qdS )aÃ  Choose a subprotocol to use for the WebSocket connection.

        The default implementation selects the first protocol requested by the
        client that is accepted by the server. Subclasses can override this
        method to implement a different subprotocol negotiation algorithm.

        :param request: A ``Request`` object.

        The method should return the subprotocol to use, or ``None`` if no
        subprotocol is chosen.
        N)rs   )r4   rM   r   r8   r8   r9   rN   b  s
   

ÿzServer.choose_subprotocol)Nr   NNNNN)
rj   rk   rl   Ú__doc__r:   Úclassmethodr€   r.   rN   Ú__classcell__r8   r8   r}   r9   rm   ø   s    þ+þ-
rm   c                       sR   e Zd ZdZ			d‡ fdd„	Ze			ddd„ƒZdd	„ Zd‡ fd
d„	Z‡  Z	S )ÚClientzËThis class implements a WebSocket client.

    Instead of creating an instance of this class directly, use the
    ``connect()`` class method to create an instance that is connected to a
    server.
    Nr   c
              	      s`  t |ƒ}
|
jdv }|
j| _|
jp|rdnd| _|
j| _|
jr(|  jd|
j 7  _|p+g | _t| jt	ƒr8| jg| _g | _
t|tƒrR| ¡ D ]\}}| j
 ||f¡ qDnt|tƒrZ|| _
tj| j| jtjd�}t|ƒdkrntƒ ‚t |d d |d d |d d ¡}|r—|d u r�tjtjjd	�}|j|| jd
�}| |d d ¡ tƒ j|tj|||||	d� d S )N)ÚhttpsÚwssi»  éP   ú?)Útyper   r   é   )Úpurpose)Úserver_hostnameé   )r5   r   r   r   r6   r7   )r   ÚschemeÚhostnameÚhostÚportÚpathÚqueryrs   r>   rA   Úextra_headeersÚdictrˆ   rf   ÚlistÚsocketÚgetaddrinfoÚSOCK_STREAMrW   r   ÚsslÚcreate_default_contextÚPurposeÚSERVER_AUTHÚwrap_socketÚconnectr|   r:   r   ZCLIENT)r4   Úurlrs   Úheadersr   r   r   Ússl_contextr6   r7   Ú
parsed_urlZ	is_securer‹   rŒ   Zconnection_argsr   r}   r8   r9   r:   {  sL   



ÿ
ÿ
ÿÿ
üzClient.__init__c
           
      C   s   | |||||||||	d�	S )a_	  Returns a WebSocket client connection.

        :param url: The connection URL. Both ``ws://`` and ``wss://`` URLs are
                    accepted.
        :param subprotocols: The name of the subprotocol to use, or a list of
                             subprotocol names in order of preference. Set to
                             ``None`` (the default) to not use a subprotocol.
        :param headers: A dictionary or list of tuples with additional HTTP
                        headers to send with the connection request. Note that
                        custom headers are not supported by the WebSocket
                        protocol, so the use of this parameter is not
                        recommended.
        :param receive_bytes: The size of the receive buffer, in bytes. The
                              default is 4096.
        :param ping_interval: Send ping packets to the server at the requested
                              interval in seconds. Set to ``None`` (the
                              default) to disable ping/pong logic. Enable to
                              prevent disconnections when the line is idle for
                              a certain amount of time, or to detect an
                              unresponsive server and disconnect. A recommended
                              interval is 25 seconds. In general it is
                              preferred to enable ping/pong on the server, and
                              let the client respond with pong (which it does
                              regardless of this setting).
        :param max_message_size: The maximum size allowed for a message, in
                                 bytes, or ``None`` for no limit. The default
                                 is ``None``.
        :param ssl_context: An ``SSLContext`` instance, if a default SSL
                            context isn't sufficient.
        :param thread_class: The ``Thread`` class to use when creating
                             background threads. The default is the
                             ``threading.Thread`` class from the Python
                             standard library.
        :param event_class: The ``Event`` class to use when creating event
                            objects. The default is the `threading.Event``
                            class from the Python standard library.
        )rs   r®   r   r   r   r¯   r6   r7   r8   )
r   r­   rs   r®   r   r   r   r¯   r6   r7   r8   r8   r9   r¬   ¢  s
   )ýzClient.connectc                 C   sª   | j  t| j| j| j| jd�¡}| j |¡ 	 | j | j	¡}| j  
|¡ z	t| j  ¡ ƒ}W n	 ty6   Y nw nqt|tƒrCt|jƒ‚t|tƒsLtdƒ‚|j| _d| _d S )N)r�   r   rs   Úextra_headersTi�  )r-   r@   r
   r�   rŸ   rs   r¡   r   rV   r   rY   Únextra   ÚStopIterationr>   r   r   Ústatus_coder   r   r!   )r4   rB   r^   r,   r8   r8   r9   r.   Ð  s*   þÿø
	


zClient.handshakec                    s   t ƒ j||d� | j ¡  d S )NrO   )r|   rL   r   )r4   rJ   rK   r}   r8   r9   rL   æ  s   zClient.closerh   ri   )
rj   rk   rl   rŽ   r:   r�   r¬   r.   rL   r�   r8   r8   r}   r9   r‘   t  s    þ'þ-r‘   )r)   r¤   r§   r   Úurllib.parser   Zwsprotor   r   Zwsproto.eventsr   r   r   r	   r
   r   r   r   r   Zwsproto.extensionsr   Zwsproto.frame_protocolr   Zwsproto.utilitiesr   Úerrorsr   r   r   rm   r‘   r8   r8   r8   r9   Ú<module>   s    , `|