o
    ¨ÝjKw  ã                   @   s°   d dl Z d dlm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y+   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 daeƒ Zd	d
„ ZG dd„ de
jƒZdS )é    N)ÚSimpleCookieé   )Úbase_client)Ú
exceptions)Úpacket)ÚpayloadFc                  C   s   dd„ } t  | ƒ ¡ dS )z>SIGINT handler.

    Disconnect all active async clients.
    c                  Ó   sv   �t jd d … D ]} |  ¡ r|  ¡ I d H  qdd„ t ¡ D ƒ}|D ]}| ¡  q!tj|ddiŽI d H  t ¡  	¡  d S )Nc                 S   s   g | ]
}|t  ¡ ur|‘qS © )ÚasyncioZcurrent_task)Ú.0Útaskr   r   úP/var/www/html/chatgpt/venv/lib/python3.10/site-packages/engineio/async_client.pyÚ
<listcomp>%   s   
 ÿz:async_signal_handler.<locals>._handler.<locals>.<listcomp>Zreturn_exceptionsT)
r   Úconnected_clientsÚis_asyncio_basedÚ
disconnectr	   Z	all_tasksÚcancelZgatherÚget_running_loopÚstop)ÚcÚtasksr   r   r   r   Ú_handler   s   €€
z&async_signal_handler.<locals>._handlerN©r	   Úensure_future)r   r   r   r   Úasync_signal_handler   s   r   c                       sÐ   e Zd ZdZdd„ Z		d0dd„Zdd	„ Zd
d„ Zd1dd„Zdd„ Z	d2d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%„ Z		d3d&d'„Zd(d)„ Zd*d+„ Zd,d-„ Zd.d/„ Z‡  ZS )4ÚAsyncClientaH	  An Engine.IO client for asyncio.

    This class implements a fully compliant Engine.IO web client with support
    for websocket and long-polling transports, compatible with the asyncio
    framework on Python 3.5 or newer.

    :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 ``aiohttp.ClientSession`` 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
                                    ``aiohttp.ws_connect()``.
    :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.
    c                 C   s   dS )NTr   ©Úselfr   r   r   r   U   s   zAsyncClient.is_asyncio_basedNú	engine.ioc                 ƒ   sÖ   �| j r)ts)t ¡ t ¡ kr)zt ¡  tj	t
¡ W n ty(   | j d¡ Y nw da| jdkr4tdƒ‚ddg‰ |durSt|tƒrD|g}‡ fdd	„|D ƒ}|sStd
ƒ‚|pVˆ | _t| d| jd  ƒ||pei |ƒI dH 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.

        Note: this method is a coroutine.

        Example usage::

            eio = engineio.Client()
            await eio.connect('http://localhost:5000')
        zSignal handler is unsupportedTÚdisconnectedz%Client is not in a disconnected stateÚpollingÚ	websocketNc                    s   g | ]}|ˆ v r|‘qS r   r   )r
   Ú	transport©Zvalid_transportsr   r   r      s    ÿz'AsyncClient.connect.<locals>.<listcomp>zNo valid transports providedZ	_connect_r   )Zhandle_sigintÚasync_signal_handler_setÚ	threadingÚcurrent_threadÚmain_threadr	   r   Zadd_signal_handlerÚsignalÚSIGINTr   ÚNotImplementedErrorÚloggerÚwarningÚstateÚ
ValueErrorÚ
isinstanceÚstrÚ
transportsÚgetattr)r   ÚurlÚheadersr0   Úengineio_pathr   r"   r   ÚconnectX   s0   €
ÿÿ




ÿzAsyncClient.connectc                 Ã   s   �| j r| j I dH  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.

        Note: this method is a coroutine.
        N)Úread_loop_taskr   r   r   r   Úwait‡   s   €ÿzAsyncClient.waitc                 Ã   s"   �|   tjtj|d�¡I dH  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.

        Note: this method is a coroutine.
        ©ÚdataN)Ú_send_packetr   ÚPacketÚMESSAGE)r   r9   r   r   r   Úsend’   s   € 	zAsyncClient.sendFc                 Ã   sÀ   �| j dkrW|  t tj¡¡I dH  | j d¡I dH  d| _ | jd|p&| jj	dd�I dH  | j
dkr:| j ¡ I dH  |sB| jI dH  d| _ ztj | ¡ W n	 tyV   Y nw |  ¡ I dH  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.

        Note: this method is a coroutine.
        Ú	connectedNZdisconnectingr   F©Ú	run_asyncr    r   )r,   r:   r   r;   ÚCLOSEÚqueueÚputÚ_trigger_eventÚreasonZCLIENT_DISCONNECTÚcurrent_transportÚwsÚcloser6   r   r   Úremover-   Ú_reset)r   ÚabortrE   r   r   r   r   �   s(   €

þ
ÿzAsyncClient.disconnectc                 O   s   t  ||i |¤Ž¡S )am  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.

        The return value is a ``asyncio.Task`` object.
        r   )r   ÚtargetÚargsÚkwargsr   r   r   Ústart_background_task·   s   z!AsyncClient.start_background_taskr   c                 Ã   s   �t  |¡I dH S )z[Sleep for the requested amount of time.

        Note: this method is a coroutine.
        N)r	   Úsleep)r   Úsecondsr   r   r   rP   Å   s   €zAsyncClient.sleepc                 O   s   t j|i |¤ŽS )zCreate a queue object.)r	   ÚQueue)r   rM   rN   r   r   r   Úcreate_queueÌ   s   zAsyncClient.create_queuec                 C   s   t jS )zlReturn the queue empty exception raised by queues created by the
        ``create_queue()`` method.
        )r	   Z
QueueEmptyr   r   r   r   Úget_queue_empty_exceptionÐ   s   z%AsyncClient.get_queue_empty_exceptionc                 C   s   t  ¡ S )zCreate an event object.)r	   ÚEventr   r   r   r   Úcreate_eventÖ   s   zAsyncClient.create_eventc                 ƒ   sr   �t ƒ  ¡  	 z| j ¡  | j ¡  W n
 | jy   Y nw q| js3| jr5| jjs7| j 	¡ I d H  d S d S d S d S ©N)
ÚsuperrJ   rB   Ú
get_nowaitÚ	task_doneÚqueue_emptyZexternal_httpÚhttpÚclosedrH   r   ©Ú	__class__r   r   rJ   Ú   s   €

ÿüþzAsyncClient._resetc                 C   s`   | j r,| j js.zt ¡ }| ¡ r| | j  ¡ ¡ W d S | | j  ¡ ¡ W d S    Y d S d S d S rW   )r\   r]   r	   Zget_event_loopZ
is_runningr   rH   Zrun_until_complete)r   Úloopr   r   r   Ú__del__æ   s   øzAsyncClient.__del__c           
   
   Ã   s¦  �t du r| j d¡ dS |  ||d¡| _| j d| j ¡ | jd| j|  ¡  || jd�I dH }|du s9t	|t
ƒrG|  ¡ I dH  t |pEd¡‚|jdk sQ|jd	krx|  ¡ I dH  z	| ¡ I dH }W n t jym   d}Y nw t d
 |j¡|¡‚ztj| ¡ I dH  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�I dH  W n# t'�y } zt#j$ (| ¡ |  ¡ I dH  t dt
|ƒ ¡‚d}~ww |jdd… D ]}	|  )|	¡I dH  �qd| jv �rCd| j*v �rC|  +|||¡I dH �rCdS |  ,| j-¡| _.|  ,| j/¡| _0dS )z<Establish a long-polling connection to the Engine.IO server.Nz3aiohttp not installed -- cannot make HTTP requests!r   z!Attempting polling connection to ÚGET)r3   Ú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>   r5   Fr?   úConnect handler failed: r   r    )1Úaiohttpr*   ÚerrorÚ_get_engineio_urlÚbase_urlÚinfoÚ_send_requestÚ_get_url_timestampÚrequest_timeoutr.   r/   rJ   r   ÚConnectionErrorÚstatusÚjsonÚClientErrorÚformatr   ÚPayloadÚreadÚdecoder-   ÚpacketsÚpacket_typer   ÚOPENr9   rh   ri   ÚintÚping_intervalÚping_timeoutrF   r,   r   r   ÚappendrD   Ú	ExceptionrI   Ú_receive_packetr0   Ú_connect_websocketrO   Ú_write_loopÚwrite_loop_taskÚ_read_loop_pollingr6   )
r   r2   r3   r4   ÚrÚargÚpÚopen_packetÚexcÚpktr   r   r   Ú_connect_pollingò   s”   €þÿÿÿþÿÿÿÿ
ÿÿ
ÿ€ý
ÿzAsyncClient._connect_pollingc              
   Ã   s\  �t du r| j d¡ dS |  ||d¡}| jr)| j d| ¡ d}|d| j 7 }nd}|| _| j d| ¡ | jdu s?| jjrDt  	¡ | _| 
¡ D ]#\}}| ¡ d	krkt|| ƒ}| jj d
d„ | 
¡ D ƒ¡ ||=  nqHdt j| jd�i}	| js‡t ¡ }
d|
_tj|
_|
|	d< | | j di ¡¡ ||	d< |	 | j¡ z| jj||  ¡  fi |	¤ŽI dH }W n  t jjt jjt jjfyÎ   |rÉ| j  d¡ Y dS t! "d¡‚w |�r�t#j$t#j%dd� &¡ }z
| '|¡I dH  W n t(�y } z| j  dt)|ƒ¡ W Y d}~dS d}~ww z
| *¡ I dH j+}W n t(�y+ } z| j  dt)|ƒ¡ W Y d}~dS d}~ww t#j$|d�}|j,t#j-k�s?|j+dk�rG| j  d¡ dS t# $t#j.¡ &¡ }z
| '|¡I dH  W n t(�yv } z| j  dt)|ƒ¡ W Y d}~dS d}~ww d| _/| j d¡ nšz
| *¡ I dH j+}W n t(�y¡ } z	t! "dt)|ƒ ¡‚d}~ww t#j$|d�}|j,t#j0k�r´t! "d¡‚| j dt)|j+ƒ ¡ |j+d | _|j+d | _1t2|j+d ƒd | _3t2|j+d  ƒd | _4d| _/d!| _5t6j7 8| ¡ z| j9d"dd#�I dH  W n# t(�y } zt6j7 :| ¡ |  ;¡ I dH  t! "d$t)|ƒ ¡‚d}~ww || _<|  =| j>¡| _?|  =| j@¡| _AdS )%z?Establish or upgrade to a WebSocket connection with the server.Nzaiohttp package not installedFr    z Attempting WebSocket upgrade to Trm   z#Attempting WebSocket connection to Úcookiec                 S   s   i | ]\}}||j “qS r   )Úvalue)r
   ÚkÚmr   r   r   Ú
<dictcomp>O  s    z2AsyncClient._connect_websocket.<locals>.<dictcomp>rc   )Zws_closeÚsslr3   z*WebSocket upgrade failed: connection errorzConnection errorÚprober8   z7WebSocket upgrade failed: unexpected send exception: %sz7WebSocket upgrade failed: unexpected recv exception: %s©Zencoded_packetz(WebSocket upgrade failed: no PONG packetz WebSocket upgrade was successfulzUnexpected recv exception: zno OPEN packetz#WebSocket connection accepted with rh   ri   rj   rk   rl   r>   r5   r?   rn   )Bro   r*   rp   rq   rh   rs   rr   r\   r]   ÚClientSessionÚitemsÚlowerr   Ú
cookie_jarZupdate_cookiesZClientWSTimeoutrv   Ú
ssl_verifyr˜   Úcreate_default_contextÚcheck_hostnameÚ	CERT_NONEÚverify_modeÚupdateZwebsocket_extra_optionsÚpopZ
ws_connectru   Úclient_exceptionsZWSServerHandshakeErrorZServerConnectionErrorZClientConnectionErrorr+   r   rw   r   r;   ÚPINGÚencodeÚsend_strr†   r/   Úreceiver9   r€   ÚPONGÚUPGRADErF   r�   ri   r‚   rƒ   r„   r,   r   r   r…   rD   rI   rJ   rG   rO   r‰   rŠ   Ú_read_loop_websocketr6   )r   r2   r3   r4   Zwebsocket_urlÚupgradeÚheaderr”   ZckZextra_optionsÚssl_contextrG   rŽ   Úer‘   r�   r�   r   r   r   rˆ   4  s  €ÿÿÿ
ÿûÿ
ÿÿ
þÿ
ø	þ€üþ€üÿþ€ü
ÿ€ÿ
ÿ
ÿ€ýÿzAsyncClient._connect_websocketc                 Ã   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r6| j
d|jdd�I dH  dS |j tjkrL|  t tj|j¡¡I dH  dS |j tjkr`| jd| jjd�I dH  dS |j tjkrhdS | j d	|j ¡ dS )
z(Handle incoming packets from the server.ÚUNKNOWNzReceived packet %s data %sú<binary>ÚmessageTr?   N)rK   rE   z%Received unexpected packet of type %s)r€   Úlenr   Úpacket_namesr*   rs   r.   r9   Úbytesr<   rD   r§   r:   r;   r«   rA   r   rE   ZSERVER_DISCONNECTZNOOPrp   )r   r‘   Zpacket_namer   r   r   r‡   ­  s,   €ÿÿþ ÿÿzAsyncClient._receive_packetc                 Ã   sV   �| j dkrdS | j |¡I dH  | 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,   rB   rC   r*   rs   r   r¶   r€   r.   r9   r·   )r   r‘   r   r   r   r:   Á  s   €

ýýzAsyncClient._send_packetc              
   Ã   s¾   �| j d u s
| j jrt ¡ | _ t| j | ¡ ƒ}z$| js,||||tj|d�dd�I d H W S ||||tj|d�d�I d H W S  tjt	j
fy^ } z| j d|||¡ t|ƒW  Y d }~S d }~ww )N)ÚtotalF)r3   r9   rc   r˜   )r3   r9   rc   z+HTTP %s request to %s failed with error %s.)r\   r]   ro   r›   r1   r�   rŸ   ZClientTimeoutrz   r	   ÚTimeoutErrorr*   rs   r/   )r   Úmethodr2   r3   Úbodyrc   Zhttp_methodr�   r   r   r   rt   Ë  s*   €
þ
þÿ€ýzAsyncClient._send_requestc                 �   s²  �|  dd¡}d}ˆˆjv r×t ˆjˆ ¡du r~|r3ˆjˆjˆ gˆ ¢R Ž }t |¡ | tj¡ |S z-zˆjˆ ˆ Ž I dH }W W |S  t	y`   ˆdkr_t
ˆ ƒdkr_ˆjˆ ƒ I dH  Y W S ‚ w  tjyk   Y |S    ˆj ˆd ¡ ˆdkr{‚ Y |S |rš‡ ‡‡fd	d
„}ˆ |¡}t |¡ | tj¡ |S z)zˆjˆ ˆ Ž }W W |S  t	yÃ   ˆdkr¾t
ˆ ƒdkr¾ˆjˆ ƒ }n‚ Y W |S w    ˆj ˆd ¡ ˆdkrÔ‚ Y |S |S )zInvoke an event handler.r@   FNTr   r   z async handler errorr5   c                   “   s   �ˆj ˆ ˆ Ž S rW   )Úhandlersr   ©rM   Úeventr   r   r   Úasync_handler  s   €z1AsyncClient._trigger_event.<locals>.async_handlerz handler error)r¥   r¼   ÚinspectÚiscoroutinefunctionrO   Útask_reference_holderÚaddZadd_done_callbackÚdiscardÚ	TypeErrorrµ   r	   ÚCancelledErrorr*   Ú	exception)r   r¾   rM   rN   r@   Úretr   r¿   r   r½   r   rD   á  sn   €
ÿ
,Õù"ßýæ

òþ	òýzAsyncClient._trigger_eventc                 Ã   sÂ  �| j dkrŸ| jrŸ| j d| j ¡ | jd| j|  ¡  t| j| j	ƒd d�I dH }|du s2t
|tƒrD| j |p8d¡ | j d¡I dH  n[|jdk sN|jd	kr`| j d
|j¡ | j d¡I dH  n?ztj| ¡ I dH  d¡d�}W n tyˆ   | j d¡ | j d¡I dH  Y nw |jD ]
}|  |¡I dH  qŒ| j dkrŸ| js	| jr®| j d¡ | jI dH  | j dkrÙ| jd| jjdd�I dH  ztj | ¡ W n	 tyÑ   Y nw |  ¡ I dH  | j d¡ dS )z-Read packets by polling the Engine.IO server.r>   zSending polling GET request to rb   é   ©rc   Nú*Connection refused by the server, abortingrd   re   ú6Unexpected status code %s in server response, abortingrf   rg   z'Unexpected packet from server, abortingú"Waiting for write loop task to endr   Fr?   úExiting read loop task)r,   rŠ   r*   rs   rr   rt   ru   Úmaxrƒ   r„   r.   r/   r+   rB   rC   rx   r   r|   r}   r~   r-   r   r‡   rD   rE   ÚTRANSPORT_ERRORr   r   rI   rJ   )r   rŒ   rŽ   r‘   r   r   r   r‹     sb   €ÿþÿÿÿÿü
ç

ÿÿzAsyncClient._read_loop_pollingc              
   Ã   sL  �| j dkrâ| jrâd}zDtj| j ¡ | j| j d�I dH }t|j	t
tfƒsK| j d|jtjjtjjfv r6dnt
|jƒt
|j	ƒ¡ | j d¡I dH  W n—|j	}W nU tjyh   | j d¡ | j d¡I dH  Y nz tjjy�   | j d¡ | j d¡I dH  Y na ty¤ } z| j dt
|ƒ¡ | j d¡I dH  W Y d}~nBd}~ww ztj|d	�}W n$ tyÑ } z| j d
t
|ƒ¡ | j d¡I dH  W Y d}~nd}~ww |  |¡I dH  | j dkrâ| js	| jrñ| j d¡ | jI dH  | j dk�r| jd| jjdd�I dH  zt j! "| ¡ W n
 t#�y   Y nw |  $¡ I dH  | j d¡ dS )z5Read packets from the Engine.IO WebSocket connection.r>   NrÊ   z'Server sent %s packet data %s, abortingrH   z*Server has stopped communicating, abortingz4Read loop: WebSocket connection was closed, abortingz1Unexpected error receiving packet: "%s", abortingrš   z0Unexpected error decoding packet: "%s", abortingrÍ   r   Fr?   rÎ   )%r,   rŠ   r	   Úwait_forrG   rª   rƒ   r„   r.   r9   r/   r·   r*   r+   Útypero   Z	WSMsgTyperA   ZCLOSINGrB   rC   r¹   r¦   ÚServerDisconnectedErrorrs   r†   r   r;   r‡   rD   rE   rÐ   r   r   rI   r-   rJ   )r   rŽ   r±   r‘   r   r   r   r­   H  s„   €
þ

ÿü
ÿÿþ€ûÿ€üÚ(
ÿÿz AsyncClient._read_loop_websocketc              
   Ã   s   �| j dk�rt| j| jƒd }d}zt | j ¡ |¡I dH g}W n | jtj	fy4   | j
 d¡ Y nÑ tjy=   Y nÈw |dgkrK| j ¡  g }n)	 z
| | j ¡ ¡ W n
 | jy`   Y nw |d du rs|dd… }| j ¡  nqL|swnŽ| jdkrÅtj|d�}| jd	| j| ¡ d
di| jd�I dH }|D ]}| j ¡  q—|du s¨t|tƒr±| j
 |p®d¡ nT|jdk s»|jdkrÄ| j
 d|j¡ nAn;z&|D ]!}|jrÙ| j | ¡ ¡I dH  n| j | ¡ ¡I dH  | j ¡  qÈW n tj 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É   Nzpacket queue is empty, abortingTéÿÿÿÿr   )r   ÚPOSTzContent-Typez
text/plain)r»   r3   rc   rË   rd   re   rÌ   z5Write loop: WebSocket connection was closed, abortingzExiting write loop task)&r,   rÏ   rƒ   r„   r	   rÑ   rB   Úgetr[   r¹   r*   rp   rÆ   rZ   r…   rY   rF   r   r|   rt   rr   r¨   rv   r.   r/   r+   rx   ÚbinaryrG   Z
send_bytesr©   ro   r¦   rÓ   ÚBrokenPipeErrorÚOSErrorrs   rŠ   )r   rc   r   rŽ   rŒ   r‘   r   r   r   r‰     s„   €ÿ

ÿ
ø	
ýÿÿýû
ÿÿû
Ê<
zAsyncClient._write_loop)NNr   )FN)r   )NNN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r5   r7   r=   r   rO   rP   rS   rT   rV   rJ   ra   r’   rˆ   r‡   r:   rt   rD   r‹   r­   r‰   Ú__classcell__r   r   r^   r   r   /   s6    %
ÿ/

By
þ=*7r   )r	   Úhttp.cookiesr   rÀ   r'   r˜   r$   ro   ÚImportErrorÚ r   r   r   r   r#   ÚsetrÂ   r   Z
BaseClientr   r   r   r   r   Ú<module>   s&    ÿ