
    2BfV                     n    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ej                        Zy)	    N   )
exceptions)packet)server)asyncio_socketc                       e Zd ZdZd Zd ZddZd Zd Zd Z	d Z
dd
Zd Zd ZddZd Zd Zd Zd ZddZd Zd Zy	)AsyncServera  An Engine.IO server for asyncio.

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

    :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",
                       "sanic", "tornado" and "asgi". If this argument is not
                       given, "aiohttp" is tried first, followed by "sanic",
                       "tornado", and finally "asgi". The first async mode that
                       has all its dependencies installed is the 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 20 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.
    :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: If set to a string, it is the name of the HTTP cookie the
                   server sends back tot he client containing the client
                   session id. If set to a dictionary, the ``'name'`` key
                   contains the cookie name and other keys define cookie
                   attributes, where the value of each attribute can be a
                   string, a callable with no arguments, or a boolean. If set
                   to ``None`` (the default), a cookie is not sent to the
                   client.
    :param cors_allowed_origins: Origin or list of origins that are allowed to
                                 connect to this server. Only the same origin
                                 is allowed by default. Set this argument to
                                 ``'*'`` to allow all origins, or to ``[]`` to
                                 disable CORS handling.
    :param cors_credentials: Whether credentials (cookies, authentication) are
                             allowed in requests to this server.
    :param logger: To enable logging set to ``True`` or pass a logger object to
                   use. To disable logging set to ``False``. Note that fatal
                   errors are 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.
    :param async_handlers: If set to ``True``, run message event handlers in
                           non-blocking threads. To run handlers synchronously,
                           set to ``False``. The default is ``True``.
    :param kwargs: Reserved for future extensions, any additional parameters
                   given as keyword arguments will be silently ignored.
    c                      y)NT selfs    W/var/www/highfloat_scraper/venv/lib/python3.12/site-packages/engineio/asyncio_server.pyis_asyncio_basedzAsyncServer.is_asyncio_basedE   s        c                 
    g dS )N)aiohttpsanictornadoasgir   r   s    r   async_modeszAsyncServer.async_modesH   s    66r   c                 r    |j                  d      } | j                  d   || dj                  |             y)z.Attach the Engine.IO server to an application./create_routez/{}/N)strip_asyncformat)r   appengineio_paths      r   attachzAsyncServer.attachK   s2    %++C0#N#Cv}}]/KLr   c                   K   	 | j                  |      }|j	                  t        j                  t
        j                  |             d{    y# t        $ r | j                  j                  d|       Y yw xY w7 0w)ai  Send a message to a client.

        :param sid: The session id of the recipient client.
        :param data: The data to send to the client. Data can be of type
                     ``str``, ``bytes``, ``list`` or ``dict``. If a ``list``
                     or ``dict``, the data will be serialized as JSON.

        Note: this method is a coroutine.
        zCannot send to sid %sN)data)_get_socketKeyErrorloggerwarningsendr   PacketMESSAGE)r   sidr!   sockets       r   r&   zAsyncServer.sendP   sm     	%%c*F
 kk&--TBCCC	  	KK 7=	 	Ds3   A?A 7A?A=A?%A:7A?9A::A?c                 D   K   | j                  |      }|j                  S w)a;  Return the user session for a client.

        :param sid: The session id of the client.

        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"   session)r   r)   r*   s      r   get_sessionzAsyncServer.get_sessionb   s"      !!#&~~s    c                 <   K   | j                  |      }||_        yw)zStore the user session for a client.

        :param sid: The session id of the client.
        :param session: The session dictionary.
        Nr,   )r   r)   r-   r*   s       r   save_sessionzAsyncServer.save_sessionn   s      !!#& s   c                 8     G f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                   (    e Zd Zd Z fdZ fdZy)5AsyncServer.session.<locals>._session_context_managerc                 .    || _         || _        d | _        y N)r   r)   r-   )r   r   r)   s      r   __init__z>AsyncServer.session.<locals>._session_context_manager.__init__   s    $#r   c                 x   K   | j                   j                         d {   | _        | j                  S 7 wr5   )r   r.   r-   )r   r)   s    r   
__aenter__z@AsyncServer.session.<locals>._session_context_manager.__aenter__   s0     %)[[%<%<S%AA||#  Bs   :8:c                 n   K   | j                   j                  | j                         d {    y 7 wr5   )r   r0   r-   )r   argsr)   s     r   	__aexit__z?AsyncServer.session.<locals>._session_context_manager.__aexit__   s%     kk..sDLLAAAs   *535N)__name__
__module____qualname__r6   r8   r;   )r)   s   r   _session_context_managerr3      s    $
$Br   r?   )object)r   r)   r?   s    ` r   r-   zAsyncServer.sessionw   s     ,	Bv 	B (c22r   Nc                 ~  K   |G	 | j                  |      }|j                          d{    || j                  v r| j                  |= yyt	        j
                  | j                  j                         D cg c]  }|j                          c}       d{    i | _        y7 z# t        $ r Y yw xY wc c}w 7 "w)zDisconnect a client.

        :param sid: The session id of the client to close. If this parameter
                    is not given, then all clients are closed.

        Note: this method is a coroutine.
        N)r"   closesocketsr#   asynciowaitvalues)r   r)   r*   clients       r   
disconnectzAsyncServer.disconnect   s      ?*))#.
 lln$$$,,&S) ' ,,.2ll.A.A.C E$* !'  E F F FDL %	   E FsJ   B=B' B=B%AB=7B6
B=B;B='	B30B=2B33	B=c                 V  K   | j                   d   }t        j                  |      r ||i | d{   }n ||i |}| j                  g k7  rk|j	                  d      }|rX| j                  |      }|E||vrA| j                  |dz   d       | j                  | j                  |dz         |       d{   S |d   }t        j                  j                  |j	                  dd            }d	|v r|d	   d
   nd}	d}
d}d	|v r|d	   d
   nd}	|	P|j	                  d      dgk7  r;| j                  dd       | j                  | j                  d      |       d{   S d|v rd}
	 t        |d   d
         }|
r'|%| j                  dd       | j                  d      }n|dk(  rW|	|j	                  ddg      d
   }d|v r|j	                  d      j!                         nd}|dk(  s||cxk(  rdk(  r n n| j#                  |||       d{   }n| j                  d|z   d       | j                  d|z         }n~|	| j$                  vr+| j                  d|	z   d       | j                  d|	z         }nE| j'                  |	      }	 |j)                  |       d{   }t+        |t,              r| j/                  ||      }n|}|	| j$                  v r| j$                  |	   j6                  r| j$                  |	= n|dk(  rx|	|	| j$                  vr*| j                  d|	z   d       | j                  d|	z         }n| j'                  |	      }	 |j9                  |       d{    | j/                  |      }nB|d k(  r| j/                         }n,| j:                  j?                  d!|       | jA                         }t+        |tB              s|S | jD                  rtG        |d"         | jH                  k\  r|j	                  d#d      jK                  d$      D cg c]$  }|jK                  d%      d
   jM                         & }}|D ]=  }|| jN                  v s tQ        | d&|z         |d"         |d"<   |d'xx   d(|fgz  cc<    n | j                  ||       d{   S 7 n7 7 K# t        t        t        f$ r Y Hw xY w7 7 )# t0        j2                  $ r< |	| j$                  v r| j5                  |	       d{  7   | j                         }Y Ow xY w7 # t0        j2                  $ r< |	| j$                  v r| j5                  |	       d{  7   | j                         }Y  | j:                  j=                  d       | j/                  |      }Y xY wc c}w 7 w))zHandle an HTTP request from the client.

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

        Note: this method is a coroutine.
        translate_requestNHTTP_ORIGINz is not an accepted origin.z
bad-originREQUEST_METHODQUERY_STRING r)   r   FEIO4zRThe client is using an unsupported version of the Socket.IO or Engine.IO protocolszbad-versionjTzInvalid JSONP index numberzbad-jsonp-indexGET	transportpollingHTTP_UPGRADE	websocketzInvalid transport zbad-transportzInvalid session zbad-sid)jsonp_indexPOSTzpost request handler errorOPTIONSzMethod %s not supportedresponseHTTP_ACCEPT_ENCODING,;_headerszContent-Encoding))r   rD   iscoroutinefunctioncors_allowed_originsget_cors_allowed_origins_log_error_once_make_response_bad_requesturllibparseparse_qsint
ValueErrorr#   
IndexErrorlower_handle_connectrC   r"   handle_get_request
isinstancelist_okr   EngineIOErrorrH   closedhandle_post_requestr$   	exceptionr%   _method_not_founddicthttp_compressionlencompression_thresholdsplitr   compression_methodsgetattr)r   r:   kwargsrJ   environoriginallowed_originsmethodqueryr)   jsonprW   rrS   upgrade_headerr*   packetse	encodingsencodings                       r   handle_requestzAsyncServer.handle_request   s     !KK(;<&&'89-t>v>>G'88G$$* [[/F"&"<"<W"E".6'4(((!>>N!%!4!4))"%BBD"! ! !
 )*%%gkk."&EF!&%eEl1oT "'%eEl1oT;599U+u4  )*7 ,,T->->).   
 %<E!%*Q-0
 [(  !=!24!!">?Au_{!IIkI;?B	 &0 ")^!<!B!B!D6: 	)$E+E"227I3>@ @A (()=	)I)8:))*>*JKAdll*(();c)A9M))*<s*BCA!--c2F	0(.(A(A'(J"J%gt4 $k JA 'A
 dll*t||C/@/G/G LL-v{c5$$%7#%=yI%%&83&>?))#.: 44W===[9A y 
AKK 96B&&(A!T"H  AjM"d&@&@@ %;R@FFsKMQa..0 MI M% t7775cHn5a
mD jMiL&8(%C$DDL ((G444o ?!& *5 "@ #K
 &33 0$,,."&//#"666 --/0 >!// ,dll*"ooc222))+A: KK))*FG[9AM 5s  0V)R BV)5R#6B%V)R&
V)'R) 8BV)SA;V)
S
 S*S
 	BV)T #T$T :BV))V!V)AV)V&V)#V)&V))S=V) SV)S
 
5T?T TV)TV)T 5VUV*V)-.VV)c                 8    t        j                   ||i |      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.
        :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.
        )rD   ensure_future)r   targetr:   r   s       r   start_background_taskz!AsyncServer.start_background_task6  s     $$VT%<V%<==r   c                 H   K   t        j                  |       d{   S 7 w)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)rD   sleep)r   secondss     r   r   zAsyncServer.sleepE  s      ]]7++++s   " "c                 ,    t        j                  |i |S )aI  Create a queue object using the appropriate async model.

        This is a utility function that applications can use to create a queue
        without having to worry about using the correct call for the selected
        async mode. For asyncio based async modes, this returns an instance of
        ``asyncio.Queue``.
        )rD   Queuer   r:   r   s      r   create_queuezAsyncServer.create_queueQ       }}d-f--r   c                 "    t         j                  S )aZ  Return the queue empty exception for the appropriate async model.

        This is a utility function that applications can use to work with a
        queue without having to worry about using the correct call for the
        selected async mode. For asyncio based async modes, this returns an
        instance of ``asyncio.QueueEmpty``.
        )rD   
QueueEmptyr   s    r   get_queue_empty_exceptionz%AsyncServer.get_queue_empty_exception[  s     !!!r   c                 ,    t        j                  |i |S )aK  Create an event object using the appropriate async model.

        This is a utility function that applications can use to create an
        event without having to worry about using the correct call for the
        selected async mode. For asyncio based async modes, this returns
        an instance of ``asyncio.Event``.
        )rD   Eventr   s      r   create_eventzAsyncServer.create_evente  r   r   c                    K   | j                  |      }| j                  d   }t        j                  |      r! ||d   |d   |z   |d   |       d {   }|S  ||d   |d   |z   |d   |      }|S 7 w)Nmake_responsestatusr_   rZ   )_cors_headersr   rD   r`   )r   response_dictr   cors_headersr   rZ   s         r   re   zAsyncServer._make_responseo  s     ))'2O4&&}5*h'i(<7j)74 4H 	 %h'i(<7j)74H 4s   AA4A2 A4c           
        K   | j                   r"d| _         | j                  | j                         | j                         }t	        j
                  | |      }|| j                  |<   t        j                  t        j                  || j                  ||      t        | j                  dz        t        | j                  dz        d      }|j                  |       d{    |j                          | j!                  d||d       d{   }|A|dur=| j                  |= | j"                  j%                  d       | j'                  |xs d      S |d	k(  rB|j)                  |       d{   }|j*                  r|| j                  v r| j                  |= |S d|_        d}| j.                  r]t1        | j.                  t2              r d
| j5                  || j.                        fg}n#d
| j5                  || j.                  ddd      fg}	 | j7                  |j9                          d{   ||      S 7 Y7 /7 7 # t:        j<                  $ r | j?                         cY S w xY ww)z#Handle a client connection request.Fi  )r)   upgradespingTimeoutpingIntervalNconnect)	run_asyncTzApplication rejected connectionrV   z
Set-Cookier   Lax)namepathSameSite)r_   rW   ) start_service_taskr   _service_taskgenerate_idr   AsyncSocketrC   r   r'   OPEN	_upgradesrj   ping_timeoutping_intervalr&   schedule_ping_trigger_eventr$   r%   _unauthorizedro   rt   	connectedcookierp   rx   _generate_sid_cookierr   pollr   r   rf   )	r   r   rS   rW   r)   spktretr_   s	            r   rn   zAsyncServer._handle_connect~  sB    ""&+D#&&t'9'9: &&tS1SmmKK&*nnS)&D),T->->-E)F*-d.@.@4.G*HJK
 ffSk	''	327 ( 9 9?s$S!KK AB%%ckT22#,,W55CxxC4<</LL%JAKG{{dkk40$11#t{{C  G %11#$(KK%8   G+xxaffh,7   9 9C 	9 6, !/(( +((**+sn   CI+H8 ,I+H;A I+-H>.BI+I ,I -
I 7I+;I+>I+ I #I(%I+'I((I+c                 ^   K   |j                  dd      }d} j                  v rt        j                   j                           du r?|r   j                   j                     g S 	   j                       d{   }|S |r fd} j	                  |      S 	   j                      }|S |S 7 7# t        j
                  $ r Y |S   j                  j                  dz          dk(  rY yY |S xY w#   j                  j                  dz          dk(  rY yY |S xY ww)	zInvoke an event handler.r   FNTz async handler errorr   c                  0   K    j                        S wr5   )handlers)r:   eventr   s   r   async_handlerz1AsyncServer._trigger_event.<locals>.async_handler  s     3t}}U3T::s   z handler error)popr   rD   r`   r   CancelledErrorr$   rv   )r   r   r:   r   r   r   r   s   ```    r   r   zAsyncServer._trigger_event  sa    JJ{E2	DMM!**4==+?@DH5455dmmE6J =7;= =	)$8DMM%$8$$??0 
 ;  55mDD)2dmmE2D9 
s
1 @"11 , 
+)--e6L.LM I- $) .& 
)--e6F.FG I- $) . 
sT   A)D-/B> B<B> 	D-&D  8D-<B> >C=D-$C=8D- %D*%D-c                   K   	 t        | j                        dk(  r$| j                  | j                         d{    =| j                  t        | j                        z  }	 | j                  j	                         j                         D ]K  }|j                  s$|j                  s|j                          d{    | j                  |       d{    M 	 7 7 #7 # t        t        t        j                  t        f$ r | j                  j                  d       Y y t        j                          j#                         r| j                  j                  d       Y y| j                  j%                  d       Y xY ww)z;Monitor connected clients and clean up those that time out.r   Nzservice task canceledz*event loop is closed, exiting service taskzservice task exception)rz   rC   r   r   copyrF   closingrt   check_ping_timeout
SystemExitKeyboardInterruptrD   r   GeneratorExitr$   infoget_event_loop	is_closedrv   )r   sleep_intervalr*   s      r   r   zAsyncServer._service_task  s?    4<< A%jj!2!2333 "..T\\1BBN@"ll//188: 5F!>>&--$77999**^4445  4 :4!&&	    !89@))+557KK$$ &, - %%&>?sd   8FC'F#AC! 9C:C! CC! FC! C! !>E>F!>E>F!E><F)z	engine.ior5   )r   )r<   r=   r>   __doc__r   r   r   r&   r.   r0   r-   rH   r   r   r   r   r   r   re   rn   r   r   r   r   r   r	   r	   
   sj    9t7M
D$
!#3J.A5F>
,.".4+l#J @r   r	   )	rD   rg   rN   r   r   r   r   Serverr	   r   r   r   <module>r      s+         o@&-- o@r   