3
uQhd%                 @   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-build-2nz6shyl/telethon/telethon/client/account.py__init__   s    z_TakeoutClient.__init__c             C   s   | j S )N)r   )r   r   r   r   success   s    z_TakeoutClient.successc             C   s
   || _ d S )N)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| 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j| }|r0|fn|}g }x@|D ]8}t|tsRt |j	| tI d H  |j
tj|| q>W | 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(   |j dr|t| jkrtt j|S )N__)
startswithtype_TakeoutClient__PROXY_INTERFACEAttributeErrorsuper__getattribute__)r   name)	__class__r   r   r3   P   s    z_TakeoutClient.__getattribute__c             C   s0   t | j|}tj|r,tjt | jj|| S |S )N)getattrr   inspectismethod	functoolspartialr5   )r   r4   r   r   r   r   __getattr__]   s
    
z_TakeoutClient.__getattr__c                s8   |j djt| jjdr*t j||S t| j||S )Nz_{}___)	r.   formatr/   __name__lstripr2   __setattr__setattrr   )r   r4   r   )r5   r   r   r@   g   s    z_TakeoutClient.__setattr__)r   r   r   r   )F)r>   
__module____qualname____doc__r0   r   propertyr   setterr   r   r   Z_sync_enterr   Z
_sync_exitr   r,   r3   r;   r@   __classcell__r   r   )r5   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   rI   rJ   rK   rL   rM   rN   rO   returnc         	   C   s\   t |||||||d}	dd |	j 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')
        )rI   Zmessage_usersZmessage_chatsZmessage_megagroupsZmessage_channelsrN   Zfile_max_sizec             s   s   | ]}|d k	V  qd S )Nr   ).0argr   r   r   	<genexpr>   s    z)AccountMethods.takeout.<locals>.<genexpr>N)	dictvaluesr   r   anyr   r    ZInitTakeoutSessionRequestr
   )r   r   rI   rJ   rK   rL   rM   rN   rO   Zrequest_kwargsZarg_specifiedr   r   r   r   takeouto   s    \zAccountMethods.takeout)r   r   rP   c                sJ   y0t d| d4 I dH }||_W dQ I dH R X W n tk
rD   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   rW   r   r   r   end_takeout   s    zAccountMethods.end_takeout)T)r>   rB   rC   boolrW   rX   r   r   r   r   rH   n   s   &erH   )r9   r7   typingrJ   r    r   r   tlr   r   ZTYPE_CHECKINGZtelegramclientr	   r
   rH   r   r   r   r   <module>   s   _