
    Ii[j                        S SK Jr  S SKJr  S SKrS SKrS SKrS SKrS SKrS SK	r	 S SK
r
 S SKrSSKJr  SSKJr  SSKJr  SSKJr  \R$                  " S	5      r " S
 S\R(                  5      rg! \ a    Sr
 NOf = f! \ a    Sr NXf = f)    )	b64encode)JSONDecodeErrorN   )base_client)
exceptions)packet)payloadzengineio.clientc                       \ rS rSrSr  SS jrS rS rSS jrS r	SS	 jr
S
 rS rS rS rS rS r  SS jrS rS rS rS rSrg)Client   a	  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                 x   U R                   S:w  a  [        S5      eSS/nUbC  [        U[        5      (       a  U/nU Vs/ s H  nXe;   d  M
  UPM     nnU(       d  [        S5      eU=(       d    UU l        U R                  5       U l        [        U SU R                  S   -   5      " X=(       d    0 U5      $ s  snf )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          5/venv/lib/python3.13/site-packages/engineio/client.pyconnectClient.connect>   s    * ::'DEE%{3!*c**(\
5? <Z	&: $ZJ < !?@@$8(8&&(
t[4??1+==>B/ 	/<s   	B7B7c                 \    U R                   (       a  U R                   R                  5         gg)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    waitClient.waitb   s$     $$&     c                 h    U R                  [        R                  " [        R                  US95        g)zSend 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    sendClient.sendk   s!     	&--TBCr(   c                 N   U R                   S:X  a  U R                  [        R                  " [        R                  5      5        U R
                  R                  S5        SU l         U R                  SU=(       d    U R                  R                  SS9  U R                  S:X  a  U R                  R                  5         U(       d  U R                  R                  5         SU l          [        R                   R#                  U 5        U R'                  5         g! [$         a     Nf = f)	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   abortr:   s      r    r4   Client.disconnectt   s     ::$fmmFLL9:JJNN4 (DJ & G$++*G*G*/   1 %%4##((*'DJ--44T: 	  s   'D 
D$#D$c                 R    [         R                  " XUSS9nUR                  5         U$ )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   rE   rF   rG   ths        r    start_background_taskClient.start_background_task   s)     Vv%)+

	r(   c                 .    [         R                  " U5      $ )z'Sleep for the requested amount of time.)timesleep)r   secondss     r    rQ   Client.sleep   s    zz'""r(   c                 \    [         R                  " U0 UD6n[         R                  Ul        U$ )zCreate a queue object.)r   QueueEmpty)r   rF   rG   qs       r    r   Client.create_queue   s%    KK((++r(   c                 .    [         R                  " U0 UD6$ )zCreate an event object.)rI   Event)r   rF   rG   s      r    create_eventClient.create_event   s    ///r(   c                 &   [         c  U R                  R                  S5        gU R                  XS5      U l        U R                  R                  SU R                  -   5        U R                  SU R                  U R                  5       -   UU R                  S9nUb  [        U[        5      (       a/  U R                  5         [        R                  " U=(       d    S5      eUR                  S:  d  UR                  S	:  aQ  U R                  5          UR                  5       n[        R                  " S
R#                  UR                  5      U5      e [$        R&                  " UR(                  R+                  S5      S9nUR.                  S   nUR0                  [2        R4                  :w  a  [        R                  " S5      eU R                  R                  S[        UR6                  5      -   5        UR6                  S   U l        UR6                  S   U l        [=        UR6                  S   5      S-  U l        [=        UR6                  S   5      S-  U l         SU l!        U =R                  SU R8                  -   -  sl        SU l"        [F        RH                  RK                  U 5        U RM                  SSS9  UR.                  SS  H  nU RO                  U5        M     SU R:                  ;   a(  SU RP                  ;   a  U RS                  XU5      (       a  gU RU                  U RV                  5      U l,        U RU                  U RZ                  5      U l.        g! [          a    Sn GNHf = f! [,         a    [        R                  " S5      Sef = f)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=r2   r!   Fr5   r   r   )/requestsloggererror_get_engineio_urlbase_urlinfo_send_request_get_url_timestamprequest_timeoutr   r   rA   r   ConnectionErrorstatus_codejsonr   formatr	   Payloadcontentdecoder   packetspacket_typer   OPENr+   re   rf   intping_intervalping_timeoutr<   r   r   r?   appendr9   _receive_packetr   _connect_websocketrM   _write_loopwrite_loop_task_read_loop_pollingr$   )	r   r   r   r   rargpopen_packetpkts	            r    _connect_pollingClient._connect_polling   s   KK 4 5..s9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&&s]CC  $99$:J:JK"88##%M #   	=,,138<=	=s   M -M. M+*M+."Nc                    [         c  U R                  R                  S5        gU R                  XS5      nU R                  (       a3  U R                  R                  SU-   5        SnUSU R                  -   -  nO&SnX@l        U R                  R                  SU-   5        Sn0 nU R                  (       Ga  S	R                  U R                  R                   Vs/ s H  nUR                   S
UR                   3PM      sn5      nUR                  5        H-  u  pU	R                  5       S:X  d  M  U(       a  US	-  nXj-  nX)	   O   SU;  a  U R                  R                  b  [        U R                  R                  [         5      (       d  [#        S5      eSR%                  U R                  R                  S   U R                  R                  S   5      R'                  S5      n[)        U5      R+                  S5      nSU-   US'   [        U R                  R,                  [         5      (       a7  U R                  R,                  S   U R                  R,                  S   S.US'   O6U R                  R,                  (       a  SU R                  R,                  0US'   U R                  R.                  (       Ga9  SnUR1                  S5      (       aJ  U R                  R.                  R3                  SU R                  R.                  R3                  S5      5      nOIU R                  R.                  R3                  SU R                  R.                  R3                  S5      5      nU(       a  [4        R6                  R9                  SU;   a  UOSU-   5      nUR:                  US'   UR<                  US'   UR>                  (       d  UR@                  (       a  UR>                  UR@                  4OSUS'   [        U R                  RB                  [D        5      (       a?  SU;   a  U R                  RB                  US   S '   O>S U R                  RB                  0US'   O"U R                  RB                  (       d  SU l#        U RF                  (       d@  SU;   a%  US   RI                  S![J        RL                  05        OS![J        RL                  0US'   URI                  U RN                  RQ                  S"0 5      5        X'S"'   XgS'   SUS#'   U RR                  US$'   URI                  U RN                  5         [         RT                  " X@RW                  5       -   40 UD6nU(       Ga  [b        Rd                  " [b        Rf                  S'S(9R'                  5       n URi                  U5         URm                  5       n[b        Rd                  " US+9nURn                  [b        Rp                  :w  d  URr                  S':w  a  U R                  R_                  S,5        g[b        Rd                  " [b        Rt                  5      R'                  5       n URi                  U5        SU l;        U R                  R                  S-5        GO/ URm                  5       n[b        Rd                  " US+9nURn                  [b        Rx                  :w  a  [`        RX                  " S/5      eU R                  R                  S0[E        URr                  5      -   5        URr                  S1   U l        URr                  S2   U l=        [}        URr                  S3   5      S4-  U l?        [}        URr                  S5   5      S4-  U l@        SU l;        S6U lA        [        R                  R                  U 5        U R                  S7SS89  XlF        U R                  R                  U R~                  U R                  -   5        U R                  U R                  5      U lJ        U R                  U R                  5      U lL        gs  snf ! [X        [Z        [         R\                  4 a;    U(       a  U R                  R_                  S%5         g[`        RX                  " S&5      ef = f! [j         a/  nU R                  R_                  S)[E        U5      5         SnAgSnAff = f! [j         a/  nU R                  R_                  S*[E        U5      5         SnAgSnAff = f! [j         a/  nU R                  R_                  S)[E        U5      5         SnAgSnAff = f! [j         a'  n[`        RX                  " S.[E        U5      -   5      eSnAff = f)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 Trj   z#Attempting WebSocket connection to z; =cookieAuthorizationz&Only basic authentication is supportedz{}:{}r   r   rb   zBasic )certfilekeyfilessloptr   zws://r=   httpwsshttpsz://z	scheme://http_proxy_hosthttp_proxy_porthttp_proxy_authca_certs	cert_reqsheaderenable_multithreadr_   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 re   rf   rg   rh   ri   r2   r!   r5   )Mr   rl   rm   rn   re   rp   ro   r   r%   cookiesnamevalueitemslowerauthr   tupler   rw   encoder   rz   certproxies
startswithgeturllibparseurlparsehostnameportusernamepasswordverifyr   
ssl_verifyupdatessl	CERT_NONEwebsocket_extra_optionspoprs   create_connectionrr   rt   OSErrorWebSocketExceptionwarningr   r   r-   PINGr/   	Exceptionrecvr|   PONGr+   UPGRADEr<   r}   rf   r~   r   r   r   r   r?   r   r9   r=   
settimeoutrM   r   r   _read_loop_websocketr$   )r   r   r   r   websocket_urlupgrader   extra_optionsr   r   r   
basic_auth	proxy_url
parsed_urlr=   r   er   r   s                      r    r   Client._connect_websocket   s   KK ? @..s;O88KK2]BDGWtxx//MG)MKK5EG
 999ii/3yy/@/@!B/@V %+KK=&,,!@/@!B CG!(<<>X-4$G "1 g-$))..2L!$))..%88$%MNN$^^IINN1%tyy~~a'8::@&/ &z299'B
+3j+@( $))..%00 $		q 1#yy~~a0+2h' +5tyy~~*Fh' yy    	 ++G4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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:< <<sy   %`"1'`' b $c  c< ;d8 'Ab*b
b=%b88b= 
c9
%c44c9<
d5%d00d58
e)"e$$e)c                 ^   UR                   [        [        R                  5      :  a  [        R                  UR                      OSnU R                  R                  SU[        UR                  [        5      (       d  UR                  OS5        UR                   [        R                  :X  a  U R                  SUR                  SS9  g	UR                   [        R                  :X  a?  U R                  [        R                  " [        R                  UR                  5      5        g	UR                   [        R                  :X  a%  U R!                  SU R"                  R$                  S9  g	UR                   [        R&                  :X  a  g	U R                  R)                  SUR                   5        g	)
z(Handle incoming packets from the server.UNKNOWNzReceived packet %s data %s<binary>messageTr5   )rB   r:   z%Received unexpected packet of type %sN)r|   lenr   packet_namesrl   rp   r   r+   bytesr.   r9   r   r,   r-   r   r7   r4   r:   SERVER_DISCONNECTNOOPrm   )r   r   packet_names      r    r   Client._receive_packet  s    V%8%8!99 ))#//:?H 	(+&sxx77CHHZ	I ??fnn,	388tD__+fmmFKKBC__,OO$t{{/L/LOM__+KKE!oo/r(   c                 ,   U R                   S:w  a  gU R                  R                  U5        U R                  R	                  S[
        R                  UR                     [        UR                  [        5      (       d  UR                  5        gS5        g)z(Queue a packet to be sent to the server.r2   NzSending packet %s data %sr   )r   r   r8   rl   rp   r   r   r|   r   r+   r   )r   r   s     r    r,   Client._send_packet  sl    ::$

s'0&sxx77CHH	I >H	Ir(   c                 r   U R                   c  [        R                  " 5       U l         U R                  (       d  SU R                   l         U R                   R                  XX4US9$ ! [        R                  R                   a2  nU R                  R                  SXU5        [        U5      s S nA$ S nAff = f)NF)r   r+   r_   z+HTTP %s request to %s failed with error %s.)r   rk   Sessionr   r   requestr   RequestExceptionrl   rp   r   )r   methodr   r   bodyr_   excs          r    rq   Client._send_request  s     99 ((*DI$DII	99$$V'-4 % 6 6""33 	KKJ##/s8O	s   A& &B6'B1+B61B6c                 z   UR                  SS5      nXR                  ;   a;  U(       a   U R                  " U R                  U   /UQ76 $   U R                  U   " U6 $ g! [         a-    US:X  a%  [	        U5      S:X  a  U R                  U   " 5       s $ e f = f!   U R
                  R                  US-   5         g= f)zInvoke an event handler.r6   Fr4   r   z handler errorN)r   handlersrM   	TypeErrorr   rl   	exception)r   eventrF   rG   r6   s        r    r9   Client._trigger_event  s    JJ{E2	MM!11$--2FNNND	"#}}U3T:: " % " L0 #D	Q $(==#7#99!"DKK))%2B*BCs$   A 3BB BB  B:c                    U R                   S:X  Ga  U R                  (       Ga  U R                  R                  SU R                  -   5        U R                  SU R                  U R                  5       -   [        U R                  U R                  5      S-   S9nUb  [        U[        5      (       a@  U R                  R                  U=(       d    S5        U R                  R                  S5        OUR                  S:  d  UR                  S	:  aB  U R                  R                  S
UR                  5        U R                  R                  S5        Ov [         R"                  " UR$                  R'                  S5      S9nUR*                   H  nU R-                  U5        M     U R                   S:X  a  U R                  (       a  GM  U R                  (       a5  U R                  R                  S5        U R                  R/                  5         U R                   S:X  aU  U R1                  SU R2                  R4                  SS9   [6        R8                  R;                  U 5        U R=                  5         U R                  R                  S5        g! [(         a;    U R                  R                  S5        U R                  R                  S5         GM  f = f! [(         a     Nf = f)z-Read packets by polling the Engine.IO server.r2   zSending polling GET request to r^      r_   N*Connection refused by the server, abortingr`   ra   6Unexpected status code %s in server response, abortingrb   rc   z'Unexpected packet from server, aborting"Waiting for write loop task to endr4   Fr5   Exiting read loop task)r   r   rl   rp   ro   rq   rr   maxr   r   r   r   r   r   r8   ru   r	   rx   ry   rz   r   r{   r   r%   r9   r:   TRANSPORT_ERRORr   r?   r@   rA   )r   r   r   r   s       r    r   Client._read_loop_polling  sG   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%   -J K A KK
K%$K%c                    U R                   S:X  a  Sn U R                  R                  5       n[        U5      S:X  a0  U R                  R                  (       d  [
        R                  " 5       e [$        R&                  " US	9nU R)                  U5        U R                   S:X  a  M  U R*                  (       a5  U R                  R!                  S5        U R*                  R-                  5         U R                   S:X  aU  U R/                  SU R0                  R2                  SS9   [4        R6                  R9                  U 5        U R=                  5         U R                  R!                  S5        g! [
        R                   a;    U R                  R                  S5        U R                  R                  S5         GM  [
        R                   a;    U R                  R                  S5        U R                  R                  S5         GMb  [         a  n[        U5      [        L a,  UR                  S:X  a  U R                  R!                  S5        O%U R                  R!                  S[#        U5      5        U R                  R                  S5         SnAGM  SnAff = f! [         aL  nU R                  R!                  S
[#        U5      5        U R                  R                  S5         SnAGMI  SnAff = f! [:         a     GNf = f)z5Read packets from the Engine.IO WebSocket connection.r2   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   r4   Fr5   r   )r   r=   r   r   r2   r   "WebSocketConnectionClosedExceptionWebSocketTimeoutExceptionrl   r   r   r8   r   typer   errnorp   r   r   r-   r   r   r%   r9   r:   r   r   r?   r@   r   rA   )r   r   r   r   s       r    r   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 !K6 ,A
J:A	J	JA>JJ
K3'A K..K36
LLc                 J   U R                   S:X  GaX  [        U R                  U R                  5      S-   nSn U R                  R                  US9/nUS/:X  a  U R                  R                  5         / nOR  UR                  U R                  R                  SS95        US   c   USS nU R                  R                  5         OMQ  U(       d  GOU R                  S	:X  a  [        R                  " US
9nU R                  SU R                  UR!                  5       SS0U R"                  S9nU H  nU R                  R                  5         M     Ub  [%        U[&        5      (       a%  U R                  R)                  U=(       d    S5        OUR*                  S:  d  UR*                  S:  a.  U R                  R)                  SUR*                  5        SU l        OO| U Hu  nUR!                  5       nUR.                  (       a  U R0                  R3                  U5        OU R0                  R5                  U5        U R                  R                  5         Mw     U R                   S:X  a  GMX  U R                  R?                  S5        g! U R                  R                   a    U R                  R                  S5         MT  f = f! U R                  R                   a     GM  f = f! [6        R8                  [:        [<        4 a    U R                  R)                  S5         M  f = f)zXThis background task sends packages to the server as they are
pushed to the send queue.
r2   r   Nr   zpacket queue is empty, abortingF)blockr   )r{   POSTzContent-Typez
text/plain)r   r   r_   r   r`   ra   r   r   zExiting write loop task) r   r   r   r   r   r   rV   rl   rm   	task_doner   r<   r	   rx   rq   ro   r   rs   r   r   r   ru   r   binaryr=   send_binaryr/   r   r   BrokenPipeErrorr   rp   )r   r_   r{   r   r   r   r   s          r    r   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 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   J 8(K A;K$ 5J?>J?K! K!$:L"!L")ro   r<   r   r   r   r   r$   re   r   r   r   rf   r   r=   )NNz	engine.io)FN)r   )NNN)__name__
__module____qualname____firstlineno____doc__r!   r&   r/   r4   rM   rQ   r   r[   r   r   r   r,   rq   r9   r   r   r   __static_attributes__ 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   rI   rP   r   rk   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= /A:9A:=BB