U
    g36                     @   s   d Z ddlmZmZmZmZmZmZ ddlZddl	m
Z
 ddlmZ ddlmZmZmZ ddlmZ ddlmZmZ dd	lmZ dd
lmZ ddlmZ eedZG dd deZdS )zSThis module contains methods to make POST and GET requests using the httpx library.    )Any
CollectionDictOptionalTupleUnionN)DefaultValue)
get_logger)HTTPVersionODVInput	SocketOpt)warn)NetworkErrorTimedOut)BaseRequest)RequestData)PTBDeprecationWarningHTTPXRequestc                   @   s$  e Zd ZdZdZdeeeee	j
e	jf  ee ee ee ee eeee  eeee	j
e	jf  ee eeeef  d	d
dZeedddZeee dddZe	jdddZddddZddddZdejejejejfeeee ee ee ee ee eeef dddZ dS )r   aJ  Implementation of :class:`~telegram.request.BaseRequest` using the library
    `httpx <https://www.python-httpx.org>`_.

    .. versionadded:: 20.0

    Args:
        connection_pool_size (:obj:`int`, optional): Number of connections to keep in the
            connection pool. Defaults to ``1``.

            Note:
                Independent of the value, one additional connection will be reserved for
                :meth:`telegram.Bot.get_updates`.
        proxy_url (:obj:`str`, optional): Legacy name for :paramref:`proxy`, kept for backward
            compatibility. Defaults to :obj:`None`.

            .. deprecated:: 20.7
        read_timeout (:obj:`float` | :obj:`None`, optional): If passed, specifies the maximum
            amount of time (in seconds) to wait for a response from Telegram's server.
            This value is used unless a different value is passed to :meth:`do_request`.
            Defaults to ``5``.
        write_timeout (:obj:`float` | :obj:`None`, optional): If passed, specifies the maximum
            amount of time (in seconds) to wait for a write operation to complete (in terms of
            a network socket; i.e. POSTing a request or uploading a file).
            This value is used unless a different value is passed to :meth:`do_request`.
            Defaults to ``5``.

            Hint:
                This timeout is used for all requests except for those that upload media/files.
                For the latter, :paramref:`media_write_timeout` is used.
        connect_timeout (:obj:`float` | :obj:`None`, optional): If passed, specifies the
            maximum amount of time (in seconds) to wait for a connection attempt to a server
            to succeed. This value is used unless a different value is passed to
            :meth:`do_request`. Defaults to ``5``.
        pool_timeout (:obj:`float` | :obj:`None`, optional): If passed, specifies the maximum
            amount of time (in seconds) to wait for a connection to become available.
            This value is used unless a different value is passed to :meth:`do_request`.
            Defaults to ``1``.

            Warning:
                With a finite pool timeout, you must expect :exc:`telegram.error.TimedOut`
                exceptions to be thrown when more requests are made simultaneously than there are
                connections in the connection pool!
        http_version (:obj:`str`, optional): If ``"2"`` or ``"2.0"``, HTTP/2 will be used instead
            of HTTP/1.1. Defaults to ``"1.1"``.

            .. versionadded:: 20.1
            .. versionchanged:: 20.2
                Reset the default version to 1.1.

            .. versionchanged:: 20.5
                Accept ``"2"`` as a valid value.
        socket_options (Collection[:obj:`tuple`], optional): Socket options to be passed to the
            underlying `library             <https://www.encode.io/httpcore/async/#httpcore.AsyncConnectionPool.__init__>`_.

            Note:
                The values accepted by this parameter depend on the operating system.
                This is a low-level parameter and should only be used if you are familiar with
                these concepts.

            .. versionadded:: 20.7
        proxy (:obj:`str` | ``httpx.Proxy`` | ``httpx.URL``, optional): The URL to a proxy server,
            a ``httpx.Proxy`` object or a ``httpx.URL`` object. For example
            ``'http://127.0.0.1:3128'`` or ``'socks5://127.0.0.1:3128'``. Defaults to :obj:`None`.

            Note:
                * The proxy URL can also be set via the environment variables ``HTTPS_PROXY`` or
                  ``ALL_PROXY``. See `the docs of httpx`_ for more info.
                * HTTPS proxies can be configured by passing a ``httpx.Proxy`` object with
                  a corresponding ``ssl_context``.
                * For Socks5 support, additional dependencies are required. Make sure to install
                  PTB via :command:`pip install "python-telegram-bot[socks]"` in this case.
                * Socks5 proxies can not be set via environment variables.

            .. _the docs of httpx: https://www.python-httpx.org/environment_variables/#proxies

            .. versionadded:: 20.7
        media_write_timeout (:obj:`float` | :obj:`None`, optional): Like :paramref:`write_timeout`,
            but used only for requests that upload media/files. This value is used unless a
            different value is passed to :paramref:`do_request.write_timeout` of
            :meth:`do_request`. Defaults to ``20`` seconds.

            .. versionadded:: 21.0
        httpx_kwargs (Dict[:obj:`str`, Any], optional): Additional keyword arguments to be passed
            to the `httpx.AsyncClient <https://www.python-httpx.org/api/#asyncclient>`_
            constructor.

            Warning:
                This parameter is intended for advanced users that want to fine-tune the behavior
                of the underlying ``httpx`` client. The values passed here will override all the
                defaults set by ``python-telegram-bot`` and all other parameters passed to
                :class:`HTTPXRequest`. The only exception is the :paramref:`media_write_timeout`
                parameter, which is not passed to the client constructor.
                No runtime warnings will be issued about parameters that are overridden in this
                way.

            .. versionadded:: 21.6

    )_client_client_kwargs_http_version_media_write_timeout   N      @      ?1.1      4@)connection_pool_size	proxy_urlread_timeoutwrite_timeoutconnect_timeoutpool_timeouthttp_versionsocket_optionsproxymedia_write_timeouthttpx_kwargsc              
   C   s(  |d k	r|	d k	rt d|d k	r6|}	ttdddd || _|
| _tj||||d}tj||d}|dkrrt d	|d
k}|| d}|rtj|dnd }||	||d||pi | _	z| 
 | _W n` tk
r" } z@dt|krdt|kr dt|krtd|td|W 5 d }~X Y nX d S )Nz>The parameters `proxy_url` and `proxy` are mutually exclusive.z20.7z=The parameter `proxy_url` is deprecated. Use `proxy` instead.   )
stacklevelconnectreadwritepool)Zmax_connectionsZmax_keepalive_connections)r   2z2.0z2`http_version` must be either '1.1', '2.0' or '2'.r   )http1Zhttp2)r$   )timeoutr%   limits	transportzhttpx[http2]zhttpx[socks]z\To use Socks5 proxies, PTB must be installed via `pip install "python-telegram-bot[socks]"`.zTTo use HTTP/2, PTB must be installed via `pip install "python-telegram-bot[http2]"`.)
ValueErrorr   r   r   r   httpxTimeoutZLimitsZAsyncHTTPTransportr   _build_clientr   ImportErrorstrRuntimeError)selfr   r   r   r    r!   r"   r#   r$   r%   r&   r'   r1   r2   r0   Zhttp_kwargsr3   exc r=   B/tmp/pip-unpacked-wheel-swnnwir2/telegram/request/_httpxrequest.py__init__   sr     	zHTTPXRequest.__init__)returnc                 C   s   | j S )zn
        :obj:`str`: Used HTTP version, see :paramref:`http_version`.

        .. versionadded:: 20.2
        )r   r;   r=   r=   r>   r#      s    zHTTPXRequest.http_versionc                 C   s
   | j jjS )zSee :attr:`BaseRequest.read_timeout`.

        Returns:
            :obj:`float` | :obj:`None`: The default read timeout in seconds as passed to
                :paramref:`HTTPXRequest.read_timeout`.
        )r   r1   r,   rA   r=   r=   r>   r      s    zHTTPXRequest.read_timeoutc                 C   s   t jf | jS )N)r5   AsyncClientr   rA   r=   r=   r>   r7      s    zHTTPXRequest._build_clientc                    s   | j jr|  | _ dS )z#See :meth:`BaseRequest.initialize`.N)r   	is_closedr7   rA   r=   r=   r>   
initialize   s    zHTTPXRequest.initializec                    s*   | j jrtd dS | j  I dH  dS )z!See :meth:`BaseRequest.shutdown`.z2This HTTPXRequest is already shut down. Returning.N)r   rC   _LOGGERdebugacloserA   r=   r=   r>   shutdown   s    
zHTTPXRequest.shutdown)urlmethodrequest_datar   r    r!   r"   r@   c              
      sP  | j jrtd|r|jnd}|r(|jnd}	t|tr@| j jj}t|trT| j jj	}t|trh| j jj
}t|tr|s| j jjn| j}tj||||d}
z(| j j||d| ji|
||	dI dH }W n tjk
r } z"t|tjrtdd|t|W 5 d}~X Y n@ tjk
rB } ztd|jj d	| |W 5 d}~X Y nX |j|jfS )
z#See :meth:`BaseRequest.do_request`.z%This HTTPXRequest is not initialized!Nr*   z
User-Agent)rJ   rI   headersr1   filesdatazPool timeout: All connections in the connection pool are occupied. Request was *not* sent to Telegram. Consider adjusting the connection pool size or the pool timeout.)messagezhttpx.z: )r   rC   r:   Zmultipart_dataZjson_parameters
isinstancer   r1   r,   r+   r.   r-   r   r5   r6   requestZ
USER_AGENTZTimeoutExceptionZPoolTimeoutr   	HTTPErrorr   	__class____name__status_codecontent)r;   rI   rJ   rK   r   r    r!   r"   rM   rN   r1   reserrr=   r=   r>   
do_request   sL    






,zHTTPXRequest.do_request)r   Nr   r   r   r   r   NNr   N)!rT   
__module____qualname____doc__	__slots__intr   r   r9   r5   ZProxyURLfloatr
   r   r   r   r   r?   propertyr#   r   rB   r7   rD   rH   r   ZDEFAULT_NONEr   r   r   bytesrY   r=   r=   r=   r>   r   )   s`   d           
L	
)r\   typingr   r   r   r   r   r   r5   Ztelegram._utils.defaultvaluer   Ztelegram._utils.loggingr	   Ztelegram._utils.typesr
   r   r   Ztelegram._utils.warningsr   Ztelegram.errorr   r   Ztelegram.request._baserequestr   Ztelegram.request._requestdatar   Ztelegram.warningsr   rT   rE   r   r=   r=   r=   r>   <module>   s    
