3
ñ\ð]Ìg  ã               @   sŒ   d dl Z d dlZd dlZd dlZd dlZd dlZddlmZ ddlmZ ddlm	Z	 ej
dƒZg Zdd„ ZejejeƒZG d	d
„ d
eƒZdS )é    Né   )Ú
exceptions)Ú	namespace)Úpacketzsocketio.clientc             C   s*   xt dd… D ]}|jjƒ  qW t| |ƒS )z•SIGINT handler.

    Notify any clients that are in a reconnect loop to abort. Other
    disconnection tasks are handled at the engine.io level.
    N)Úreconnecting_clientsÚ_reconnect_abortÚsetÚoriginal_signal_handler)ÚsigÚframeÚclient© r   ú:/tmp/pip-build-mqc4i71p/python-socketio/socketio/client.pyÚsignal_handler   s    r   c               @   sþ   e Zd ZdZdAd	d
„Zdd„ ZdBdd„Zdd„ Zdd„ Zi dddfdd„Z	dd„ Z
dCdd„ZdDdd„ZdEdd„Zdd „ Zd!d"„ Zd#d$„ ZdFd%d&„Zd'd(„ Zd)d*„ Zd+d,„ Zd-d.„ Zd/d0„ Zd1d2„ Zd3d4„ Zd5d6„ Zd7d8„ Zd9d:„ Zd;d<„ Zd=d>„ Zd?d@„ ZdS )GÚClienta¼
  A Socket.IO client.

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

    :param reconnection: ``True`` if the client should automatically attempt to
                         reconnect to the server after an interruption, or
                         ``False`` to not reconnect. The default is ``True``.
    :param reconnection_attempts: How many reconnection attempts to issue
                                  before giving up, or 0 for infinity attempts.
                                  The default is 0.
    :param reconnection_delay: How long to wait in seconds before the first
                               reconnection attempt. Each successive attempt
                               doubles this delay.
    :param reconnection_delay_max: The maximum delay between reconnection
                                   attempts.
    :param randomization_factor: Randomization amount for each delay between
                                 reconnection attempts. The default is 0.5,
                                 which means that each delay is randomly
                                 adjusted by +/- 50%.
    :param logger: To enable logging set to ``True`` or pass a logger object to
                   use. To disable logging set to ``False``. The default is
                   ``False``.
    :param binary: ``True`` to support binary payloads, ``False`` to treat all
                   payloads as text. On Python 2, if this is set to ``True``,
                   ``unicode`` values are treated as text, and ``str`` and
                   ``bytes`` values are treated as binary.  This option has no
                   effect on Python 3, where text and binary payloads are
                   always automatically discovered.
    :param json: An alternative json module to use for encoding and decoding
                 packets. Custom json modules must have ``dumps`` and ``loads``
                 functions that are compatible with the standard library
                 versions.

    The Engine.IO configuration supports the following settings:

    :param request_timeout: A timeout in seconds for requests. The default is
                            5 seconds.
    :param ssl_verify: ``True`` to verify SSL certificates, or ``False`` to
                       skip SSL certificate verification, allowing
                       connections to servers with self signed certificates.
                       The default is ``True``.
    :param engineio_logger: To enable Engine.IO logging set to ``True`` or pass
                            a logger object to use. To disable logging set to
                            ``False``. The default is ``False``.
    Tr   r   é   ç      à?FNc	             K   s^  || _ || _|| _|| _|| _|| _|	}
|
jdd ƒ}|d k	rD||
d< |d k	r\|tj_	||
d< | j
ƒ f |
Ž| _| jjd| jƒ | jjd| jƒ | jjd| jƒ t|tƒs®|| _nRt| _tjj oÊ| jjtjk�r |râ| jjtjƒ n| jjtjƒ | jjtjƒ ƒ d | _d | _d | _ d | _!d | _"d | _#d| _$g | _%i | _i | _&i | _'d | _(d | _)| jj*ƒ | _+d S )NÚengineio_loggerÚloggerÚjsonÚconnectÚmessageÚ
disconnectF),ÚreconnectionÚreconnection_attemptsÚreconnection_delayÚreconnection_delay_maxÚrandomization_factorÚbinaryÚpopr   ÚPacketr   Ú_engineio_client_classÚeioÚonÚ_handle_eio_connectÚ_handle_eio_messageÚ_handle_eio_disconnectÚ
isinstanceÚboolr   Údefault_loggerÚloggingÚrootÚhandlersÚlevelÚNOTSETÚsetLevelÚINFOÚERRORÚ
addHandlerÚStreamHandlerÚconnection_urlÚconnection_headersÚconnection_transportsÚconnection_namespacesÚsocketio_pathÚsidÚ	connectedÚ
namespacesÚnamespace_handlersÚ	callbacksÚ_binary_packetÚ_reconnect_taskÚcreate_eventr   )Úselfr   r   r   r   r   r   r   r   ÚkwargsZengineio_optionsr   r   r   r   Ú__init__N   sP    

zClient.__init__c             C   s   dS )NFr   )rA   r   r   r   Úis_asyncio_based‚   s    zClient.is_asyncio_basedc                s0   ˆpd‰‡ ‡‡fdd„}|dkr$|S ||ƒ dS )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:
            @sio.on('connect')
            def connect_handler():
                print('Connected!')

            # as a method:
            def message_handler(msg):
                print('Received message: ', msg)
                sio.send( 'response')
            sio.on('message', message_handler)

        The ``'connect'`` event handler receives no arguments. The
        ``'message'`` handler and handlers for custom event names receive the
        message payload as only 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
        arguments.
        ú/c                s&   ˆˆj kri ˆj ˆ< | ˆj ˆ ˆ < | S )N)r,   )Úhandler)Úeventr   rA   r   r   Úset_handler¨   s    

zClient.on.<locals>.set_handlerNr   )rA   rG   rF   r   rH   r   )rG   r   rA   r   r#   …   s
    !z	Client.onc                sT   t ˆ ƒdkr<t ˆƒdkr<tˆ d ƒr<ˆjˆ d jƒˆ d ƒS ‡ ‡‡fdd„}|S 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                s   ˆj | jfˆ žˆŽ| ƒS )N)r#   Ú__name__)rF   )ÚargsrB   rA   r   r   rH   Ð   s    z!Client.event.<locals>.set_handlerN)ÚlenÚcallabler#   rI   )rA   rJ   rB   rH   r   )rJ   rB   rA   r   rG   ²   s    $zClient.eventc             C   sF   t |tjƒstdƒ‚| jƒ |jƒ kr,tdƒ‚|j| ƒ || j|j< dS )zõRegister 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 clientN)r'   r   ZClientNamespaceÚ
ValueErrorrD   Z_set_clientr<   )rA   Únamespace_handlerr   r   r   Úregister_namespaceÕ   s    
zClient.register_namespacez	socket.ioc             C   sÐ   || _ || _|| _|| _|| _|dkrFt| jjƒ ƒjt| j	jƒ ƒƒ}nt
|tjƒr^|g}|| _dd„ |D ƒ| _y| jj||||d� W n> tjjk
rÄ } ztjtj|jd ƒdƒ W Y dd}~X nX d| _dS )a”  Connect to a Socket.IO server.

        :param url: The URL of the Socket.IO server. It can include custom
                    query string parameters if required by the server.
        :param headers: A dictionary with custom headers to send with the
                        connection request.
        :param transports: The list of allowed transports. Valid transports
                           are ``'polling'`` and ``'websocket'``. If not
                           given, the polling transport is connected first,
                           then an upgrade to websocket is attempted.
        :param namespaces: The list of custom namespaces to connect, in
                           addition to the default namespace. If not given,
                           the namespace list is obtained from the registered
                           event handlers.
        :param socketio_path: The endpoint where the Socket.IO server is
                              installed. The default value is appropriate for
                              most cases.

        Example usage::

            sio = socketio.Client()
            sio.connect('http://localhost:5000')
        Nc             S   s   g | ]}|d kr|‘qS )rE   r   )Ú.0Únr   r   r   ú
<listcomp>	  s    z"Client.connect.<locals>.<listcomp>)ÚheadersÚ
transportsZengineio_pathr   T)r4   r5   r6   r7   r8   r   r,   ÚkeysÚunionr<   r'   ÚsixÚstring_typesr;   r"   r   Úengineior   ÚConnectionErrorÚ
raise_fromrJ   r:   )rA   ÚurlrS   rT   r;   r8   Úexcr   r   r   r   ä   s$    *zClient.connectc             C   s>   x8| j jƒ  | jdƒ | jsP | jjƒ  | j jdkrP qW dS )z¯Wait until the connection with the server ends.

        Client applications can use this function to block the main thread
        during the life of the connection.
        r   r:   N)r"   ÚwaitÚsleepr?   ÚjoinÚstate)rA   r   r   r   r^     s    


zClient.waitc             C   s¸   |pd}|dkr(|| j kr(tj|d ƒ‚| jjd||ƒ |dk	rN| j||ƒ}nd}tjrf| j rfd}nd}t	|t
ƒr~t|ƒ}n|dk	rŽ|g}ng }| jtjtj||g| ||d�ƒ dS )a0  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 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.
        rE   z is not a connected namespace.zEmitting event "%s" [%s]NF)r   ÚdataÚidr   )r;   r   ZBadNamespaceErrorr   ÚinfoÚ_generate_ack_idrW   ÚPY2r   r'   ÚtupleÚlistÚ_send_packetr   r    ÚEVENT)rA   rG   rb   r   Úcallbackrc   r   r   r   r   Úemit   s&    



zClient.emitc             C   s   | j d|||d� 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 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.
        r   )rb   r   rk   N)rl   )rA   rb   r   rk   r   r   r   ÚsendK  s    
zClient.sendé<   c                sz   | j jƒ ‰g ‰ ‡ ‡fdd„}| j||||d� ˆj|d�sBtjƒ ‚tˆ d ƒdkrZˆ d S tˆ d ƒdkrvˆ 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 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.
        c                 s   ˆ j | ƒ ˆjƒ  d S )N)Úappendr   )rJ   )Úcallback_argsÚcallback_eventr   r   Úevent_callbacks  s    
z#Client.call.<locals>.event_callback)rb   r   rk   )Útimeoutr   r   N)r"   r@   rl   r^   r   ÚTimeoutErrorrK   )rA   rG   rb   r   rs   rr   r   )rp   rq   r   Úcall`  s    

zClient.callc             C   sT   x$| j D ]}| jtjtj|d�ƒ qW | jtjtjdd�ƒ d| _| jjdd� dS )zDisconnect from the server.)r   rE   FT)ÚabortN)r;   ri   r   r    Ú
DISCONNECTr:   r"   r   )rA   rQ   r   r   r   r     s    zClient.disconnectc             C   s
   | j jƒ S )z§Return the name of the transport used by the client.

        The two possible values returned by this function are ``'polling'``
        and ``'websocket'``.
        )r"   Ú	transport)rA   r   r   r   rx   Š  s    zClient.transportc             O   s   | j j|f|ž|Ž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)rA   ÚtargetrJ   rB   r   r   r   ry   ’  s    zClient.start_background_taskc             C   s   | j j|ƒS )a  Sleep for the requested amount of time using the appropriate async
        model.

        This is a utility function that applications can use to put a task to
        sleep without having to worry about using the correct call for the
        selected async mode.
        )r"   r_   )rA   Úsecondsr   r   r   r_   £  s    zClient.sleepc             C   sN   |j ƒ }t|tƒr:d}x2|D ]}| jj||d� d}qW n| jj|dd� dS )z&Send a Socket.IO packet to the server.F)r   TN)Úencoder'   rh   r"   rm   )rA   ÚpktÚencoded_packetr   Úepr   r   r   ri   ­  s    


zClient._send_packetc             C   sL   |pd}|| j kr&dtjdƒi| j |< tj| j | d ƒ}|| j | |< |S )z/Generate a unique identifier for an ACK packet.rE   r   r   )r=   Ú	itertoolsÚcountrW   Únext)rA   r   rk   rc   r   r   r   re   ¸  s    
zClient._generate_ack_idc             C   sr   |pd}| j jdj|ƒƒ | jd|d� |dkrXx<| jD ]}| jtjtj|d�ƒ q8W n|| jkrn| jj	|ƒ d S )NrE   zNamespace {} is connectedr   )r   )
r   rd   ÚformatÚ_trigger_eventr;   ri   r   r    ÚCONNECTro   )rA   r   rQ   r   r   r   Ú_handle_connectÁ  s    
zClient._handle_connectc             C   st   | j s
d S |pd}|dkr>x| jD ]}| jd|d� q"W g | _| jd|d� || jkrb| jj|ƒ |dkrpd| _ d S )NrE   r   )r   F)r:   r;   r„   Úremove)rA   r   rQ   r   r   r   Ú_handle_disconnectË  s    
zClient._handle_disconnectc             C   s¢   |pd}| j jd|d |ƒ | j|d |f|dd … žŽ }|d k	rž|d krPg }nt|tƒrdt|ƒ}n|g}tjr~| j r~d}nd }| j	t
jt
j||||d�ƒ d S )NrE   zReceived event "%s" [%s]r   r   F)r   rc   rb   r   )r   rd   r„   r'   rg   rh   rW   rf   r   ri   r   r    ÚACK)rA   r   rc   rb   Úrr   r   r   r   Ú_handle_eventÙ  s    

zClient._handle_eventc             C   sn   |pd}| j jd|ƒ d }y| j| | }W n  tk
rL   | j jdƒ Y nX | j| |= |d k	rj||Ž  d S )NrE   zReceived ack [%s]z$Unknown callback received, ignoring.)r   rd   r=   ÚKeyErrorÚwarning)rA   r   rc   rb   rk   r   r   r   Ú_handle_ackí  s    zClient._handle_ackc             C   s~   |pd}| j jdj|ƒƒ |d kr*tƒ }nt|ttfƒs>|f}| jd|f|žŽ  || jkrf| jj|ƒ |dkrzg | _d| _	d S )NrE   z'Connection to namespace {} was rejectedZconnect_errorF)
r   rd   rƒ   rg   r'   rh   r„   r;   r‡   r:   )rA   r   rb   r   r   r   Ú_handle_errorû  s    

zClient._handle_errorc             G   sN   || j kr*|| j | kr*| j | | |Ž S || jkrJ| j| j|f|žŽ S dS )z$Invoke an application event handler.N)r,   r<   Ztrigger_event)rA   rG   r   rJ   r   r   r   r„   
  s
    

zClient._trigger_eventc             C   s  | j jƒ  tj| ƒ d}| j}xÞ|}|d9 }|| jkr<| j}|| jdtjƒ  d  7 }| jj	dj
|ƒƒ | j j|ƒr‚| jj	dƒ P |d7 }y"| j| j| j| j| j| jd� W n tjtfk
rÆ   Y nX | jj	dƒ d | _P | jr || jkr | jj	dƒ P q W tj| ƒ d S )	Nr   é   r   z1Connection failed, new attempt in {:.02f} secondszReconnect task aborted)rS   rT   r;   r8   zReconnection successfulz0Maximum reconnection attempts reached, giving up)r   Úclearr   ro   r   r   r   Úrandomr   rd   rƒ   r^   r   r4   r5   r6   r7   r8   r   rZ   rM   r?   r   r‡   )rA   Zattempt_countZcurrent_delayÚdelayr   r   r   Ú_handle_reconnect  sD    



zClient._handle_reconnectc             C   s   | j jdƒ | jj| _dS )z&Handle the Engine.IO connection event.z Engine.IO connection establishedN)r   rd   r"   r9   )rA   r   r   r   r$   :  s    zClient._handle_eio_connectc             C   s$  | j rT| j }|j|ƒrRd| _ |jtjkr>| j|j|j|jƒ n| j	|j|j|jƒ nÌtj
|d�}|jtjkrz| j|jƒ n¦|jtjkr”| j|jƒ nŒ|jtjkr¶| j|j|j|jƒ nj|jtjkrØ| j	|j|j|jƒ nH|jtjksð|jtjkrø|| _ n(|jtjk�r| j|j|jƒ ntdƒ‚dS )zDispatch Engine.IO messages.N)r~   zUnknown packet type.)r>   Úadd_attachmentZpacket_typer   ZBINARY_EVENTr‹   r   rc   rb   rŽ   r    r…   r†   rw   rˆ   rj   r‰   Z
BINARY_ACKr1   r�   rM   )rA   rb   r}   r   r   r   r%   ?  s,    
zClient._handle_eio_messagec             C   s€   | j jdƒ | jrJx| jD ]}| jd|d� qW | jddd� g | _d| _i | _d| _d| _| jj	dkr|| j
r|| j| jƒ| _dS )z)Handle the Engine.IO disconnection event.zEngine.IO connection droppedr   )r   rE   FNr:   )r   rd   r:   r;   r„   r=   r>   r9   r"   ra   r   ry   r”   r?   )rA   rQ   r   r   r   r&   [  s    zClient._handle_eio_disconnectc             C   s   t jS )N)rY   r   )rA   r   r   r   r!   k  s    zClient._engineio_client_class)Tr   r   r   r   FFN)NN)NNN)NN)NNrn   )r   )rI   Ú
__module__Ú__qualname__Ú__doc__rC   rD   r#   rG   rO   r   r^   rl   rm   ru   r   rx   ry   r_   ri   re   r†   rˆ   r‹   rŽ   r�   r„   r”   r$   r%   r&   r!   r   r   r   r   r      s@   .   
1
-#,
+



	
%r   )r€   r*   r’   ÚsignalrY   rW   Ú r   r   r   Ú	getLoggerr)   r   r   ÚSIGINTr	   Úobjectr   r   r   r   r   Ú<module>   s   
