Telethon/telethon/_client/account.py

75 lines
2.0 KiB
Python
Raw Normal View History

2019-01-05 19:18:40 +03:00
import functools
import inspect
import typing
2022-01-15 13:22:33 +03:00
import dataclasses
2022-01-09 16:41:10 +03:00
from contextvars import ContextVar
2019-01-05 19:18:40 +03:00
from .users import _NOT_A_REQUEST
from .._misc import helpers, utils
from .. import _tl
2019-01-05 19:18:40 +03:00
if typing.TYPE_CHECKING:
from .telegramclient import TelegramClient
2019-01-05 19:18:40 +03:00
2022-01-09 16:41:10 +03:00
ignore_takeout = ContextVar('ignore_takeout', default=False)
# TODO Make use of :tl:`InvokeWithMessagesRange` somehow
# For that, we need to use :tl:`GetSplitRanges` first.
2022-01-09 16:41:10 +03:00
class _Takeout:
def __init__(self, client, kwargs):
self._client = client
self._kwargs = kwargs
2019-01-05 19:18:40 +03:00
async def __aenter__(self):
2022-01-09 16:41:10 +03:00
await self._client.begin_takeout(**kwargs)
return self._client
2019-01-05 19:18:40 +03:00
async def __aexit__(self, exc_type, exc_value, traceback):
2022-01-09 16:41:10 +03:00
await self._client.end_takeout(success=exc_type is None)
def takeout(self: 'TelegramClient', **kwargs):
return _Takeout(self, kwargs)
async def begin_takeout(
self: 'TelegramClient',
*,
contacts: bool = None,
users: bool = None,
chats: bool = None,
megagroups: bool = None,
channels: bool = None,
files: bool = None,
max_file_size: bool = None,
) -> 'TelegramClient':
if takeout_active():
raise ValueError('a previous takeout session was already active')
2022-01-15 13:22:33 +03:00
await self._replace_session_state(takeout_id=(await client(
contacts=contacts,
message_users=users,
message_chats=chats,
message_megagroups=megagroups,
message_channels=channels,
files=files,
file_max_size=max_file_size
2022-01-15 13:22:33 +03:00
)).id)
2022-01-09 16:41:10 +03:00
2022-01-09 16:41:10 +03:00
def takeout_active(self: 'TelegramClient') -> bool:
return self._session_state.takeout_id is not None
async def end_takeout(self: 'TelegramClient', success: bool) -> bool:
2022-01-09 16:41:10 +03:00
if not takeout_active():
raise ValueError('no previous takeout session was active')
result = await self(_tl.fn.account.FinishTakeoutSession(success))
if not result:
raise ValueError("could not end the active takeout session")
2022-01-15 13:22:33 +03:00
await self._replace_session_state(takeout_id=None)