
    2Bf                     ~    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	      Z
y)
    N   )base_manager)
exceptions	namespace)packetzsocketio.serverc                      e Zd ZdZ	 	 d$dZd Zd%dZd Zd Z	 	 d&dZ		 	 d'd	Z
	 	 d(d
Zd)dZd)dZd)dZd)dZd)dZd)dZd)dZd*dZd Zd)dZd Zd Zd+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$y),Servera  A Socket.IO server.

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

    :param client_manager: The client manager instance that will manage the
                           client list. When this is omitted, the client list
                           is stored in an in-memory structure, so the use of
                           multiple connected servers is not possible.
    :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 async_handlers: If set to ``True``, event handlers for a client are
                           executed in separate threads. To run handlers for a
                           client synchronously, set to ``False``. The default
                           is ``True``.
    :param always_connect: When set to ``False``, new connections are
                           provisory until the connect handler returns
                           something other than ``False``, at which point they
                           are accepted. When set to ``True``, connections are
                           immediately accepted, and then if the connect
                           handler returns ``False`` a disconnect is issued.
                           Set to ``True`` if you need to emit events from the
                           connect handler and your client is confused when it
                           receives events before the connection acceptance.
                           In any other case use the default of ``False``.
    :param kwargs: Connection parameters for the underlying Engine.IO server.

    The Engine.IO configuration supports the following settings:

    :param async_mode: The asynchronous model to use. See the Deployment
                       section in the documentation for a description of the
                       available options. Valid async modes are
                       ``'threading'``, ``'eventlet'``, ``'gevent'`` and
                       ``'gevent_uwsgi'``. If this argument is not given,
                       ``'eventlet'`` is tried first, then ``'gevent_uwsgi'``,
                       then ``'gevent'``, and finally ``'threading'``.
                       The first async mode that has all its dependencies
                       installed is then one that is chosen.
    :param ping_interval: The interval in seconds at which the server pings
                          the client. The default is 25 seconds. For advanced
                          control, a two element tuple can be given, where
                          the first number is the ping interval and the second
                          is a grace period added by the server.
    :param ping_timeout: The time in seconds that the client waits for the
                         server to respond before disconnecting. The default
                         is 5 seconds.
    :param max_http_buffer_size: The maximum size of a message when using the
                                 polling transport. The default is 1,000,000
                                 bytes.
    :param allow_upgrades: Whether to allow transport upgrades or not. The
                           default is ``True``.
    :param http_compression: Whether to compress packages when using the
                             polling transport. The default is ``True``.
    :param compression_threshold: Only compress messages when their byte size
                                  is greater than this value. The default is
                                  1024 bytes.
    :param cookie: If set to a string, it is the name of the HTTP cookie the
                   server sends back tot he client containing the client
                   session id. If set to a dictionary, the ``'name'`` key
                   contains the cookie name and other keys define cookie
                   attributes, where the value of each attribute can be a
                   string, a callable with no arguments, or a boolean. If set
                   to ``None`` (the default), a cookie is not sent to the
                   client.
    :param cors_allowed_origins: Origin or list of origins that are allowed to
                                 connect to this server. Only the same origin
                                 is allowed by default. Set this argument to
                                 ``'*'`` to allow all origins, or to ``[]`` to
                                 disable CORS handling.
    :param cors_credentials: Whether credentials (cookies, authentication) are
                             allowed in requests to this server. The default is
                             ``True``.
    :param monitor_clients: If set to ``True``, a background task will ensure
                            inactive clients are closed. Set to ``False`` to
                            disable the monitoring task (not recommended). 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``.
    Nc                    |}|j                  dd       }	|	|	|d<   |dk(  rt        j                  | _        n$|dk(  rddlm}
 |
j                  | _        n|| _        ||| j                  _        ||d<   d|d	<    | j                         di || _	        | j                  j                  d
| j                         | j                  j                  d| j                         | j                  j                  d| j                         i | _        i | _        i | _        i | _        t%        |t&              s|| _        nt*        | _        | j(                  j,                  t.        j0                  k(  r|r*| j(                  j3                  t.        j4                         n)| j(                  j3                  t.        j6                         | j(                  j9                  t/        j:                                |t=        j>                         }|| _         | j@                  jC                  |        d| _"        || _#        || _$        | j                  jJ                  | _%        y )Nengineio_loggerloggerdefaultmsgpackr   )msgpack_packetjsonFasync_handlersconnectmessage
disconnect )&popr   Packetpacket_class r   MsgPackPacketr   _engineio_server_classeioon_handle_eio_connect_handle_eio_message_handle_eio_disconnectenvironhandlersnamespace_handlers_binary_packet
isinstanceboolr   default_loggerlevelloggingNOTSETsetLevelINFOERROR
addHandlerStreamHandlerr   BaseManagermanager
set_servermanager_initializedr   always_connect
async_mode)selfclient_managerr   
serializerr   r   r5   kwargsengineio_optionsr   r   s              O/var/www/highfloat_scraper/venv/lib/python3.12/site-packages/socketio/server.py__init__zServer.__init__m   s    "*../@$G&)8X&" &D9$( . < <D *D%)D"'+V$-2)*04..0D3CDIt778It778L$"="=>"$ &$' DK(DK{{  GNN2KK((6KK((7&&w'<'<'>?!)557N%%#( ,,((--    c                      yNFr   r7   s    r<   is_asyncio_basedzServer.is_asyncio_based   s    r>   c                 <     xs d fd}||S  ||       y)a  Register an event handler.

        :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 handler: The function that should be invoked to handle the
                        event. When this parameter is not given, the method
                        acts as a decorator for the handler function.
        :param namespace: The Socket.IO namespace for the event. If this
                          argument is omitted the handler is associated with
                          the default namespace.

        Example usage::

            # as a decorator:
            @socket_io.on('connect', namespace='/chat')
            def connect_handler(sid, environ):
                print('Connection request')
                if environ['REMOTE_ADDR'] in blacklisted:
                    return False  # reject

            # as a method:
            def message_handler(sid, msg):
                print('Received message: ', msg)
                eio.send(sid, 'response')
            socket_io.on('message', namespace='/chat', handler=message_handler)

        The handler function receives the ``sid`` (session ID) for the
        client as first argument. The ``'connect'`` event handler receives the
        WSGI environment as a second argument, and can return ``False`` to
        reject the connection. The ``'message'`` handler and handlers for
        custom event names receive the message payload as a second argument.
        Any values returned from a message handler will be passed to the
        client's acknowledgement callback function if it exists. The
        ``'disconnect'`` handler does not take a second argument.
        /c                 f    j                   vri j                   <   | j                      <   | S N)r#   )handlereventr   r7   s    r<   set_handlerzServer.on.<locals>.set_handler   s5    -+-i(.5DMM)$U+Nr>   Nr   )r7   rH   rG   r   rI   s   `` ` r<   r   z	Server.on   s*    J $		 ?Gr>   c                      t              dk(  rCt              dk(  r5t        d         r'  j                  d   j                        d         S  fd}|S )a  Decorator to register an event handler.

        This is a simplified version of the ``on()`` method that takes the
        event name from the decorated function.

        Example usage::

            @sio.event
            def my_event(data):
                print('Received data: ', data)

        The above example is equivalent to::

            @sio.on('my_event')
            def my_event(data):
                print('Received data: ', data)

        A custom namespace can be given as an argument to the decorator::

            @sio.event(namespace='/test')
            def my_event(data):
                print('Received data: ', data)
        r   r   c                 P      j                   | j                  gi |       S rF   )r   __name__)rG   argsr:   r7   s    r<   rI   z!Server.event.<locals>.set_handler   s+    Awtwww//A$A&A'JJr>   )lencallabler   rL   )r7   rM   r:   rI   s   ``` r<   rH   zServer.event   sZ    0 t9>c&kQ.8DG3D -47747++,T!W55K r>   c                     t        |t        j                        st        d      | j	                         |j	                         k7  rt        d      |j                  |        || j                  |j                  <   y)zRegister a namespace handler object.

        :param namespace_handler: An instance of a :class:`Namespace`
                                  subclass that handles all the event traffic
                                  for a namespace.
        zNot a namespace instancez+Not a valid namespace class for this serverN)r&   r   	Namespace
ValueErrorrB   _set_serverr$   )r7   namespace_handlers     r<   register_namespacezServer.register_namespace   sp     +Y-@-@A788  "&7&H&H&JJJKK%%d+ 	 1 ; ;<r>   c                     |xs d}|xs |}| j                   j                  d||xs d|        | j                  j                  |||f|||d| y)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 client or clients. 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 to: The recipient of the message. This can be set to the
                   session ID of a client to address only that client, to any
                   any custom room created by the application to address all
                   the clients in that room, or to a list of custom room
                   names. If this argument is omitted the event is broadcasted
                   to all connected clients.
        :param room: Alias for the ``to`` parameter.
        :param skip_sid: The session ID of a client to skip when broadcasting
                         to a room or to all clients. This can be used to
                         prevent a message from being sent to the sender. To
                         skip multiple sids, pass a list.
        :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 client has received the message. The arguments
                         that will be passed to the function are those provided
                         by the client. Callback functions can only be used
                         when addressing an individual client.
        :param ignore_queue: Only used when a message queue is configured. If
                             set to ``True``, the event is emitted to the
                             clients directly, without going through the queue.
                             This is more efficient, but only works when a
                             single server process is used. It is recommended
                             to always leave this parameter with its default
                             value of ``False``.

        Note: this method is not thread safe. If multiple threads are emitting
        at the same time to the same client, 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.
        rD   zemitting event "%s" to %s [%s]all)roomskip_sidcallbackN)r   infor2   emit)	r7   rH   datatorX   rY   r   rZ   r:   s	            r<   r\   zServer.emit  si    X $	zT95		3%y 	Jt#+h	JBH	Jr>   c           
      6     | j                   d||||||d| y)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 client or clients. 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 to: The recipient of the message. This can be set to the
                   session ID of a client to address only that client, to any
                   any custom room created by the application to address all
                   the clients in that room, or to a list of custom room
                   names. If this argument is omitted the event is broadcasted
                   to all connected clients.
        :param room: Alias for the ``to`` parameter.
        :param skip_sid: The session ID of a client to skip when broadcasting
                         to a room or to all clients. This can be used to
                         prevent a message from being sent to the sender. To
                         skip multiple sids, pass a list.
        :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 client has received the message. The arguments
                         that will be passed to the function are those provided
                         by the client. Callback functions can only be used
                         when addressing an individual client.
        :param ignore_queue: Only used when a message queue is configured. If
                             set to ``True``, the event is emitted to the
                             clients directly, without going through the queue.
                             This is more efficient, but only works when a
                             single server process is used. It is recommended
                             to always leave this parameter with its default
                             value of ``False``.
        )r]   r^   rX   rY   r   rZ   N)r   )r\   )r7   r]   r^   rX   rY   r   rZ   r:   s           r<   sendzServer.send9  s0    L 			 	D$2D8%	D<B	Dr>   c                 |  	
 ||t        d      | j                  st        d      | j                  j	                         
g 		
fd} | j
                  |f||xs |||d| 
j                  |      st        j                         t        	d         dkD  r	d   S t        	d         dk(  r	d   d   S dS )	at  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 client or clients. 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 to: The session ID of the recipient client.
        :param sid: Alias for the ``to`` parameter.
        :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.
        :param ignore_queue: Only used when a message queue is configured. If
                             set to ``True``, the event is emitted to the
                             client directly, without going through the queue.
                             This is more efficient, but only works when a
                             single server process is used. It is recommended
                             to always leave this parameter with its default
                             value of ``False``.

        Note: this method is not thread safe. If multiple threads are emitting
        at the same time to the same client, 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.
        NzCannot use call() to broadcast.z/Cannot use call() when async_handlers is False.c                  H    j                  |        j                          y rF   )appendset)rM   callback_argscallback_events    r<   event_callbackz#Server.call.<locals>.event_callback  s      & r>   )r]   rX   r   rZ   )timeoutr   r   )
rR   r   RuntimeErrorr   create_eventr\   waitr   TimeoutErrorrN   )r7   rH   r]   r^   sidr   rh   r:   rg   re   rf   s            @@r<   callzServer.callb  s    B :#+>??""AC C..0	! 			% 	5dsi)	5-3	5""7"3))++#&}Q'7#81#<}Q 	(+M!,<(=(Bq!!$		r>   c                     |xs d}| j                   j                  d|||       | j                  j                  |||       y)a  Enter a room.

        This function adds the client to a room. The :func:`emit` and
        :func:`send` functions can optionally broadcast events to all the
        clients in a room.

        :param sid: Session ID of the client.
        :param room: Room name. If the room does not exist it is created.
        :param namespace: The Socket.IO namespace for the event. If this
                          argument is omitted the default namespace is used.
        rD   z%s is entering room %s [%s]N)r   r[   r2   
enter_roomr7   rm   rX   r   s       r<   rp   zServer.enter_room  s=     $	6T9MY5r>   c                     |xs d}| j                   j                  d|||       | j                  j                  |||       y)a2  Leave a room.

        This function removes the client from a room.

        :param sid: Session ID of the client.
        :param room: Room name.
        :param namespace: The Socket.IO namespace for the event. If this
                          argument is omitted the default namespace is used.
        rD   z%s is leaving room %s [%s]N)r   r[   r2   
leave_roomrq   s       r<   rs   zServer.leave_room  s=     $	5sD)LY5r>   c                     |xs d}| j                   j                  d||       | j                  j                  ||       y)a  Close a room.

        This function removes all the clients from the given room.

        :param room: Room name.
        :param namespace: The Socket.IO namespace for the event. If this
                          argument is omitted the default namespace is used.
        rD   zroom %s is closing [%s]N)r   r[   r2   
close_room)r7   rX   r   s      r<   ru   zServer.close_room  s9     $	2D)Di0r>   c                 F    |xs d}| j                   j                  ||      S )zReturn the rooms a client is in.

        :param sid: Session ID of the client.
        :param namespace: The Socket.IO namespace for the event. If this
                          argument is omitted the default namespace is used.
        rD   )r2   	get_rooms)r7   rm   r   s      r<   roomszServer.rooms  s%     $	||%%c955r>   c                     |xs d}| j                   j                  ||      }| j                  j                  |      }|j	                  |i       S )a  Return the user session for a client.

        :param sid: The session id of the client.
        :param namespace: The Socket.IO namespace. If this argument is omitted
                          the default namespace is used.

        The return value is a dictionary. Modifications made to this
        dictionary are not guaranteed to be preserved unless
        ``save_session()`` is called, or when the ``session`` context manager
        is used.
        rD   )r2   eio_sid_from_sidr   get_session
setdefault)r7   rm   r   eio_sideio_sessions        r<   r{   zServer.get_session  sK     $	,,//Y?hh**73%%i44r>   c                     |xs d}| j                   j                  ||      }| j                  j                  |      }|||<   y)a  Store the user session for a client.

        :param sid: The session id of the client.
        :param session: The session dictionary.
        :param namespace: The Socket.IO namespace. If this argument is omitted
                          the default namespace is used.
        rD   N)r2   rz   r   r{   )r7   rm   sessionr   r}   r~   s         r<   save_sessionzServer.save_session  sB     $	,,//Y?hh**73!(Ir>   c                 >     G fddt               } ||       S )aN  Return the user session for a client with context manager syntax.

        :param sid: The session id of the client.

        This is a context manager that returns the user session dictionary for
        the client. Any changes that are made to this dictionary inside the
        context manager block are saved back to the session. Example usage::

            @sio.on('connect')
            def on_connect(sid, environ):
                username = authenticate_user(environ)
                if not username:
                    return False
                with sio.session(sid) as session:
                    session['username'] = username

            @sio.on('message')
            def on_message(sid, msg):
                with sio.session(sid) as session:
                    print('received message from ', session['username'])
        c                   ,    e Zd Zd Z fdZ fdZy)0Server.session.<locals>._session_context_managerc                 <    || _         || _        || _        d | _        y rF   )serverrm   r   r   )r7   r   rm   r   s       r<   r=   z9Server.session.<locals>._session_context_manager.__init__  s    $!*#r>   c                 `    | j                   j                        | _        | j                  S Nr   )r   r{   r   )r7   r   rm   s    r<   	__enter__z:Server.session.<locals>._session_context_manager.__enter__  s.    #{{66sAJ  7  L||#r>   c                 V    | j                   j                  | j                         y r   )r   r   r   )r7   rM   r   rm   s     r<   __exit__z9Server.session.<locals>._session_context_manager.__exit__  s%    ((dll3< ) >r>   N)rL   
__module____qualname__r=   r   r   )r   rm   s   r<   _session_context_managerr      s    $$
>r>   r   )object)r7   rm   r   r   s    `` r<   r   zServer.session  s     ,	>v 	>  (c9==r>   c                    |xs d}|r| j                   j                  ||      }n| j                   j                  ||      }|r| j                  j	                  d||       | j                   j                  ||      }| j                  || j                  t        j                  |             | j                  d||       | j                   j                  ||       yy)aS  Disconnect a client.

        :param sid: Session ID of the client.
        :param namespace: The Socket.IO namespace to disconnect. If this
                          argument is omitted the default namespace is used.
        :param ignore_queue: Only used when a message queue is configured. If
                             set to ``True``, the disconnect is processed
                             locally, without broadcasting on the queue. It is
                             recommended to always leave this parameter with
                             its default value of ``False``.
        rD   zDisconnecting %s [%s]r   r   N)r2   is_connectedcan_disconnectr   r[   pre_disconnect_send_packetr   r   
DISCONNECT_trigger_eventr   )r7   rm   r   ignore_queue	delete_itr}   s         r<   r   zServer.disconnect  s     $	11#yAI33CCIKK4c9Ell11#1KGgt'8'8!!Y (9 (8 9i=LL##C9#= r>   c                 8    | j                   j                  |      S )zReturn the name of the transport used by the client.

        The two possible values returned by this function are ``'polling'``
        and ``'websocket'``.

        :param sid: The session of the client.
        )r   	transport)r7   rm   s     r<   r   zServer.transport+  s     xx!!#&&r>   c                 x    | j                   j                  ||xs d      }| j                  j                  |      S )zReturn the WSGI environ dictionary for a client.

        :param sid: The session of the client.
        :param namespace: The Socket.IO namespace. If this argument is omitted
                          the default namespace is used.
        rD   )r2   rz   r"   get)r7   rm   r   r}   s       r<   get_environzServer.get_environ5  s4     ,,//Y5E#F||((r>   c                 :    | j                   j                  ||      S )a+  Handle an HTTP request from the client.

        This is the entry point of the Socket.IO application, using the same
        interface as a WSGI application. For the typical usage, this function
        is invoked by the :class:`Middleware` instance, but it can be invoked
        directly when the middleware is not used.

        :param environ: The WSGI environment.
        :param start_response: The WSGI ``start_response`` function.

        This function returns the HTTP response body to deliver to the client
        as a byte sequence.
        )r   handle_request)r7   r"   start_responses      r<   r   zServer.handle_request?  s     xx&&w??r>   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)r7   targetrM   r:   s       r<   r   zServer.start_background_taskO  s%     .txx--fFtFvFFr>   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   sleep)r7   secondss     r<   r   zServer.sleep`  s     xx~~g&&r>   c           	          t        |t              rt        |      }n||g}ng }| j                  || j	                  t
        j                  ||g|z   |             y)zSend a message to a client.N)r   r]   id)r&   tuplelistr   r   r   EVENT)r7   r}   rH   r]   r   r   s         r<   _emit_internalzServer._emit_internalj  s`     dE":D6DD'4#4#4LLIUGdNr $5 $K 	Lr>   c                     |j                         }t        |t              r$|D ]  }| j                  j	                  ||         y| j                  j	                  ||       y)z$Send a Socket.IO packet to a client.N)encoder&   r   r   r`   )r7   r}   pktencoded_packeteps        r<   r   zServer._send_packetw  sL    nd+$ +gr*+ HHMM'>2r>   c                    |xs d}| j                   j                  ||      }|3| j                  || j                  t        j
                  d|             y| j                  r4| j                  || j                  t        j                  d|i|             t        j                         j                  }	 |r#| j                  d||| j                  |   |      }n"	 | j                  d||| j                  |         }|du r| j                  rO| j                   j                  ||       | j                  || j                  t        j                  ||             n2| j                  || j                  t        j
                  ||             | j                   j!                  ||       y| j                  s5| j                  || j                  t        j                  d|i|             yy# t        $ r& | j                  d||| j                  |   d      }Y w xY w# t        j                  $ r}|j                  }d}Y d}~Id}~ww xY w)	z#Handle a client connection request.rD   NzUnable to connect)r]   r   rm   r   r   F)r2   r   r   r   r   CONNECT_ERRORr5   CONNECTr   ConnectionRefusedError
error_argsr   r"   	TypeErrorr   r   r   )r7   r}   r   r]   rm   fail_reasonsuccessexcs           r<   _handle_connectzServer._handle_connect  sA   $	ll""7I6;gt'8'8$$+># (9 (% & gt'8'8	 (9 (C D 779DD	--y#t||G/DdLP"11!9c4<<3HJG e""++C;!!'4+<+<%%K9 ,= ,N O !!'4+<+<(({' ,= ,) * LL##C3$$gt'8'8	 (9 (C D %# ! P"11!9c4<<3H$PGP 00 	..KG	s6   7%H  !G. .+HH  HH   I3IIc                    |xs d}| j                   j                  ||      }| j                   j                  ||      sy| j                   j                  ||       | j	                  d||       | j                   j                  ||       y)zHandle a client disconnect.rD   Nr   r   )r2   sid_from_eio_sidr   r   r   r   )r7   r}   r   rm   s       r<   _handle_disconnectzServer._handle_disconnect  sv    $	ll++GY?||((i8##C9#=L)S9Y/r>   c           	         |xs d}| j                   j                  ||      }| j                  j                  d|d   ||       | j                   j	                  ||      s| j                  j                  d||       y| j                  r"| j                  | j                  | |||||       y| j                  | |||||       y)z Handle an incoming client event.rD   z received event "%s" from %s [%s]r   z#%s is not connected to namespace %sN)	r2   r   r   r[   r   warningr   r   _handle_event_internalr7   r}   r   r   r]   rm   s         r<   _handle_eventzServer._handle_event  s    $	ll++GY?;T!Wc"	$||((i8KK E #Y0&&t'B'BD#'.iE ''c7D)(*,r>   c           	           |j                   |d   ||g|dd   }|X|g }nt        |t              rt        |      }n|g}|j	                  || j                  t        j                  |||             y y )Nr   r   )r   r   r]   )r   r&   r   r   r   r   r   ACK)r7   r   rm   r}   r]   r   r   rs           r<   r   zServer._handle_event_internal  s    !F!!$q'9cEDHE> yAu%Aws):):

iBT *; *C D r>   c                     |xs d}| j                   j                  ||      }| j                  j                  d||       | j                   j	                  |||       y)z#Handle ACK packets from the client.rD   zreceived ack from %s [%s]N)r2   r   r   r[   trigger_callbackr   s         r<   _handle_ackzServer._handle_ack  sO    $	ll++GY?4c9E%%c2t4r>   c                     || j                   v r&|| j                   |   v r | j                   |   |   | S || j                  v r  | j                  |   j                  |g| S y)z$Invoke an application event handler.N)r#   r$   trigger_event)r7   rH   r   rM   s       r<   r   zServer._trigger_event  s{     %%4==3K*K24==+E2D99 $111C4**95CC  2r>   c                 |    | j                   s!d| _         | j                  j                          || j                  |<   y)z&Handle the Engine.IO connection event.TN)r4   r2   
initializer"   )r7   r}   r"   s      r<   r   zServer._handle_eio_connect  s1    '''+D$LL##% 'Wr>   c                    || j                   v r| j                   |   }|j                  |      r| j                   |= |j                  t        j                  k(  r3| 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(  r3| j                  ||j                  |j                  |j                         y|j                  t        j                   k(  r3| j                  ||j                  |j                  |j                         y|j                  t        j                  k(  s|j                  t        j"                  k(  r|| j                   |<   y|j                  t        j$                  k(  rt'        d      t'        d      )zDispatch Engine.IO messages.)r   z Unexpected CONNECT_ERROR packet.zUnknown packet type.N)r%   add_attachmentpacket_typer   BINARY_EVENTr   r   r   r]   r   r   r   r   r   r   r   r   
BINARY_ACKr   rR   )r7   r}   r]   r   s       r<   r    zServer._handle_eio_message  s   d)))%%g.C!!$'''0??f&9&99&&wsvv'*xx1 $$WcmmSVVSXXN ( ##4#8C&..0$$WcmmSXXFF$5$55''?FLL0""7CMM366388LFJJ.  #--JF$7$77OOv'8'88/2##G,F$8$88 !CDD !788r>   c                     t        | j                  j                               j                         D ]  }| j	                  ||        || j
                  v r| j
                  |= yy)z"Handle Engine.IO disconnect event.N)r   r2   get_namespacescopyr   r"   )r7   r}   ns      r<   r!   zServer._handle_eio_disconnect  sY    dll113499; 	0A##GQ/	0dll"W% #r>   c                 "    t         j                  S rF   )engineior
   rA   s    r<   r   zServer._engineio_server_class  s    r>   )NFr   NTF)NN)NNNNNN)NNNNN)NNNN<   rF   r@   )r   )%rL   r   r   __doc__r=   rB   r   rH   rU   r\   r`   rn   rp   rs   ru   rx   r{   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   r   r   r>   r<   r
   r
      s    ^~ FO@E1.f/b!F CG&*1Jf GK'DR CG3j6 6165")&>P>2')@ G"'L3)DV0,"D5	(9:&r>   r
   )r*   r   r   r   r   r   r   	getLoggerr(   r   r
   r   r>   r<   <module>r      s8         """#45FV Fr>   