
    ik                         S SK r S SKrS SKrSSKJr  SSKJr  SSKJr  SSKJr  \" 5       r	 " S S\R                  5      rg)	    N   )base_server)
exceptions)packet)async_socketc                       \ rS rSrSrS rS rSS jrS rS r	S r
S	 rS
 rSS jrS rS rS rSS jrS rS rS rS rSS jrS rS rSrg)AsyncServer   a  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 that is accepted for incoming
                             messages.  The default is 1,000,000 bytes. In
                             spite of its name, the value set in this
                             argument is enforced for HTTP long-polling and
                             WebSocket connections.
: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
                             ``'*'`` or ``['*']`` 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. This is a process-wide setting, all instantiated
             servers and clients must use the same JSON module.
: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 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 transports: The list of allowed transports. Valid transports
                   are ``'polling'`` and ``'websocket'``. Defaults to
                   ``['polling', 'websocket']``.
:param kwargs: Reserved for future extensions, any additional parameters
               given as keyword arguments will be silently ignored.
c                     g)NT selfs    R/home/admin/cozy_coffee/venv/lib/python3.13/site-packages/engineio/async_server.pyis_asyncio_basedAsyncServer.is_asyncio_basedU   s        c                 
    / SQ$ )N)aiohttpsanictornadoasgir   r   s    r   async_modesAsyncServer.async_modesX   s    66r   c                 Z    UR                  S5      nU R                  S   " XSU S35        g)z.Attach the Engine.IO server to an application./create_routeN)strip_async)r   appengineio_paths      r   attachAsyncServer.attach[   s.    %++C0N#C=//CDr   c                    #    U R                  U[        R                  " [        R                  US95      I Sh  vN   g N7f)a9  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.
)dataN)send_packetr   PacketMESSAGE)r   sidr$   s      r   sendAsyncServer.send`   s,      sFMM&..t$LMMMs   7A?Ac                    #     U R                  U5      nUR	                  U5      I Sh  vN   g! [         a    U R                  R                  SU5         gf = f N17f)zSend a raw packet to a client.

:param sid: The session id of the recipient client.
:param pkt: The packet to send to the client.

Note: this method is a coroutine.
zCannot send to sid %sN)_get_socketKeyErrorloggerwarningr)   )r   r(   pktsockets       r   r%   AsyncServer.send_packetl   s\     	%%c*F
 kk#	  	KK 7=	 	s/   A/ AAA&AAAAc                 D   #    U R                  U5      nUR                  $ 7f)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(   r1   s      r   get_sessionAsyncServer.get_session|   s!      !!#&~~s    c                 :   #    U R                  U5      nX#l        g7f)zxStore the user session for a client.

:param sid: The session id of the client.
:param session: The session dictionary.
Nr4   )r   r(   r5   r1   s       r   save_sessionAsyncServer.save_session   s      !!#& s   c                 0   ^  " U4S jS5      nU" U T5      $ )a  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                   4   > \ rS rSrS rU 4S jrU 4S jrSrg)5AsyncServer.session.<locals>._session_context_manager   c                 *    Xl         X l        S U l        g N)serverr(   r5   )r   rA   r(   s      r   __init__>AsyncServer.session.<locals>._session_context_manager.__init__   s    $#r   c                 x   >#    U R                   R                  T5      I S h  vN U l        U R                  $  N7fr@   )rA   r6   r5   )r   r(   s    r   
__aenter__@AsyncServer.session.<locals>._session_context_manager.__aenter__   s/     %)[[%<%<S%AA||#  Bs   :8:c                 n   >#    U R                   R                  TU R                  5      I S h  vN   g  N7fr@   )rA   r9   r5   )r   argsr(   s     r   	__aexit__?AsyncServer.session.<locals>._session_context_manager.__aexit__   s$     kk..sDLLAAAs   *535)rA   r5   r(   N)__name__
__module____qualname____firstlineno__rB   rE   rI   __static_attributes__)r(   s   r   _session_context_managerr=      s    $
$B Br   rP   r   )r   r(   rP   s    ` r   r5   AsyncServer.session   s    ,	B 	B (c22r   Nc                    #    Ub[   U R                  U5      nUR                  U R                  R                  S9I Sh  vN   XR                  ;   a  U R                  U	 gg[        R                  " U R                  R                  5        Vs/ s H:  n[        R                  " UR                  U R                  R                  S95      PM<     sn5      I Sh  vN   0 U l        g N! [
         a     gf = fs  snf  N#7f)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)reason)
r,   closerS   SERVER_DISCONNECTsocketsr-   asynciowaitvaluescreate_task)r   r(   r1   clients       r   
disconnectAsyncServer.disconnect   s      ?*))#.
 ll$++*G*GlHHH,,&S) ' ,, #ll113  4F ##FLL;;88 %1 %: ;3    
 DL I	    sK   C>C' &C>C%AC>AC7
C>C<C>'
C41C>3C44	C>c                 t  #    U R                   S   n[        R                  " U5      (       a  U" U0 UD6I Sh  vN nOU" U0 UD6nU R                  / :w  as  UR	                  S5      nU(       a[  U R                  U5      nUbG  UU;  aA  U R                  US-   S5        U R                  U R                  US-   5      U5      I Sh  vN $ US   n[        R                  R                  UR	                  SS5      5      nS	U;   a  US	   S
   OSn	Sn
SnUR	                  SS/5      S
   nXR                  ;  a;  U R                  SS5        U R                  U R                  S5      U5      I Sh  vN $ S	U;   a  US	   S
   OSn	U	cQ  UR	                  S5      S/:w  a;  U R                  SS5        U R                  U R                  S5      U5      I Sh  vN $ SU;   a  Sn
 [        US   S
   5      nU
(       a(  Uc%  U R                  SS5        U R                  S5      nGOSUS:X  Ga  SU;   a  UR	                  S5      R#                  5       OSnU	cV  US:X  d  Xs=:X  a  S:X  a  O  OU R%                  XLU5      I Sh  vN nGOU R                  SS5        U R                  S5      nGOXR&                  ;  a+  U R                  SU	 3S5        U R                  SU	 35      nGO U R)                  U	5      nU R+                  U	5      U:w  a-  X:w  a(  U R                  SU	 3S5        U R                  S5      nGO> UR-                  U5      I Sh  vN n[/        U[0        5      (       a  U R3                  UUS 9nOUn XR&                  ;   a+  U R&                  U	   R:                  (       a  U R&                  U		 OUS":X  aw  U	b  XR&                  ;  a*  U R                  SU	 3S5        U R                  SU	 35      nO~U R)                  U	5      n UR=                  U5      I Sh  vN   U R3                  US 9nOCUS$:X  a  U R3                  5       nO,U R>                  RC                  S%U5        U RE                  5       n[/        U[F        5      (       d  U$ U RH                  (       a  [K        US&   5      U RL                  :  a  UR	                  S'S5      RO                  S(5       Vs/ s H%  nURO                  S)5      S
   RQ                  5       PM'     nnU H@  nUU RR                  ;   d  M  [U        U S*U-   5      " US&   5      US&'   US+==   S,U4/-  ss'     O   U R                  X5      I Sh  vN $  GN- GN GN GN! [        [        [         4 a     GNf = f GN GNH! [4        R6                   a=    XR&                  ;   a  U R9                  U	5      I Sh  vN    U R                  5       n GNmf = f! [         a8  nU R                  U S!U	 3S5        U R                  U S!U	 35      n SnAGNSnAff = f GN! [4        R6                   a=    XR&                  ;   a  U R9                  U	5      I Sh  vN    U R                  5       n GN  U R>                  RA                  S#5        U R3                  US 9n GN<= fs  snf  GNU7f)-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	transportpollingzInvalid transportzbad-transport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HTTP_UPGRADE	websocketzInvalid websocket upgradezbad-upgradezInvalid session zbad-sidzInvalid transport for session )jsonp_index POSTzpost request handler errorOPTIONSzMethod %s not supportedresponseHTTP_ACCEPT_ENCODING,;_headerszContent-Encoding)+r   inspectiscoroutinefunctioncors_allowed_originsget_cors_allowed_origins_log_error_once_make_response_bad_requesturllibparseparse_qs
transportsint
ValueErrorr-   
IndexErrorlower_handle_connectrV   r,   rd   handle_get_request
isinstancelist_okr   EngineIOErrorr\   closedhandle_post_requestr.   	exceptionr/   _method_not_founddicthttp_compressionlencompression_thresholdsplitr   compression_methodsgetattr)r   rH   kwargsr_   environoriginallowed_originsmethodqueryr(   jsonprl   rd   rupgrade_headerr1   packetse	encodingsencodings                       r   handle_requestAsyncServer.handle_request   s     !KK(;<&&'899-t>v>>G'88G$$* [[/F"&"<"<W"E".6'4(((!>>N!%!4!4))"%BBD"! ! !
 )*%%gkk."&EF!&%eEl1oT IIkI;7:	OO+  !4oF,,!!"56A A A "'%eEl1oT;599U+u4  )*7 ,,T->->).   
 %<E!%*Q-0
 [(  !=!24!!">?Au_!W, %[[8>>@26 { 	)$E+E"2273>@ @A (()D)68))*EFAll*((+;C5)A9M)),<SE*BCA6!%!1!1#!6
  >>#.); ) ; 00"@ F /1 !% 1 12E FA8060I0I$+1- +-#-gt#<#<(,=H )1 )JA )0A
  #ll2$(LL$5$<$<$(LL$5v{c5$$'7u%=yI%%(8&>?))#.: 44W===[9A y 
AKK 96B&&(A!T""H  AjM"d&@&@@ %;R@FFsKMK 67a..0K  M%t777cHn5a
mD jMiL&8(%C$DDL & ((444Y ?! A *5  @2+- $.#;#; 8#&,,#6*.//#*>$>$>$($5$5$78' $ <,,s!C5\9E --1SEl;<B >!// ,ll*"ooc222))+A: KK))*FG[9AM 5sV  6Z8U%BZ8U(B'Z8,U+-A#Z8U.Z8U1 /B
Z89V:A%Z8 W' 1AZ84V V	)V 2Z83V 5BZ8X/ X,X/ -B+Z8,Z0Z8AZ8 Z5!Z8(Z8+Z8.Z81V
Z8	V

Z8V 7W$
WW$ Z8#W$$Z8'
X)1-X$Z8$X))Z8,X/ /7Z-&Y)'Z-<Z8?+Z-*Z8c                    #    U R                   R                  S5        U R                  (       a6  U R                  R                  5         U R                  I Sh  vN   SU l        gg N7f)zStop Socket.IO background tasks.

This method stops background activity initiated by the Socket.IO
server. It must be called before shutting down the web server.
zSocket.IO is shutting downN)r.   infoservice_task_eventsetservice_task_handler   s    r   shutdownAsyncServer.shutdownh  sT      	56""##'')****'+D$ #*s   AA(A&A(c                 :    [         R                  " U" U0 UD65      $ )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.
)rW   ensure_future)r   targetrH   r   s       r   start_background_task!AsyncServer.start_background_taskt  s     $$VT%<V%<==r   c                 J   #    [         R                  " U5      I Sh  vN $  N7f)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)rW   sleep)r   secondss     r   r   AsyncServer.sleep  s      ]]7++++s   #!#c                 .    [         R                  " U0 UD6$ )a!  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``.
)rW   Queuer   rH   r   s      r   create_queueAsyncServer.create_queue       }}d-f--r   c                 "    [         R                  $ )a2  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``.
)rW   
QueueEmptyr   s    r   get_queue_empty_exception%AsyncServer.get_queue_empty_exception  s     !!!r   c                 .    [         R                  " U0 UD6$ )a#  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``.
)rW   Eventr   s      r   create_eventAsyncServer.create_event  r   r   c                    #    U R                  U5      nU R                  S   n[        R                  " U5      (       a!  U" US   US   U-   US   U5      I S h  vN nU$ U" US   US   U-   US   U5      nU$  N7f)Nmake_responsestatusru   rp   )_cors_headersr   rv   rw   )r   response_dictr   cors_headersr   rp   s         r   r|   AsyncServer._make_response  s     ))'2O4&&}55*h'i(<7j)74 4H 	 %h'i(<7j)74H 4s   AA:A8 A:c           
      >  #    U R                   (       a'  SU l         U R                  U R                  5      U l        U R	                  5       n[
        R                  " X5      nXPR                  U'   [        R                  " [        R                  UU R                  XB5      [        U R                  S-  5      [        U R                  U R                  -   5      S-  U R                   S.5      nUR#                  U5      I Sh  vN   UR%                  5         U R'                  SXASS9I Sh  vN nUbG  USLaB  U R                  U	 U R(                  R+                  S5        U R-                  U=(       d    S5      $ US	:X  aH  UR/                  U5      I Sh  vN nUR0                  (       a  X@R                  ;   a  U R                  U	 U$ SUl        SnU R4                  (       aa  [7        U R4                  [8        5      (       a  S
U R;                  X@R4                  5      4/nO#S
U R;                  UU R4                  SSS.5      4/n U R=                  UR?                  5       I Sh  vN UUS9$  GNi GNC N N! [@        RB                   a    U RE                  5       s $ f = f7f)z#Handle a client connection request.Fi  )r(   upgradespingTimeoutpingInterval
maxPayloadNconnect)	run_asyncTzApplication rejected connectionrk   z
Set-Cookier   Lax)namepathSameSite)ru   rl   )#start_service_taskr   _service_taskr   generate_idr   AsyncSocketrV   r   r&   OPEN	_upgradesr   ping_timeoutping_intervalping_interval_grace_periodmax_http_buffer_sizer)   schedule_ping_trigger_eventr.   r/   _unauthorizedr   r   	connectedcookier   r   _generate_sid_cookier   pollr   r   r}   )	r   r   rd   rl   r(   sr0   retru   s	            r   r   AsyncServer._handle_connect  sY    ""&+D#'+'A'A""($D$  $$T/SmmFKKs6t00478""T%D%DDFHLM33*
  ffSk	''	327 ( 9 9?s$S!KK AB%%ckT22#,,W55CxxC<</LL%JAKG{{dkk400$11#{{C  G %11#$(KK%8   G+xxaffh,7   9 9C 	9 6, !/(( +((**+sn   C>J I)(J)I,*A(JI/B.JI3  I1!I3 (J,J/J1I3 3$JJJJc                 N  ^ ^^#    UR                  SS5      nSnTT R                  ;   a  [        R                  " T R                  T   5      (       ah  UUU 4S jnU(       aG  T R	                  U5      n[
        R                  U5        UR                  [
        R                  5        U$ U" 5       I Sh  vN n U$ UUU 4S jnU(       aG  T R	                  U5      n[
        R                  U5        UR                  [
        R                  5        U$ U" 5       I Sh  vN nU$  Nn N7f)zInvoke an event handler.r   FNc                  Z  >#      TR                   T   " T 6 I S h  vN $  N! [         a:    TS:X  a2  [        T 5      S:X  a#  TR                   T   " T S   5      I S h  vN  s $ e f = f! [        R                   a     g   TR
                  R                  TS-   5        TS:X  a   g g = f7f)Nr\      r   z async handler errorr   F)handlers	TypeErrorr   rW   CancelledErrorr.   r   rH   eventr   s   r   run_async_handler5AsyncServer._trigger_event.<locals>.run_async_handler  s     )	&)-u)=t)D#DD#D( &$4$'IN .2]]5-A$q'-J'J'J J %& #11 )--e6L.LM I- $) .s[   B+"  " B+" :A&AA&"A) #B+$A&&A) )B(=B+?%B($B+c                  
  >#      TR                   T   " T 6 $ ! [         a1    TS:X  a)  [        T 5      S:X  a  TR                   T   " T S   5      s $ e f = f!   TR                  R	                  TS-   5        TS:X  a   g g = f7f)Nr\   r   r   z handler errorr   F)r   r   r   r.   r   r   s   r   run_sync_handler4AsyncServer._trigger_event.<locals>.run_sync_handler  s     )	&#'==#7#>>( &$4$'IN (,}}U';DG'D D %&)--e6F.FG I- $) .s7   B B7AA BAA &B <B)	popr   rv   rw   r   task_reference_holderaddadd_done_callbackdiscard)r   r   rH   r   r   r   r   r   s   ```     r   r   AsyncServer._trigger_event  s     JJ{E2	DMM!**4==+?@@)* 445FGC)--c2))*?*G*GH: 
7 !2 33C6 
3)& 445EFC)--c2))*?*G*GH 
 !1 22C
7 44 3s%   B-D%2D!3A'D%D#D%#D%c                 (  #    [         R                  " 5       nU R                  5       U l        U R                  R	                  5       (       Gd`  [        U R                  5      S:X  aA   [         R                  " U R                  R                  5       U R                  S9I Sh  vN   gU R                  [        U R                  5      -  n U R                  R                  5       R                  5        H  nUR                  (       a   U R                  UR                  	 O)UR                   (       d  UR#                  5       I Sh  vN    [         R                  " U R                  R                  5       US9I Sh  vN   [%        5       e   U R                  R	                  5       (       d  GM_  gg GN! [         R                   a     GM  f = f! [         a     Nf = f N Ne! [         R                   a     GM  f = f! [&        [$        [         R(                  [*        4 a    U R,                  R/                  S5         g  UR1                  5       (       a  U R,                  R/                  S5         gU R,                  R3                  S5         GN= f7f)z;Monitor connected clients and clean up those that time out.r   )timeoutNzservice task canceledz*event loop is closed, exiting service taskzservice task exception)rW   get_running_loopr   r   is_setr   rV   wait_forrX   r   TimeoutErrorcopyrY   r   r(   r-   closingcheck_ping_timeoutKeyboardInterrupt
SystemExitr   GeneratorExitr.   r   	is_closedr   )r   loopsleep_intervalr   s       r   r   AsyncServer._service_task3  s%    '')"&"3"3"5))00224<< A%!**4+B+B+G+G+I373D3DF F F
 "..T\\1BBN!@**,335Axx! $QUU 3
 YY22444!%..t/F/F/K/K/M7EG G G/11 6 ))0022F ++   ( ! !!
 5G #// ! ! !&&	    !89@>>##KK$$ &, - %%&>?s   A$J':F1 !F."F1 &#J
<G= G%G= GG= 	0G!9G:G!G= 
J,J.F1 1G
J	G

J
GG= GG= G!!G:5G= 9G::G= =?J<J>1J/J1JJ)r   r   rV   r   )z	engine.ior@   )r   )rK   rL   rM   rN   __doc__r   r   r!   r)   r%   r6   r9   r5   r\   r   r   r   r   r   r   r   r|   r   r   r   rO   r   r   r   r	   r	      su    CH7E

N 
!#3J4V5p
,>
,.".8+t;z2@r   r	   )rW   rv   r~   rc   r   r   r   r   r   r   
BaseServerr	   r   r   r   <module>r     s:          
  U	@+(( U	@r   