
    wge                     b    d dl Z d dlZddlmZ ddlmZ ddlmZ  G d dej                        Zy)    N   )base_client)
exceptions)packetc                       e Zd ZdZi d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 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)!ClientaM  A Socket.IO client.

    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 serializer: The serialization method to use when transmitting
                       packets. Valid values are ``'default'``, ``'pickle'``,
                       ``'msgpack'`` and ``'cbor'``. Alternatively, a subclass
                       of the :class:`Packet` class with custom implementations
                       of the ``encode()`` and ``decode()`` methods can be
                       provided. Client and server must use compatible
                       serializers.
    :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 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.

    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, 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 websocket_extra_options: Dictionary containing additional keyword
                                    arguments passed to
                                    ``websocket.create_connection()``.
    :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``.
    Nz	socket.ioTr   Fc
           	      n   | j                   rt        j                  d      || _        || _        || _        || _        || _        || _        |t        t        | j                  j                               j                  t        | j                  j                                           }d|v r|j                  d       t!        |      dk(  rdg}nt#        |t$              r|g}|| _        i | _        | j(                   | j*                  j-                         | _        n| j(                  j/                          | j1                  | j                        }
| j1                  | j                        }	 | j*                  j3                  |
|||       |r| j(                  j?                  |
      rc| j(                  j/                          t        | j&                        t        | j                        k(  rn| j(                  j?                  |
      rct        | j&                        t        | j                        k7  r%| jA                          t        j                  d      d| _         y# t4        j                  j                  $ r}| j                  D ]I  }| j7                  d|t!        |j8                        dkD  r|j8                  d   n|j8                  d          K |	r.| j;                          | j*                  j<                  d	k(  rY d}~yt        j                  |j8                  d         dd}~ww xY w)a0
  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``.
        :param retry: Apply the reconnection logic if the initial connection
                      attempt fails. The default is ``False``.

        Example usage::

            sio = socketio.Client()
            sio.connect('http://localhost:5000')
        zAlready connectedN*r   /)headers
transportsengineio_pathconnect_errorr   	connectedtimeoutz(One or more namespaces failed to connectT)!r   r   ConnectionErrorconnection_urlconnection_headersconnection_authconnection_transportsconnection_namespacessocketio_pathlistsethandlerskeysunionnamespace_handlersremovelen
isinstancestr
namespaces_connect_eventeiocreate_eventclear_get_real_valueconnectengineio_trigger_eventargs_handle_reconnectstatewait
disconnect)selfurlr   authr   r$   r   r0   wait_timeoutretryreal_urlreal_headersexcns                 T/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/socketio/client.pyr*   zClient.connectI   s   \ >>,,-@AA!")#%/"%/"*c$--"4"4"67==D++00235 6Jj !!#&:!#!U

C($J%/"&"&(("7"7"9D%%'''(;(;<++D,C,CD	DHHX|(2+8  : %%**<*@##))+t'3t/I/I+JJ %%**<*@ 4??#s4+E+E'FF! 00>@ @ + ""22 		D// G###Q#&sxx=1#4CHHQK#((1+GG &&(88>>[0,,SXXa[9tC		Ds   /I' 'L4BL/#L//L4c                    	 | j                   j                          | j                  d       | j                  s| j                   j                  dk(  rRy| j                  j                          | j                   j                  dk7  r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.
        r   r   N)r&   r0   sleep_reconnect_taskr/   joinr2   s    r;   r0   zClient.wait   sj     HHMMOJJqM''88>>[0   %%'xx~~,     c                 x   |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   |             y)a/  Emit a custom event to the server.

        :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 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 thread safe. If multiple threads are emitting
        at the same time on the same client connection, 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.
        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)r2   eventrD   rC   callbackrE   s         r;   emitzClient.emit   s    0 $	DOO+..<<> >3UIF&&y(;BB dE":D6DD$++FLLI274B , H 	IrA   c                 .    | j                  d|||       y)a  Send a message to the server.

        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 server has received the message. The arguments
                         that will be passed to the function are those provided
                         by the server.
        messagerD   rC   rO   N)rP   )r2   rD   rC   rO   s       r;   sendzClient.send   s    $ 			)$)# 	 	%rA   c                 "   | j                   j                         g fd}| j                  ||||       j                  |      st	        j
                         t        d         dkD  rd   S t        d         dk(  rd   d   S dS )aZ  Emit a custom event to the server and wait for the response.

        This method issues an emit with a callback and waits for the callback
        to be invoked before returning. If the callback isn't invoked before
        the timeout, then a ``TimeoutError`` exception is raised. If the
        Socket.IO connection drops during the wait, this method still waits
        until the specified timeout.

        :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 server acknowledges the event, then a
                        ``TimeoutError`` exception is raised.

        Note: this method is not thread safe. If multiple threads are emitting
        at the same time on the same client connection, 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.
        c                  H    j                  |        j                          y N)appendr   )r-   callback_argscallback_events    r;   event_callbackz#Client.call.<locals>.event_callback"  s      & rA   rS   r   r   r   N)r&   r'   rP   r0   r   TimeoutErrorr!   )r2   rN   rD   rC   r   r[   rY   rZ   s         @@r;   callzClient.call  s    : ..0	! 			%di) 	 	+""7"3))++#&}Q'7#81#<}Q 	(+M!,<(=(Bq!!$		rA   c                     | j                   D ]2  }| j                  | j                  t        j                  |             4 | j
                  j                  d       y)zDisconnect from the server.rC   TabortN)r$   rK   rL   r   
DISCONNECTr&   r1   )r2   r:   s     r;   r1   zClient.disconnect.  sY      	1Ad//!!Q 0 0 1	1 	$'rA   c                     | j                   r| j                          y| j                  r5| j                  j	                          | j                  j                          yy)aA  Stop the client.

        If the client is connected to a server, it is disconnected. If the
        client is attempting to reconnect to server, the reconnection attempts
        are stopped. If the client is not connected to a server and is not
        attempting to reconnect, then this function does nothing.
        N)r   r1   r>   _reconnect_abortr   r?   r@   s    r;   shutdownzClient.shutdown7  sG     >>OO!!!!%%'  %%' "rA   c                 B     | j                   j                  |g|i |S )aO  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 that represents the background task,
        on which the ``join()`` methond can be invoked to wait for the task to
        complete.
        )r&   start_background_task)r2   targetr-   kwargss       r;   rg   zClient.start_background_taskE  s%     .txx--fFtFvFFrA   c                 8    | j                   j                  |      S )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.
        )r&   r=   )r2   secondss     r;   r=   zClient.sleepV  s     xx~~g&&rA   c                 *    t        |      s|S  |       S )zTReturn the actual value, for parameters that can also be given as
        callables.)callable)r2   values     r;   r)   zClient._get_real_value`  s     LwrA   c                     |j                         }t        |t              r#|D ]  }| j                  j	                  |        y| j                  j	                  |       y)z&Send a Socket.IO packet to the server.N)encoder"   r   r&   rT   )r2   pktencoded_packeteps       r;   rK   zClient._send_packetg  sH    nd+$ "b!" HHMM.)rA   c                     |xs d}|| j                   vrz| j                  j                  d| d       |xs i j                  d| j                        | j                   |<   | j                  d|       | j                  j                          y y )Nr   z
Namespace z is connectedsidr*   r_   )r$   rG   rH   getru   r,   r%   r   r2   rC   rD   s      r;   _handle_connectzClient._handle_connectp  s    $	DOO+KKz)MBC*.*")9)9%)JDOOI&	Y?##%	 ,rA   c                 2   | j                   sy |xs d}| j                  d|| j                  j                         | j                  d|       || j                  v r| j                  |= | j                  s$d| _         | j
                  j                  d       y y )Nr   r1   __disconnect_finalFTr`   )r   r,   reasonSERVER_DISCONNECTr$   r&   r1   )r2   rC   s     r;   _handle_disconnectzClient._handle_disconnectx  s    ~~$	L) KK99	;0)<'	*"DNHHd+ rA   c                 6   |xs d}| j                   j                  d|d   |        | j                  |d   |g|dd   }|W|g }nt        |t              rt        |      }n|g}| j                  | j                  t        j                  |||             y y )Nr   zReceived event "%s" [%s]r   r   )rC   rE   rD   )
rG   rH   r,   r"   rJ   r   rK   rL   r   ACK)r2   rC   rE   rD   rs        r;   _handle_eventzClient._handle_event  s    $	3T!WiHDQ>T!"X>> yAu%Awsd//

iBT 0 C D rA   c                     |xs d}| j                   j                  d|       d }	 | j                  |   |   }| j                  |   |= | ||  y y # t        $ r | j                   j	                  d       Y /w xY w)Nr   zReceived ack [%s]z$Unknown callback received, ignoring.)rG   rH   	callbacksKeyErrorwarning)r2   rC   rE   rD   rO   s        r;   _handle_ackzClient._handle_ack  s    $	,i8	.~~i04H
 y)"-dO    	HKK FG	Hs   A $A87A8c                 j   |xs d}| j                   j                  dj                  |             |t               }nt	        |t        t
        f      s|f} | j                  d|g|  | j                  j                          || j                  v r| j                  |= |dk(  ri | _	        d| _
        y y )Nr   z'Connection to namespace {} was rejectedr   F)rG   rH   formatrJ   r"   r   r,   r%   r   r$   r   rw   s      r;   _handle_errorzClient._handle_error  s    $	BII 	<7DD5$-07DOY>>!'	* DO"DN rA   c                     | j                  |||      \  }}|r	  || S | j                  ||      \  }}|r |j                  |g| S y# t        $ r |dk(  r
 ||dd  cY S  w xY w)z$Invoke an application event handler.r1   N)_get_event_handler	TypeError_get_namespace_handlertrigger_event)r2   rN   rC   r-   handlers        r;   r,   zClient._trigger_event  s     //y$G~% 33ItD(7((666   L("D"I..s   A
 
A$"A$c           	         | 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                  |             | j                   j                  |      r@| j                  j                  d       | j                  D ]  }| j!                  d|        n}|dz  }	 | j#                  | j$                  | j&                  | j(                  | j*                  | j                  | j,                  d	       | j                  j                  d
       d | _        	 t        j
                  j9                  |        y # t0        j2                  t4        f$ r Y nw xY w| j6                  rO|| j6                  k\  r@| j                  j                  d       | j                  D ]  }| j!                  d|        )Nr      r   z1Connection failed, new attempt in {:.02f} secondszReconnect task abortedrz   r_   F)r   r4   r   r$   r   r6   zReconnection successfulz0Maximum reconnection attempts reached, giving up)rd   r&   r'   r(   r   reconnecting_clientsrX   reconnection_delayreconnection_delay_maxrandomization_factorrandomrG   rH   r   r0   r   r,   r*   r   r   r   r   r   r>   r   r   
ValueErrorreconnection_attemptsr    )r2   attempt_countcurrent_delaydelayr:   s        r;   r.   zClient._handle_reconnect  s3     ($(HH$9$9$;D!##%((//5//!EQMt22233T..!fmmo2E2IJJEKKCJJ $$))%0  !9:33 KA''(<'JKQMT00%)%<%<"&"6"6(,(B(B(,(B(B+/+=+=#(  *   !:;'+$ 	((//5 ..
;  ))!T%?%??  FH33 KA''(<'JKG s   AG" "G>=G>c                 2   | j                   j                  d       | j                  j                  | _        | j	                  | j
                        xs i }| j                  D ]3  }| j                  | j                  t        j                  ||             5 y)z&Handle the Engine.IO connection event.z Engine.IO connection established)rD   rC   N)rG   rH   r&   ru   r)   r   r   rK   rL   r   CONNECT)r2   	real_authr:   s      r;   _handle_eio_connectzClient._handle_eio_connect  s    ;<88<<(()=)=>D"	++ 	>Ad//Y! 0 = >	>rA   c                    | j                   r| j                   }|j                  |      rd| _         |j                  t        j                  k(  r2| j                  |j                  |j                  |j                         y| j                  |j                  |j                  |j                         yy| j                  |      }|j                  t        j                  k(  r'| j                  |j                  |j                         y|j                  t        j                  k(  r| j                  |j                         y|j                  t        j                  k(  r2| j                  |j                  |j                  |j                         y|j                  t        j                   k(  r2| j                  |j                  |j                  |j                         y|j                  t        j                  k(  s|j                  t        j"                  k(  r|| _         y|j                  t        j$                  k(  r'| j'                  |j                  |j                         yt)        d      )zDispatch Engine.IO messages.N)rr   zUnknown packet type.)_binary_packetadd_attachmentpacket_typer   BINARY_EVENTr   rC   rE   rD   r   rL   r   rx   rb   r}   rM   r   
BINARY_ACKCONNECT_ERRORr   r   )r2   rD   rq   s      r;   _handle_eio_messagezClient._handle_eio_message  s   %%C!!$'&*#??f&9&99&&s}}cffchhG$$S]]CFFCHHE ( ##4#8C&..0$$S]]CHH=F$5$55''6FLL0""3==#&&#((CFJJ.  AF$7$77OOv'8'88&)#F$8$88""3==#((; !788rA   c                    | j                   j                  d       | j                  xr | j                  j                  dk(  }| j
                  rG| j                  D ]*  }| j                  d||       |r| j                  d|       , i | _        d| _        i | _        d| _	        d| _
        |r.| j                  s!| j                  | j                        | _        yyy)z)Handle the Engine.IO disconnection event.zEngine.IO connection droppedr   r1   rz   FN)rG   rH   reconnectionr&   r/   r   r$   r,   r   r   ru   r>   rg   r.   )r2   r{   will_reconnectr:   s       r;   _handle_eio_disconnectzClient._handle_eio_disconnect  s    78**Ltxx~~/L>>__ A##L!V<%''(<a@A !DO"DN"$"6"6#'#=#=&&$(D  #7>rA   c                 "    t         j                  S rW   )r+   r   r@   s    r;   _engineio_client_classzClient._engineio_client_class*  s    rA   )NNN)NN)NN<   )r   )__name__
__module____qualname____doc__r*   r0   rP   rT   r]   r1   re   rg   r=   r)   rK   rx   r}   r   r   r   r,   r.   r   r   r   r    rA   r;   r   r   
   s    =| $&DT{ebH(*IX%**X((G"'*&,D # 7&+6Z>98($rA   r   )r   r+    r   r   r   
BaseClientr   r   rA   r;   <module>r      s(        a[## arA   