
    wgx                     |   d dl mZ d dlZd dlZdZ	 d dlmZ er ed        ej                  d       d dl
Z
d dl
mZmZ d d	lm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 ddlmZ  G d dej4                        Z G d dee      Z G d d      Zd Zd Z d Z!ddZ"ddZ#ddZ$ddZ%ddZ&y# e$ r dZY w xY w)     )wrapsNT)socketio_manageFzThe gevent-socketio package is incompatible with this version of the Flask-SocketIO extension. Please uninstall it, and then install the latest version of python-socketio in its place.   )has_request_contextjson)SessionMixin)ConnectionRefusedError)DebuggedApplication)run_with_reloader)	NamespaceSocketIOTestClientc                   .     e Zd ZdZd fd	Z fdZ xZS )_SocketIOMiddlewarezxThis WSGI middleware simply exposes the Flask application in the WSGI
    environment before executing the request.
    c                 L    || _         t        | 	  ||j                  |       y )Nsocketio_path)	flask_appsuper__init__wsgi_app)selfsocketio_appr   r   	__class__s       \/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/flask_socketio/__init__.pyr   z_SocketIOMiddleware.__init__"   s)    "y'9'9'4 	 	6    c                 b    |j                         }| j                  |d<   t        |   ||      S )N	flask.app)copyr   r   __call__)r   environstart_responser   s      r   r    z_SocketIOMiddleware.__call__'   s.    ,,.#~~w88r   )	socket.io)__name__
__module____qualname____doc__r   r    __classcell__)r   s   @r   r   r      s    6
9 9r   r   c                       e Zd ZdZy)_ManagedSessionzThis class is used for user sessions that are managed by
    Flask-SocketIO. It is simple dict, expanded with the Flask session
    attributes.N)r$   r%   r&   r'    r   r   r*   r*   -   s     	r   r*   c                       e Zd ZdZej
                  j                  ZddZd ZddZ	ddZ
d ZddZd	 Zd
 Zd Zd Z	 	 ddZddZddZd Zd ZddZ	 	 ddZd Zy)SocketIOa  Create a Flask-SocketIO server.

    :param app: The flask application instance. If the application instance
                isn't known at the time this class is instantiated, then call
                ``socketio.init_app(app)`` once the application instance is
                available.
    :param manage_session: If set to ``True``, this extension manages the user
                           session for Socket.IO events. If set to ``False``,
                           Flask's own session management is used. When using
                           Flask's cookie based sessions it is recommended that
                           you leave this set to the default of ``True``. When
                           using server-side sessions, a ``False`` setting
                           enables sharing the user session between HTTP routes
                           and Socket.IO events.
    :param message_queue: A connection URL for a message queue service the
                          server can use for multi-process communication. A
                          message queue is not required when using a single
                          server process.
    :param channel: The channel name, when using a message queue. If a channel
                    isn't specified, a default channel will be used. If
                    multiple clusters of SocketIO processes need to use the
                    same message queue without interfering with each other,
                    then each cluster should use a different channel.
    :param path: The path where the Socket.IO server is exposed. Defaults to
                 ``'socket.io'``. Leave this as is unless you know what you are
                 doing.
    :param resource: Alias to ``path``.
    :param kwargs: Socket.IO and Engine.IO server options.

    The Socket.IO server options are detailed below:

    :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. In most
                           cases, this argument does not need to be set
                           explicitly.
    :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 will be 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. To use the same json encoder and decoder as a Flask
                 application, use ``flask.json``.
    :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``.

    The Engine.IO server 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 to the 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                     d | _         i | _        d | _        g | _        g | _        i | _        d | _        d| _        |d|v r | j                  |fi | y | j                  j                  |       y )NTmessage_queue)
serverserver_optionswsgi_serverhandlersnamespace_handlersexception_handlersdefault_exception_handlermanage_sessioninit_appupdate)r   appkwargss      r   r   zSocketIO.__init__   su     "$"$)-&" ?o7DMM#((&&v.r   c                    "t        d      si _        | j                  d<   | j                  j                  |       | j                  j	                  d| j
                        | _        d|vr| j                  j                  dd       }| j                  j	                  dd      }d u }|r|j                  d      rt        j                  }nT|j                  d	      rt        j                  }n2|j                  d
      rt        j                  }nt        j                  } ||||      }|| j                  d<   d| j                  v r1| j                  d   t        k(  r G fdd      }|| j                  d<   | j                  j	                  dd       xs  | j                  j	                  dd       xs d}	|	j                  d      r|	dd  }	t        j                  j                  d      r*| j                  j                  d      d| j                  d<   t        j                   di | j                  | _        | j"                  j$                  | _        | j&                  D ])  }
| j"                  j)                  |
d   |
d   |
d          + | j*                  D ]  }| j"                  j-                  |        /t/        | j"                  |	      | _        | j0                  _        y y )N
extensionssocketior7   client_managerr/   channelzflask-socketio)zredis://z	rediss://zkafka://zmq)r@   
write_onlyr   c                   6    e Zd Ze fd       Ze fd       Zy)(SocketIO.init_app.<locals>.FlaskSafeJSONc                  z    j                         5  t        j                  | i |cd d d        S # 1 sw Y   y xY wN)app_context
flask_jsondumpsargsr;   r:   s     r   rI   z.SocketIO.init_app.<locals>.FlaskSafeJSON.dumps   9    * A)//@@A A A   1:c                  z    j                         5  t        j                  | i |cd d d        S # 1 sw Y   y xY wrF   )rG   rH   loadsrJ   s     r   rO   z.SocketIO.init_app.<locals>.FlaskSafeJSON.loads   rL   rM   N)r$   r%   r&   staticmethodrI   rO   )r:   s   r   FlaskSafeJSONrD      s-    A A A Ar   rQ   pathresourcer#   /r   FLASK_RUN_FROM_CLI
async_mode	threadingr      	namespacer   r+   )hasattrr=   r1   r9   popr7   get
startswithr>   RedisManagerKafkaManager
ZmqManagerKombuManagerrH   osr!   Serverr0   rV   r3   onr4   register_namespacer   	sockio_mwr   )r   r:   r;   urlr@   rB   queue_classqueuerQ   rS   handlernamespace_handlers    `          r   r8   zSocketIO.init_app   s   ?3-!#)-CNN:&""6*"11556F6:6I6IK 6)%%))/4@C))--i9IJGJ>>";<"*"7"7K^^J/"*"7"7K^^E*"*"5"5K"*"7"7K#C/9;8=##$45T(((##F+z9
	A 	A +8D'&&**648 E##J5E9D 	s#|H::>>./""&&|4<4?##L1oo<(;(;<++00}} 	IGKKNN71:wqzWQZNH	I!%!8!8 	>KK**+<=	> ? 1c?GIDN>>CL r   c                 &     xs d fd}|S )a  Decorator to register a SocketIO event handler.

        This decorator must be applied to SocketIO event handlers. Example::

            @socketio.on('my event', namespace='/chat')
            def handle_my_custom_event(json):
                print('received json: ' + str(json))

        :param message: The name of the event. This is normally a user defined
                        string, but a few event names are already defined. Use
                        ``'message'`` to define a handler that takes a string
                        payload, ``'json'`` to define a handler that takes a
                        JSON blob payload, ``'connect'`` or ``'disconnect'``
                        to create handlers for connection and disconnection
                        events.
        :param namespace: The namespace on which the handler is to be
                          registered. Defaults to the global namespace.
        rT   c                      t                fd       }j                  r j                  j                  |        S j                  j	                  |f        S )Nc                     }dk(  r| }|d   } |dd  }}dk(  r| }|d   } |gt        |dd        z   } j                  || g| S )N*r   r   )list_handle_event)sidrK   real_nsreal_msgrk   messagerZ   r   s       r   _handlerz0SocketIO.on.<locals>.decorator.<locals>._handler  s     $#!Gq'C8D"c>"Hq'C$:T!"X6D)t))'7GS 1+/1 1r   rY   )r   r0   re   r3   append)rk   rw   rv   rZ   r   s   ` r   	decoratorzSocketIO.on.<locals>.decorator  s_    7^1 1 {{wIF N $$gx%CDNr   r+   )r   rv   rZ   ry   s   ``` r   re   zSocketIO.on  s    & $		, r   c                 "     xs d fd}|S )a  Decorator to define a custom error handler for SocketIO events.

        This decorator can be applied to a function that acts as an error
        handler for a namespace. This handler will be invoked when a SocketIO
        event handler raises an exception. The handler function must accept one
        argument, which is the exception raised. Example::

            @socketio.on_error(namespace='/chat')
            def chat_error_handler(e):
                print('An error has occurred: ' + str(e))

        :param namespace: The namespace for which to register the error
                          handler. Defaults to the global namespace.
        rT   c                 R    t        |       st        d      | j                  <   | S )N"exception_handler must be callable)callable
ValueErrorr5   )exception_handlerrZ   r   s    r   ry   z$SocketIO.on_error.<locals>.decorator?  s.    -. !EFF1BD##I.$$r   r+   )r   rZ   ry   s   `` r   on_errorzSocketIO.on_error.  s     $		%
 r   c                 @    t        |      st        d      || _        |S )ay  Decorator to define a default error handler for SocketIO events.

        This decorator can be applied to a function that acts as a default
        error handler for any namespaces that do not have a specific handler.
        Example::

            @socketio.on_error_default
            def error_handler(e):
                print('An error has occurred: ' + str(e))
        r|   )r}   r~   r6   )r   r   s     r   on_error_defaultzSocketIO.on_error_defaultF  s'     )*ABB):&  r   c                 6     | j                  ||      |       y)a  Register a SocketIO event handler.

        ``on_event`` is the non-decorator version of ``'on'``.

        Example::

            def on_foo_event(json):
                print('received json: ' + str(json))

            socketio.on_event('my event', on_foo_event, namespace='/chat')

        :param message: The name of the event. This is normally a user defined
                        string, but a few event names are already defined. Use
                        ``'message'`` to define a handler that takes a string
                        payload, ``'json'`` to define a handler that takes a
                        JSON blob payload, ``'connect'`` or ``'disconnect'``
                        to create handlers for connection and disconnection
                        events.
        :param handler: The function that handles the event.
        :param namespace: The namespace on which the handler is to be
                          registered. Defaults to the global namespace.
        rY   N)re   )r   rv   rk   rZ   s       r   on_eventzSocketIO.on_eventV  s    . 	.9-g6r   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::

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

        The above example is equivalent to::

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

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

            @socketio.event(namespace='/test')
            def my_event(data):
                print('Received data: ', data)
        r   r   c                 P      j                   | j                  gi |       S rF   )re   r$   )rk   rK   r;   r   s    r   set_handlerz#SocketIO.event.<locals>.set_handler  s+    Awtwww//A$A&A'JJr   )lenr}   re   r$   )r   rK   r;   r   s   ``` r   eventzSocketIO.evento  sZ    0 t9>c&kQ.8DG3D -47747++,T!W55K r   c                     t        |t              st        d      |j                  |        | j                  r| j                  j                  |       y | j                  j                  |       y )NzNot a namespace instance.)
isinstancer   r~   _set_socketior0   rf   r4   rx   )r   rl   s     r   on_namespacezSocketIO.on_namespace  sV    +Y7899''-;;KK**+<=##**+<=r   c                    
 |j                  dd      }|j                  dd      xs |j                  dd      }|j                  dd      }|j                  dd      }|s|st        j                  j                  }|j                  d	d      }|rRd|
|t	               r6t        t        j                  d
d      t        t        j                  dd      
 fd}	r|	}  j                  j                  |g|||||d| y)a  Emit a server generated SocketIO event.

        This function emits a SocketIO event to one or more connected clients.
        A JSON blob can be attached to the event as payload. This function can
        be used outside of a SocketIO event context, so it is appropriate to
        use when the server is the originator of an event, outside of any
        client context, such as in a regular HTTP request handler or a
        background task. Example::

            @app.route('/ping')
            def ping():
                socketio.emit('ping event', {'data': 42}, namespace='/chat')

        :param event: The name of the user event to emit.
        :param args: A dictionary with the JSON data to send as payload.
        :param namespace: The namespace under which the message is to be sent.
                          Defaults to the global namespace.
        :param to: Send the message to all the users in the given room, or to
                   the user with the given session ID. If this parameter is not
                   included, the event is sent to all connected users.
        :param include_self: ``True`` to include the sender when broadcasting
                             or addressing a room, or ``False`` to send to
                             everyone but the sender.
        :param skip_sid: The session id of a client to ignore when broadcasting
                         or addressing a room. This is typically set to the
                         originator of the message, so that everyone except
                         that client receive the message. To skip multiple sids
                         pass a list.
        :param callback: If given, this function will be called to acknowledge
                         that 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.
        rZ   rT   toNroominclude_selfTskip_sidcallbackrs   c                  0     j                   d g|  S rF   )rr   )rK   original_callbackoriginal_namespacer   rs   s    r   _callback_wrapperz(SocketIO.emit.<locals>._callback_wrapper  s-    )t))*;T*<cJDHJ Jr   rZ   r   r   r   )r\   flaskrequestrs   r   getattrr0   emit)r   r   rK   r;   rZ   r   r   r   r   r   r   r   rs   s   `         @@@r   r   zSocketIO.emit  s   F JJ{C0	ZZd#?vzz&$'?zz.$7::j$/H}}((H::j$/C (!*"$emmUD9%,U]]K%N"J 
 - 	I 	Ir"*X	IAG	Ir   c                     |j                  dd      }|j                  dd      xs |j                  dd      } | j                  j                  |g|||d|S )u  Emit a SocketIO event and wait for the response.

        This method issues an emit with a callback and waits for the callback
        to be invoked by the client 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. Example::

            def get_status(client, data):
                status = call('status', {'data': data}, to=client)

        :param event: The name of the user event to emit.
        :param args: A dictionary with the JSON data to send as payload.
        :param namespace: The namespace under which the message is to be sent.
                          Defaults to the global namespace.
        :param to: The session ID of the recipient client.
        :param timeout: The waiting timeout. If the timeout is reached before
                        the client acknowledges the event, then a
                        ``TimeoutError`` exception is raised. The default is 60
                        seconds.
        :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, or when there is a
                             single addressee. It is recommended to always
                             leave this parameter with its default value of
                             ``False``.
        rZ   rT   r   Nr   )rZ   r   )r\   r0   call)r   r   rK   r;   rZ   r   s         r   r   zSocketIO.call  sg    < JJ{C0	ZZd#?vzz&$'?t{{ * *	b *"(* 	*r   c                     |st         j                  j                  n|}|r | j                  d|f||||d| y | j                  d|f||||d| y)ao  Send a server-generated SocketIO message.

        This function sends a simple SocketIO message to one or more connected
        clients. The message can be a string or a JSON blob. This is a simpler
        version of ``emit()``, which should be preferred. This function can be
        used outside of a SocketIO event context, so it is appropriate to use
        when the server is the originator of an event.

        :param data: The message to send, either a string or a JSON blob.
        :param json: ``True`` if ``message`` is a JSON blob, ``False``
                     otherwise.
        :param namespace: The namespace under which the message is to be sent.
                          Defaults to the global namespace.
        :param to: Send the message to all the users in the given room, or to
                   the user with the given session ID. If this parameter is not
                   included, the event is sent to all connected users.
        :param include_self: ``True`` to include the sender when broadcasting
                             or addressing a room, or ``False`` to send to
                             everyone but the sender.
        :param skip_sid: The session id of a client to ignore when broadcasting
                         or addressing a room. This is typically set to the
                         originator of the message, so that everyone except
                         that client receive the message. To skip multiple sids
                         pass a list.
        :param callback: If given, this function will be called to acknowledge
                         that 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.
        r   r   rv   N)r   r   rs   r   )	r   datar   rZ   r   r   r   r   r;   s	            r   sendzSocketIO.send  ss    @ -95==$$hDIIfd FiB'(F>DF DIIi Fr'(F>DFr   c                 <    | j                   j                  ||       y)a  Close a room.

        This function removes any users that are in the given room and then
        deletes the room from the server. This function can be used outside
        of a SocketIO event context.

        :param room: The name of the room to close.
        :param namespace: The namespace under which the room exists. Defaults
                          to the global namespace.
        N)r0   
close_room)r   r   rZ   s      r   r   zSocketIO.close_room&  s     	tY/r   c                     d6j                   d   }|r#d|v rt        |j                  dd      d         ndj                  dj                        }j                  d|      j                  d	|      }j                  d
d      }j                  di       }	|r||	d
<   |_        j                  rS j
                  j                  j                  dk7  r0t         j                  j                  d       j                  _
        j                  dd      }
 j
                  j                  j                  dk(  ri	 ddl}t        j                   rt        j                   j#                         s|
st%        d      ddlm}  |dd        j&                  d"d|d|	 y j
                  j                  j                  dk(  r fd}|rt)        |fi |	 y |        y j
                  j                  j                  dk(  rddlm} 	 ddlm} d}d}sd}|r |j2                  ff|d _        n |j2                  ffd|i _        |r8dd lm} |j9                          |j;                           fd!}t)        |fi |	 y j4                  j=                          yy# t        $ r ddlm}  |dd       Y w xY w# t        $ r d}Y w xY w)#a  Run the SocketIO web server.

        :param app: The Flask application instance.
        :param host: The hostname or IP address for the server to listen on.
                     Defaults to 127.0.0.1.
        :param port: The port number for the server to listen on. Defaults to
                     5000.
        :param debug: ``True`` to start the server in debug mode, ``False`` to
                      start in normal mode.
        :param use_reloader: ``True`` to enable the Flask reloader, ``False``
                             to disable it.
        :param reloader_options: A dictionary with options that are passed to
                                 the Flask reloader, such as ``extra_files``,
                                 ``reloader_type``, etc.
        :param extra_files: A list of additional files that the Flask
                            reloader should watch. Defaults to ``None``.
                            Deprecated, use ``reloader_options`` instead.
        :param log_output: If ``True``, the server logs all incoming
                           connections. If ``False`` logging is disabled.
                           Defaults to ``True`` in debug mode, ``False``
                           in normal mode. Unused when the threading async
                           mode is used.
        :param allow_unsafe_werkzeug: Set to ``True`` to allow the use of the
                                      Werkzeug web server in a production
                                      setting. Default is ``False``. Set to
                                      ``True`` at your own risk.
        :param kwargs: Additional web server options. The web server options
                       are specific to the server used in each of the supported
                       async modes. Note that options provided here will
                       not be seen when using an external web server such
                       as gunicorn, since this method is not called in that
                       case.
        Nz	127.0.0.1SERVER_NAME:r   i  debug
log_outputuse_reloaderextra_filesreloader_optionsrW   T)evalexallow_unsafe_werkzeugFr   )_logwarningzUWebSocket transport not available. Install simple-websocket for improved performance.zThe Werkzeug web server is not designed to run in production. Pass allow_unsafe_werkzeug=True to the run() method to disable this error.znWerkzeug appears to be used in a production deployment. Consider switching to a production web server instead.)hostportthreadedr   eventletc                     dd l } dd l} dd l} | j                  j                  j                  
      }|st        d      | j                  |d   d   |d   d         }g d}D ci c]  }||v r|   ||    }}|D ]  }j                  |d         t        |      dkD  rd|d<    | j                  |fi |} | j                  j                  |fd	i y c c}w )Nr   z)Could not resolve host to a valid address   )	keyfilecertfileserver_side	cert_reqsssl_versionca_certsdo_handshake_on_connectsuppress_ragged_eofsciphersTr   r   )r   eventlet.wsgieventlet.greengreensocketgetaddrinfoRuntimeErrorlistenr\   r   wrap_sslwsgir0   )r   	addresseseventlet_socketssl_argsk
ssl_paramsr:   r   r;   r   r   s         r   
run_serverz SocketIO.run.<locals>.run_server  s%   $%$NN11==dDI	 &CE E"*//)A,q/2;A,q/#C' 5; Jq!"h6!93H  l J
 J! (AJJq$'(z?Q&04J}-&7h&7&7 'F:D'FO %$$_c F0:F>DFJs   'Cgevent)pywsgi)WebSocketHandlerdefault)handler_classlogr   )monkeyc                  :     j                   j                          y rF   )r2   serve_forever)r   s   r   r   z SocketIO.run.<locals>.run_server  s    $$224r   r+   )configintrsplitr\   r   r0   eiorV   r
   rg   r   simple_websocketImportErrorwerkzeug._internalr   sysstdinisattyr   runr   r   r   geventwebsocket.handlerr   
WSGIServerr2   r   patch_thread
patch_timer   )r   r:   r   r   r;   server_namer   r   r   r   r   r   r   r   r   r   gevent_websocketr   r   r   s   `````              @r   r   zSocketIO.run3  s   D <D<**]3Ksk1;--c15a89

7CII.ZZe4
zz.%8jj5!::&8"=.9]+	9933{B, ':'''6DNN# !'

+BE J;;??%%4N'
 99CII$4$4$6,& (M N N
 8 &0 2 CGG MD4!-M1AMEKM[[__'':5F F8 !*A0@A[[__''83%)D#' 
 C#46#4#44L#$'5E$'%$'  $56#4#4dD\3 $H9<$H@F$H  )##%!!#5 "*A0@A  ..0? 4g  N3Y !M NNp  )#( )s$   
K K  KK K.-K.c                    | j                   j                  j                  dk(  r>t        j                  j
                  j                  d      }|r |        yt        d      | j                   j                  j                  dk(  rt        | j                   j                  j                  dk(  r| j                  j                          yy)zzStop a running SocketIO web server.

        This method must be called from a HTTP or SocketIO handler function.
        rW   zwerkzeug.server.shutdownzCannot stop unknown web serverr   r   N)r0   r   rV   r   r   r!   r]   r   
SystemExitr2   stop)r   funcs     r   r   zSocketIO.stop  s    
 ;;??%%4==((,,-GHD"#CDD[[__'':5[[__''83!!# 4r   c                 B     | j                   j                  |g|i |S )aN  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()`` method can be invoked to wait for the task to
        complete.
        )r0   start_background_task)r   targetrK   r;   s       r   r   zSocketIO.start_background_task  s%     1t{{00I$I&IIr   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.
        )r0   sleep)r   secondss     r   r   zSocketIO.sleep  s     {{  ))r   c           	      &    t        || |||||      S )a(  The Socket.IO test client is useful for testing a Flask-SocketIO
        server. It works in a similar way to the Flask Test Client, but
        adapted to the Socket.IO server.

        :param app: The Flask application instance.
        :param namespace: The namespace for the client. If not provided, the
                          client connects to the server on the global
                          namespace.
        :param query_string: A string with custom query string arguments.
        :param headers: A dictionary with custom HTTP headers.
        :param auth: Optional authentication data, given as a dictionary.
        :param flask_test_client: The instance of the Flask test client
                                  currently in use. Passing the Flask test
                                  client is optional, but is necessary if you
                                  want the Flask user session and any other
                                  cookies set in HTTP routes accessible from
                                  Socket.IO events.
        )rZ   query_stringheadersauthflask_test_clientr   )r   r:   rZ   r   r   r   r   s          r   test_clientzSocketIO.test_client  s$    ( "#ty/;W'+4EG 	Gr   c                    | j                   j                  ||      }|sy|d   }|j                  |      5  | j                  rd|vrt	        t
        j                        |d<   |d   }t        t
        d      rCt        t
        j                  d      r)t
        j                  j                  j                         }	nt
        j                  j                  }	||	_        nt
        j                  j                         }|t
        j                  _        |t
        j                  _        ||dt
        j                  _        	 |dk(  rt#        |      d	kD  r|d	   nd }
	  ||
      }n || }| j                  sEt        |d
      r|j2                  r-|j5                         }|j6                  j9                  |||       |cd d d        S # t$        $ r
  |       }Y nw xY w# t&        $ r   | j(                  j+                  || j,                        }| t/        j0                         \  }}} ||      cY cd d d        S xY w# 1 sw Y   y xY w)NrY   ) i  r   saved_sessionglobalsrequest_ctx)rv   rK   connectr   modified)r0   get_environrequest_contextr7   r*   r   sessionr[   r   r   _get_current_object_request_ctx_stacktopr   rs   rZ   r   r   	TypeErrorr	   r5   r]   r6   r   exc_infor   response_classsession_interfacesave_session)r   rk   rv   rZ   rs   rK   r!   r:   session_objctxr   reterr_handlertypevalue	tracebackresps                    r   rr   zSocketIO._handle_event  s
   ++))#)Ck"  ) 1	"" #'1/>u}}/MGO,%o65),}=--33GGIC  2266C) $mm??A #EMM&/EMM#.5t"DEMM*i'&)$i!m47D(%dm "4.C &&{J7#,,--/D))66sKNc1	 1	< % (%i( * *"5599t==?&),&eY"5))U1	 1	 1	 1	sP   DH<?GG"G(AH<GGGGAH9.H<9H<<IrF   )FNNNTNNN)r   )NNNNN)r$   r%   r&   r'   r>   rd   reasonr   r8   re   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rr   r+   r   r   r-   r-   4   s    rf __##F/(A*F+Z0! 72!F>>I@!*F 9=8<&FP0c1J$ J"* =A?CG27r   r-   c           
         d|v r|d   }nt         j                  j                  }|j                  d      }|j                  d      }|j	                  dd      xs |j	                  dd      }||st         j                  j
                  }|j                  dd      }|j                  d	      }|j                  d
d      }	t         j                  j                  d   }
 |
j                  | g|||||||	dS )ab	  Emit a SocketIO event.

    This function emits a SocketIO event to one or more connected clients. A
    JSON blob can be attached to the event as payload. This is a function that
    can only be called from a SocketIO event handler, as in obtains some
    information from the current client context. Example::

        @socketio.on('my event')
        def handle_my_custom_event(json):
            emit('my response', {'data': 42})

    :param event: The name of the user event to emit.
    :param args: A dictionary with the JSON data to send as payload.
    :param namespace: The namespace under which the message is to be sent.
                      Defaults to the namespace used by the originating event.
                      A ``'/'`` can be used to explicitly specify the global
                      namespace.
    :param callback: Callback function to invoke with the client's
                     acknowledgement.
    :param broadcast: ``True`` to send the message to all clients, or ``False``
                      to only reply to the sender of the originating event.
    :param to: Send the message to all the users in the given room, or to the
               user with the given session ID. If this argument is not set and
               ``broadcast`` is ``False``, then the message is sent only to the
               originating user.
    :param include_self: ``True`` to include the sender when broadcasting or
                         addressing a room, or ``False`` to send to everyone
                         but the sender.
    :param skip_sid: The session id of a client to ignore when broadcasting
                     or addressing a room. This is typically set to the
                     originator of the message, so that everyone except
                     that client receive the message. To skip multiple sids
                     pass a list.
    :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, or when there is a
                         single addressee. It is recommended to always leave
                         this parameter with its default value of ``False``.
    rZ   r   	broadcastr   Nr   r   Tr   ignore_queueFr>   )rZ   r   r   r   r   r  )	r   r   rZ   r]   r\   rs   current_appr=   r   )r   rK   r;   rZ   r   r  r   r   r   r  r>   s              r   r   r   V  s    T f;'	MM++	zz*%H

;'I	D$		;6::fd#;B	z)]]::nd3Lzz*%H::ne4L  ++J7H8== G Gr&2X"*G Gr   c                    d|v r|d   }nt         j                  j                  }|j                  dd      xs |j                  dd      }|t         j                  j                  }|j                  dd      }|j                  dd      }t         j                  j                  d	   } |j                  | g|||||d
S )u  Emit a SocketIO event and wait for the response.

    This function issues an emit with a callback and waits for the callback to
    be invoked by the client 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. Example::

        def get_status(client, data):
            status = call('status', {'data': data}, to=client)

    :param event: The name of the user event to emit.
    :param args: A dictionary with the JSON data to send as payload.
    :param namespace: The namespace under which the message is to be sent.
                      Defaults to the namespace used by the originating event.
                      A ``'/'`` can be used to explicitly specify the global
                      namespace.
    :param to: The session ID of the recipient client. If this argument is not
               given, the event is sent to the originating client.
    :param timeout: The waiting timeout. If the timeout is reached before the
                    client acknowledges the event, then a ``TimeoutError``
                    exception is raised. The default is 60 seconds.
    :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, or when there is a
                         single addressee. It is recommended to always leave
                         this parameter with its default value of ``False``.
    rZ   r   Nr   timeout<   r  Fr>   )rZ   r   r  r  )	r   r   rZ   r\   rs   r]   r  r=   r   )r   rK   r;   rZ   r   r  r  r>   s           r   r   r     s    > f;'	MM++		D$		;6::fd#;B	z]]jjB'G::ne4L  ++J7H8== E Er&2GE Er   c           
         |j                  dd      }d|v r|d   }nt        j                  j                  }|j                  d      }|j                  d      }|j	                  dd      xs |j	                  dd      }||st        j                  j
                  }|j                  d	d
      }|j                  d      }|j                  dd      }	t        j                  j                  d   }
 |
j                  | |||||||	      S )a	  Send a SocketIO message.

    This function sends a simple SocketIO message to one or more connected
    clients. The message can be a string or a JSON blob. This is a simpler
    version of ``emit()``, which should be preferred. This is a function that
    can only be called from a SocketIO event handler.

    :param message: The message to send, either a string or a JSON blob.
    :param json: ``True`` if ``message`` is a JSON blob, ``False``
                     otherwise.
    :param namespace: The namespace under which the message is to be sent.
                      Defaults to the namespace used by the originating event.
                      An empty string can be used to use the global namespace.
    :param callback: Callback function to invoke with the client's
                     acknowledgement.
    :param broadcast: ``True`` to send the message to all connected clients, or
                      ``False`` to only reply to the sender of the originating
                      event.
    :param to: Send the message to all the users in the given room, or to the
               user with the given session ID. If this argument is not set and
               ``broadcast`` is ``False``, then the message is sent only to the
               originating user.
    :param include_self: ``True`` to include the sender when broadcasting or
                         addressing a room, or ``False`` to send to everyone
                         but the sender.
    :param skip_sid: The session id of a client to ignore when broadcasting
                     or addressing a room. This is typically set to the
                     originator of the message, so that everyone except
                     that client receive the message. To skip multiple sids
                     pass a list.
    :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, or when there is a
                         single addressee. It is recommended to always leave
                         this parameter with its default value of ``False``.
    r   FrZ   r   r  r   Nr   r   Tr   r  r>   )r   rZ   r   r   r   r   r  )	r]   r   r   rZ   r\   rs   r  r=   r   )rv   r;   r   rZ   r   r  r   r   r   r  r>   s              r   r   r     s    N ::fe$Df;'	MM++	zz*%H

;'I	D$		;6::fd#;B	z)]]::nd3Lzz*%H::ne4L  ++J7H8==tyR&2X"*G Gr   c                     t         j                  j                  d   }|xs t         j                  j                  }|xs t         j                  j
                  }|j                  j                  || |       y)a  Join a room.

    This function puts the user in a room, under the current namespace. The
    user and the namespace are obtained from the event context. This is a
    function that can only be called from a SocketIO event handler. Example::

        @socketio.on('join')
        def on_join(data):
            username = session['username']
            room = data['room']
            join_room(room)
            send(username + ' has entered the room.', to=room)

    :param room: The name of the room to join.
    :param sid: The session id of the client. If not provided, the client is
                obtained from the request context.
    :param namespace: The namespace for the room. If not provided, the
                      namespace is obtained from the request context.
    r>   rY   N)r   r  r=   r   rs   rZ   r0   
enter_roomr   rs   rZ   r>   s       r   	join_roomr    s[    (   ++J7H

"""C4U]]44IOOsDI>r   c                     t         j                  j                  d   }|xs t         j                  j                  }|xs t         j                  j
                  }|j                  j                  || |       y)a  Leave a room.

    This function removes the user from a room, under the current namespace.
    The user and the namespace are obtained from the event context. Example::

        @socketio.on('leave')
        def on_leave(data):
            username = session['username']
            room = data['room']
            leave_room(room)
            send(username + ' has left the room.', to=room)

    :param room: The name of the room to leave.
    :param sid: The session id of the client. If not provided, the client is
                obtained from the request context.
    :param namespace: The namespace for the room. If not provided, the
                      namespace is obtained from the request context.
    r>   rY   N)r   r  r=   r   rs   rZ   r0   
leave_roomr  s       r   r!  r!    s[    &   ++J7H

"""C4U]]44IOOsDI>r   c                     t         j                  j                  d   }|xs t         j                  j                  }|j
                  j                  | |       y)a?  Close a room.

    This function removes any users that are in the given room and then deletes
    the room from the server.

    :param room: The name of the room to close.
    :param namespace: The namespace for the room. If not provided, the
                      namespace is obtained from the request context.
    r>   rY   N)r   r  r=   r   rZ   r0   r   )r   rZ   r>   s      r   r   r   /  sE       ++J7H4U]]44IOOty9r   c                     t         j                  j                  d   }| xs t         j                  j                  } |xs t         j                  j
                  }|j                  j                  | |      S )a  Return a list of the rooms the client is in.

    This function returns all the rooms the client has entered, including its
    own room, assigned by the Socket.IO server.

    :param sid: The session id of the client. If not provided, the client is
                obtained from the request context.
    :param namespace: The namespace for the room. If not provided, the
                      namespace is obtained from the request context.
    r>   rY   )r   r  r=   r   rs   rZ   r0   rooms)rs   rZ   r>   s      r   r$  r$  >  s\       ++J7H

"""C4U]]44I??  	 ::r   c                     t         j                  j                  d   }| xs t         j                  j                  } |xs t         j                  j
                  }|j                  j                  | |      S )a  Disconnect the client.

    This function terminates the connection with the client. As a result of
    this call the client will receive a disconnect event. Example::

        @socketio.on('message')
        def receive_message(msg):
            if is_banned(session['username']):
                disconnect()
            else:
                # ...

    :param sid: The session id of the client. If not provided, the client is
                obtained from the request context.
    :param namespace: The namespace for the room. If not provided, the
                      namespace is obtained from the request context.
    :param silent: this option is deprecated.
    r>   rY   )r   r  r=   r   rs   rZ   r0   
disconnect)rs   rZ   silentr>   s       r   r&  r&  O  s\    &   ++J7H

"""C4U]]44I??%%cY%??r   r  rF   )NNF)'	functoolsr   rc   r   gevent_socketio_foundr>   r   r   printexitr   r   r   rH   flask.sessionsr   socketio.exceptionsr	   werkzeug.debugr
   werkzeug._reloaderr   rZ   r   r   r   WSGIAppr   dictr*   r-   r   r   r   r  r!  r   r$  r&  r+   r   r   <module>r2     s     	 
  "( 	 H I CHHQK  9 '  6 . 0   +9(** 9	dL 	_ _D:Gz+E\8Gv?4?2:;"@K"  "!"s   B1 1B;:B;