U
    -en4                     @  sh  d Z ddlmZ ddlZddlZddlZddlmZ ddlmZm	Z	m
Z
mZ ddlmZmZ ddlmZ ddlmZ dd	lmZmZ dd
lmZmZ ddlmZ ddlmZ ddlmZmZ ddl m!Z! ddl"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/ dgZ0dddddZ1dddddZ2G dd dZ3G dd dZ4dddd d!Z5G d"d dZ6dS )#z
Telnet server.
    )annotationsN)get_running_loop)	AwaitableCallableTextIOcast)create_app_sessionget_app)run_in_terminal)Size)AnyFormattedTextto_formatted_text)	PipeInputcreate_pipe_input)Vt100_Output)print_formatted_text)	BaseStyle
DummyStyle   )logger)DOECHOIACLINEMODEMODENAWSSBSESENDSUPPRESS_GO_AHEADTTYPEWILLTelnetProtocolParserTelnetServerintbytes)numberreturnc                 C  s
   t | fS N)r%   )r&    r)   e/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/prompt_toolkit/contrib/telnet/server.pyint2byte+   s    r+   socket.socketNone)
connectionr'   c                 C  s   t d | tt t  | tt t  | tt t t	 t
d t t  | tt t  | tt t  | tt t  | tt t t t t  d S )NzInitializing telnet connectionr   )r   infosendr   r   r   r!   r   r   r   r+   r   r   r   r    r   r.   r)   r)   r*   _initialize_telnet/   s    
&r2   c                   @  s   e Zd ZdZddddddZdddd	d
ZddddZddddZddddZe	ddddZ
e	ddddZdS )_ConnectionStdoutzk
    Wrapper around socket which provides `write` and `flush` methods for the
    Vt100_Output output.
    r,   strr-   )r.   encodingr'   c                 C  s"   || _ || _d| _g | _d| _d S )NstrictF)	_encoding_connection_errors_buffer_closed)selfr.   r5   r)   r)   r*   __init__R   s
    z_ConnectionStdout.__init__datar'   c                 C  s2   | dd}| j|j| j| jd |   d S )N
z
)errors)replacer:   appendencoder7   r9   flushr<   r?   r)   r)   r*   writeY   s    z_ConnectionStdout.writeboolr'   c                 C  s   dS NTr)   r<   r)   r)   r*   isatty^   s    z_ConnectionStdout.isattyc              
   C  sZ   z| j s| jd| j W n0 tk
rN } ztd|  W 5 d }~X Y nX g | _d S )N    z"Couldn't send data over socket: %s)r;   r8   r0   joinr:   OSErrorr   warning)r<   er)   r)   r*   rE   a   s     z_ConnectionStdout.flushc                 C  s
   d| _ d S rJ   )r;   rK   r)   r)   r*   closej   s    z_ConnectionStdout.closec                 C  s   | j S r(   )r7   rK   r)   r)   r*   r5   m   s    z_ConnectionStdout.encodingc                 C  s   | j S r(   )r9   rK   r)   r)   r*   rA   q   s    z_ConnectionStdout.errorsN)__name__
__module____qualname____doc__r=   rG   rL   rE   rR   propertyr5   rA   r)   r)   r)   r*   r3   L   s   	r3   c                   @  s   e Zd ZdZd%ddddddd	d
dd	ddZddddZdddddZddddZdddddZdddddZ	dddd d!Z
ddd"d#Zd$S )&TelnetConnectionz6
    Class that represents one Telnet connection.
    Tr,   ztuple[str, int]-Callable[[TelnetConnection], Awaitable[None]]r#   r4   BaseStyle | Noner   rH   r-   )	connaddrinteractserverr5   stylevt100_input
enable_cprr'   c	                   s   |_ |_|_|_|_|_d_t _	|_
 _d _tddd_t| ddfddttt||d	_d
ddfdd}	ddddfdd}
ddd fdd}t|	|
|_d _d S )NF(   O   rowscolumnsr   rI   c                     s    j S r(   )sizer)   rK   r)   r*   get_size   s    z+TelnetConnection.__init__.<locals>.get_size)r5   r%   r-   r>   c                   s    j |  dS )z-TelnetProtocolParser 'data_received' callbackN)r`   Z
send_bytesr?   rK   r)   r*   data_received   s    z0TelnetConnection.__init__.<locals>.data_receivedr$   )re   rf   r'   c                   s2   t | |d _ jdk	r. jr. jdd  dS )z-TelnetProtocolParser 'size_received' callbackrd   Nc                   S  s
   t   S r(   )r	   Z
_on_resizer)   r)   r)   r*   <lambda>   rM   zBTelnetConnection.__init__.<locals>.size_received.<locals>.<lambda>)r   rg   vt100_outputcontextrunrd   rK   r)   r*   size_received   s    z0TelnetConnection.__init__.<locals>.size_receivedr4   )ttyper'   c                   s"   t j|  d_j  dS )z.TelnetProtocolParser 'ttype_received' callback)termra   N)r   stdoutrl   _readyset)rp   ra   rh   r<   r)   r*   ttype_received   s       z1TelnetConnection.__init__.<locals>.ttype_received)r[   r\   r]   r^   r5   r_   r;   asyncioEventrs   r`   ra   rl   r   rg   r2   r   r   r3   rr   r"   parserrm   )r<   r[   r\   r]   r^   r5   r_   r`   ra   rj   ro   rv   r)   ru   r*   r=   {   s(    
zTelnetConnection.__init__rI   c              	     s   dd fdd}t  }| j| zJ j I dH  t j jd  t	
  _  I dH  W 5 Q R X W 5    X dS )z"
        Run application.
        r-   rI   c                    s8    j d} | r |  ntd j     d S )Ni   z"Connection closed by client. %r %r)r[   recvfeedr   r/   r\   rR   ri   rK   r)   r*   handle_incoming_data   s
    z>TelnetConnection.run_application.<locals>.handle_incoming_dataN)inputoutput)r   
add_readerr[   rR   rs   waitr   r`   rl   contextvarscopy_contextrm   r]   )r<   r|   loopr)   rK   r*   run_application   s    

z TelnetConnection.run_applicationr%   r>   c                 C  s   | j | dS )zF
        Handler for incoming data. (Called by TelnetServer.)
        N)ry   r{   rF   r)   r)   r*   r{      s    zTelnetConnection.feedc                 C  s<   | j s8d| _ | j  t | j | j  | j  dS )z#
        Closed by client.
        TN)r;   r`   rR   r   remove_readerr[   rr   rK   r)   r)   r*   rR      s    

zTelnetConnection.closer   )formatted_textr'   c                 C  s0   | j dkrdS t|}t| j || jp(t  dS )z*
        Send text to the client.
        N)rl   r   r   r_   r   r<   r   r)   r)   r*   r0      s    
  
zTelnetConnection.sendc                   s   t    fddS )z\
        Send text to the client.
        This is asynchronous, returns a `Future`.
        c                     s
     S r(   )r0   r)   r   r<   r)   r*   rk      rM   z4TelnetConnection.send_above_prompt.<locals>.<lambda>)r   _run_in_terminalr   r)   r   r*   send_above_prompt   s    z"TelnetConnection.send_above_promptzCallable[[], None])funcr'   c                 C  s"   | j r| j t| ntdd S )Nz2Called _run_in_terminal outside `run_application`.)rm   rn   r
   RuntimeError)r<   r   r)   r)   r*   r      s    z!TelnetConnection._run_in_terminalc                 C  s4   | j dkrdS | j   | j dd | j   dS )zB
        Erase the screen and move the cursor to the top.
        Nr   )rl   erase_screenZcursor_gotorE   rK   r)   r)   r*   r      s
    

zTelnetConnection.erase_screenN)T)rS   rT   rU   rV   r=   r   r{   rR   r0   r   r   r   r)   r)   r)   r*   rX   v   s     7rX   c                   s   d S r(   r)   r1   r)   r)   r*   _dummy_interact  s    r   c                	   @  s   e Zd ZdZddedddfddd	dd
dddddZeddddddZd dddddZddddZ	ddddZ
dddddZdS )!r#   a  
    Telnet server implementation.

    Example::

        async def interact(connection):
            connection.send("Welcome")
            session = PromptSession()
            result = await session.prompt_async(message="Say something: ")
            connection.send(f"You said: {result}
")

        async def main():
            server = TelnetServer(interact=interact, port=2323)
            await server.run()
    z	127.0.0.1   zutf-8NTr4   r$   rY   rZ   rH   r-   )hostportr]   r5   r_   ra   r'   c                 C  s<   || _ || _|| _|| _|| _|| _d | _g | _t | _	d S r(   )
r   r   r]   r5   r_   ra   	_run_task_application_tasksrt   connections)r<   r   r   r]   r5   r_   ra   r)   r)   r*   r=     s    	zTelnetServer.__init__r,   )r   r   r'   c                 C  s>   t  t jt j}|t jt jd |||f |d |S )Nr      )socketAF_INETSOCK_STREAM
setsockopt
SOL_SOCKETSO_REUSEADDRbindlisten)clsr   r   sr)   r)   r*   _create_socket/  s
    
zTelnetServer._create_socketzCallable[[], None] | None)ready_cbr'   c                   s      j jtd j j t  fdd |rD|  zt I dH  W 5 t     j	D ]}|
  qrt j	dkrtj j	dtjdI dH  X dS )z
        Run the telnet server, until this gets cancelled.

        :param ready_cb: Callback that will be called at the point that we're
            actually listening.
        z.Listening for telnet connections on %s port %rc                     s
     S r(   )_acceptr)   r<   r   r)   r*   rk   E  rM   z"TelnetServer.run.<locals>.<lambda>r   N)timeoutreturn_when)r   r   r   r   r/   r   r   r   rR   r   cancellenrw   r   ALL_COMPLETEDFuture)r<   r   tr)   r   r*   rn   9  s*      

zTelnetServer.runrI   c                 C  s$   | j dk	rdS t |  | _ dS )z}
        Deprecated: Use `.run()` instead.

        Start the telnet server (stop by calling and awaiting `stop()`).
        N)r   r   create_taskrn   rK   r)   r)   r*   start`  s    
zTelnetServer.startc                   s@   | j dk	r<| j   z| j I dH  W n tjk
r:   Y nX dS )z
        Deprecated: Use `.run()` instead.

        Stop a telnet server that was started using `.start()` and wait for the
        cancellation to complete.
        N)r   r   rw   CancelledErrorrK   r)   r)   r*   stopl  s    

zTelnetServer.stop)listen_socketr'   c                   sP   |  \ tjd   dd fdd}t | j dS )z1
        Accept new incoming connection.
        New connection %r %rr-   rI   c                    s  zzt p} t jjj| jd}j	| t
jd   z| I d H  W 5 j| t
jd	   X W 5 Q R X W n tk
r   t
d Y nd tk
r   t
d Y nH tk
r } z(tdt|j | dd l}|  W 5 d }~X Y nX W 5 j  X d S )
N)r5   r_   r`   ra   Starting interaction %r %rStopping interaction %r %rz)Unhandled EOFError in telnet application.z2Unhandled KeyboardInterrupt in telnet application.zGot %sr   )r   )r   )r   remover   rX   r]   r5   r_   ra   r   addr   r/   r   EOFErrorKeyboardInterruptBaseExceptionprinttyperS   	traceback	print_exc)r`   r.   rQ   r   r\   r[   r<   taskr)   r*   rn     s6    
z!TelnetServer._accept.<locals>.runN)r   )acceptr   r/   r   r   r   rC   )r<   r   rn   r)   r   r*   r   z  s
    &zTelnetServer._accept)N)rS   rT   rU   rV   r   r=   classmethodr   rn   r   r   r   r)   r)   r)   r*   r#   	  s   	')7rV   
__future__r   rw   r   r   r   typingr   r   r   r   Z"prompt_toolkit.application.currentr   r	   Z*prompt_toolkit.application.run_in_terminalr
   Zprompt_toolkit.data_structuresr   Zprompt_toolkit.formatted_textr   r   Zprompt_toolkit.inputr   r   Zprompt_toolkit.output.vt100r   Zprompt_toolkit.rendererr   Zprompt_toolkit.stylesr   r   logr   protocolr   r   r   r   r   r   r   r   r   r   r    r!   r"   __all__r+   r2   r3   rX   r   r#   r)   r)   r)   r*   <module>   s2   <* 