
    i/Z                         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  \ R                  " S5      r " S S	\R                  5      r
g)
    N   )base_server)
exceptions)packet)socketzengineio.serverc                   t    \ rS rSrS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S jrS rS rSrg)Server   a  An Engine.IO server.

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

:param async_mode: The asynchronous model to use. See the Deployment
                   section in the documentation for a description of the
                   available options. Valid async modes are "threading",
                   "eventlet", "gevent" and "gevent_uwsgi". If this
                   argument is not given, "eventlet" is tried first, then
                   "gevent_uwsgi", then "gevent", and finally "threading".
                   The first async mode that has all its dependencies
                   installed is 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. The
                       default is ``True``.
:param http_compression: Whether to compress packages when using the
                         polling transport. The default is ``True``.
:param compression_threshold: Only compress messages when their byte size
                              is greater than this value. The default is
                              1024 bytes.
:param cookie: If set to a string, it is the name of the HTTP cookie the
               server sends back 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. The default
                         is ``True``.
:param logger: To enable logging set to ``True`` or pass a logger object to
               use. To disable logging set to ``False``. The default is
               ``False``. Note that fatal errors 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                 j    U R                  U[        R                  " [        R                  US95        g)a  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.
)dataN)send_packetr   PacketMESSAGE)selfsidr   s      L/home/admin/cozy_coffee/venv/lib/python3.13/site-packages/engineio/server.pysendServer.sendT   s#     	fmmFNNFG    c                      U R                  U5      nUR                  " U5        g! [         a    U R                  R                  SU5         gf = 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.
zCannot send to sid %sN)_get_socketKeyErrorloggerwarningr   )r   r   pktr   s       r   r   Server.send_packet^   sN    	%%c*F
 	C	  	KK 7=	s   & &AAc                 <    U R                  U5      nUR                  $ )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 unless
``save_session()`` is called, or when the ``session`` context manager
is used.
r   session)r   r   r   s      r   get_sessionServer.get_sessionl   s     !!#&~~r   c                 2    U R                  U5      nX#l        g)zxStore 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_sessionServer.save_sessiony   s     !!#& r   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):
        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)0Server.session.<locals>._session_context_manager   c                 *    Xl         X l        S U l        g N)serverr   r   )r   r+   r   s      r   __init__9Server.session.<locals>._session_context_manager.__init__   s    $#r   c                 \   > U R                   R                  T5      U l        U R                  $ r*   )r+   r    r   )r   r   s    r   	__enter__:Server.session.<locals>._session_context_manager.__enter__   s#    #{{66s;||#r   c                 R   > U R                   R                  TU R                  5        g r*   )r+   r#   r   )r   argsr   s     r   __exit__9Server.session.<locals>._session_context_manager.__exit__   s    ((dll;r   )r+   r   r   N)__name__
__module____qualname____firstlineno__r,   r/   r3   __static_attributes__)r   s   r   _session_context_managerr'      s    $
$< <r   r:    )r   r   r:   s    ` r   r   Server.session   s    ,	< 	< (c22r   Nc                    UbT   U R                  U5      nUR                  " U R                  R                  S9  XR                  ;   a  U R                  U	 ggU R                  R                  5       R                  5        H&  nUR                  U R                  R                  S9  M(     0 U l        g! [
         a     gf = 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.
N)reason)r   closer>   SERVER_DISCONNECTsocketsr   copyvalues)r   r   r   clients       r   
disconnectServer.disconnect   s     ?*))#.
 DKK$A$AB,,&S) ' ,,++-446DKK$A$AB 7DL  s   B2 2
B?>B?c                 L   U R                   / :w  am  UR                  S5      nU(       aU  U R                  U5      nUbA  UU;  a;  U R                  US-   S5        U R	                  S5      nU" US   US   5        US   /$ US	   n[
        R                  R                  UR                  S
S5      5      nSnSn	UR                  SS/5      S   n
XR                  ;  a8  U R                  SS5        U R	                  S5      nU" US   US   5        US   /$ SU;   a  US   S   OSnUcN  UR                  S5      S/:w  a8  U R                  SS5        U R	                  S5      nU" US   US   5        US   /$ 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O=US:X  Ga}  SU;   a  UR                  S5      R                  5       OSnUcN  U
S:X  d  Xs=:X  a  S:X  a  O  OU R                  XX5      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O0 UR$                  " X5      n['        U[(        5      (       a  U R+                  UU	S#9nOUn XR                  ;   a+  U R                  U   R2                  (       a  U R                  U	 OUS%:X  ap  Ub  XR                  ;  a*  U R                  S U 3S!5        U R	                  S U 35      nOwU R!                  U5      n UR4                  " U5        U R+                  U	S#9nOCUS':X  a  U R+                  5       nO,U R6                  R;                  S(U5        U R=                  5       n['        U[>        5      (       d  U$ U R@                  (       a  [C        US   5      U RD                  :  a  UR                  S)S5      RG                  S*5       Vs/ s H$  oRG                  S+5      S   RI                  5       PM&     nnU H@  nUU RJ                  ;   d  M  [M        U S,U-   5      " US   5      US'   US==   S-U4/-  ss'     O   U RO                  U5      nU" US   US   U-   5        US   /$ ! [        [        [        4 a     GNf = f! [,        R.                   a4    XR                  ;   a  U R1                  U5        U R	                  5       n GNZf = 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! [,        R.                   a4    XR                  ;   a  U R1                  U5        U R	                  5       n GN  U R6                  R9                  S&5        U R+                  U	S#9n GN$= fs  snf ).a  Handle an HTTP request from the client.

This is the entry point of the Engine.IO application, using the same
interface as a WSGI application. For the typical usage, this function
is invoked by the :class:`Middleware` instance, but it can be invoked
directly when the middleware is not used.

:param environ: The WSGI environment.
:param start_response: The WSGI ``start_response`` function.

This function returns the HTTP response body to deliver to the client
as a byte sequence.
HTTP_ORIGINNz is not an accepted origin.z
bad-originzNot an accepted origin.statusheadersresponseREQUEST_METHODQUERY_STRING F	transportpollingr   zInvalid transportzbad-transportr   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HTTP_ACCEPT_ENCODING,;_zContent-Encoding)(cors_allowed_originsget_cors_allowed_origins_log_error_once_bad_requesturllibparseparse_qs
transportsint
ValueErrorr   
IndexErrorlower_handle_connectrA   r   rO   handle_get_request
isinstancelist_okr   EngineIOErrorrE   closedhandle_post_requestr   	exceptionr   _method_not_founddicthttp_compressionlencompression_thresholdsplitstripcompression_methodsgetattr_cors_headers)r   environstart_responseoriginallowed_originsrmethodqueryjsonprW   rO   r   upgrade_headerr   packetse	encodingsencodingcors_headerss                      r   handle_requestServer.handle_request   s4    $$* [[/F"&"<"<W"E".6'4(((!>>N))*CDA"1X;)=jM?*)*%%gkk."&EF IIkI;7:	OO+  !4oF!!"56A1X;)5jM?" "'%eEl1oT;599U+u4  )*79 !!)*A 1X;)5jM?"%<E!%*Q-0
 [(  !=!24!!">?Au_!W, %[[8>>@26 { 	)$E+E,,W-6EA (()D)68))*EFAll*((+;C5)A9M)),<SE*BCA6!%!1!1#!6
  >>#.); ) ; 00"@ F /1 !% 1 12E FA8*0*C*C$++=#-gt#<#<(,=H )1 )JA )0A
  #ll2$(LL$5$<$<$(LL$5v{c5$$'7u%=yI%%(8&>?))#.:..w7[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 & ))'2q{AiL<$?@*{ *5 ` $.#;#; 8#&,,#6$(OOC$8$($5$5$78' $ <,,s!C5\9E --1SEl;<F "// ,ll*,))+A: KK))*FG[9AMs\   =S= 7U$ 7T T !V) !+X!=TTAU! U!$
V&.-V!!V&)AX0+Xc                     U R                   R                  S5        U R                  (       a<  U R                  R                  5         U R                  R                  5         SU l        gg)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_handlejoin)r   s    r   shutdownServer.shutdownU  sQ     	56""##'')$$))+'+D$ #r   c                 N    U R                   S   " XUS9nUR                  5         U$ )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.

This function returns an object that represents the background task,
on which the ``join()`` methond can be invoked to wait for the task to
complete.
thread)targetr2   kwargs)_asyncstart)r   r   r2   r   ths        r   start_background_taskServer.start_background_taska  s'     [["&FK

	r   c                 ,    U R                   S   " U5      $ )zSleep 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.
sleep)r   )r   secondss     r   r   Server.sleept  s     {{7#G,,r   c           
         U R                   (       a'  SU l         U R                  U R                  5      U l        U R	                  5       n[
        R                  " X5      nX`R                  U'   [        R                  " [        R                  UU R                  XS5      [        U R                  S-  5      [        U R                  U R                  -   5      S-  U R                   S.5      nUR#                  U5        UR%                  5         U R'                  SXQSS9nUbG  USLaB  U R                  U	 U R(                  R+                  S5        U R-                  U=(       d    S5      $ US	:X  a@  UR/                  X5      nUR0                  (       a  XPR                  ;   a  U R                  U	 U$ SUl        Sn	U R4                  (       aa  [7        U R4                  [8        5      (       a  S
U R;                  XPR4                  5      4/n	O#S
U R;                  UU R4                  SSS.5      4/n	 U R=                  UR?                  5       U	US9$ ! [@        RB                   a    U RE                  5       s $ f = f)z#Handle a client connection request.Fi  )r   upgradespingTimeoutpingInterval
maxPayloadconnect)	run_asyncNTzApplication rejected connectionrV   z
Set-Cookie/Lax)namepathSameSite)rJ   rW   )#start_service_taskr   _service_taskr   generate_idr   SocketrA   r   r   OPEN	_upgradesrh   ping_timeoutping_intervalping_interval_grace_periodmax_http_buffer_sizer   schedule_ping_trigger_eventr   r   _unauthorizedrm   rr   	connectedcookiern   rv   _generate_sid_cookierp   pollr   
QueueEmptyrc   )
r   r   r   rO   rW   r   sr   retrJ   s
             r   rl   Server._handle_connect~  s/    ""&+D#'+'A'A""($D$  MM$$SmmFKKs6t00478""T%D%DDFHLM33*
  	
s	 !!)SU!K?s$S!KK AB%%ckT22#&&w?CxxC<</LL%JAKG{{dkk400$11#{{C  G %11#$(KK%8   G+xx',7   9 9(( +((**+s   (I $I.-I.c                    ^ ^^ UR                  SS5      nTT R                  ;   a'  UUU 4S jnU(       a  T R                  U5      $ U" 5       $ g)zInvoke an event handler.r   Fc                    >   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)NrE      r   z handler errorr   F)handlers	TypeErrorrx   r   rt   )r2   eventr   s   r   run_handler*Server._trigger_event.<locals>.run_handler  s    %	"#}}U3T::$ " L0 #D	Q $(==#7Q#@@!"%KK))%2B*BC	)  % *s!    7AA AA &A>N)popr   r   )r   r   r2   r   r   r   s   ```   r   r   Server._trigger_event  sG    JJ{E2	DMM!%& 11+>>"}$/ "r   c                    U R                  5       U l        U R                  R                  5       (       Gd5  [        U R                  5      S:X  a+  U R                  R                  U R                  S9(       a  gMd  [        U R                  5      [        U R                  5      -  n U R                  R                  5       R                  5        Hv  nUR                  (       a   U R                  UR                  	 O!UR                  (       d  UR                  5         U R                  R                  US9(       d  Mn  [        5       e   U R                  R                  5       (       d  GM4  gg! [         a     N\f = f! [         [        4 a    U R"                  R%                  S5         g  U R"                  R'                  S5         N= f)z;Monitor connected clients and clean up those that time out.r   )timeoutzservice task canceledzservice task exceptionN)create_eventr   is_setrx   rA   waitr   floatrB   rC   rr   r   r   closingcheck_ping_timeoutKeyboardInterrupt
SystemExitr   r   rt   )r   sleep_intervalr   s      r   r   Server._service_task  sc   "&"3"3"5))00224<< A%**//8I8I/J #4#4#45DLL8IIN@**,335Axx! $QUU 3
 YY,,...33N3KK/11 6 ))0022   ( ! !!  12   !89@%%&>?s<   &<E< #E,:>E< <E< ,
E96E< 8E99E< <+G)G)r   r   rA   r   r*   )r   )r5   r6   r7   r8   __doc__r   r   r    r#   r   rE   r   r   r   r   rl   r   r   r9   r;   r   r   r	   r	      sU    FNH!#3J*Wr
,&- %)<+|%8 @r   r	   )loggingrd   rN   r   r   r   r   	getLoggerdefault_logger
BaseServerr	   r;   r   r   <module>r      s>         ""#45l@[## l@r   