U
    gc                     @   s   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 d dl	m
Z
 d dlmZmZmZmZ d dlZd dlmZ zd d	lmZ d
ZW n ek
r   dZY nX d dlmZ d dlmZ d dlmZ erd dlmZ eeddZ G dd dZ!G dd dej"j#Z$G dd dej"j%Z&dS )    N)
HTTPStatus)Path)socket)
SSLContext)TracebackType)TYPE_CHECKINGOptionalTypeUnion)
HTTPServer)bind_unix_socketTF)Update)
get_logger)ExtBot)BotZUpdater)
class_namec                
   @   sd   e Zd ZdZdZdeedee ee	ee
ef  dddZdeej ddd	d
ZddddZdS )WebhookServerz6Thin wrapper around ``tornado.httpserver.HTTPServer``.)_http_server_server_lock_shutdown_lock
is_runninglistenportunixNWebhookAppClass)r   r   webhook_appssl_ctxr   c                 C   sv   |rt stdt||d| _|| _|| _d| _d | _|rLt|t	rL|| _n|r^t
t|| _t | _t | _d S )Nz.This OS does not support binding unix sockets.)Zssl_optionsF)UNIX_AVAILABLERuntimeErrorr   r   r   r   r   r   
isinstancer   r   strasyncioLockr   r   )selfr   r   r   r   r    r$   F/tmp/pip-unpacked-wheel-swnnwir2/telegram/ext/_utils/webhookhandler.py__init__A   s    
zWebhookServer.__init__)readyreturnc              
      sn   | j 4 I d H P | jr&| j| j n| jj| j| jd d| _|d k	rP|  t	d W 5 Q I d H R X d S )N)addressTzWebhook Server started.)
r   r   r   Z
add_socketr   r   r   set_LOGGERdebug)r#   r'   r$   r$   r%   serve_foreverW   s    zWebhookServer.serve_foreverr(   c              
      sr   | j 4 I d H T | js4td W 5 Q I d H R  d S d| _| j  | j I d H  td W 5 Q I d H R X d S )Nz.Webhook Server is already shut down. ReturningFzWebhook Server stopped)r   r   r+   r,   r   stopZclose_all_connectionsr#   r$   r$   r%   shutdownd   s    

zWebhookServer.shutdown)N)N)__name__
__module____qualname____doc__	__slots__r    intr   r   r
   r   r   r&   r!   Eventr-   r1   r$   r$   r$   r%   r   4   s    r   c                   @   s@   e Zd ZdZd
edejee dddZe	j
jdddd	ZdS )r   z!Application used in the WebserverNr   )webhook_pathbotupdate_queuesecret_tokenc                 C   s6   |||d| _ | dt| j fg}tjj| | d S )N)r:   r;   r<   z/?)Zshared_objectsTelegramHandlertornadowebApplicationr&   )r#   r9   r:   r;   r<   handlersr$   r$   r%   r&   r   s    zWebhookAppClass.__init__)handlerr(   c                 C   s   dS )zIOverrides the default implementation since we have our own logging setup.Nr$   )r#   rB   r$   r$   r%   log_request   s    zWebhookAppClass.log_request)N)r2   r3   r4   r5   r    r!   Queuer   r&   r>   r?   RequestHandlerrC   r$   r$   r$   r%   r   o   s    r   c                   @   s|   e Zd ZdZdZdZdejeddddZ	dd	d
dZ
dd	ddZdd	ddZeee  ee ee ddddZdS )r=   z:BaseHandler that processes incoming requests from Telegram)r:   r<   r;   )POSTr   N)r:   r;   r<   r(   c                 C   s$   || _ || _|| _|r td dS )zFInitialize for each request - that's the interface provided by tornadozLThe webhook server has a secret token, expecting it in incoming requests nowN)r:   r;   r<   r+   r,   )r#   r:   r;   r<   r$   r$   r%   
initialize   s    zTelegramHandler.initializer.   c                 C   s   |  dd dS )zSets default headersContent-Typez!application/json; charset="utf-8"N)Z
set_headerr0   r$   r$   r%   set_default_headers   s    z#TelegramHandler.set_default_headersc              
      s   t d |   | jj }t|}| t	j
 t d| zt|| j}W nF tk
r } z(t jd||d tjjt	jdd|W 5 d}~X Y nX |rt d|j t| jtr| j| | j|I dH  dS )	zHandle incoming POST requestzWebhook triggeredzWebhook received data: %szySomething went wrong processing the data received from Telegram. Received data was *not* processed! Received data was: %rexc_infozUpdate could not be processedreasonNz%Received Update with ID %d on Webhook)r+   r,   _validate_postrequestbodydecodejsonloadsZ
set_statusr   OKr   Zde_jsonr:   	Exceptioncriticalr>   r?   	HTTPErrorBAD_REQUESTZ	update_idr   r   Zinsert_callback_datar;   put)r#   Zjson_stringdataupdateexcr$   r$   r%   post   s8    

 zTelegramHandler.postc                 C   s   | j jdd}|dkr&tjtj| jdk	r| j jd}|s^t	
d tjjtjdd|| jkrt	
d| tjjtjdddS )	z+Only accept requests with content type JSONrH   Nzapplication/jsonzX-Telegram-Bot-Api-Secret-Tokenz(Request did not include the secret tokenrL   z&Request had the wrong secret token: %sz"Request had the wrong secret token)rO   headersgetr>   r?   rW   r   	FORBIDDENr<   r+   r,   )r#   Z	ct_headertokenr$   r$   r%   rN      s"    

 
 zTelegramHandler._validate_post)typvaluetbr(   c                 C   s0   t jd| jjd|r$|r$|r$|||fn|d dS )z@Override the default logging and instead use our custom logging.z%s - %szException in TelegramHandlerrJ   N)r+   r,   rO   Z	remote_ip)r#   rb   rc   rd   r$   r$   r%   log_exception   s    zTelegramHandler.log_exception)r2   r3   r4   r5   r6   ZSUPPORTED_METHODSr!   rD   r    rG   rI   r]   rN   r   r	   BaseExceptionr   re   r$   r$   r$   r%   r=      s   $
r=   )'r!   rR   httpr   pathlibr   r   sslr   typesr   typingr   r   r	   r
   Ztornado.webr>   Ztornado.httpserverr   Ztornado.netutilr   r   ImportErrorZtelegramr   Ztelegram._utils.loggingr   Ztelegram.ext._extbotr   r   r2   r+   r   r?   r@   r   rE   r=   r$   r$   r$   r%   <module>   s.   
;