
    2Bf_                         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  ej                  d      Z	 G d dej                        Zy)	    N   )client)
exceptions)packetzsocketio.clientc                       e Zd ZdZd Zi ddddddfdZd Zdd	Zdd
ZddZ	d Z
d ZddZd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zy) AsyncClienta  A Socket.IO client for asyncio.

    This class implements a fully compliant Socket.IO web client with support
    for websocket and long-polling transports.

    :param reconnection: ``True`` if the client should automatically attempt to
                         reconnect to the server after an interruption, or
                         ``False`` to not reconnect. The default is ``True``.
    :param reconnection_attempts: How many reconnection attempts to issue
                                  before giving up, or 0 for infinite attempts.
                                  The default is 0.
    :param reconnection_delay: How long to wait in seconds before the first
                               reconnection attempt. Each successive attempt
                               doubles this delay.
    :param reconnection_delay_max: The maximum delay between reconnection
                                   attempts.
    :param randomization_factor: Randomization amount for each delay between
                                 reconnection attempts. The default is 0.5,
                                 which means that each delay is randomly
                                 adjusted by +/- 50%.
    :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.

    The Engine.IO configuration supports the following settings:

    :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, 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 engineio_logger: To enable Engine.IO 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
                            ``engineio_logger`` is ``False``.
    c                      y)NT selfs    W/var/www/highfloat_scraper/venv/lib/python3.12/site-packages/socketio/asyncio_client.pyis_asyncio_basedzAsyncClient.is_asyncio_based>   s        Nz	socket.ioTr   c	                 l  K   | j                   rt        j                  d      || _        || _        || _        || _        || _        || _        |nt        t        | j                  j                               j                  t        | j                  j                                           }t        |      dk(  rdg}nt!        |t"              r|g}|| _        i | _        | j&                   | j(                  j+                         | _        n| j&                  j-                          | j/                  | j                         d{   }	| j/                  | j                         d{   }
	 | j(                  j1                  |	|
||       d{    |r	 	 t9        j:                  | j&                  j=                         |       d{    | j&                  j-                          t        | j$                        t        | j                        k(  rn}	 t        | j$                        t        | j                        k7  r-| jA                          d{    t        j                  d	      d| _         y7 27 7 # t2        j                  j                  $ rx}| j5                  ddt        |j6                        dkD  r|j6                  d   n|j6                  d          d{  7   t        j                  |j6                  d         dd}~ww xY w7 M# t8        j>                  $ r Y w xY w7 ޭw)
a	  Connect to a Socket.IO server.

        :param url: The URL of the Socket.IO server. It can include custom
                    query string parameters if required by the server. If a
                    function is provided, the client will invoke it to obtain
                    the URL each time a connection or reconnection is
                    attempted.
        :param headers: A dictionary with custom headers to send with the
                        connection request. If a function is provided, the
                        client will invoke it to obtain the headers dictionary
                        each time a connection or reconnection is attempted.
        :param auth: Authentication data passed to the server with the
                     connection request, normally a dictionary with one or
                     more string key/value pairs. If a function is provided,
                     the client will invoke it to obtain the authentication
                     data each time a connection or reconnection is attempted.
        :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 namespaces: The namespaces to connect as a string or list of
                           strings. If not given, the namespaces that have
                           registered event handlers are connected.
        :param socketio_path: The endpoint where the Socket.IO server is
                              installed. The default value is appropriate for
                              most cases.
        :param wait: if set to ``True`` (the default) the call only returns
                     when all the namespaces are connected. If set to
                     ``False``, the call returns as soon as the Engine.IO
                     transport is connected, and the namespaces will connect
                     in the background.
        :param wait_timeout: How long the client should wait for the
                             connection. The default is 1 second. This
                             argument is only considered when ``wait`` is set
                             to ``True``.

        Note: this method is a coroutine.

        Example usage::

            sio = socketio.AsyncClient()
            sio.connect('http://localhost:5000')
        zAlready connectedNr   /)headers
transportsengineio_pathconnect_errorr   Tz(One or more namespaces failed to connect)!	connectedr   ConnectionErrorconnection_urlconnection_headersconnection_authconnection_transportsconnection_namespacessocketio_pathlistsethandlerskeysunionnamespace_handlerslen
isinstancestr
namespaces_connect_eventeiocreate_eventclear_get_real_valueconnectengineio_trigger_eventargsasynciowait_forwaitTimeoutError
disconnect)r   urlr   authr   r'   r   r3   wait_timeoutreal_urlreal_headersexcs               r   r-   zAsyncClient.connectA   s    \ >>,,-@AA!")#%/"%/"*c$--"4"4"67==D++00235 6J:!#!U

C($J%/"&"&(("7"7"9D%%'--d.A.ABB!11$2I2IJJ	D((""8\.81> # @ @ @ !**4+>+>+C+C+E+79 9 9''--/4??+s43M3M/NN 
  4??#s4+E+E'FFoo''' 00>@ @ 7 CJ@ ""22 	D%%"388}q0chhqkC C C ,,SXXa[9tC		D9
 ''  (s   EL4I5"L4&I8'L4,"I= I;I= L42L L	AL ?L4L2"L48L4;I= =LA
L$K'%(LLL4L L/+L4.L//L4c                   K   	 | j                   j                          d{    | j                  d       d{    | j                  sy| j                   d{    | j                   j                  dk7  ryw7 Y7 B7 #w)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.

        Note: this method is a coroutine.
        Nr   r   )r)   r3   sleep_reconnect_taskstater   s    r   r3   zAsyncClient.wait   so      ((--/!!**Q-''&&&&xx~~, ! 's1   BA;BA= BA? B=B?Bc                   K   |xs d}|| j                   vrt        j                  |dz         | j                  j	                  d||       || j                  ||      }nd}t        |t              rt        |      }n||g}ng }| j                  | j                  t        j                  ||g|z   |             d{    y7 w)a  Emit a custom event to one or more connected clients.

        :param event: The event name. It can be any string. The event names
                      ``'connect'``, ``'message'`` and ``'disconnect'`` are
                      reserved and should not be used.
        :param data: The data to send to the server. Data can be of
                     type ``str``, ``bytes``, ``list`` or ``dict``. To send
                     multiple arguments, use a tuple where each element is of
                     one of the types indicated above.
        :param namespace: The Socket.IO namespace for the event. If this
                          argument is omitted the event is emitted to the
                          default namespace.
        :param callback: If given, this function will be called to acknowledge
                         the the server has received the message. The arguments
                         that will be passed to the function are those provided
                         by the server.

        Note: this method is not designed to be used concurrently. If multiple
        tasks are emitting at the same time on the same client connection, then
        messages composed of multiple packets may end up being sent in an
        incorrect sequence. Use standard concurrency solutions (such as a Lock
        object) to prevent this situation.

        Note 2: this method is a coroutine.
        r   z is not a connected namespace.zEmitting event "%s" [%s]N)	namespacedataid)r'   r   BadNamespaceErrorloggerinfo_generate_ack_idr%   tupler   _send_packetpacket_classr   EVENT)r   eventrB   rA   callbackrC   s         r   emitzAsyncClient.emit   s     4 $	DOO+..<<> >3UIF&&y(;BB dE":D6DD 1 1LLIUGdNr !2 !K L 	L 	Ls   B>C CCc                 J   K   | j                  d|||       d{    y7 w)a  Send a message to one or more connected clients.

        This function emits an event with the name ``'message'``. Use
        :func:`emit` to issue custom event names.

        :param data: The data to send to the server. Data can be of
                     type ``str``, ``bytes``, ``list`` or ``dict``. To send
                     multiple arguments, use a tuple where each element is of
                     one of the types indicated above.
        :param namespace: The Socket.IO namespace for the event. If this
                          argument is omitted the event is emitted to the
                          default namespace.
        :param callback: If given, this function will be called to acknowledge
                         the the server has received the message. The arguments
                         that will be passed to the function are those provided
                         by the server.

        Note: this method is a coroutine.
        messagerB   rA   rM   N)rN   )r   rB   rA   rM   s       r   sendzAsyncClient.send   s,     ( ii		!)  + 	+ 	+s   #!#c                   K   | j                   j                         g fd}| j                  ||||       d{    	 t        j                  j                         |       d{    t        d         dkD  rd   S t        d         dk(  rd   d   S dS 7 b7 7# t        j                  $ r t        j                         dw xY ww)aG  Emit a custom event to a client and wait for the response.

        :param event: The event name. It can be any string. The event names
                      ``'connect'``, ``'message'`` and ``'disconnect'`` are
                      reserved and should not be used.
        :param data: The data to send to the server. Data can be of
                     type ``str``, ``bytes``, ``list`` or ``dict``. To send
                     multiple arguments, use a tuple where each element is of
                     one of the types indicated above.
        :param namespace: The Socket.IO namespace for the event. If this
                          argument is omitted the event is emitted to the
                          default namespace.
        :param timeout: The waiting timeout. If the timeout is reached before
                        the client acknowledges the event, then a
                        ``TimeoutError`` exception is raised.

        Note: this method is not designed to be used concurrently. If multiple
        tasks are emitting at the same time on the same client connection, then
        messages composed of multiple packets may end up being sent in an
        incorrect sequence. Use standard concurrency solutions (such as a Lock
        object) to prevent this situation.

        Note 2: this method is a coroutine.
        c                  H    j                  |        j                          y N)appendr   )r0   callback_argscallback_events    r   event_callbackz(AsyncClient.call.<locals>.event_callback  s      & r   rQ   Nr   r   )	r)   r*   rN   r1   r2   r3   r4   r   r$   )r   rL   rB   rA   timeoutrY   rW   rX   s         @@r   callzAsyncClient.call   s     2 ..0	! iiDI!/  1 	1 	1	6"">#6#6#8'BBB $'}Q'7#81#<}Q 	(+M!,<(=(Bq!!$			1 C## 	6))+5	6s:   ;CB" C'B& ,B$-B& 12C$B& &)CCc                    K   | j                   D ]:  }| j                  | j                  t        j                  |             d{    < | j
                  j                  d       d{    y7 +7 w)zODisconnect from the server.

        Note: this method is a coroutine.
        rA   NTabort)r'   rI   rJ   r   
DISCONNECTr)   r5   r   ns     r   r5   zAsyncClient.disconnect#  sv       	2A##D$5$5f6G6G./ %6 %1 2 2 2	2 hh!!!---2-s$   AA5A1%A5+A3,A53A5c                 B     | j                   j                  |g|i |S )ad  Start a background task using the appropriate async model.

        This is a utility function that applications can use to start a
        background task using the method that is compatible with the
        selected async mode.

        :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 compatible with the `Thread` class in
        the Python standard library. The `start()` method on this object is
        already called by this function.
        )r)   start_background_task)r   targetr0   kwargss       r   rd   z!AsyncClient.start_background_task/  s%     .txx--fFtFvFFr   c                 T   K   | j                   j                  |       d{   S 7 w)a<  Sleep for the requested amount of time using the appropriate async
        model.

        This is a utility function that applications can use to put a task to
        sleep without having to worry about using the correct call for the
        selected async mode.

        Note: this method is a coroutine.
        N)r)   r=   )r   secondss     r   r=   zAsyncClient.sleep@  s!      XX^^G,,,,s   (&(c                 ~   K   t        |      s|S t        j                  |      r |        d{   S  |       S 7 w)zTReturn the actual value, for parameters that can also be given as
        callables.N)callabler1   iscoroutinefunction)r   values     r   r,   zAsyncClient._get_real_valueL  s8      L&&u-= w !s   -=;=c                    K   |j                         }t        |t              r+|D ]%  }| j                  j	                  |       d{    ' y| j                  j	                  |       d{    y7 +7 w)z&Send a Socket.IO packet to the server.N)encoder%   r   r)   rR   )r   pktencoded_packeteps       r   rI   zAsyncClient._send_packetU  sa     nd+$ (hhmmB'''( ((--/// (/s$   AA6A2%A6,A4-A64A6c                 R  K   |xs d}|| j                   vr| j                  j                  dj                  |             |xs i j	                  d| j
                        | j                   |<   | j                  d|       d {    | j                  j                          y y 7  w)Nr   zNamespace {} is connectedsidr-   r]   )	r'   rE   rF   formatgetrs   r/   r(   r   r   rA   rB   s      r   _handle_connectzAsyncClient._handle_connect^  s     $	DOO+KK8??	JK*.*")9)9%)JDOOI&%%i9%EEE##%	 , Fs   BB'B%!B'c                   K   | j                   sy |xs d}| j                  d|       d {    || j                  v r| j                  |= | j                  s,d| _         | j                  j	                  d       d {    y y 7 X7 w)Nr   r5   r]   FTr^   )r   r/   r'   r)   r5   )r   rA   s     r   _handle_disconnectzAsyncClient._handle_disconnectf  s     ~~$	!!,)!DDD'	*"DN((%%D%111  	E
 2s"   *B	BAB	>B?B	B	c                 f  K   |xs d}| j                   j                  d|d   |        | j                  |d   |g|dd    d {   }|_|g }nt        |t              rt        |      }n|g}| j                  | j                  t        j                  |||             d {    y y 7 f7 w)Nr   zReceived event "%s" [%s]r   r   )rA   rC   rB   )
rE   rF   r/   r%   rH   r   rI   rJ   r   ACK)r   rA   rC   rB   rs        r   _handle_eventzAsyncClient._handle_eventq  s     $	3T!WiH%$%%d1gyD48DD> yAu%Aws##D$5$5

iBT %6 %C D D D  EDs%   AB1B-AB1&B/'B1/B1c                 H  K   |xs d}| j                   j                  d|       d }	 | j                  |   |   }| j                  |   |= |)t        j                  |      r ||  d {    y  ||  y y # t        $ r | j                   j	                  d       Y Rw xY w7 6w)Nr   zReceived ack [%s]z$Unknown callback received, ignoring.)rE   rF   	callbacksKeyErrorwarningr1   rk   )r   rA   rC   rB   rM   s        r   _handle_ackzAsyncClient._handle_ack  s     $	,i8	.~~i04H
 y)"-**84o%%$	    	HKK FG	H &s3   %B"A6 /B")B *B"6$BB"BB"c                   K   |xs d}| j                   j                  dj                  |             |t               }nt	        |t        t
        f      s|f} | j                  d|g|  d {    | j                  j                          || j                  v r| j                  |= |dk(  ri | _	        d| _
        y y 7 Nw)Nr   z'Connection to namespace {} was rejectedr   F)rE   rF   rt   rH   r%   r   r/   r(   r   r'   r   rv   s      r   _handle_errorzAsyncClient._handle_error  s     $	BII 	<7DD5$-07D!d!!/9DtDDD!'	* DO"DN 	 	Es   A.C0B?1ACc                   K   || j                   v rm|| j                   |   v r\t        j                  | j                   |   |         r 	  | j                   |   |   |  d{   }|S  | j                   |   |   | }|S || j                  v r( | j                  |   j
                  |g|  d{   S y7 T# t        j                  $ r d}Y |S w xY w7 #w)z$Invoke an application event handler.N)r    r1   rk   CancelledErrorr#   trigger_event)r   rL   rA   r0   rets        r   r/   zAsyncClient._trigger_event  s      %%4==3K*K**4==+CE+JK ?i 8 ? FFC
 J 6dmmI.u5t<J $111I00;II   2 G-- C J	sI   ACB7  B5!B7 %A
C/C0C5B7 7CCCCc                   K   | j                   | j                  j                         | _         | j                   j                          t        j
                  j                  |        d}| j                  }	 |}|dz  }|| j                  kD  r| j                  }|| j                  dt        j                         z  dz
  z  z  }| j                  j                  dj                  |             	 t        j                  | j                   j!                         |       d {    | j                  j                  d       	 t        j
                  j?                  |        y 7 @# t        j"                  t        j$                  f$ r Y nw xY w|dz  }	 | j'                  | j(                  | j*                  | j,                  | j.                  | j0                  | j2                         d {  7   | j                  j                  d       d | _        # t6        j8                  t:        f$ r Y nw xY w| j<                  r,|| j<                  k\  r| j                  j                  d       'w)	Nr      r   z1Connection failed, new attempt in {:.02f} secondszReconnect task aborted)r   r7   r   r'   r   zReconnection successfulz0Maximum reconnection attempts reached, giving up) _reconnect_abortr)   r*   r+   r   reconnecting_clientsrV   reconnection_delayreconnection_delay_maxrandomization_factorrandomrE   rF   rt   r1   r2   r3   r4   r   r-   r   r   r   r   r   r   r>   r   r   
ValueErrorreconnection_attemptsremove)r   attempt_countcurrent_delaydelays       r   _handle_reconnectzAsyncClient._handle_reconnect  s*      ($(HH$9$9$;D!##%##**40//!EQMt22233T..!fmmo2E2IJJEKKCJJ&&t'<'<'A'A'CUKKK  !9:, 	##**401 L (('*@*@A QMll4#6#6+/+B+B(,(<(<.2.H.H.2.H.H151C1C # E E E   !:;'+$ ..
;  ))!T%?%??  FHC sm   C*I(-1E! EE! >!I(E! !#FI(FI(AH &G)'H ,#I(H+(I(*H++=I(c                 Z  K   | j                   j                  d       | j                  j                  | _        | j	                  | j
                         d{   }| j                  D ];  }| j                  | j                  t        j                  ||             d{    = y7 O7 	w)z&Handle the Engine.IO connection event.z Engine.IO connection establishedN)rB   rA   )rE   rF   r)   rs   r,   r   r   rI   rJ   r   CONNECT)r   	real_authrb   s      r   _handle_eio_connectzAsyncClient._handle_eio_connect  s     ;<88<<..t/C/CDD	++ 	>A##D$5$5Y! %6 %= > > >	> E>s%   AB+B'AB+B) B+)B+c                   K   | j                   r| j                   }|j                  |      rd| _         |j                  t        j                  k(  r:| j                  |j                  |j                  |j                         d{    y| j                  |j                  |j                  |j                         d{    yy| j                  |      }|j                  t        j                  k(  r/| j                  |j                  |j                         d{    y|j                  t        j                  k(  r$| j                  |j                         d{    y|j                  t        j                  k(  r:| j                  |j                  |j                  |j                         d{    y|j                  t        j                   k(  r:| j                  |j                  |j                  |j                         d{    y|j                  t        j                  k(  s|j                  t        j"                  k(  r|| _         y|j                  t        j$                  k(  r/| j'                  |j                  |j                         d{    yt)        d      7 '7 7 7 V7 7 7 !w)zDispatch Engine.IO messages.N)rp   zUnknown packet type.)_binary_packetadd_attachmentpacket_typer   BINARY_EVENTr}   rA   rC   rB   r   rJ   r   rw   r`   ry   rK   r{   
BINARY_ACKCONNECT_ERRORr   r   )r   rB   ro   s      r   _handle_eio_messagezAsyncClient._handle_eio_message  s    %%C!!$'&*#??f&9&99,,S]]CFFCHHMMM**3==#&&#((KKK ( ##4#8C&..0**3==#((CCCF$5$55--cmm<<<FLL0((IIIFJJ.&&s}}cffchhGGGF$7$77OOv'8'88&)#F$8$88((AAA !788' NK D<IG
 Bs   BJ>J+9J>>J.?AJ>J1A J>J4AJ>5J76AJ>J:BJ>J<J>.J>1J>4J>7J>:J><J>c                   K   | j                   j                  d       | j                  r:| j                  D ]  }| j	                  d|       d{     i | _        d| _        i | _        d| _        d| _        | j                  j                  dk(  r.| j                  r!| j                  | j                        | _        yyy7 qw)z)Handle the Engine.IO disconnection event.zEngine.IO connection droppedr5   r]   NFr   )rE   rF   r   r'   r/   r   r   rs   r)   r?   reconnectionrd   r   r>   ra   s     r   _handle_eio_disconnectz"AsyncClient._handle_eio_disconnect  s     78>>__ E)),!)DDDE DO"DN"88>>[(T->->#'#=#=&&$(D  .?( Es   ACCA2Cc                 "    t         j                  S rU   )r.   r   r   s    r   _engineio_client_classz"AsyncClient._engineio_client_class  s    ###r   )NNN)NN)NN<   )r   )__name__
__module____qualname____doc__r   r-   r3   rN   rR   r[   r5   rd   r=   r,   rI   rw   ry   r}   r   r   r/   r   r   r   r   r   r
   r   r   r   r      s    .^ *,$4!%[t#$`D",L\+.(T
.G"
-0&	2D  "# $)1V>98($r   r   )r1   loggingr   r.    r   r   r   	getLoggerdefault_loggerClientr   r
   r   r   <module>r      s?          """#45F$&-- F$r   