U
    hd%                     @   sv   d dl Z d dlZd dlZddlmZ ddlmZmZ ddlm	Z	m
Z
 ejrVddlmZ G dd	 d	ZG d
d dZdS )    N   )_NOT_A_REQUEST   )helpersutils)	functions	TLRequest)TelegramClientc                       s   e Zd ZdZdZdd Zedd Zejdd Zdd	 Z	d
d Z
ejZejZdddZ fddZdd Z fddZ  ZS )_TakeoutClientz'
    Proxy object over the client.
    )	__enter____exit__
__aenter__	__aexit__c                 C   s   || _ || _|| _d | _d S N)_TakeoutClient__finalize_TakeoutClient__client_TakeoutClient__request_TakeoutClient__success)selffinalizeclientrequest r   ;/tmp/pip-unpacked-wheel-c81u5j2r/telethon/client/account.py__init__   s    z_TakeoutClient.__init__c                 C   s   | j S r   r   )r   r   r   r   success   s    z_TakeoutClient.successc                 C   s
   || _ d S r   r   )r   valuer   r   r   r   "   s    c                    s@   | j }|jjd kr*|| jI d H j|j_n| jd k	r<td| S )NzgCan't send a takeout request while another takeout for the current session still not been finished yet.)r   session
takeout_idr   id
ValueError)r   r   r   r   r   r   &   s    
z_TakeoutClient.__aenter__c                    sT   | j d kr| jr|d k| _ | j d k	rP| tj| j I d H }|sHtdd | j_d S )NzFailed to finish the takeout.)r   r   r   accountZFinishTakeoutSessionRequestr!   r   r   )r   exc_type	exc_value	tracebackresultr   r   r   r   0   s    

z_TakeoutClient.__aexit__Fc                    s   | j jj}|d krtdt| }|r0|fn|}g }|D ]8}t|tsPt |	| tI d H  |
t|| q<| j |r|d n||dI d H S )NzJTakeout mode has not been initialized (are you calling outside of "with"?)r   )ordered)r   r   r   r!   r   Zis_list_like
isinstancer   r   resolveappendr   ZInvokeWithTakeoutRequest)r   r   r'   r   Zsinglerequestswrappedrr   r   r   __call__>   s    

 z_TakeoutClient.__call__c                    s(   | dr|t| jkrtt |S )N__)
startswithtype_TakeoutClient__PROXY_INTERFACEAttributeErrorsuper__getattribute__)r   name	__class__r   r   r5   P   s    z_TakeoutClient.__getattribute__c                 C   s0   t | j|}t|r,tt | jj|| S |S r   )getattrr   inspectismethod	functoolspartialr8   r   r6   r   r   r   r   __getattr__]   s    
 z_TakeoutClient.__getattr__c                    s8   | dt| jdr*t ||S t| j||S )Nz_{}___)	r0   formatr1   __name__lstripr4   __setattr__setattrr   r>   r7   r   r   rD   g   s    z_TakeoutClient.__setattr__)F)rB   
__module____qualname____doc__r2   r   propertyr   setterr   r   r   Z_sync_enterr   Z
_sync_exitr   r.   r5   r?   rD   __classcell__r   r   r7   r   r
      s   	




r
   c                   @   sR   e Zd Zddddddddddeeeeeeeedd
ddZdeedd	d
ZdS )AccountMethodsTN)contactsuserschats
megagroupschannelsfilesmax_file_sizer	   )
r   r   rM   rN   rO   rP   rQ   rR   rS   returnc             	   C   s\   t |||||||d}	dd |	 D }
| jjdks<t|
rLtjjf |	}nd}t|| |S )a~  
        Returns a :ref:`telethon-client` which calls methods behind a takeout session.

        It does so by creating a proxy object over the current client through
        which making requests will use :tl:`InvokeWithTakeoutRequest` to wrap
        them. In other words, returns the current client modified so that
        requests are done as a takeout:

        Some of the calls made through the takeout session will have lower
        flood limits. This is useful if you want to export the data from
        conversations or mass-download media, since the rate limits will
        be lower. Only some requests will be affected, and you will need
        to adjust the `wait_time` of methods like `client.iter_messages
        <telethon.client.messages.MessageMethods.iter_messages>`.

        By default, all parameters are `None`, and you need to enable those
        you plan to use by setting them to either `True` or `False`.

        You should ``except errors.TakeoutInitDelayError as e``, since this
        exception will raise depending on the condition of the session. You
        can then access ``e.seconds`` to know how long you should wait for
        before calling the method again.

        There's also a `success` property available in the takeout proxy
        object, so from the `with` body you can set the boolean result that
        will be sent back to Telegram. But if it's left `None` as by
        default, then the action is based on the `finalize` parameter. If
        it's `True` then the takeout will be finished, and if no exception
        occurred during it, then `True` will be considered as a result.
        Otherwise, the takeout will not be finished and its ID will be
        preserved for future usage as `client.session.takeout_id
        <telethon.sessions.abstract.Session.takeout_id>`.

        Arguments
            finalize (`bool`):
                Whether the takeout session should be finalized upon
                exit or not.

            contacts (`bool`):
                Set to `True` if you plan on downloading contacts.

            users (`bool`):
                Set to `True` if you plan on downloading information
                from users and their private conversations with you.

            chats (`bool`):
                Set to `True` if you plan on downloading information
                from small group chats, such as messages and media.

            megagroups (`bool`):
                Set to `True` if you plan on downloading information
                from megagroups (channels), such as messages and media.

            channels (`bool`):
                Set to `True` if you plan on downloading information
                from broadcast channels, such as messages and media.

            files (`bool`):
                Set to `True` if you plan on downloading media and
                you don't only wish to export messages.

            max_file_size (`int`):
                The maximum file size, in bytes, that you plan
                to download for each message with media.

        Example
            .. code-block:: python

                from telethon import errors

                try:
                    async with client.takeout() as takeout:
                        await client.get_messages('me')  # normal call
                        await takeout.get_messages('me')  # wrapped through takeout (less limits)

                        async for message in takeout.iter_messages(chat, wait_time=0):
                            ...  # Do something with the message

                except errors.TakeoutInitDelayError as e:
                    print('Must wait', e.seconds, 'before takeout')
        )rM   Zmessage_usersZmessage_chatsZmessage_megagroupsZmessage_channelsrR   Zfile_max_sizec                 s   s   | ]}|d k	V  qd S r   r   ).0argr   r   r   	<genexpr>   s     z)AccountMethods.takeout.<locals>.<genexpr>N)	dictvaluesr   r   anyr   r"   ZInitTakeoutSessionRequestr
   )r   r   rM   rN   rO   rP   rQ   rR   rS   Zrequest_kwargsZarg_specifiedr   r   r   r   takeouto   s     \	zAccountMethods.takeout)r   r   rT   c              
      sL   z0t d| d4 I dH }||_W 5 Q I dH R X W n tk
rF   Y dS X dS )ap  
        Finishes the current takeout session.

        Arguments
            success (`bool`):
                Whether the takeout completed successfully or not.

        Returns
            `True` if the operation was successful, `False` otherwise.

        Example
            .. code-block:: python

                await client.end_takeout(success=False)
        TNF)r
   r   r!   )r   r   r[   r   r   r   end_takeout   s    zAccountMethods.end_takeout)T)rB   rF   rG   boolr[   r\   r   r   r   r   rL   n   s,     orL   )r<   r:   typingrN   r    r   r   tlr   r   TYPE_CHECKINGZtelegramclientr	   r
   rL   r   r   r   r   <module>   s   _