3
ñ\ð]èc  ã               @   s^   d dl Z d dlZd dlZddlmZ ddlmZ ddlmZ ddlmZ G dd„ dejƒZ	dS )	é    Né   )Úasyncio_manager)Ú
exceptions)Úpacket)Úserverc                   s   e Zd ZdZd<‡ fdd„	Zdd„ Zd=d
d„Zd>dd„Zd?dd„Zd@dd„Z	dAdd„Z
dBdd„ZdCdd„ZdDdd„ZdEdd„Zdd„ Zdd „ ZdFd"d#„ZdGd$d%„Zd&d'„ Zd(d)„ Zd*d+„ Zd,d-„ Zd.d/„ Zd0d1„ Zd2d3„ Zd4d5„ Zd6d7„ Zd8d9„ Zd:d;„ Z‡  ZS )HÚAsyncServeraÂ  A Socket.IO server for asyncio.

    This class implements a fully compliant Socket.IO web server with support
    for websocket and long-polling transports, compatible with the asyncio
    framework on Python 3.5 or newer.

    :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``.
    :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 are executed in
                           separate threads. To run handlers synchronously,
                           set to ``False``. The default is ``True``.
    :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 "aiohttp". If
                       this argument is not given, an async mode is chosen
                       based on the installed packages.
    :param ping_timeout: The time in seconds that the client waits for the
                         server to respond before disconnecting.
    :param ping_interval: The interval in seconds at which the client pings
                          the server.
    :param max_http_buffer_size: The maximum size of a message when using the
                                 polling transport.
    :param allow_upgrades: Whether to allow transport upgrades or not.
    :param http_compression: Whether to compress packages when using the
                             polling transport.
    :param compression_threshold: Only compress messages when their byte size
                                  is greater than this value.
    :param cookie: Name of the HTTP cookie that contains the client session
                   id. If set to ``None``, 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.
    :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``.
    NFTc                s2   |d krt jƒ }tƒ jf ||d||dœ|—Ž d S )NF)Úclient_managerÚloggerÚbinaryÚjsonÚasync_handlers)r   ZAsyncManagerÚsuperÚ__init__)Úselfr   r	   r   r   Úkwargs)Ú	__class__© úB/tmp/pip-build-mqc4i71p/python-socketio/socketio/asyncio_server.pyr   E   s
    zAsyncServer.__init__c             C   s   dS )NTr   )r   r   r   r   Úis_asyncio_basedM   s    zAsyncServer.is_asyncio_basedú	socket.ioc             C   s   | j j||ƒ dS )z.Attach the Socket.IO server to an application.N)ÚeioÚattach)r   ZappZsocketio_pathr   r   r   r   P   s    zAsyncServer.attachc       	      Ë   sP   |pd}|p|}| j jd||p d|ƒ | jj|||f|||dœ|—ŽI dH  dS )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``. If a
                     ``list`` or ``dict``, the data will be serialized as JSON.
        :param to: The recipient of the message. This can be set to the
                   session ID of a client to address only that client, or to
                   to any custom room created by the application to address all
                   the clients in that room, 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.
        :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 a coroutine.
        ú/zemitting event "%s" to %s [%s]Úall)ÚroomÚskip_sidÚcallbackN)r	   ÚinfoÚmanagerÚemit)	r   ÚeventÚdataÚtor   r   Ú	namespacer   r   r   r   r   r   T   s    %
zAsyncServer.emitc          	   Ë   s(   | j d||||||dœ|—ŽI dH  dS )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``. If a
                     ``list`` or ``dict``, the data will be serialized as JSON.
        :param to: The recipient of the message. This can be set to the
                   session ID of a client to address only that client, or to
                   to any custom room created by the application to address all
                   the clients in that room, 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.
        :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 a coroutine.
        Úmessage)r!   r"   r   r   r#   r   N)r$   )r   )r   r!   r"   r   r   r#   r   r   r   r   r   Úsend�   s    %zAsyncServer.sendé<   c       	      ‹   sÊ   | j stdƒ‚| jjƒ ‰g ‰ ‡ ‡fdd„}| j|f||p:|||dœ|—ŽI dH  ytjˆjƒ |ƒI dH  W n& tjk
r�   t	j
tjƒ dƒ Y nX tˆ d ƒdkrªˆ d S tˆ d ƒdkrÆˆ d d S dS )aö  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``. If a
                     ``list`` or ``dict``, the data will be serialized as JSON.
        :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``.
        z/Cannot use call() when async_handlers is False.c                 s   ˆ j | ƒ ˆjƒ  d S )N)ÚappendÚset)Úargs)Úcallback_argsÚcallback_eventr   r   Úevent_callbackÊ   s    
z(AsyncServer.call.<locals>.event_callback)r!   r   r#   r   Nr   r   )r   ÚRuntimeErrorr   Zcreate_eventr   ÚasyncioÚwait_forÚwaitÚTimeoutErrorÚsixÚ
raise_fromr   Úlen)	r   r    r!   r"   Úsidr#   Útimeoutr   r,   r   )r*   r+   r   Úcallª   s    
zAsyncServer.callc             Ã   s0   |pd}| j jd||ƒ | jj||ƒI dH  dS )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.

        Note: this method is a coroutine.
        r   zroom %s is closing [%s]N)r	   r   r   Ú
close_room)r   r   r#   r   r   r   r8   Ø   s    zAsyncServer.close_roomc             Ã   s&   |pd}| j j|ƒI dH }|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. If you want to modify
        the user session, use the ``session`` context manager instead.
        r   N)r   Úget_sessionÚ
setdefault)r   r5   r#   Úeio_sessionr   r   r   r9   ç   s    zAsyncServer.get_sessionc             Ã   s&   |pd}| j j|ƒI dH }|||< dS )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.
        r   N)r   r9   )r   r5   Úsessionr#   r;   r   r   r   Úsave_sessionö   s    zAsyncServer.save_sessionc                s    G ‡ fdd„dt ƒ}|| ˆ |ƒS )aT  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::

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

            @eio.on('message')
            def on_message(sid, msg):
                async with eio.session(sid) as session:
                    print('received message from ', session['username'])
        c                   s,   e Zd Zdd„ Z‡ fdd„Z‡ fdd„ZdS )z5AsyncServer.session.<locals>._session_context_managerc             S   s   || _ || _|| _d | _d S )N)r   r5   r#   r<   )r   r   r5   r#   r   r   r   r     s    z>AsyncServer.session.<locals>._session_context_manager.__init__c             “   s    | j jˆ | jd�I d H | _| jS )N)r#   )r   r9   r#   r<   )r   )r5   r   r   Ú
__aenter__  s    z@AsyncServer.session.<locals>._session_context_manager.__aenter__c             —   s    | j jˆ | j| jd�I d H  d S )N)r#   )r   r=   r<   r#   )r   r)   )r5   r   r   Ú	__aexit__$  s    z?AsyncServer.session.<locals>._session_context_manager.__aexit__N)Ú__name__Ú
__module__Ú__qualname__r   r>   r?   r   )r5   r   r   Ú_session_context_manager  s   rC   )Úobject)r   r5   r#   rC   r   )r5   r   r<     s    zAsyncServer.sessionc             Ã   s˜   |pd}| j j||d�r”| jjd||ƒ | j j||d� | j|tjtj|d�ƒI dH  | j	d||ƒI dH  | j j
||d� |dkr”| jj
|ƒI dH  dS )a  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.

        Note: this method is a coroutine.
        r   )r#   zDisconnecting %s [%s]NÚ
disconnect)r   Úis_connectedr	   r   Úpre_disconnectÚ_send_packetr   ÚPacketÚ
DISCONNECTÚ_trigger_eventrE   r   )r   r5   r#   r   r   r   rE   *  s    	zAsyncServer.disconnectc             Ï   s   | j j||ŽI dH S )zéHandle an HTTP request from the client.

        This is the entry point of the Socket.IO application. This function
        returns the HTTP response body to deliver to the client.

        Note: this method is a coroutine.
        N)r   Úhandle_request)r   r)   r   r   r   r   rL   >  s    zAsyncServer.handle_requestc             O   s   | j j|f|ž|ŽS )a  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. Must be a coroutine.
        :param args: arguments to pass to the function.
        :param kwargs: keyword arguments to pass to the function.

        The return value is a ``asyncio.Task`` object.

        Note: this method is a coroutine.
        )r   Ústart_background_task)r   Útargetr)   r   r   r   r   rM   H  s    z!AsyncServer.start_background_taskr   c             Ã   s   | j j|ƒI dH 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.

        Note: this method is a coroutine.
        N)r   Úsleep)r   Úsecondsr   r   r   rO   Y  s    
zAsyncServer.sleepc          	   Ã   sH   t |tƒrt|ƒ}n|g}| j|tjtj||g| |dd�ƒI dH  dS )zSend a message to a client.N)r#   r!   Úidr
   )Ú
isinstanceÚtupleÚlistrH   r   rI   ÚEVENT)r   r5   r    r!   r#   rQ   r   r   r   Ú_emit_internale  s    


zAsyncServer._emit_internalc             Ã   s^   |j ƒ }t|tƒrBd}xB|D ] }| jj|||d�I dH  d}qW n| jj||dd�I dH  dS )z$Send a Socket.IO packet to a client.F)r
   NT)ÚencoderR   rT   r   r%   )r   r5   ÚpktÚencoded_packetr
   Úepr   r   r   rH   q  s    


zAsyncServer._send_packetc             Ã   sB  |pd}| j j||ƒ | jr:| j|tjtj|d�ƒI dH  d}y | jd||| j| ƒI dH }W n. t	j
k
rŒ } z|j}d}W Y dd}~X nX |dk�r| jrÌ| j j||ƒ | j|tjtj||d�ƒI dH  | j j||ƒ | j�s| j|tjtj||d�ƒI dH  || jk�r>| j|= n&| j�s>| j|tjtj|d�ƒI dH  dS )z#Handle a client connection request.r   )r#   NÚconnectF)r!   r#   )r   r[   Zalways_connectrH   r   rI   ÚCONNECTrK   Úenvironr   ÚConnectionRefusedErrorZ
error_argsrG   rJ   rE   ÚERROR)r   r5   r#   Zfail_reasonÚsuccessÚexcr   r   r   Ú_handle_connect|  s4    




zAsyncServer._handle_connectc             Ã   s¨   |pd}|dkr t | jjƒ ƒ}n|g}xD|D ]<}|dkr,| jj||ƒr,| jd||ƒI dH  | jj||ƒ q,W |dkr¤| jj||ƒr¤| jdd|ƒI dH  | jj|dƒ dS )zHandle a client disconnect.r   rE   N)rT   r   Zget_namespacesrF   rK   rE   )r   r5   r#   Znamespace_listÚnr   r   r   Ú_handle_disconnectš  s    
zAsyncServer._handle_disconnectc             Ã   sz   |pd}| j jd|d ||ƒ | jj||ƒs@| j jd||ƒ dS | jr^| j| j| ||||ƒ n| j| ||||ƒI dH  dS )z Handle an incoming client event.r   z received event "%s" from %s [%s]r   z#%s is not connected to namespace %sN)r	   r   r   rF   Úwarningr   rM   Ú_handle_event_internal)r   r5   r#   rQ   r!   r   r   r   Ú_handle_event©  s    zAsyncServer._handle_eventc          	   Ã   s~   |j |d ||f|dd … žŽ I d H }|d k	rz|d kr<g }nt|tƒrPt|ƒ}n|g}|j|tjtj|||d d�ƒI d H  d S )Nr   r   )r#   rQ   r!   r
   )rK   rR   rS   rT   rH   r   rI   ÚACK)r   r   r5   r!   r#   rQ   Úrr   r   r   rf   ¸  s    &

z"AsyncServer._handle_event_internalc             Ã   s4   |pd}| j jd||ƒ | jj||||ƒI dH  dS )z#Handle ACK packets from the client.r   zreceived ack from %s [%s]N)r	   r   r   Ztrigger_callback)r   r5   r#   rQ   r!   r   r   r   Ú_handle_ackÈ  s    zAsyncServer._handle_ackc             Ç   sª   || j kr€|| j | kr€tj| j | | ƒdkrjy| j | | |Ž I dH }W q| tjk
rf   d}Y q|X n| j | | |Ž }|S || jkr¦| j| j|f|žŽ I dH S dS )z$Invoke an application event handler.TN)Úhandlersr.   ÚiscoroutinefunctionZCancelledErrorZnamespace_handlersZtrigger_event)r   r    r#   r)   Úretr   r   r   rK   Î  s    

zAsyncServer._trigger_eventc             Ã   s2   | j sd| _ | jjƒ  || j|< | j|dƒI dH S )z&Handle the Engine.IO connection event.Tr   N)Zmanager_initializedr   Z
initializer]   rb   )r   r5   r]   r   r   r   Ú_handle_eio_connectá  s
    

zAsyncServer._handle_eio_connectc             Ã   s`  || j krn| j | }|j|ƒrl| j |= |jtjkrP| j||j|j|jƒI dH  n| j	||j|j|jƒI dH  nîtj
|d�}|jtjkrœ| j||jƒI dH  nÀ|jtjkr¾| j||jƒI dH  nž|jtjkrè| j||j|j|jƒI dH  nt|jtjk�r| j	||j|j|jƒI dH  nH|jtjk�s0|jtjk�r<|| j |< n |jtjk�rTtdƒ‚ntdƒ‚dS )zDispatch Engine.IO messages.N)rY   zUnexpected ERROR packet.zUnknown packet type.)Z_binary_packetÚadd_attachmentZpacket_typer   ZBINARY_EVENTrg   r#   rQ   r!   rj   rI   r\   rb   rJ   rd   rU   rh   Z
BINARY_ACKr_   Ú
ValueError)r   r5   r!   rX   r   r   r   Ú_handle_eio_messageé  s0    



zAsyncServer._handle_eio_messagec             Ã   s(   | j |dƒI dH  || jkr$| j|= dS )z"Handle Engine.IO disconnect event.r   N)rd   r]   )r   r5   r   r   r   Ú_handle_eio_disconnect  s    
z"AsyncServer._handle_eio_disconnectc             C   s   t jS )N)Úengineior   )r   r   r   r   Ú_engineio_server_class  s    z"AsyncServer._engineio_server_class)NFNT)r   )NNNNNN)NNNNN)NNNNr&   )N)N)N)N)N)r   )NN)r@   rA   rB   Ú__doc__r   r   r   r   r%   r7   r8   r9   r=   r<   rE   rL   rM   rO   rV   rH   rb   rd   rg   rf   rj   rK   rn   rq   rr   rt   Ú__classcell__r   r   )r   r   r      s>   8 
 
, 
( 
-



(



r   )
r.   rs   r2   Ú r   r   r   r   ÚServerr   r   r   r   r   Ú<module>   s   