
    wg[j                        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
Z
	 d dlZddlmZ ddlmZ ddlmZ ddlmZ  ej$                  d	      Z G d
 dej(                        Zy# e$ r dZ
Y Nw xY w# e$ r dZY Vw xY w)    )	b64encode)JSONDecodeErrorN   )base_client)
exceptions)packet)payloadzengineio.clientc                       e Zd ZdZ	 	 ddZd Zd ZddZd ZddZ	d	 Z
d
 Zd Zd Zd Zd Z	 	 ddZd Zd Zd Zd Zy)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()``.
    :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.
    Nc                 B   | j                   dk7  rt        d      ddg}|3t        |t              r|g}|D cg c]  }||v r|
 }}|st        d      |xs || _        | j                         | _         t        | d| j                  d   z         ||xs i |      S c c}w )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	websocketzNo valid transports provided	_connect_r   )state
ValueError
isinstancestr
transportscreate_queuequeuegetattr)selfurlheadersr   engineio_pathvalid_transports	transports          T/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/engineio/client.pyconnectzClient.connect>   s    * ::'DEE%{3!*c*(\
5? <	&*:: $ <J < !?@@$8(8&&(
>wt[4??1+==>B/ 	/<s   Bc                 R    | j                   r| j                   j                          yy)zWait 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   s    r   waitzClient.waitb   s$     $$&     c                 l    | j                  t        j                  t        j                  |             y)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(   s     r   sendzClient.sendk   s!     	&--TBCr%   c                 8   | j                   dk(  r| j                  t        j                  t        j                               | j
                  j                  d       d| _         | j                  d|xs | j                  j                  d       | j                  dk(  r| j                  j                          |s| j                  j                          d| _         	 t        j                   j#                  |        | j'                          y# t$        $ r Y w xY w)	zDisconnect from the server.

        :param abort: If set to ``True``, do not wait for background tasks
                      associated with the connection to end.
        	connectedNdisconnecting
disconnectF	run_asyncr   r   )r   r)   r   r*   CLOSEr   put_trigger_eventreasonCLIENT_DISCONNECTcurrent_transportwscloser"   r#   r   connected_clientsremover   _reset)r   abortr6   s      r   r0   zClient.disconnectt   s     ::$fmmFLL9:JJNN4 (DJ & G$++*G*G*/   1 %%4##((*'DJ--44T: 	  s   D 	DDc                 X    t        j                  |||d      }|j                          |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@   rA   rB   ths        r   start_background_taskzClient.start_background_task   s+     V$v%)+

	r%   c                 ,    t        j                  |      S )z'Sleep for the requested amount of time.)timesleep)r   secondss     r   rK   zClient.sleep   s    zz'""r%   c                 Z    t        j                  |i |}t         j                  |_        |S )zCreate a queue object.)r   QueueEmpty)r   rA   rB   qs       r   r   zClient.create_queue   s%    KK((++r%   c                 ,    t        j                  |i |S )zCreate an event object.)rD   Event)r   rA   rB   s      r   create_eventzClient.create_event   s    ///r%   c                    t         | j                  j                  d       y| j                  ||d      | _        | j                  j                  d| j                  z          | j                  d| j                  | j                         z   || j                        }|t        |t              r)| j                          t        j                  |xs d      |j                  dk  s|j                  d	k\  rP| j                          	 |j                         }t        j                  d
j#                  |j                        |      	 t%        j&                  |j(                  j+                  d            }|j.                  d   }|j0                  t2        j4                  k7  rt        j                  d      | j                  j                  dt        |j6                        z          |j6                  d   | _        |j6                  d   | _        t=        |j6                  d         dz  | _        t=        |j6                  d         dz  | _         d| _!        | xj                  d| j8                  z   z  c_        d| _"        tF        jH                  jK                  |        | jM                  dd       |j.                  dd D ]  }| jO                  |        d| j:                  v r"d| jP                  v r| jS                  |||      ry| jU                  | jV                        | _,        | jU                  | jZ                        | _.        y# t         $ r d}Y ?w xY w# t,        $ r t        j                  d      dw xY w)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encoded_payloadzUnexpected response from serverr   z"OPEN packet not returned by serverz!Polling connection accepted with sidupgradespingInterval     @@pingTimeout&sid=r.   r    Fr1   r   r   )/requestsloggererror_get_engineio_urlbase_urlinfo_send_request_get_url_timestamprequest_timeoutr   r   r=   r   ConnectionErrorstatus_codejsonr   formatr	   Payloadcontentdecoder   packetspacket_typer   OPENr(   r\   r]   intping_intervalping_timeoutr8   r   r   r;   appendr5   _receive_packetr   _connect_websocketrH   _write_loopwrite_loop_task_read_loop_pollingr"   )	r   r   r   r   rargpopen_packetpkts	            r   _connect_pollingzClient._connect_polling   s   KK 4 5..sM9M<t}}LM4==4#:#:#<<g((  * 9
1c*KKM,,779 9==3!--3"6KKMffh ,,>EEMM#$') )	=		0@0@0IJA iil""fkk1,,46 6/#k6F6F2GG	I##E*#((4 !1!1.!ABVK 0 0 ?@6I!*488++ 
%%,,T2I799QR= 	&C  %	& $--'K4??,J&&sG]C  $99$:J:JK"88##%M #   	=,,138<=	=s   M /M MM M:c                 "   t         | j                  j                  d       y| j                  ||d      }| j                  r3| j                  j                  d|z          d}|d| j                  z   z  }n'd}|| _        | j                  j                  d|z          d}i }| j                  rd	j                  | j                  j                  D cg c]  }|j                   d
|j                    c}      }|j                         D ])  \  }	}
|	j                         dk(  s|r|d	z  }||
z  }||	=  n d|vr| j                  j                  t        | j                  j                  t               st#        d      dj%                  | j                  j                  d   | j                  j                  d         j'                  d      }t)        |      j+                  d      }d|z   |d<   t        | j                  j,                  t               r7| j                  j,                  d   | j                  j,                  d   d|d<   n1| j                  j,                  rd| j                  j,                  i|d<   | j                  j.                  r#d}|j1                  d      rJ| j                  j.                  j3                  d| j                  j.                  j3                  d            }nI| j                  j.                  j3                  d| j                  j.                  j3                  d            }|r{t4        j6                  j9                  d|v r|nd|z         }|j:                  |d<   |j<                  |d<   |j>                  s|j@                  r|j>                  |j@                  fnd|d<   t        | j                  jB                  tD              r=d|v r| j                  jB                  |d   d <   n9d | j                  jB                  i|d<   n| j                  jB                  sd| _#        | jF                  s>d|v r%|d   jI                  d!tJ        jL                  i       nd!tJ        jL                  i|d<   |jI                  | jN                  jQ                  d"i              ||d"<   ||d<   d|d#<   | jR                  |d$<   |jI                  | jN                         	 t        jT                  || jW                         z   fi |}|rtc        jd                  tb        jf                  d'(      j'                         }	 |ji                  |       	 |jm                         }tc        jd                  |+      }|jn                  tb        jp                  k7  s|jr                  d'k7  r| j                  j_                  d,       ytc        jd                  tb        jt                        j'                         }	 |ji                  |       d| _;        | j                  j                  d-       n2	 |jm                         }tc        jd                  |+      }|jn                  tb        jx                  k7  rta        jX                  d/      | j                  j                  d0tE        |jr                        z          |jr                  d1   | _        |jr                  d2   | _=        t}        |jr                  d3         d4z  | _?        t}        |jr                  d5         d4z  | _@        d| _;        d6| _A        t        j                  j                  |        | j                  d7d8       || _F        | j                  j                  | j~                  | j                  z          | j                  | j                        | _J        | j                  | j                        | _L        yc c}w # tX        tZ        t         j\                  f$ r5 |r| j                  j_                  d%       Y yta        jX                  d&      w xY w# tj        $ r/}| j                  j_                  d)tE        |             Y d}~yd}~ww xY w# tj        $ r/}| j                  j_                  d*tE        |             Y d}~yd}~ww xY w# tj        $ r/}| j                  j_                  d)tE        |             Y d}~yd}~ww xY w# tj        $ r&}ta        jX                  d.tE        |      z         d}~ww xY w)9z?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 Tra   z#Attempting WebSocket connection to z; =cookieAuthorizationz&Only basic authentication is supportedz{}:{}r   r   rY   zBasic )certfilekeyfilessloptr   zws://r9   httpwsshttpsz://z	scheme://http_proxy_hosthttp_proxy_porthttp_proxy_authca_certs	cert_reqsheader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    r1   )Mr   rc   rd   re   r\   rg   rf   r   r#   cookiesnamevalueitemslowerauthr   tupler   rn   encoder   rq   certproxies
startswithgeturllibparseurlparsehostnameportusernamepasswordverifyr   
ssl_verifyupdatessl	CERT_NONEwebsocket_extra_optionspoprj   create_connectionri   rk   OSErrorWebSocketExceptionwarningr   r   r*   PINGr,   	Exceptionrecvrs   PONGr(   UPGRADEr8   rt   r]   ru   rv   rw   r   r   r;   rx   r5   r9   
settimeoutrH   r{   r|   _read_loop_websocketr"   )r   r   r   r   websocket_urlupgrader   extra_optionsr   r   r   
basic_auth	proxy_url
parsed_urlr9   r   er   r   s                      r   rz   zClient._connect_websocket   s   KK ? @..sM;O88KK2]BDGWtxx//MG)DMKK5EG
 99ii/3yy/@/@!B%+ %+KK=&,,!@ !B CG!( <<>X-4u$G g-$))..2L!$))..%8$%MNN$^^IINN1%tyy~~a'8::@&/ &z299'B
+3j+@( $))..%0 $		q 1#yy~~a0+2h' +5tyy~~*Fh' yy   	 ++G4 $		 1 1 5 5dii//33F;!=I !%		 1 1 5 5tyy0044W=!?I!'!6!6%*i%7	(94"6J 8B7J7JM"347AM"34 &..*2E2E $,,j.A.AB! ""34 $))**C0},:>)):J:JM(+J7/9499;K;K.LM(+YY%%"'=(h'..S]]/KL+6*Fh' 	t3377"EF")h")h.2*+#'#7#7i T99:		E,, 7 7 99L=JLB fkk8??AA
GGI --q1C&++-W1D##>@fnn-446A
 &1D"KK?@<GGI !--q9K&&&++5 001ABBKK5K<L<L8MMO"''.DH',,Z8DM!$[%5%5n%E!F!OD #K$4$4]$C Dv MD%0D"$DJ))006	U;4--0A0AAB  $99$:J:JK"88%%'W!BT  )*F*FG 	E##@B 001CDD	E  ##MF 	  ##MF 	  ##MF 	  < 001CF:< <<sx   "_"'_  `. a) 2b$ (c ;`+`+.	a&7%a!!a&)	b!2%bb!$	c-%cc	d(!d		dc                 T   |j                   t        t        j                        k  rt        j                  |j                      nd}| j                  j                  d|t        |j                  t              s|j                  nd       |j                   t        j                  k(  r| j                  d|j                  d       y	|j                   t        j                  k(  r>| j                  t        j                  t        j                  |j                               y	|j                   t        j                  k(  r(| j!                  d| j"                  j$                         y	|j                   t        j&                  k(  ry	| j                  j)                  d|j                          y	)
z(Handle incoming packets from the server.UNKNOWNzReceived packet %s data %s<binary>messageTr1   )r>   r6   z%Received unexpected packet of type %sN)rs   lenr   packet_namesrc   rg   r   r(   bytesr+   r5   r   r)   r*   r   r3   r0   r6   SERVER_DISCONNECTNOOPrd   )r   r   packet_names      r   ry   zClient._receive_packet  s    V%8%8!99 ))#//:?H 	(+&sxx7CHHZ	I ??fnn,	388tD__+fmmFKKBC__,OO$t{{/L/LOM__+KKE!oo/r%   c                     | j                   dk7  ry| j                  j                  |       | j                  j	                  dt
        j                  |j                     t        |j                  t              s|j                         yd       y)z(Queue a packet to be sent to the server.r.   NzSending packet %s data %sr   )r   r   r4   rc   rg   r   r   rs   r   r(   r   )r   r   s     r   r)   zClient._send_packet  si    ::$

s'0&sxx7CHH	I >H	Ir%   c                 n   | j                   t        j                         | _         | j                  sd| j                   _        	 | j                   j                  |||||      S # t        j                  j                  $ r3}| j                  j                  d|||       t        |      cY d }~S d }~ww xY w)NF)r   r(   rV   z+HTTP %s request to %s failed with error %s.)r   rb   Sessionr   r   requestr   RequestExceptionrc   rg   r   )r   methodr   r   bodyrV   excs          r   rh   zClient._send_request  s     99 ((*DI$DII	99$$VS'-4 % 6 6""33 	KKJ#S#/s8O	s   A$ $B4(B/)B4/B4c                 h   |j                  dd      }|| j                  v r6|r  | j                  | j                  |   g| S 	 	  | j                  |   | S y# t        $ r+ |dk(  r$t	        |      dk(  r | j                  |          cY S  w xY w#  | j
                  j                  |dz          Y yxY w)zInvoke an event handler.r2   Fr0   r   z handler errorN)r   handlersrH   	TypeErrorr   rc   	exception)r   eventrA   rB   r2   s        r   r5   zClient._trigger_event  s    JJ{E2	DMM!1t11$--2FNNND	"3t}}U3T:: " % " L0 #D	Q $84==#7#99!"DKK))%2B*BCs$   A 0BB 
BB  B1c                    | j                   dk(  r| j                  r| j                  j                  d| j                  z          | j                  d| j                  | j                         z   t        | j                  | j                        dz         }|t        |t              r;| j                  j                  |xs d       | j                  j                  d       n|j                  dk  s|j                  d	k\  rB| j                  j                  d
|j                         | j                  j                  d       no	 t!        j"                  |j$                  j'                  d            }|j*                  D ]  }| j-                  |        | j                   dk(  r| j                  r| j                  r5| j                  j                  d       | j                  j/                          | j                   dk(  rX| j1                  d| j2                  j4                  d       	 t6        j8                  j;                  |        | j=                          | j                  j                  d       y# t(        $ r: | j                  j                  d       | j                  j                  d       Y w xY w# t(        $ r Y }w xY w)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 endr0   Fr1   Exiting read loop task)r   r|   rc   rg   rf   rh   ri   maxrv   rw   r   r   r   r   r4   rl   r	   ro   rp   rq   r   rr   ry   r#   r5   r6   TRANSPORT_ERRORr   r;   r<   r=   )r   r~   r   r   s       r   r}   zClient._read_loop_polling  sC   jjK'D,@,@KK1DMMAC""t}}t'>'>'@@D..0A0ABQF # HA yJq#.##EEG

t$}}s"amms&:## %9:;--I

t$OOAII4D4DW4MN yy *$$S)*/ jjK'D,@,@4 KKAB  %%'::$dkk.I.I*/   1--44T: KKM12'  ##=?

t$	   s$   /I6 +J< 6?J98J9<	KKc                    | j                   dk(  rd}	 | j                  j                         }t        |      dk(  r*| j                  j                  st        j                         	 t%        j&                  |	      }| j)                  |       | j                   dk(  r| j*                  r5| j                  j!                  d       | j*                  j-                          | j                   dk(  rX| j/                  d| j0                  j2                  d       	 t4        j6                  j9                  |        | j=                          | j                  j!                  d       y# t
        j                  $ r: | j                  j                  d       | j                  j                  d       Y t
        j                  $ r: | j                  j                  d       | j                  j                  d       Y [t        $ r}t        |      t        u r+|j                  dk(  r| j                  j!                  d       n%| j                  j!                  dt#        |             | j                  j                  d       Y d}~d}~ww xY w# t        $ rK}| j                  j!                  d
t#        |             | j                  j                  d       Y d}~<d}~ww xY w# t:        $ r Y w xY w)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   r0   Fr1   r   )r   r9   r   r   r.   r   "WebSocketConnectionClosedExceptionWebSocketTimeoutExceptionrc   r   r   r4   r   typer   errnorg   r   r   r*   ry   r|   r#   r5   r6   r   r   r;   r<   r   r=   )r   r   r   r   s       r   r   zClient._read_loop_websocket  sJ   jjK'AGGLLNq6Q;tww'8'8#FFHH*mm15   %E jjK'H KKAB  %%'::$dkk.I.I*/   1--44T: KKM12Q 66 ##@B

t$?? ##?A

t$ 	7g%!''Q,KK$$CE KK$$KA  

t$	    FAP

t$	  sR   AE! &J
 K! !A	J-AJ8J A<JJ
	KA KK!	K.-K.c                    | j                   dk(  rBt        | j                  | j                        dz   }d}	 | j                  j                  |      g}|dgk(  r| j                  j                          g }nS	 	 |j                  | j                  j                  d             |d    |dd }| j                  j                          nR|sn| j                  d	k(  rt        j                  |
      }| j                  d| j                  |j!                         ddi| j"                        }|D ]  }| j                  j                           |t%        |t&              r | j                  j)                  |xs d       n|j*                  dk  s|j*                  dk\  r| j                  j)                  d|j*                         d| _        n	 |D ]o  }|j!                         }|j.                  r| j0                  j3                  |       n| j0                  j5                  |       | j                  j                          q 	 | j                   dk(  rB| j                  j?                  d       y# | j                  j                  $ r | j                  j                  d       Y Rw xY w# | j                  j                  $ r Y w xY w# t6        j8                  t:        t<        f$ r | j                  j)                  d       Y w xY w)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)blockr   )rr   POSTzContent-Typez
text/plain)r   r   rV   r   rW   rX   r   r   zExiting write loop task) r   r   rv   rw   r   r   rO   rc   rd   	task_donerx   r8   r	   ro   rh   rf   r   rj   r   r   r   rl   r|   binaryr9   send_binaryr,   r   r   BrokenPipeErrorr   rg   )r   rV   rr   r   r~   r   r   s          r   r{   zClient._write_loop-  s    jjK' $,,d.?.?@1DGG::>>'>:; 4& 

$$&tzz~~E~'BC r{*")#2,

,,.  %%2OOG4&&DMM
+\: 00 ' 2 # +CJJ((*+9
1c 2KK''IIK==3&!--3*>KK'' )=>?mmM+/D(& /),:: GG//? GGLL8

,,./_ jjK'v 	23g ::## !!"CD  ::++ H "DD'2 KK''CE	s6   I/ 9+J) A4K	 /4J&%J&)KK	9LL)NNz	engine.io)FN)r   )NNN)__name__
__module____qualname____doc__r    r$   r,   r0   rH   rK   r   rS   r   rz   ry   r)   rh   r5   r}   r   r{    r%   r   r   r      sv    "F 59)"/H'D0&#0;%zdL/&I 37D*'3R13f?4r%   r   )base64r   engineio.jsonr   loggingr   r   rD   rJ   r   rb   ImportErrorr    r   r   r   r	   	getLoggerdefault_logger
BaseClientr   r   r%   r   <module>r      s     )   
       """#45R	4[## R	4  H  Is"   A/ A< /A98A9<BB