
    !nil                        d dl mZ d dlmZ d dlZd dlZd dlZd dlZd dlZd dl	Z	d dl
mZ 	 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)SimpleCookieN)JSONDecodeError   )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 fdZd Zd Zd Zd Z	 	 ddZd Zd Zd Zd Z xZ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()``.
    :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                    | j                   dk7  rt        d      ddg}|3t        |t              r|g}|D cg c]  }||v r|
 }}|st        d      |xs || _         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getattr)selfurlheadersr   engineio_pathvalid_transports	transports          O/home/homepc/tiktok-worker/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*   CLOSEqueueput_trigger_eventreasonCLIENT_DISCONNECTcurrent_transportwscloser!   r"   r   connected_clientsremover   _reset)r   abortr7   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   rA   rB   rC   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   rL   zClient.sleep   s    zz'""r%   c                 ,    t        j                  |i |S )zCreate a queue object.)r4   Queuer   rB   rC   s      r   create_queuezClient.create_queue   s    {{D+F++r%   c                 "    t         j                  S )zlReturn the queue empty exception raised by queues created by the
        ``create_queue()`` method.
        )r4   Emptyr#   s    r   get_queue_empty_exceptionz Client.get_queue_empty_exception   s     {{r%   c                 ,    t        j                  |i |S )zCreate an event object.)rE   EventrP   s      r   create_eventzClient.create_event   s    ///r%   c                     t         |           	 	 | j                  j                          | j                  j	                          6# | j
                  $ r Y y w xY w)N)superr>   r4   
get_nowait	task_donequeue_empty)r   	__class__s    r   r>   zClient._reset   sT    

%%'

$$&  ## s   4A AA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(   rf   rg   intping_intervalping_timeoutr9   r   r   r<   appendr6   _receive_packetr   _connect_websocketrI   _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                  rt               }| j                  j                  D ]  }	|	j                  ||	j                  <    |j                  d	d
      j                         }|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                  j0                  t$              r7| j                  j0                  d   | j                  j0                  d   d|d<   n1| j                  j0                  rd| j                  j0                  i|d<   | j                  j2                  r#d}|j5                  d      rJ| j                  j2                  j7                  d| j                  j2                  j7                  d            }nI| j                  j2                  j7                  d| j                  j2                  j7                  d            }|r{t8        j:                  j=                  d|v r|nd|z         }|j>                  |d<   |j@                  |d <   |jB                  s|jD                  r|jB                  |jD                  fnd|d!<   t#        | j                  jF                  tH              r=d|v r| j                  jF                  |d   d"<   n9d"| j                  jF                  i|d<   n| j                  jF                  sd| _%        | jJ                  s>d|v r%|d   jM                  d#tN        jP                  i       nd#tN        jP                  i|d<   |jM                  | jR                  jU                  d$i              ||d$<   ||d<   d|d%<   | jV                  |d&<   |jM                  | jR                         	 t        jX                  || j[                         z   fi |}|rtg        jh                  tf        jj                  d)*      j+                         }	 |jm                  |       	 |jq                         }tg        jh                  |-      }|jr                  tf        jt                  k7  s|jv                  d)k7  r| j                  jc                  d.       ytg        jh                  tf        jx                        j+                         }	 |jm                  |       d| _=        | j                  j                  d/       n2	 |jq                         }tg        jh                  |-      }|jr                  tf        j|                  k7  rte        j\                  d1      | j                  j                  d2tI        |jv                        z          |jv                  d3   | _        |jv                  d4   | _?        t        |jv                  d5         d6z  | _A        t        |jv                  d7         d6z  | _B        d| _=        d8| _C        t        j                  j                  |        | j                  d9d:       || _H        | j                  j                  | j                  | j                  z          | j                  | j                        | _L        | j                  | j                        | _N        y# t\        t^        t         j`                  f$ r5 |r| j                  jc                  d'       Y yte        j\                  d(      w xY w# tn        $ r/}| j                  jc                  d+tI        |             Y d}~yd}~ww xY w# tn        $ r/}| j                  jc                  d,tI        |             Y d}~yd}~ww xY w# tn        $ r/}| j                  jc                  d+tI        |             Y d}~yd}~ww xY w# tn        $ r&}te        j\                  d0tI        |      z         d}~ww xY w);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 Trk   z#Attempting WebSocket connection to  ;)headersepcookiez; Authorizationz&Only basic authentication is supportedz{}:{}r   r   rc   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_reqsr   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 rf   rg   rh   ri   rj   r.   r   r1   )Or   rm   rn   ro   rf   rq   rp   r   r   cookiesvaluenameoutputstripitemslowerauthr   tupler   rx   encoder   r{   certproxies
startswithgeturllibparseurlparsehostnameportusernamepasswordverifyr   
ssl_verifyupdatessl	CERT_NONEwebsocket_extra_optionspoprt   create_connectionrs   ru   OSErrorWebSocketExceptionwarningr   r	   r*   PINGr,   	Exceptionrecvr}   PONGr(   UPGRADEr9   r~   rg   r   r   r   r   r   r<   r   r6   r:   
settimeoutrI   r   r   _read_loop_websocketr!   )r   r   r   r   websocket_urlupgrader   extra_optionsckr   r   r   
basic_auth	proxy_url
parsed_urlr:   r   er   r   s                       r   r   zClient._connect_websocket   s   KK ? @..sM;O88KK2]BDGWtxx//MG)DMKK5EG
 99B))++ /"(,,6;;/iirsi399;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%%'C  )*F*FG 	E##@B 001CDD	E  ##MF 	  ##MF 	  ##MF 	  < 001CF:< <<sr   5'_& `< %a7 b2 ;c- &;`9#`9<	a4%a//a47	b/ %b**b/2	c*;%c%%c*-	d6!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?   r7   z%Received unexpected packet of type %sN)r}   lenr	   packet_namesrm   rq   r   r(   bytesr+   r6   r   r)   r*   r   r3   r0   r7   SERVER_DISCONNECTNOOPrn   )r   r   packet_names      r   r   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   r4   r5   rm   rq   r	   r   r}   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(   r`   z+HTTP %s request to %s failed with error %s.)r   rl   Sessionr   r   requestr   RequestExceptionrm   rq   r   )r   methodr   r   bodyr`   excs          r   rr   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   handlersrI   	TypeErrorr   rm   	exception)r   eventrB   rC   r2   s        r   r6   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 r_      r`   N*Connection refused by the server, abortingra   rb   6Unexpected status code %s in server response, abortingrc   rd   z'Unexpected packet from server, aborting"Waiting for write loop task to endr0   Fr1   Exiting read loop task)r   r   rm   rq   rp   rr   rs   maxr   r   r   r   r   r4   r5   rv   r
   ry   rz   r{   r   r|   r   r"   r6   r7   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   r:   r   r   r.   r   "WebSocketConnectionClosedExceptionWebSocketTimeoutExceptionrm   r   r4   r5   r   typer   errnorq   r   r	   r*   r   r   r"   r6   r7   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                  $ r | j                  j                  d       Y Hw xY w# | 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   )r|   POSTzContent-Typez
text/plain)r   r   r`   r   ra   rb   r   r   zExiting write loop task) r   r   r   r   r4   r   r\   rm   rn   r[   r   r9   r
   ry   rr   rp   r   rt   r   r   r   rv   r   binaryr:   send_binaryr,   r   r   BrokenPipeErrorr   rq   )r   r`   r|   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 A4J5 /*JJJ21J259K10K1)NNz	engine.io)FN)r   )NNN)__name__
__module____qualname____doc__r   r$   r,   r0   rI   rL   rQ   rT   rW   r>   r   r   r   r)   rr   r6   r   r   r   __classcell__)r]   s   @r   r   r      s    "F 59)!/F'D0&#,0;%zfP/&I 37D*'3R13f?4r%   r   )base64r   http.cookiesr   loggingr4   r   rE   rK   r   engineio.jsonr   rl   ImportErrorr   r   r   r   r	   r
   	getLoggerdefault_logger
BaseClientr    r%   r   <module>r     s     %   
    )    """#45`	4[## `	4  H  Is"   A5 B 5A?>A?BB