o
    ¨ÝjGr  ã                   @   sì   d dl mZ 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
mZ zd dlZW n ey;   dZY nw zd dlZW n eyM   dZY nw ddlmZ ddlmZ ddlmZ dd	lmZ e d
¡ZG dd„ dejƒZdS )é    )Ú	b64encode)ÚSimpleCookieN)ÚJSONDecodeErroré   )Úbase_client)Ú
exceptions)Úpacket)Úpayloadzengineio.clientc                       sÀ   e Zd ZdZ		d,dd„Zdd„ Zdd	„ Zd-dd„Zdd„ Zd.dd„Z	dd„ Z
dd„ Zdd„ Z‡ fdd„Zdd„ Z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‡  ZS )0ÚClientaþ  An Engine.IO client.

    This class implements a fully compliant Engine.IO web client with support
    for websocket and long-polling transports.

    :param logger: To enable logging set to ``True`` or pass a logger object to
                   use. To disable logging set to ``False``. The default is
                   ``False``. Note that fatal errors are logged even when
                   ``logger`` is ``False``.
    :param json: An alternative JSON module to use for encoding and decoding
                 packets. Custom json modules must have ``dumps`` and ``loads``
                 functions that are compatible with the standard library
                 versions. This is a process-wide setting, all instantiated
                 servers and clients must use the same JSON module.
    :param request_timeout: A timeout in seconds for requests. The default is
                            5 seconds.
    :param http_session: an initialized ``requests.Session`` object to be used
                         when sending requests to the server. Use it if you
                         need to add special client options such as proxy
                         servers, SSL certificates, custom CA bundle, etc.
    :param ssl_verify: ``True`` to verify SSL certificates, or ``False`` to
                       skip SSL certificate verification, allowing
                       connections to servers with self signed certificates.
                       The default is ``True``.
    :param handle_sigint: Set to ``True`` to automatically handle disconnection
                          when the process is interrupted, or to ``False`` to
                          leave interrupt handling to the calling application.
                          Interrupt handling can only be enabled when the
                          client instance is created in the main thread.
    :param websocket_extra_options: Dictionary containing additional keyword
                                    arguments passed to
                                    ``websocket.create_connection()``.
    :param timestamp_requests: If ``True`` a timestamp is added to the query
                               string of Socket.IO requests as a cache-busting
                               measure. Set to ``False`` to disable.
    Nú	engine.ioc                    sz   | j dkr	tdƒ‚ddg‰ |dur(t|tƒr|g}‡ fdd„|D ƒ}|s(tdƒ‚|p+ˆ | _t| d	| jd
  ƒ||p:i |ƒS )aˆ  Connect to an Engine.IO server.

        :param url: The URL of the Engine.IO server. It can include custom
                    query string parameters if required by the server.
        :param headers: A dictionary with custom headers to send with the
                        connection request.
        :param transports: The list of allowed transports. Valid transports
                           are ``'polling'`` and ``'websocket'``. If not
                           given, the polling transport is connected first,
                           then an upgrade to websocket is attempted.
        :param engineio_path: The endpoint where the Engine.IO server is
                              installed. The default value is appropriate for
                              most cases.

        Example usage::

            eio = engineio.Client()
            eio.connect('http://localhost:5000')
        Údisconnectedz%Client is not in a disconnected stateÚpollingÚ	websocketNc                    s   g | ]}|ˆ v r|‘qS © r   )Ú.0Ú	transport©Zvalid_transportsr   úJ/var/www/html/chatgpt/venv/lib/python3.10/site-packages/engineio/client.pyÚ
<listcomp>[   s    ÿz"Client.connect.<locals>.<listcomp>zNo valid transports providedZ	_connect_r   )ÚstateÚ
ValueErrorÚ
isinstanceÚstrÚ
transportsÚgetattr)ÚselfÚurlÚheadersr   Úengineio_pathr   r   r   Úconnect@   s   



ÿzClient.connectc                 C   s   | j r
| j  ¡  dS dS )z¯Wait until the connection with the server ends.

        Client applications can use this function to block the main thread
        during the life of the connection.
        N)Úread_loop_taskÚjoin©r   r   r   r   Úwaitc   s   ÿzClient.waitc                 C   s   |   tjtj|d�¡ dS )a  Send a message to the server.

        :param data: The data to send to the server. Data can be of type
                     ``str``, ``bytes``, ``list`` or ``dict``. If a ``list``
                     or ``dict``, the data will be serialized as JSON.
        ©ÚdataN)Ú_send_packetr   ÚPacketÚMESSAGE)r   r%   r   r   r   Úsendl   s   zClient.sendFc                 C   sž   | j dkrI|  t tj¡¡ | j d¡ d| _ | jd|p| jj	dd� | j
dkr-| j ¡  |s4| j ¡  d| _ ztj | ¡ W n	 tyH   Y nw |  ¡  dS )	z­Disconnect from the server.

        :param abort: If set to ``True``, do not wait for background tasks
                      associated with the connection to end.
        Ú	connectedNZdisconnectingÚ
disconnectF©Ú	run_asyncr   r   )r   r&   r   r'   ÚCLOSEÚqueueÚputÚ_trigger_eventÚreasonZCLIENT_DISCONNECTÚcurrent_transportÚwsÚcloser    r!   r   Úconnected_clientsÚremover   Ú_reset)r   Úabortr2   r   r   r   r+   u   s&   

þ


ÿzClient.disconnectc                 O   s   t j|||dd�}| ¡  |S )aã  Start a background task.

        This is a utility function that applications can use to start a
        background task.

        :param target: the target function to execute.
        :param args: arguments to pass to the function.
        :param kwargs: keyword arguments to pass to the function.

        This function returns an object that represents the background task,
        on which the ``join()`` method can be invoked to wait for the task to
        complete.
        T)ÚtargetÚargsÚkwargsÚdaemon)Ú	threadingÚThreadÚstart)r   r:   r;   r<   Úthr   r   r   Ústart_background_task�   s
   
ÿzClient.start_background_taskr   c                 C   s
   t  |¡S )z'Sleep for the requested amount of time.)ÚtimeÚsleep)r   Úsecondsr   r   r   rD       s   
zClient.sleepc                 O   ó   t j|i |¤ŽS )zCreate a queue object.)r/   ÚQueue©r   r;   r<   r   r   r   Úcreate_queue¤   ó   zClient.create_queuec                 C   s   t jS )zlReturn the queue empty exception raised by queues created by the
        ``create_queue()`` method.
        )r/   ÚEmptyr"   r   r   r   Úget_queue_empty_exception¨   s   z Client.get_queue_empty_exceptionc                 O   rF   )zCreate an event object.)r>   ÚEventrH   r   r   r   Úcreate_event®   rJ   zClient.create_eventc                    s>   t ƒ  ¡  	 z| j ¡  | j ¡  W n | jy   Y d S w q)N)Úsuperr8   r/   Ú
get_nowaitÚ	task_doneÚqueue_emptyr"   ©Ú	__class__r   r   r8   ²   s   

ÿüzClient._resetc           
   
   C   sj  t du r| j d¡ dS |  ||d¡| _| j d| j ¡ | jd| j|  ¡  || jd�}|du s5t	|t
ƒr@|  ¡  t |p>d¡‚|jdk sJ|jd	krj|  ¡  z| ¡ }W n ty_   d}Y nw t d
 |j¡|¡‚ztj|j d¡d�}W n tyƒ   t d¡d‚w |jd }|jtjkr”t d¡‚| j dt
|jƒ ¡ |jd | _|jd | _t|jd ƒd | _t|jd ƒd | _ d| _!|  jd| j 7  _d| _"t#j$ %| ¡ z
| j&dddd� W n t'yþ } zt#j$ (| ¡ |  ¡  t dt
|ƒ ¡‚d}~ww |jdd… D ]}	|  )|	¡ �qd| jv �r%d| j*v �r%|  +|||¡�r%dS |  ,| j-¡| _.|  ,| j/¡| _0dS )z<Establish a long-polling connection to the Engine.IO server.Nz?requests package is not installed -- cannot send HTTP requests!r   z!Attempting polling connection to ÚGET)r   Útimeoutz Connection refused by the serveréÈ   é,  z,Unexpected status code {} in server responseúutf-8©Zencoded_payloadzUnexpected response from serverr   z"OPEN packet not returned by serverz!Polling connection accepted with ÚsidÚupgradesÚpingIntervalç     @�@ÚpingTimeoutú&sid=r*   r   FT©r-   ÚreraiseúConnect handler failed: r   r   )1ÚrequestsÚloggerÚerrorÚ_get_engineio_urlÚbase_urlÚinfoÚ_send_requestÚ_get_url_timestampÚrequest_timeoutr   r   r8   r   ÚConnectionErrorÚstatus_codeÚjsonr   Úformatr	   ÚPayloadÚcontentÚdecoder   ÚpacketsÚpacket_typer   ÚOPENr%   r[   r\   ÚintÚping_intervalÚping_timeoutr3   r   r   r6   Úappendr1   Ú	Exceptionr7   Ú_receive_packetr   Ú_connect_websocketrB   Ú_write_loopÚwrite_loop_taskÚ_read_loop_pollingr    )
r   r   r   r   ÚrÚargÚpÚopen_packetÚexcÚpktr   r   r   Ú_connect_polling»   sŽ   þÿÿÿþÿÿÿ
ÿÿ
ÿ€ý
ÿzClient._connect_pollingc              
   C   s  t du r| j d¡ dS |  ||d¡}| jr(| j d| ¡ d}|d| j 7 }nd}|| _| j d| ¡ d}i }| j�rEtƒ }| jj	D ]}	|	j
||	j< qD|jd	d
d� ¡ }| ¡ D ]\}
}|
 ¡ dkrs|rj|d7 }||7 }||
=  nqZd|vr§| jjdur§t| jjtƒs‰tdƒ‚d | jjd | jjd ¡ d¡}t|ƒ d¡}d| |d< t| jjtƒr¾| jjd | jjd dœ|d< n| jjrÊd| jji|d< | jj�rd}| d¡rä| jj d| jj d¡¡}n| jj d| jj d¡¡}|�rtj d|v rý|nd| ¡}|j|d< |j |d < |j!�s|j"�r|j!|j"fnd|d!< t| jj#t$ƒ�r=d|v �r4| jj#|d d"< nd"| jj#i|d< n| jj#�sEd| _%| j%�s`d|v �rY|d  &d#t'j(i¡ nd#t'j(i|d< | &| j) *d$i ¡¡ ||d$< ||d< d|d%< | j+|d&< | &| j)¡ zt j,||  -¡  fi |¤Ž}W n t.t/t j0f�y­   |�r¨| j 1d'¡ Y dS t2 .d(¡‚w |�rVt3j4t3j5d)d*� ¡ }z| 6|¡ W n t7�yß } z| j 1d+t$|ƒ¡ W Y d}~dS d}~ww z| 8¡ }W n t7�y } z| j 1d,t$|ƒ¡ W Y d}~dS d}~ww t3j4|d-�}|j9t3j:k�s|j;d)k�r| j 1d.¡ dS t3 4t3j<¡ ¡ }z| 6|¡ W n t7�yK } z| j 1d+t$|ƒ¡ W Y d}~dS d}~ww d| _=| j d/¡ n‘z| 8¡ }W n t7�yr } z	t2 .d0t$|ƒ ¡‚d}~ww t3j4|d-�}|j9t3j>k�r…t2 .d1¡‚| j d2t$|j;ƒ ¡ |j;d3 | _|j;d4 | _?t@|j;d5 ƒd6 | _At@|j;d7 ƒd6 | _Bd| _=d8| _CtDjE F| ¡ z
| jGd9ddd:� W n  t7�yæ } ztDjE H| ¡ |  I¡  t2 .d;t$|ƒ ¡‚d}~ww || _J| jJ K| jA| jB ¡ |  L| jM¡| _N|  L| jO¡| _PdS )<z?Establish or upgrade to a WebSocket connection with the server.NzKwebsocket-client package not installed, only polling transport is availableFr   z Attempting WebSocket upgrade to Tr`   z#Attempting WebSocket connection to Ú ú;)ÚheaderÚsepÚcookiez; ÚAuthorizationz&Only basic authentication is supportedz{}:{}r   r   rY   zBasic )ÚcertfileÚkeyfileZssloptrŽ   zws://r4   ÚhttpÚwssÚhttpsz://z	scheme://Zhttp_proxy_hostZhttp_proxy_portZhttp_proxy_authÚca_certsÚ	cert_reqsrŠ   Zenable_multithreadrV   z*WebSocket upgrade failed: connection errorzConnection errorÚprober$   z7WebSocket upgrade failed: unexpected send exception: %sz7WebSocket upgrade failed: unexpected recv exception: %s©Úencoded_packetz(WebSocket upgrade failed: no PONG packetz WebSocket upgrade was successfulzUnexpected recv exception: zno OPEN packetz#WebSocket connection accepted with r[   r\   r]   r^   r_   r*   r   ra   rc   )Qr   re   rf   rg   r[   ri   rh   r�   r   ÚcookiesÚvalueÚnameÚoutputÚstripÚitemsÚlowerÚauthr   Útupler   rp   Úencoder   rs   ÚcertÚproxiesÚ
startswithÚgetÚurllibÚparseÚurlparseÚhostnameÚportÚusernameÚpasswordÚverifyr   Ú
ssl_verifyÚupdateÚsslÚ	CERT_NONEZwebsocket_extra_optionsÚpoprl   Úcreate_connectionrk   rm   ÚOSErrorZWebSocketExceptionÚwarningr   r   r'   ÚPINGr)   r{   Úrecvru   ÚPONGr%   ÚUPGRADEr3   rv   r\   rw   rx   ry   r   r   r6   rz   r1   r7   r8   r4   Ú
settimeoutrB   r~   r   Ú_read_loop_websocketr    )r   r   r   r   Zwebsocket_urlÚupgrader˜   Zextra_optionsZckrŒ   rŠ   r™   Ú
basic_authÚ	proxy_urlÚ
parsed_urlr4   rƒ   Úer†   r„   r…   r   r   r   r}   þ   sb  ÿÿûÿÿ

þ

ÿÿþ

ÿÿý




ÿ
ÿÿ
úþ€üþ€üÿþ€ü
ÿ€ÿ
ÿ
ÿ€ýÿzClient._connect_websocketc                 C   sÐ   |j ttjƒk rtj|j  nd}| j d|t|jtƒs|jnd¡ |j tj	kr2| j
d|jdd� d	S |j tjkrE|  t tj|j¡¡ d	S |j tjkrV| jd| jjd� d	S |j tjkr^d	S | j d|j ¡ d	S )
z(Handle incoming packets from the server.ÚUNKNOWNzReceived packet %s data %sú<binary>ÚmessageTr,   )r9   r2   z%Received unexpected packet of type %sN)ru   Úlenr   Úpacket_namesre   ri   r   r%   Úbytesr(   r1   r¶   r&   r'   r¸   r.   r+   r2   ZSERVER_DISCONNECTZNOOPrf   )r   r†   Zpacket_namer   r   r   r|   ¬  s&   ÿÿþÿzClient._receive_packetc                 C   sN   | j dkrdS | j |¡ | j dtj|j t|j	t
ƒs"|j	¡ dS d¡ dS )z(Queue a packet to be sent to the server.r*   NzSending packet %s data %srÂ   )r   r/   r0   re   ri   r   rÅ   ru   r   r%   rÆ   )r   r†   r   r   r   r&   ¿  s   

ýýzClient._send_packetc              
   C   s~   | j d u r
t ¡ | _ | jsd| j _z| j j|||||d�W S  tjjy> } z| j 	d|||¡ t
|ƒW  Y d }~S d }~ww )NF)r   r%   rV   z+HTTP %s request to %s failed with error %s.)r�   rd   ÚSessionr®   r­   Úrequestr   ÚRequestExceptionre   ri   r   )r   Úmethodr   r   ÚbodyrV   r…   r   r   r   rj   É  s   

ÿÿ€ýzClient._send_requestc                 O   s¨   |  dd¡}|| jv rR|r| j| j| g|¢R Ž S z%z	| j| |Ž W W S  ty>   |dkr=t|ƒdkr=| j| ƒ  Y W S ‚ w    | j |d ¡ |dkrO‚ Y dS dS )zInvoke an event handler.r-   Fr+   r   z handler errorr   N)r²   ÚhandlersrB   Ú	TypeErrorrÄ   re   Ú	exception)r   Úeventr;   r<   r-   r   r   r   r1   Ø  s&   
ùýïzClient._trigger_eventc                 C   s°  | j dkr‹| jr‹| j d| j ¡ | jd| j|  ¡  t| j| j	ƒd d�}|du s.t
|tƒr=| j |p4d¡ | j d¡ nN|jdk sG|jd	krV| j d
|j¡ | j d¡ n5ztj|j d¡d�}W n tyw   | j d¡ | j d¡ Y nw |jD ]}|  |¡ q{| j dkr‹| js| jr«| j d¡ z| j ¡  W n tyª   | jdur¨‚ Y nw | j dkrÐ| jd| jjdd� ztj | ¡ W n	 tyË   Y nw |  ¡  | j d¡ dS )z-Read packets by polling the Engine.IO server.r*   zSending polling GET request to rU   é   ©rV   Nú*Connection refused by the server, abortingrW   rX   ú6Unexpected status code %s in server response, abortingrY   rZ   z'Unexpected packet from server, abortingú"Waiting for write loop task to endr+   Fr,   úExiting read loop task) r   r   re   ri   rh   rj   rk   Úmaxrx   ry   r   r   rµ   r/   r0   rn   r	   rq   rr   rs   r   rt   r|   r!   ÚAttributeErrorr1   r2   ÚTRANSPORT_ERRORr   r6   r7   r8   )r   r�   rƒ   r†   r   r   r   r€   ñ  sh   ÿþÿÿÿü
è
ÿÿ
ÿÿzClient._read_loop_pollingc              
   C   s  | j dkr´| jr´d}z| j ¡ }t|ƒdkr| jjst ¡ ‚W n] tjy5   | j	 
d¡ | j d¡ Y n tjyJ   | j	 
d¡ | j d¡ Y nj ty| } z't|ƒtu rc|jdkrc| j	 d¡ n	| j	 dt|ƒ¡ | j d¡ W Y d}~n<d}~ww ztj|d	�}W n! ty¦ } z| j	 d
t|ƒ¡ | j d¡ W Y d}~nd}~ww |  |¡ | j dkr´| js| jrÔ| j	 d¡ z| j ¡  W n tyÓ   | jdurÑ‚ Y nw | j dkrù| jd| jjdd� ztj | ¡ W n	 tyô   Y nw |  ¡  | j	 d¡ dS )z5Read packets from the Engine.IO WebSocket connection.r*   Nr   z*Server has stopped communicating, abortingú)WebSocket connection was closed, abortingé	   z)WebSocket connection is closing, abortingz1Unexpected error receiving packet: "%s", abortingr–   z0Unexpected error decoding packet: "%s", abortingrÔ   r+   Fr,   rÕ   ) r   r   r4   r·   rÄ   r*   r   Ú"WebSocketConnectionClosedExceptionZWebSocketTimeoutExceptionre   rµ   r/   r0   r{   Útyper´   Úerrnori   r   r   r'   r|   r!   r×   r1   r2   rØ   r   r6   r7   r   r8   )r   rƒ   rÀ   r†   r   r   r   r»      s€   
€ÿÿÿþ€÷
ÿ€ü
Þ$
ÿÿ
ÿÿzClient._read_loop_websocketc              
   C   sê  | j dkrêt| j| jƒd }d}z
| jj|d�g}W n | jy*   | j d¡ Y nÀw |dgkr8| j 	¡  g }n+	 z| 
| jjdd�¡ W n
 | jyO   Y nw |d	 du rb|dd	… }| j 	¡  nq9|sfn„| jd
kr±tj|d�}| jd| j| ¡ ddi| jd�}|D ]}| j 	¡  qƒ|du s”t|tƒr�| j |pšd¡ nM|jdk s§|jdkr°| j d|j¡ n:n4z |D ]}| ¡ }|jrÄ| j |¡ n| j |¡ | j 	¡  q´W n tjttfyä   | j d¡ Y nw | j dks| j d¡ d| _dS )zhThis background task sends packages to the server as they are
        pushed to the send queue.
        r*   rÐ   NrÑ   zpacket queue is empty, abortingTF)Úblockéÿÿÿÿr   )rt   ÚPOSTzContent-Typez
text/plain)rË   r   rV   rÒ   rW   rX   rÓ   rÙ   zExiting write loop task) r   rÖ   rx   ry   r/   r¥   rR   re   rf   rQ   rz   r3   r	   rq   rj   rh   r¡   rl   r   r   rµ   rn   Úbinaryr4   Zsend_binaryr)   r   rÛ   ÚBrokenPipeErrorr´   ri   r   )r   rV   rt   rƒ   r�   r†   r—   r   r   r   r~   Y  s€   
þ

ÿ
ø	
ýÿÿýú
ÿÿü
Ë:
zClient._write_loop)NNr   )FN)r   )NNN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r#   r)   r+   rB   rD   rI   rL   rN   r8   r‡   r}   r|   r&   rj   r1   r€   r»   r~   Ú__classcell__r   r   rS   r   r
      s4    $
ÿ#	
	
	C /
þ/9r
   )Úbase64r   Úhttp.cookiesr   Úloggingr/   r°   r>   rC   r¦   Zengineio.jsonr   rd   ÚImportErrorr   rˆ   r   r   r   r	   Ú	getLoggerZdefault_loggerZ
BaseClientr
   r   r   r   r   Ú<module>   s2    ÿÿ
