U
    ²@ÛfÍf  ã                   @   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	zd dl
Z
W n ek
rl   dZ
Y nX zd dlZW n ek
r’   dZY nX 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)ÚJSONDecodeErrorNé   )Ú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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S ),Ú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.
    :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()``.
    Nú	engine.ioc                    s„   | j dkrtdƒ‚ddg‰ |dk	rPt|tƒr2|g}‡ fdd„|D ƒ}|sPtdƒ‚|pVˆ | _|  ¡ | _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 | ]}|ˆ kr|‘qS © r   )Ú.0Ú	transport©Zvalid_transportsr   úI/var/www/html/chatgpt/venv/lib/python3.8/site-packages/engineio/client.pyÚ
<listcomp>V   s    ÿz"Client.connect.<locals>.<listcomp>zNo valid transports providedZ	_connect_r   )ÚstateÚ
ValueErrorÚ
isinstanceÚstrÚ
transportsÚcreate_queueÚqueueÚgetattr)ÚselfÚurlÚheadersr   Úengineio_pathr   r   r   Úconnect;   s     



  ÿzClient.connectc                 C   s   | j r| j  ¡  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   Úwait_   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   Úsendh   s    zClient.sendFc                 C   s–   | j dkrŠ|  t tj¡¡ | j d¡ d| _ | jddd� | jdkrP| j	 
¡  |s^| j ¡  d| _ ztj | ¡ W n tk
rˆ   Y nX |  ¡  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'   ÚCLOSEr   ÚputÚ_trigger_eventÚcurrent_transportÚwsÚcloser!   r"   r   Úconnected_clientsÚremover   Ú_reset)r   Úabortr   r   r   r+   q   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   r8   r9   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   rB   š   s    zClient.sleepc                 O   s   t j||Ž}t j|_|S )zCreate a queue object.)r   ÚQueueÚEmpty)r   r9   r:   Úqr   r   r   r   ž   s    zClient.create_queuec                 O   s   t j||ŽS )zCreate an event object.)r<   ÚEvent)r   r9   r:   r   r   r   Úcreate_event¤   s    zClient.create_eventc           	      C   s0  t dkr| j d¡ dS |  ||d¡| _| j d| j ¡ | jd| j|  ¡  || jd�}|dksjt	|t
ƒr€|  ¡  t |p|d¡‚|jdk s”|jd	krÖ|  ¡  z| ¡ }W n tk
rÀ   d}Y nX t d
 |j¡|¡‚ztj|j d¡d�}W n" tk
�r   t d¡d‚Y nX |jd }|jtjk�r4t 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$ %| ¡ | j&ddd� |jdd… D ]}|  '|¡ �qÒd| jk�rd| j(k�r|  )|||¡�rdS |  *| j+¡| _,|  *| j-¡| _.d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    Fr,   r   r   )/ÚrequestsÚloggerÚerrorÚ_get_engineio_urlÚbase_urlÚinfoÚ_send_requestÚ_get_url_timestampÚrequest_timeoutr   r   r6   r   ÚConnectionErrorÚstatus_codeÚjsonr   Úformatr   ÚPayloadÚcontentÚdecoder   ÚpacketsÚpacket_typer   ÚOPENr%   rO   rP   ÚintÚping_intervalÚping_timeoutr1   r   r   r4   Úappendr0   Ú_receive_packetr   Ú_connect_websocketr@   Ú_write_loopÚwrite_loop_taskÚ_read_loop_pollingr!   )	r   r   r   r   ÚrÚargÚpÚopen_packetÚpktr   r   r   Ú_connect_polling¨   s|      þÿ
ÿþÿÿ
ÿÿÿzClient._connect_pollingc              
   C   sÄ  t dkr| j d¡ dS |  ||d¡}| jrP| j d| ¡ d}|d| j 7 }nd}|| _| j d| ¡ d}i }| j�r|d	 d
d„ | jj	D ƒ¡}| 
¡ D ]2\}}	| ¡ dkrš|rº|d	7 }||	7 }||=  qÎqšd|k�r8| jjdk	�r8t| jjtƒsütdƒ‚d | jjd | jjd ¡ d¡}
t|
ƒ d¡}
d|
 |d< t| jjtƒ�rh| 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|k�rì|nd| ¡}|j|d< |j|d< |j�s|j�r&|j|jfnd|d < t| jjt ƒ�rld|k�rZ| jj|d d!< nd!| jji|d< n| jj�s|d| _!| j!�s²d|k�r¤|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|Ž}W n@ t*t+t j,fk
�rN   |�r@| j -d&¡ Y dS t. *d'¡‚Y nX |�r¦t/j0t/j1d(d)� ¡ }z| 2|¡ W n< t3k
�r´ } z| j -d*t |ƒ¡ W Y ¢dS d}~X Y nX z| 4¡ }W n< t3k
�rþ } z| j -d+t |ƒ¡ W Y ¢dS d}~X Y nX t/j0|d,�}|j5t/j6k�s&|j7d(k�r6| j -d-¡ dS t/ 0t/j8¡ ¡ }z| 2|¡ W n< t3k
�r� } z| j -d*t |ƒ¡ W Y ¢dS d}~X Y nX d| _9| j d.¡ näz| 4¡ }W n6 t3k
�rè } zt. *d/t |ƒ ¡‚W 5 d}~X Y nX t/j0|d,�}|j5t/j:k�rt. *d0¡‚| j d1t |j7ƒ ¡ |j7d2 | _|j7d3 | _;t<|j7d4 ƒd5 | _=t<|j7d6 ƒd5 | _>d| _9d7| _?t@jA B| ¡ | jCd8dd9� || _D| jD E| j=| j> ¡ |  F| jG¡| _H|  F| jI¡| _Jd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 TrT   z#Attempting WebSocket connection to z; c                 S   s   g | ]}d   |j|j¡‘qS )z{}={})ra   ÚnameÚvalue)r   Úcookier   r   r   r   þ   s   ÿz-Client._connect_websocket.<locals>.<listcomp>ry   ÚAuthorizationz&Only basic authentication is supportedz{}:{}r   r   rM   zBasic )ÚcertfileÚkeyfileZssloptr{   zws://r2   ÚhttpÚwssÚhttpsz://z	scheme://Zhttp_proxy_hostZhttp_proxy_portZhttp_proxy_authÚca_certsÚ	cert_reqsÚheaderZenable_multithreadrJ   z*WebSocket upgrade failed: connection errorzConnection errorZ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 rO   rP   rQ   rR   rS   r*   r    r,   )Kr   rV   rW   rX   rO   rZ   rY   r}   r"   ÚcookiesÚitemsÚlowerÚauthr   Útupler   ra   Úencoder   rd   ÚcertÚproxiesÚ
startswithÚgetÚurllibÚparseÚurlparseÚhostnameÚportÚusernameÚpasswordÚverifyr   Ú
ssl_verifyÚupdateÚsslÚ	CERT_NONEZwebsocket_extra_optionsÚpopr]   Úcreate_connectionr\   r^   ÚIOErrorZWebSocketExceptionÚwarningr   r   r'   ÚPINGr)   Ú	ExceptionÚrecvrf   ÚPONGr%   ÚUPGRADEr1   rg   rP   rh   ri   rj   r   r   r4   rk   r0   r2   Ú
settimeoutr@   rn   ro   Ú_read_loop_websocketr!   )r   r   r   r   Zwebsocket_urlÚupgrader…   Zextra_optionsr‚   rx   Ú
basic_authÚ	proxy_urlÚ
parsed_urlr2   rs   Úeru   rt   r   r   r   rm   å   s@   ÿÿ
ÿ
 
ÿÿ

þ

 ÿ ÿþ

ÿÿý




ÿÿÿþþÿþ
ÿ
ÿÿ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rb| j
d|jdd� n\|j tjkr†|  t tj|j¡¡ n8|j tjkr | jdd� n|j tjkr®n| j d|j ¡ d	S )
z(Handle incoming packets from the server.ÚUNKNOWNzReceived packet %s data %sú<binary>ÚmessageTr,   )r7   z%Received unexpected packet of type %sN)rf   Úlenr   Úpacket_namesrV   rZ   r   r%   Úbytesr(   r0   rŸ   r&   r'   r¢   r.   r+   ZNOOPrW   )r   ru   Zpacket_namer   r   r   rl   ‹  s(    ÿÿ þÿzClient._receive_packetc                 C   sH   | j dkrdS | j |¡ | j dtj|j t|j	t
ƒs>|j	nd¡ dS )z(Queue a packet to be sent to the server.r*   NzSending packet %s data %sr¬   )r   r   r/   rV   rZ   r   r¯   rf   r   r%   r°   )r   ru   r   r   r   r&   ž  s    

ýzClient._send_packetc              
   C   s„   | j d krt ¡ | _ | js"d| j _z| j j|||||d�W S  tjjk
r~ } z"| j 	d|||¡ t
|ƒ W Y ¢S d }~X Y nX d S )NF)r   r%   rJ   z+HTTP %s request to %s failed with error %s.)r}   rU   ÚSessionr—   r–   Úrequestr   ÚRequestExceptionrV   rZ   r   )r   Úmethodr   r   ÚbodyrJ   Úexcr   r   r   r[   ¨  s    

ÿ  ÿzClient._send_requestc                 O   sb   |  dd¡}|| jkr^|r0| j| j| f|žŽ S z| j| |Ž W S    | j |d ¡ Y nX dS )zInvoke an event handler.r-   Fz handler errorN)r›   Úhandlersr@   rV   Ú	exception)r   Úeventr9   r:   r-   r   r   r   r0   ·  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ks`t
|tƒr€| j |pld¡ | j d¡ �q|jdk s”|jd	kr´| j d
|j¡ | j d¡ �qztj|j d¡d�}W n2 tk
rþ   | j d¡ | j d¡ Y �qY nX |jD ]}|  |¡ �qq | j�r8| j d¡ | j ¡  | j dk�r‚| jddd� ztj | ¡ W n tk
�rx   Y nX |  ¡  | j d¡ dS )z-Read packets by polling the Engine.IO server.r*   zSending polling GET request to rI   é   ©rJ   Nú*Connection refused by the server, abortingrK   rL   ú6Unexpected status code %s in server response, abortingrM   rN   z'Unexpected packet from server, abortingú"Waiting for write loop task to endr+   Fr,   úExiting read loop task)r   ro   rV   rZ   rY   r[   r\   Úmaxri   rj   r   r   rž   r   r/   r_   r   rb   rc   rd   r   re   rl   r"   r0   r   r4   r5   r6   )r   rq   rs   ru   r   r   r   rp   Ã  sT    ÿ þÿÿÿ

zClient._read_loop_pollingc              
   C   sø  | j dk�r€d}z*| j ¡ }t|ƒdkr8| jjs8t ¡ ‚W nÚ tjk
rn   | j 	d¡ | j
 d¡ Y �q€Y n¨ tjk
r    | j 	d¡ | j
 d¡ Y �q€Y nv tk
�r } zVt|ƒtkrÜ|jdkrÜ| j dt|ƒ¡ n| j dt|ƒ¡ | j
 d¡ W Y ¢�q€W 5 d}~X Y nX ztj|d	�}W nL tk
�rr } z,| j d
t|ƒ¡ | j
 d¡ W Y ¢�q€W 5 d}~X Y nX |  |¡ q | j�rž| j d¡ | j ¡  | j dk�rè| jddd� ztj | ¡ W n tk
�rÞ   Y nX |  ¡  | 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   r2   r¡   r®   r*   r   Ú"WebSocketConnectionClosedExceptionZWebSocketTimeoutExceptionrV   rž   r   r/   r    ÚtypeÚOSErrorÚerrnorZ   r   r   r'   rl   ro   r"   r0   r   r4   r5   r   r6   )r   rs   rª   ru   r   r   r   r¥   ë  sf    
ÿ
ÿ
þþ ÿ
zClient._read_loop_websocketc              
   C   s  | j dk�rt| j| jƒd }d}z| jj|d�g}W n* | jjk
r`   | j d¡ Y �qY nX |dgkr|| j 	¡  g }n\z| 
| jjdd�¡ W n | jjk
r°   Y qØY nX |d dkr||dd… }| j 	¡  qØq||sà�q| jd	k�rŽtj|d
�}| jd| j| ¡ ddi| jd�}|D ]}| j 	¡  �q|dk�sDt|tƒ�rZ| j |�pRd¡ �q|jdk �sr|jdk�r| j d|j¡ d| _�qq zD|D ]:}| ¡ }|j�r¶| j |¡ n| j |¡ | j 	¡  �q”W q  tjttfk
�r   | j d¡ Y �qY q X q | j 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, abortingF)Úblockéÿÿÿÿr   )re   ÚPOSTzContent-Typez
text/plain)rµ   r   rJ   r¼   rK   rL   r½   rÁ   zExiting write loop task) r   rÀ   ri   rj   r   rŽ   rE   rV   rW   Ú	task_donerk   r1   r   rb   r[   rY   rŠ   r]   r   r   rž   r_   ro   Úbinaryr2   Zsend_binaryr)   r   rÃ   ÚBrokenPipeErrorrÅ   rZ   )r   rJ   re   rs   rq   ru   r„   r   r   r   rn     sv    



  ýÿÿ ÿÿzClient._write_loop)NNr
   )F)r   )NNN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r    r#   r)   r+   r@   rB   r   rH   rv   rm   rl   r&   r[   r0   rp   r¥   rn   r   r   r   r   r	      s0      ÿ
$		

= '    þ
(3r	   )Úbase64r   Zengineio.jsonr   Úloggingr   r™   r<   rA   r�   rU   ÚImportErrorr   Ú r   r   r   r   Ú	getLoggerZdefault_loggerZ
BaseClientr	   r   r   r   r   Ú<module>   s*   


