o
    ¨Ýj«9  ã                   @   sl   d dl Z d dlZd dlZd dlZd dlZd dlZd dlZddlmZ ddlm	Z	 e 
d¡ZG dd„ dƒZdS )é    Né   )Úpacket)Úpayloadzengineio.serverc                   @   sø   e Zd ZddgZg d¢ZddgZdZdZG dd	„ d	ƒZ				
	
	
d:dd„Z	dd„ Z
dd„ Zd;dd„Zdd„ Zdd„ Zdd„ Zdd„ Zd d!„ Zd"d#„ Zd$d%„ Zd&d'„ Zd<d(d)„Zd;d*d+„Zd,d-„ Zd;d.d/„Zd0d1„ Zd2d3„ Zd4d5„ Zd6d7„ Zd8d9„ Zd
S )=Ú
BaseServerÚgzipÚdeflate)ÚconnectZ
disconnectÚmessageÚpollingÚ	websocketTr   c                   @   s$   e Zd ZdZdZdZdZdZdZdS )zBaseServer.reasonzDisconnection reasons.zserver disconnectzclient disconnectzping timeoutztransport closeztransport errorN)	Ú__name__Ú
__module__Ú__qualname__Ú__doc__ZSERVER_DISCONNECTZCLIENT_DISCONNECTZPING_TIMEOUTZTRANSPORT_CLOSEÚTRANSPORT_ERROR© r   r   úO/var/www/html/chatgpt/venv/lib/python3.10/site-packages/engineio/base_server.pyÚreason   s    r   Né   é   é@B é   Fc              	      sF  |ˆ _ t|tƒr|d ˆ _|d ˆ _n|ˆ _dˆ _|ˆ _|ˆ _|ˆ _|ˆ _|ˆ _	|	ˆ _
|
ˆ _|ˆ _i ˆ _i ˆ _tƒ ˆ _|d urA|nˆ jˆ _d ˆ _d ˆ _|d urS|tj_t|tƒs\|ˆ _n#tˆ _ˆ jjtjkr|rpˆ j tj¡ nˆ j tj ¡ ˆ j !t "¡ ¡ ˆ  #¡ }|d ur�||v rŽ|gng }d ˆ _$d ˆ _%|D ].}z#t& 'd| ¡j$ˆ _$dˆ j$v r®ˆ j$d nd}|ˆ  (¡ kr¸W q˜|ˆ _%W  n	 t)yÆ   Y q˜w ˆ j%d u rÐt*dƒ‚ˆ  (¡ râdˆ j$vsÞˆ j$d sât*dƒ‚ˆ  (¡ sôdˆ j$v rôˆ j$d rôt*dƒ‚|d u�rt|t+ƒ�r|g}‡ fd	d
„|D ƒ}|�st*dƒ‚|�pˆ j,ˆ _-ˆ j .dˆ j%¡ d S )Nr   r   zengineio.async_drivers.ZasyncioFzInvalid async_mode specifiedz1The selected async_mode is not asyncio compatiblezKThe selected async_mode requires asyncio and must use the AsyncServer classc                    s   g | ]	}|ˆ j v r|‘qS r   )Úvalid_transports)Ú.0Ú	transport©Úselfr   r   Ú
<listcomp>k   s    
ÿz'BaseServer.__init__.<locals>.<listcomp>zNo valid transports providedzServer initialized for %s.)/Úping_timeoutÚ
isinstanceÚtupleÚping_intervalZping_interval_grace_periodÚmax_http_buffer_sizeÚallow_upgradesÚhttp_compressionÚcompression_thresholdÚcookieÚcors_allowed_originsÚcors_credentialsÚasync_handlersÚsocketsÚhandlersÚsetÚlog_message_keysÚ_default_monitor_clientsZstart_service_taskZservice_task_handleZservice_task_eventr   ÚPacketÚjsonÚboolÚloggerÚdefault_loggerÚlevelÚloggingÚNOTSETÚsetLevelÚINFOÚERRORÚ
addHandlerÚStreamHandlerÚasync_modesÚ_asyncÚ
async_modeÚ	importlibÚimport_moduleÚis_asyncio_basedÚImportErrorÚ
ValueErrorÚstrr   Ú
transportsÚinfo)r   r>   r!   r   r"   r#   r$   r%   r&   r'   r(   r2   r0   r)   Zmonitor_clientsrE   ÚkwargsÚmodesÚmodeZasyncio_basedr   r   r   Ú__init__#   s–   

ÿÿ
ÿÿ

ÿÿÿ

ÿÿ
zBaseServer.__init__c                 C   s   dS )NFr   r   r   r   r   rA   r   s   zBaseServer.is_asyncio_basedc                 C   s   g d¢S )N)ZeventletZgevent_uwsgiZgeventÚ	threadingr   r   r   r   r   r<   u   s   zBaseServer.async_modesc                    s8   ˆ ˆj vr	tdƒ‚‡ ‡fdd„}|du r|S ||ƒ dS )aù  Register an event handler.

        :param event: The event name. Can be ``'connect'``, ``'message'`` or
                      ``'disconnect'``.
        :param handler: The function that should be invoked to handle the
                        event. When this parameter is not given, the method
                        acts as a decorator for the handler function.

        Example usage::

            # as a decorator:
            @eio.on('connect')
            def connect_handler(sid, environ):
                print('Connection request')
                if environ['REMOTE_ADDR'] in blacklisted:
                    return False  # reject

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

        The handler function receives the ``sid`` (session ID) for the
        client as first argument. The ``'connect'`` event handler receives the
        WSGI environment as a second argument, and can return ``False`` to
        reject the connection. The ``'message'`` handler receives the message
        payload as a second argument. The ``'disconnect'`` handler does not
        take a second argument.
        zInvalid eventc                    s   | ˆj ˆ < | S ©N)r+   )Úhandler©Úeventr   r   r   Úset_handlerš   s   
z"BaseServer.on.<locals>.set_handlerN)Úevent_namesrC   )r   rO   rM   rP   r   rN   r   Úonx   s   
zBaseServer.onc                 C   s   |   |¡jrdS dS )z×Return the name of the transport used by the client.

        The two possible values returned by this function are ``'polling'``
        and ``'websocket'``.

        :param sid: The session of the client.
        r   r
   )Ú_get_socketÚupgraded)r   Úsidr   r   r   r   ¢   s   zBaseServer.transportc                 O   ó   | j d |i |¤ŽS )zó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.
        Úqueue©r=   ©r   ÚargsrG   r   r   r   Úcreate_queue¬   ó   zBaseServer.create_queuec                 C   s
   | j d S )zÿ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.
        Zqueue_emptyrX   r   r   r   r   Úget_queue_empty_exceptionµ   s   
z$BaseServer.get_queue_empty_exceptionc                 O   rV   )zõ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.
        rO   rX   rY   r   r   r   Úcreate_event¾   r\   zBaseServer.create_eventc                 C   sH   t  t d¡| j dd¡ ¡}| jd d@ | _| d¡ dd¡ d	d
¡S )zGenerate a unique session id.é   é   Úbigr   iÿÿÿ úutf-8ú/Ú_ú+ú-)Úbase64Ú	b64encodeÚsecretsZtoken_bytesÚsequence_numberÚto_bytesÚdecodeÚreplace)r   Úidr   r   r   Úgenerate_idÇ   s
   ÿzBaseServer.generate_idc                 C   sl   |  dd¡d | }| ¡ D ]%\}}|dkrqt|ƒr|ƒ }|du r)|d| 7 }q|d| d | 7 }q|S )zGenerate the sid cookie.ÚnameÚioú=Tz; )ÚgetÚitemsÚcallable)r   rU   Ú
attributesr&   Ú	attributeÚvaluer   r   r   Ú_generate_sid_cookieÎ   s   zBaseServer._generate_sid_cookiec                 C   sB   | j r|  |¡js|dkrg S | jd du r|  dd¡ g S dgS )z=Return the list of possible upgrades for a client connection.r   Nz¦The WebSocket transport is not available, you must install a WebSocket server that is compatible with your async mode to enable it. See the documentation for details.zno-websocket)r#   rS   rT   r=   Ú_log_error_once)r   rU   r   r   r   r   Ú	_upgradesÜ   s   üzBaseServer._upgradesc                 C   s@   z| j | }W n ty   tdƒ‚w |jr| j |= tdƒ‚|S )z-Return the socket object for a given session.zSession not foundzSession is disconnected)r*   ÚKeyErrorÚclosed)r   rU   Úsr   r   r   rS   ê   s   ÿzBaseServer._get_socketc                 C   sN   |dur |du r
g }|dg7 }d|t j|d�j|d� d¡dœS ddgd	dœS )
z$Generate a successful HTTP response.N)úContent-Typeztext/plain; charset=UTF-8z200 OK)Úpackets)Újsonp_indexrb   ©ÚstatusÚheadersÚresponse©r   z
text/plains   OK)r   ZPayloadÚencode)r   r€   r„   r�   r   r   r   Ú_okõ   s   
ÿýþzBaseServer._okc                 C   ó.   |du rd}t jj |¡}ddg| d¡dœS )z+Generate a bad request HTTP error response.NzBad Requestz400 BAD REQUESTr†   rb   r‚   ©r   r/   r0   Údumpsr‡   ©r   r	   r   r   r   Ú_bad_request  ó   þzBaseServer._bad_requestc                 C   s   ddgddœS )z0Generate a method not found HTTP error response.z405 METHOD NOT FOUNDr†   s   Method Not Foundr‚   r   r   r   r   r   Ú_method_not_found  s   þzBaseServer._method_not_foundc                 C   r‰   )z,Generate a unauthorized HTTP error response.NÚUnauthorizedz401 UNAUTHORIZED)r   zapplication/jsonrb   r‚   rŠ   rŒ   r   r   r   Ú_unauthorized  rŽ   zBaseServer._unauthorizedc              	   C   s8  | j d u rMg }d|v rKd|v rK| dj|d |d d�¡ d|v s%d|v rK| d|d ¡ d¡d  ¡ }| dj|| d|d ¡ d¡d  ¡ d�¡ |S | j d	krVd }|S t| j tƒrb| j g}|S t| j ƒrŽ| d
¡}z|   ||¡}W n t	y‚   |   |¡}Y nw |rŠ|g}|S g }|S d	| j v r—d }|S | j }|S )Nzwsgi.url_schemeZ	HTTP_HOSTz{scheme}://{host})ÚschemeÚhostZHTTP_X_FORWARDED_PROTOZHTTP_X_FORWARDED_HOSTú,r   Ú*ÚHTTP_ORIGIN)
r'   ÚappendÚformatrs   ÚsplitÚstripr   rD   ru   Ú	TypeError)r   ÚenvironÚallowed_originsr’   ÚoriginZ
is_allowedr   r   r   Ú_cors_allowed_origins  sh   
þþþþþÿýü
ðò
ô
ÿ
ú
üÿz BaseServer._cors_allowed_originsc                 C   sŠ   | j g krg S g }|  |¡}d|v r#|du s|d |v r#d|d fg}|d dkr.|dg7 }d|v r;|d|d fg7 }| jrC|d	g7 }|S )
z1Return the cross-origin-resource-sharing headers.r–   NzAccess-Control-Allow-OriginÚREQUEST_METHODÚOPTIONS)zAccess-Control-Allow-MethodszOPTIONS, GET, POSTZ#HTTP_ACCESS_CONTROL_REQUEST_HEADERSzAccess-Control-Allow-Headers)z Access-Control-Allow-CredentialsÚtrue)r'   rŸ   r(   )r   rœ   r„   r�   r   r   r   Ú_cors_headers?  s$   

ÿ
ÿ
zBaseServer._cors_headersc                 C   sN   t  ¡ }tj|dd��}| |¡ W d  ƒ | ¡ S 1 sw   Y  | ¡ S )z%Apply gzip compression to a response.Úw)ÚfileobjrI   N)rq   ÚBytesIOr   ÚGzipFileÚwriteÚgetvalue)r   r…   ZbytesioÚgzr   r   r   Ú_gzipS  s   
ÿþzBaseServer._gzipc                 C   s
   t  |¡S )z(Apply deflate compression to a response.)ÚzlibÚcompress)r   r…   r   r   r   Ú_deflateZ  s   
zBaseServer._deflatec                 C   s:   || j vr| j |d ¡ | j  |¡ dS | j |¡ dS )zWLog message with logging.ERROR level the first time, then log
        with given level.zC (further occurrences of this error will be logged with level INFO)N)r-   r2   ÚerrorÚaddrF   )r   r	   Zmessage_keyr   r   r   rz   ^  s   
zBaseServer._log_error_once)Nr   r   r   TTr   NNTFNTNNrL   )NNN)r   r   r   Zcompression_methodsrQ   r   r.   rj   r   rJ   rA   r<   rR   r   r[   r]   r^   ro   ry   r{   rS   rˆ   r�   r�   r‘   rŸ   r£   r«   r®   rz   r   r   r   r   r      sD    
ûO
*
			

	
	#r   )rg   r   r?   rq   r5   ri   r¬   Ú r   r   Ú	getLoggerr3   r   r   r   r   r   Ú<module>   s    
