
    wgY                         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  e j                  d      Z G d d	ej                        Z
y)
    N   )base_server)
exceptions)packet)socketzengineio.serverc                   f    e Zd ZdZd Zd Zd Zd Zd ZddZ	d	 Z
d
 Zd ZddZ	 ddZd Zd Zy)Servera,  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
                                 ``'*'`` 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.
    :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                 n    | j                  |t        j                  t        j                  |             y)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      T/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/engineio/server.pysendzServer.sendS   s#     	fmmFNNFG    c                     	 | j                  |      } |j                  |       y# t        $ r | j                  j                  d|       Y yw xY w)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   zServer.send_packet]   sP    	%%c*F
 	C	  	KK 7=	s   & %AAc                 <    | j                  |      }|j                  S )aC  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_sessionzServer.get_sessionk   s     !!#&~~r   c                 4    | j                  |      }||_        y)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Server.save_sessionx   s     !!#& r   c                 .     G fdd      } ||       S )aN  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                   (    e Zd Zd Z fdZ fdZy)0Server.session.<locals>._session_context_managerc                 .    || _         || _        d | _        y N)serverr   r   )r   r%   r   s      r   __init__z9Server.session.<locals>._session_context_manager.__init__   s    $#r   c                 \    | j                   j                        | _        | j                  S r$   )r%   r   r   )r   r   s    r   	__enter__z:Server.session.<locals>._session_context_manager.__enter__   s#    #{{66s;||#r   c                 R    | j                   j                  | j                         y r$   )r%   r   r   )r   argsr   s     r   __exit__z9Server.session.<locals>._session_context_manager.__exit__   s    ((dll;r   N)__name__
__module____qualname__r&   r(   r+   )r   s   r   _session_context_managerr"      s    $
$<r   r/    )r   r   r/   s    ` r   r   zServer.session   s    ,	< 	< (c22r   Nc                    |V	 | j                  |      } |j                  | j                  j                         || j                  v r| j                  |= yy| j                  j                         j                         D ](  }|j                  | j                  j                         * i | _        y# t
        $ r Y yw xY 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.
        N)reason)r   closer2   SERVER_DISCONNECTsocketsr   copyvalues)r   r   r   clients       r   
disconnectzServer.disconnect   s     ?*))#.
 DKK$A$AB$,,&S) ' ,,++-446 CDKK$A$ABCDL  s   B4 4	C ?C c                    | j                   g k7  re|j                  d      }|rR| j                  |      }|?||vr;| j                  |dz   d       | j	                  d      } ||d   |d          |d   gS |d	   }t
        j                  j                  |j                  d
d            }d}d}	|j                  ddg      d   }
|
| j                  vr8| j                  dd       | j	                  d      } ||d   |d          |d   gS d|v r|d   d   nd}|M|j                  d      dgk7  r8| j                  dd       | j	                  d      } ||d   |d          |d   gS d|v rd}	 t        |d   d         }	|r'|	%| j                  dd       | j	                  d      }n.|dk(  rpd|v r|j                  d      j                         nd}|N|
dk(  s|
|cxk(  rdk(  rn n| j                  |||
|	      }n| j                  dd       | j	                  d      }n|| j                  vr+| j                  d | d!       | j	                  d |       }nz	 | j!                  |      }| j#                  |      |
k7  r-|
|k7  r(| j                  d"| d       | j	                  d      }n'	  |j$                  ||      }t'        |t(              r| j+                  ||	#      }n|}|| j                  v r| j                  |   j2                  r| j                  |= n|d%k(  rq||| j                  vr*| j                  d | d!       | j	                  d |       }ny| j!                  |      }	  |j4                  |       | j+                  |	#      }nB|d'k(  r| j+                         }n,| j6                  j;                  d(|       | j=                         }t'        |t>              s|S | j@                  rtC        |d         | jD                  k\  r|j                  d)d      jG                  d*      D cg c]$  }|jG                  d+      d   jI                         & }}|D ]=  }|| jJ                  v s tM        | d,|z         |d         |d<   |dxx   d-|fgz  cc<    n | jO                  |      } ||d   |d   |z          |d   gS # t        t        t        f$ r Y `w xY w# t,        j.                  $ r3 || j                  v r| j1                  |       | j	                         }Y ?w xY w# t        $ r8}| j                  | d$| d!       | j	                  | d$|       }Y d}~d}~ww xY w# t,        j.                  $ r3 || j                  v r| j1                  |       | j	                         }Y  | j6                  j9                  d&       | j+                  |	#      }Y xY wc c}w ).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_connectr5   r   rB   handle_get_request
isinstancelist_okr   EngineIOErrorr9   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jsonprJ   rB   r   upgrade_headerr   packetse	encodingsencodingcors_headerss                      r   handle_requestzServer.handle_request   sJ    $$* [[/F"&"<"<W"E".6'4(((!>>N))*CDA"1X;)=jM?*)*%%gkk."&EF IIkI;7:	DOO+  !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,,Wn-6EA (()D)68))*EFAdll*((+;C5)A9M)),<SE*BCA6!%!1!1#!6
  >>#.); )^ ; 00"@ F /1 !% 1 12E FA8*C&*C*C$+^+=#-gt#<(,=H )1 )JA )0A
  #dll2$(LL$5$<$<$(LL$5v{c5$$'7u%=yI%%(8&>?))#.:.F..w7[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 ))'2q{AiL<$?@*{ *5 ` $.#;#; 8#&$,,#6$(OOC$8$($5$5$78' $ <,,s!C5\9E --1SEl;<F "// ,dll*,))+A: KK))*FG[9AMsV   -S T+ /9S" .$U/ 1)W(SS"AT('T(+	U,4-U''U,/AW%4.W%c                     | j                   j                  d       | j                  r<| j                  j                          | j                  j                          d| _        yy)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   shutdownzServer.shutdownT  sQ     	56""##'')$$))+'+D$ #r   c                 V     | j                   d   |||      }|j                          |S )aO  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)targetr*   kwargs)_asyncstart)r   r   r*   r   ths        r   start_background_taskzServer.start_background_task`  s+     #T[["&tFK

	r   c                 ,     | j                   d   |      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.
        sleep)r   )r   secondss     r   r   zServer.sleeps  s     $t{{7#G,,r   c           
         | j                   r'd| _         | j                  | j                        | _        | j	                         }t        j                  | |      }|| j                  |<   t        j                  t        j                  || j                  ||      t        | j                  dz        t        | j                  | j                  z         dz  | j                   d      }|j#                  |       |j%                          | j'                  d||d      }|A|dur=| j                  |= | j(                  j+                  d       | j-                  |xs d      S |d	k(  r;|j/                  ||      }|j0                  r|| j                  v r| j                  |= |S d|_        d}	| j4                  r]t7        | j4                  t8              r d
| j;                  || j4                        fg}	n#d
| j;                  || j4                  ddd      fg}		 | j=                  |j?                         |	|      S # t@        jB                  $ r | jE                         cY S w xY w)z#Handle a client connection request.Fi  )r   upgradespingTimeoutpingInterval
maxPayloadconnect)	run_asyncNTzApplication rejected connectionrI   z
Set-Cookie/Lax)namepathSameSite)r=   rJ   )#start_service_taskr   _service_taskr   generate_idr   Socketr5   r   r   OPEN	_upgradesr[   ping_timeoutping_intervalping_interval_grace_periodmax_http_buffer_sizer   schedule_ping_trigger_eventr   r   _unauthorizedr`   re   	connectedcookiera   ri   _generate_sid_cookierc   pollr   
QueueEmptyrV   )
r   rr   rs   rB   rJ   r   sr   retr=   s
             r   r_   zServer._handle_connect}  s:    ""&+D#'+'A'A""($D$  MM$$SmmFKKsI6t00478""T%D%DDFHLM33*
  	
s	 !!)S'U!K?s$S!KK AB%%ckT22#&&w?CxxC4<</LL%JAKG{{dkk40$11#t{{C  G %11#$(KK%8   G+xx',7   9 9(( +((**+s   !H4 4#IIc                      |j                  dd      } j                  v r! fd}|r j                  |      S  |       S y)zInvoke an event handler.r   Fc                      	 	  j                        S # t        $ r/ dk(  r(t               dk(  r j                       d         cY S  w xY w#  j                  j	                  dz          dk(  rY yY y xY w)Nr9      r   z handler errorr   F)handlers	TypeErrorrk   r   rg   )r*   eventr   s   r   run_handlerz*Server._trigger_event.<locals>.run_handler  s    %	"3t}}U3T::$ " L0 #D	Q $84==#7Q#@@!"%KK))%2B*BC	)  % *s!    4A
A AA %A:N)popr   r   )r   r   r*   r   r   r   s   ```   r   r   zServer._trigger_event  sG    JJ{E2	DMM!%& 11+>>"}$/ "r   c                 X   | j                         | _        | j                  j                         st        | j                        dk(  r(| j                  j                  | j                        ry[t        | j                        t        | j                        z  }	 | j                  j                         j                         D ]i  }|j                  r	 | j                  |j                  = n|j                  s|j                          | j                  j                  |      sat                	 | j                  j                         syy# t        $ r Y Rw xY w# t         t        f$ r | j"                  j%                  d       Y y | j"                  j'                  d       Y wxY w)z;Monitor connected clients and clean up those that time out.r   )timeoutzservice task canceledzservice task exceptionN)create_eventr   is_setrk   r5   waitr   floatr6   r7   re   r   r   closingcheck_ping_timeoutKeyboardInterrupt
SystemExitr   r   rg   )r   sleep_intervalr   s      r   r   zServer._service_task  sb   "&"3"3"5))0024<< A%**//8I8I/J #4#4#45DLL8IIN@**,335 2Axx! $QUU 3
 YY,,...33N3K/112 ))0022   ( ! !!  12   !89@%%&>?s<   7E E,9E &E 	EE EE *F)F)r$   )r   )r,   r-   r.   __doc__r   r   r   r   r   r9   r   r   r   r   r_   r   r   r0   r   r   r	   r	      sU    ELH!#3J*Wr
,&- %)<+|%8 @r   r	   )loggingrW   rA   r   r   r   r   	getLoggerdefault_logger
BaseServerr	   r0   r   r   <module>r      s@         """#45k@[## k@r   