2020-03-21 14:43:32 +00:00
|
|
|
# Pyrogram - Telegram MTProto API Client Library for Python
|
2021-01-01 21:58:48 +00:00
|
|
|
# Copyright (C) 2017-2021 Dan <https://github.com/delivrance>
|
2017-12-05 11:41:07 +00:00
|
|
|
#
|
2020-03-21 14:43:32 +00:00
|
|
|
# This file is part of Pyrogram.
|
2017-12-05 11:41:07 +00:00
|
|
|
#
|
2020-03-21 14:43:32 +00:00
|
|
|
# Pyrogram is free software: you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU Lesser General Public License as published
|
|
|
|
# by the Free Software Foundation, either version 3 of the License, or
|
|
|
|
# (at your option) any later version.
|
2017-12-05 11:41:07 +00:00
|
|
|
#
|
2020-03-21 14:43:32 +00:00
|
|
|
# Pyrogram is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU Lesser General Public License for more details.
|
2017-12-05 11:41:07 +00:00
|
|
|
#
|
2020-03-21 14:43:32 +00:00
|
|
|
# You should have received a copy of the GNU Lesser General Public License
|
|
|
|
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.
|
2017-12-05 11:41:07 +00:00
|
|
|
|
2020-08-21 05:28:27 +00:00
|
|
|
import asyncio
|
2017-12-05 11:41:07 +00:00
|
|
|
import logging
|
2020-08-26 07:01:01 +00:00
|
|
|
import os
|
2020-12-12 15:46:40 +00:00
|
|
|
import time
|
2020-08-21 05:28:27 +00:00
|
|
|
from datetime import datetime, timedelta
|
|
|
|
from hashlib import sha1
|
2017-12-05 11:41:07 +00:00
|
|
|
from io import BytesIO
|
|
|
|
|
2018-01-31 20:03:26 +00:00
|
|
|
import pyrogram
|
2021-01-02 17:45:43 +00:00
|
|
|
from pyrogram import __copyright__, __license__, __version__
|
2020-08-22 06:05:05 +00:00
|
|
|
from pyrogram import raw
|
2017-12-05 11:41:07 +00:00
|
|
|
from pyrogram.connection import Connection
|
2020-08-22 06:05:05 +00:00
|
|
|
from pyrogram.crypto import mtproto
|
2021-04-12 07:21:20 +00:00
|
|
|
from pyrogram.errors import RPCError, InternalServerError, AuthKeyDuplicated, FloodWait, ServiceUnavailable
|
2020-08-22 06:05:05 +00:00
|
|
|
from pyrogram.raw.all import layer
|
2020-08-26 07:01:01 +00:00
|
|
|
from pyrogram.raw.core import TLObject, MsgContainer, Int, FutureSalt, FutureSalts
|
2018-06-13 11:37:35 +00:00
|
|
|
from .internals import MsgId, MsgFactory
|
2017-12-05 11:41:07 +00:00
|
|
|
|
2019-09-08 17:24:06 +00:00
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
|
2017-12-05 11:41:07 +00:00
|
|
|
|
|
|
|
class Result:
|
|
|
|
def __init__(self):
|
|
|
|
self.value = None
|
2020-08-21 05:28:27 +00:00
|
|
|
self.event = asyncio.Event()
|
2017-12-05 11:41:07 +00:00
|
|
|
|
|
|
|
|
|
|
|
class Session:
|
|
|
|
INITIAL_SALT = 0x616e67656c696361
|
2019-03-03 15:50:25 +00:00
|
|
|
START_TIMEOUT = 1
|
2018-04-12 06:29:39 +00:00
|
|
|
WAIT_TIMEOUT = 15
|
2020-08-26 07:01:01 +00:00
|
|
|
SLEEP_THRESHOLD = 10
|
2017-12-05 11:41:07 +00:00
|
|
|
MAX_RETRIES = 5
|
|
|
|
ACKS_THRESHOLD = 8
|
|
|
|
PING_INTERVAL = 5
|
|
|
|
|
2017-12-09 16:09:39 +00:00
|
|
|
notice_displayed = False
|
|
|
|
|
2018-02-22 00:28:46 +00:00
|
|
|
BAD_MSG_DESCRIPTION = {
|
|
|
|
16: "[16] msg_id too low, the client time has to be synchronized",
|
|
|
|
17: "[17] msg_id too high, the client time has to be synchronized",
|
|
|
|
18: "[18] incorrect two lower order msg_id bits, the server expects client message msg_id to be divisible by 4",
|
|
|
|
19: "[19] container msg_id is the same as msg_id of a previously received message",
|
|
|
|
20: "[20] message too old, it cannot be verified by the server",
|
|
|
|
32: "[32] msg_seqno too low",
|
|
|
|
33: "[33] msg_seqno too high",
|
|
|
|
34: "[34] an even msg_seqno expected, but odd received",
|
|
|
|
35: "[35] odd msg_seqno expected, but even received",
|
|
|
|
48: "[48] incorrect server salt",
|
|
|
|
64: "[64] invalid container"
|
|
|
|
}
|
|
|
|
|
2019-06-19 14:01:23 +00:00
|
|
|
def __init__(
|
|
|
|
self,
|
2020-08-22 06:05:05 +00:00
|
|
|
client: "pyrogram.Client",
|
2019-06-19 14:01:23 +00:00
|
|
|
dc_id: int,
|
|
|
|
auth_key: bytes,
|
2020-08-22 06:05:05 +00:00
|
|
|
test_mode: bool,
|
2019-06-19 14:01:23 +00:00
|
|
|
is_media: bool = False,
|
|
|
|
is_cdn: bool = False
|
|
|
|
):
|
2017-12-09 16:09:39 +00:00
|
|
|
if not Session.notice_displayed:
|
2020-08-22 06:05:05 +00:00
|
|
|
print(f"Pyrogram v{__version__}, {__copyright__}")
|
|
|
|
print(f"Licensed under the terms of the {__license__}", end="\n\n")
|
2017-12-09 16:09:39 +00:00
|
|
|
Session.notice_displayed = True
|
2017-12-05 11:41:07 +00:00
|
|
|
|
2018-06-24 16:26:11 +00:00
|
|
|
self.client = client
|
2018-05-24 19:19:57 +00:00
|
|
|
self.dc_id = dc_id
|
2018-06-24 16:26:11 +00:00
|
|
|
self.auth_key = auth_key
|
2020-08-22 06:05:05 +00:00
|
|
|
self.test_mode = test_mode
|
2018-06-24 16:26:11 +00:00
|
|
|
self.is_media = is_media
|
2018-02-08 18:48:01 +00:00
|
|
|
self.is_cdn = is_cdn
|
2017-12-05 11:41:07 +00:00
|
|
|
|
2018-05-24 19:19:57 +00:00
|
|
|
self.connection = None
|
|
|
|
|
2017-12-05 11:41:07 +00:00
|
|
|
self.auth_key_id = sha1(auth_key).digest()[-8:]
|
|
|
|
|
2020-08-22 09:26:11 +00:00
|
|
|
self.session_id = os.urandom(8)
|
2018-02-18 16:31:00 +00:00
|
|
|
self.msg_factory = MsgFactory()
|
2017-12-05 11:41:07 +00:00
|
|
|
|
|
|
|
self.current_salt = None
|
|
|
|
|
|
|
|
self.pending_acks = set()
|
|
|
|
|
|
|
|
self.results = {}
|
|
|
|
|
2020-08-21 05:28:27 +00:00
|
|
|
self.ping_task = None
|
|
|
|
self.ping_task_event = asyncio.Event()
|
2017-12-05 11:41:07 +00:00
|
|
|
|
2020-08-21 05:28:27 +00:00
|
|
|
self.next_salt_task = None
|
|
|
|
self.next_salt_task_event = asyncio.Event()
|
2017-12-05 11:41:07 +00:00
|
|
|
|
2020-08-22 06:05:05 +00:00
|
|
|
self.network_task = None
|
2018-04-29 18:30:32 +00:00
|
|
|
|
2020-08-21 05:28:27 +00:00
|
|
|
self.is_connected = asyncio.Event()
|
2017-12-05 11:41:07 +00:00
|
|
|
|
2020-08-22 06:05:05 +00:00
|
|
|
self.loop = asyncio.get_event_loop()
|
|
|
|
|
2020-08-21 05:28:27 +00:00
|
|
|
async def start(self):
|
2017-12-05 11:41:07 +00:00
|
|
|
while True:
|
2019-06-19 14:01:23 +00:00
|
|
|
self.connection = Connection(
|
|
|
|
self.dc_id,
|
2020-08-22 06:05:05 +00:00
|
|
|
self.test_mode,
|
2019-06-19 14:01:23 +00:00
|
|
|
self.client.ipv6,
|
|
|
|
self.client.proxy
|
|
|
|
)
|
2018-05-24 19:19:57 +00:00
|
|
|
|
2017-12-05 11:41:07 +00:00
|
|
|
try:
|
2020-08-21 05:28:27 +00:00
|
|
|
await self.connection.connect()
|
2017-12-05 11:41:07 +00:00
|
|
|
|
2020-08-22 06:05:05 +00:00
|
|
|
self.network_task = self.loop.create_task(self.network_worker())
|
2017-12-05 11:41:07 +00:00
|
|
|
|
2020-08-21 05:28:27 +00:00
|
|
|
self.current_salt = FutureSalt(0, 0, Session.INITIAL_SALT)
|
2019-03-03 15:50:25 +00:00
|
|
|
self.current_salt = FutureSalt(
|
|
|
|
0, 0,
|
2020-08-21 05:28:27 +00:00
|
|
|
(await self._send(
|
2020-08-22 06:05:05 +00:00
|
|
|
raw.functions.Ping(ping_id=0),
|
2019-03-03 15:50:25 +00:00
|
|
|
timeout=self.START_TIMEOUT
|
2020-08-21 05:28:27 +00:00
|
|
|
)).new_server_salt
|
2019-03-03 15:50:25 +00:00
|
|
|
)
|
2020-08-22 06:05:05 +00:00
|
|
|
self.current_salt = (await self._send(
|
|
|
|
raw.functions.GetFutureSalts(num=1),
|
|
|
|
timeout=self.START_TIMEOUT)).salts[0]
|
2017-12-05 11:41:07 +00:00
|
|
|
|
2020-08-22 06:05:05 +00:00
|
|
|
self.next_salt_task = self.loop.create_task(self.next_salt_worker())
|
2017-12-05 11:41:07 +00:00
|
|
|
|
2017-12-19 10:38:15 +00:00
|
|
|
if not self.is_cdn:
|
2020-08-21 05:28:27 +00:00
|
|
|
await self._send(
|
2020-08-22 06:05:05 +00:00
|
|
|
raw.functions.InvokeWithLayer(
|
2019-03-16 15:50:40 +00:00
|
|
|
layer=layer,
|
2020-08-22 06:05:05 +00:00
|
|
|
query=raw.functions.InitConnection(
|
2018-06-24 16:26:11 +00:00
|
|
|
api_id=self.client.api_id,
|
2018-06-24 16:47:49 +00:00
|
|
|
app_version=self.client.app_version,
|
|
|
|
device_model=self.client.device_model,
|
|
|
|
system_version=self.client.system_version,
|
2018-06-26 22:42:32 +00:00
|
|
|
system_lang_code=self.client.lang_code,
|
2018-06-24 16:47:49 +00:00
|
|
|
lang_code=self.client.lang_code,
|
2018-06-24 16:26:11 +00:00
|
|
|
lang_pack="",
|
2020-08-22 06:05:05 +00:00
|
|
|
query=raw.functions.help.GetConfig(),
|
2017-12-19 10:38:15 +00:00
|
|
|
)
|
2019-03-03 15:50:25 +00:00
|
|
|
),
|
|
|
|
timeout=self.START_TIMEOUT
|
2018-03-15 11:03:02 +00:00
|
|
|
)
|
2017-12-05 11:41:07 +00:00
|
|
|
|
2020-08-22 06:05:05 +00:00
|
|
|
self.ping_task = self.loop.create_task(self.ping_worker())
|
2017-12-05 11:41:07 +00:00
|
|
|
|
2020-08-22 06:05:05 +00:00
|
|
|
log.info(f"Session initialized: Layer {layer}")
|
|
|
|
log.info(f"Device: {self.client.device_model} - {self.client.app_version}")
|
|
|
|
log.info(f"System: {self.client.system_version} ({self.client.lang_code.upper()})")
|
2018-08-28 10:39:14 +00:00
|
|
|
|
2018-06-27 22:16:12 +00:00
|
|
|
except AuthKeyDuplicated as e:
|
2020-08-21 05:28:27 +00:00
|
|
|
await self.stop()
|
2018-06-27 22:16:12 +00:00
|
|
|
raise e
|
2019-03-25 10:10:46 +00:00
|
|
|
except (OSError, TimeoutError, RPCError):
|
2020-08-21 05:28:27 +00:00
|
|
|
await self.stop()
|
2018-04-12 06:30:52 +00:00
|
|
|
except Exception as e:
|
2020-08-21 05:28:27 +00:00
|
|
|
await self.stop()
|
2018-04-12 06:30:52 +00:00
|
|
|
raise e
|
2017-12-05 11:41:07 +00:00
|
|
|
else:
|
|
|
|
break
|
|
|
|
|
|
|
|
self.is_connected.set()
|
|
|
|
|
2020-08-21 05:28:27 +00:00
|
|
|
log.info("Session started")
|
2017-12-05 11:41:07 +00:00
|
|
|
|
2020-08-21 05:28:27 +00:00
|
|
|
async def stop(self):
|
2017-12-05 11:41:07 +00:00
|
|
|
self.is_connected.clear()
|
2017-12-23 22:43:20 +00:00
|
|
|
|
2020-08-21 05:28:27 +00:00
|
|
|
self.ping_task_event.set()
|
|
|
|
self.next_salt_task_event.set()
|
2017-12-23 22:43:20 +00:00
|
|
|
|
2020-08-21 05:28:27 +00:00
|
|
|
if self.ping_task is not None:
|
|
|
|
await self.ping_task
|
2017-12-26 00:19:38 +00:00
|
|
|
|
2020-08-21 05:28:27 +00:00
|
|
|
if self.next_salt_task is not None:
|
|
|
|
await self.next_salt_task
|
2017-12-23 22:43:20 +00:00
|
|
|
|
2020-08-21 05:28:27 +00:00
|
|
|
self.ping_task_event.clear()
|
|
|
|
self.next_salt_task_event.clear()
|
2017-12-23 22:43:20 +00:00
|
|
|
|
2017-12-05 11:41:07 +00:00
|
|
|
self.connection.close()
|
|
|
|
|
2020-08-22 06:05:05 +00:00
|
|
|
if self.network_task:
|
|
|
|
await self.network_task
|
2018-04-29 18:30:32 +00:00
|
|
|
|
2018-03-16 10:18:16 +00:00
|
|
|
for i in self.results.values():
|
|
|
|
i.event.set()
|
|
|
|
|
2018-06-24 17:29:12 +00:00
|
|
|
if not self.is_media and callable(self.client.disconnect_handler):
|
2018-05-23 12:27:17 +00:00
|
|
|
try:
|
2020-08-21 05:28:27 +00:00
|
|
|
await self.client.disconnect_handler(self.client)
|
2018-05-23 12:27:17 +00:00
|
|
|
except Exception as e:
|
2019-09-08 17:24:06 +00:00
|
|
|
log.error(e, exc_info=True)
|
2018-05-23 12:27:17 +00:00
|
|
|
|
2020-08-21 05:28:27 +00:00
|
|
|
log.info("Session stopped")
|
2017-12-09 01:21:23 +00:00
|
|
|
|
2020-08-21 05:28:27 +00:00
|
|
|
async def restart(self):
|
|
|
|
await self.stop()
|
|
|
|
await self.start()
|
2017-12-09 01:21:23 +00:00
|
|
|
|
2020-08-22 06:05:05 +00:00
|
|
|
async def handle_packet(self, packet):
|
2021-01-02 17:45:43 +00:00
|
|
|
data = await self.loop.run_in_executor(
|
|
|
|
pyrogram.crypto_executor,
|
|
|
|
mtproto.unpack,
|
|
|
|
BytesIO(packet),
|
2020-12-07 18:16:46 +00:00
|
|
|
self.session_id,
|
|
|
|
self.auth_key,
|
|
|
|
self.auth_key_id
|
|
|
|
)
|
2017-12-05 11:41:07 +00:00
|
|
|
|
2020-08-22 06:05:05 +00:00
|
|
|
messages = (
|
|
|
|
data.body.messages
|
|
|
|
if isinstance(data.body, MsgContainer)
|
|
|
|
else [data]
|
|
|
|
)
|
2017-12-05 11:41:07 +00:00
|
|
|
|
2020-11-20 00:53:19 +00:00
|
|
|
# Call log.debug twice because calling it once by appending "data" to the previous string (i.e. f"Kind: {data}")
|
|
|
|
# will cause "data" to be evaluated as string every time instead of only when debug is actually enabled.
|
|
|
|
log.debug("Received:")
|
|
|
|
log.debug(data)
|
2017-12-05 11:41:07 +00:00
|
|
|
|
2020-08-22 06:05:05 +00:00
|
|
|
for msg in messages:
|
|
|
|
if msg.seq_no == 0:
|
2020-08-22 09:26:11 +00:00
|
|
|
MsgId.set_server_time(msg.msg_id / (2 ** 32))
|
2018-05-06 12:55:41 +00:00
|
|
|
|
2020-08-22 06:05:05 +00:00
|
|
|
if msg.seq_no % 2 != 0:
|
|
|
|
if msg.msg_id in self.pending_acks:
|
|
|
|
continue
|
|
|
|
else:
|
|
|
|
self.pending_acks.add(msg.msg_id)
|
2018-05-06 12:55:41 +00:00
|
|
|
|
2020-08-22 06:05:05 +00:00
|
|
|
if isinstance(msg.body, (raw.types.MsgDetailedInfo, raw.types.MsgNewDetailedInfo)):
|
|
|
|
self.pending_acks.add(msg.body.answer_msg_id)
|
|
|
|
continue
|
2017-12-05 11:41:07 +00:00
|
|
|
|
2020-08-22 06:05:05 +00:00
|
|
|
if isinstance(msg.body, raw.types.NewSessionCreated):
|
|
|
|
continue
|
2017-12-05 11:41:07 +00:00
|
|
|
|
2020-08-22 06:05:05 +00:00
|
|
|
msg_id = None
|
|
|
|
|
|
|
|
if isinstance(msg.body, (raw.types.BadMsgNotification, raw.types.BadServerSalt)):
|
|
|
|
msg_id = msg.body.bad_msg_id
|
|
|
|
elif isinstance(msg.body, (FutureSalts, raw.types.RpcResult)):
|
|
|
|
msg_id = msg.body.req_msg_id
|
|
|
|
elif isinstance(msg.body, raw.types.Pong):
|
|
|
|
msg_id = msg.body.msg_id
|
|
|
|
else:
|
|
|
|
if self.client is not None:
|
|
|
|
self.loop.create_task(self.client.handle_updates(msg.body))
|
|
|
|
|
|
|
|
if msg_id in self.results:
|
|
|
|
self.results[msg_id].value = getattr(msg.body, "result", msg.body)
|
|
|
|
self.results[msg_id].event.set()
|
|
|
|
|
|
|
|
if len(self.pending_acks) >= self.ACKS_THRESHOLD:
|
|
|
|
log.debug(f"Send {len(self.pending_acks)} acks")
|
|
|
|
|
|
|
|
try:
|
|
|
|
await self._send(raw.types.MsgsAck(msg_ids=list(self.pending_acks)), False)
|
|
|
|
except (OSError, TimeoutError):
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
self.pending_acks.clear()
|
|
|
|
|
|
|
|
async def ping_worker(self):
|
2020-08-21 05:28:27 +00:00
|
|
|
log.info("PingTask started")
|
2017-12-05 11:41:07 +00:00
|
|
|
|
|
|
|
while True:
|
2020-08-21 05:28:27 +00:00
|
|
|
try:
|
|
|
|
await asyncio.wait_for(self.ping_task_event.wait(), self.PING_INTERVAL)
|
|
|
|
except asyncio.TimeoutError:
|
|
|
|
pass
|
|
|
|
else:
|
2017-12-05 11:41:07 +00:00
|
|
|
break
|
|
|
|
|
|
|
|
try:
|
2020-08-21 05:28:27 +00:00
|
|
|
await self._send(
|
2020-08-22 06:05:05 +00:00
|
|
|
raw.functions.PingDelayDisconnect(
|
2020-08-21 05:28:27 +00:00
|
|
|
ping_id=0, disconnect_delay=self.WAIT_TIMEOUT + 10
|
|
|
|
), False
|
|
|
|
)
|
2019-03-25 10:10:46 +00:00
|
|
|
except (OSError, TimeoutError, RPCError):
|
2017-12-05 11:41:07 +00:00
|
|
|
pass
|
|
|
|
|
2020-08-21 05:28:27 +00:00
|
|
|
log.info("PingTask stopped")
|
2017-12-05 11:41:07 +00:00
|
|
|
|
2020-08-22 06:05:05 +00:00
|
|
|
async def next_salt_worker(self):
|
2020-08-21 05:28:27 +00:00
|
|
|
log.info("NextSaltTask started")
|
2017-12-05 11:41:07 +00:00
|
|
|
|
|
|
|
while True:
|
2020-12-12 15:46:40 +00:00
|
|
|
now = datetime.fromtimestamp(time.perf_counter() - MsgId.reference_clock + MsgId.server_time)
|
2017-12-05 11:41:07 +00:00
|
|
|
|
|
|
|
# Seconds to wait until middle-overlap, which is
|
|
|
|
# 15 minutes before/after the current/next salt end/start time
|
2019-05-31 14:36:20 +00:00
|
|
|
valid_until = datetime.fromtimestamp(self.current_salt.valid_until)
|
|
|
|
dt = (valid_until - now).total_seconds() - 900
|
2017-12-05 11:41:07 +00:00
|
|
|
|
2020-12-12 15:46:40 +00:00
|
|
|
minutes, seconds = divmod(int(dt), 60)
|
|
|
|
log.info(f"Next salt in {minutes:.0f}m {seconds:.0f}s (at {now + timedelta(seconds=dt)})")
|
2017-12-05 11:41:07 +00:00
|
|
|
|
2020-08-21 05:28:27 +00:00
|
|
|
try:
|
|
|
|
await asyncio.wait_for(self.next_salt_task_event.wait(), dt)
|
|
|
|
except asyncio.TimeoutError:
|
|
|
|
pass
|
|
|
|
else:
|
2017-12-05 11:41:07 +00:00
|
|
|
break
|
|
|
|
|
|
|
|
try:
|
2020-08-22 06:05:05 +00:00
|
|
|
self.current_salt = (await self._send(raw.functions.GetFutureSalts(num=1))).salts[0]
|
2019-03-25 10:10:46 +00:00
|
|
|
except (OSError, TimeoutError, RPCError):
|
2017-12-05 11:41:07 +00:00
|
|
|
self.connection.close()
|
|
|
|
break
|
|
|
|
|
2020-08-21 05:28:27 +00:00
|
|
|
log.info("NextSaltTask stopped")
|
2017-12-05 11:41:07 +00:00
|
|
|
|
2020-08-22 06:05:05 +00:00
|
|
|
async def network_worker(self):
|
|
|
|
log.info("NetworkTask started")
|
2017-12-05 11:41:07 +00:00
|
|
|
|
|
|
|
while True:
|
2020-08-21 05:28:27 +00:00
|
|
|
packet = await self.connection.recv()
|
2017-12-05 11:41:07 +00:00
|
|
|
|
2018-02-18 19:33:33 +00:00
|
|
|
if packet is None or len(packet) == 4:
|
|
|
|
if packet:
|
2020-08-22 06:05:05 +00:00
|
|
|
log.warning(f'Server sent "{Int.read(BytesIO(packet))}"')
|
2018-02-18 19:33:33 +00:00
|
|
|
|
2017-12-05 11:41:07 +00:00
|
|
|
if self.is_connected.is_set():
|
2020-08-22 06:05:05 +00:00
|
|
|
self.loop.create_task(self.restart())
|
2020-08-21 05:28:27 +00:00
|
|
|
|
2017-12-05 11:41:07 +00:00
|
|
|
break
|
|
|
|
|
2020-08-22 06:05:05 +00:00
|
|
|
self.loop.create_task(self.handle_packet(packet))
|
2017-12-05 11:41:07 +00:00
|
|
|
|
2020-08-22 06:05:05 +00:00
|
|
|
log.info("NetworkTask stopped")
|
2017-12-05 11:41:07 +00:00
|
|
|
|
2020-08-21 05:28:27 +00:00
|
|
|
async def _send(self, data: TLObject, wait_response: bool = True, timeout: float = WAIT_TIMEOUT):
|
2017-12-05 11:41:07 +00:00
|
|
|
message = self.msg_factory(data)
|
|
|
|
msg_id = message.msg_id
|
|
|
|
|
|
|
|
if wait_response:
|
|
|
|
self.results[msg_id] = Result()
|
|
|
|
|
2020-11-20 00:53:19 +00:00
|
|
|
# Call log.debug twice because calling it once by appending "data" to the previous string (i.e. f"Kind: {data}")
|
|
|
|
# will cause "data" to be evaluated as string every time instead of only when debug is actually enabled.
|
|
|
|
log.debug(f"Sent:")
|
|
|
|
log.debug(message)
|
2020-06-02 11:05:26 +00:00
|
|
|
|
2021-01-02 17:45:43 +00:00
|
|
|
payload = await self.loop.run_in_executor(
|
|
|
|
pyrogram.crypto_executor,
|
|
|
|
mtproto.pack,
|
|
|
|
message,
|
2020-12-07 18:16:46 +00:00
|
|
|
self.current_salt.salt,
|
|
|
|
self.session_id,
|
|
|
|
self.auth_key,
|
|
|
|
self.auth_key_id
|
|
|
|
)
|
2017-12-05 11:41:07 +00:00
|
|
|
|
|
|
|
try:
|
2020-08-21 05:28:27 +00:00
|
|
|
await self.connection.send(payload)
|
2017-12-05 11:41:07 +00:00
|
|
|
except OSError as e:
|
|
|
|
self.results.pop(msg_id, None)
|
|
|
|
raise e
|
|
|
|
|
|
|
|
if wait_response:
|
2020-08-21 05:28:27 +00:00
|
|
|
try:
|
|
|
|
await asyncio.wait_for(self.results[msg_id].event.wait(), timeout)
|
|
|
|
except asyncio.TimeoutError:
|
|
|
|
pass
|
|
|
|
finally:
|
|
|
|
result = self.results.pop(msg_id).value
|
2017-12-05 11:41:07 +00:00
|
|
|
|
|
|
|
if result is None:
|
|
|
|
raise TimeoutError
|
2020-08-22 06:05:05 +00:00
|
|
|
elif isinstance(result, raw.types.RpcError):
|
|
|
|
if isinstance(data, (raw.functions.InvokeWithoutUpdates, raw.functions.InvokeWithTakeout)):
|
2020-02-01 14:19:05 +00:00
|
|
|
data = data.query
|
|
|
|
|
2019-03-25 10:10:46 +00:00
|
|
|
RPCError.raise_it(result, type(data))
|
2020-08-22 06:05:05 +00:00
|
|
|
elif isinstance(result, raw.types.BadMsgNotification):
|
2018-02-22 00:28:46 +00:00
|
|
|
raise Exception(self.BAD_MSG_DESCRIPTION.get(
|
|
|
|
result.error_code,
|
2020-08-22 06:05:05 +00:00
|
|
|
f"Error code {result.error_code}"
|
2018-02-22 00:28:46 +00:00
|
|
|
))
|
2017-12-05 11:41:07 +00:00
|
|
|
else:
|
|
|
|
return result
|
|
|
|
|
2020-08-21 05:28:27 +00:00
|
|
|
async def send(
|
2020-05-07 11:38:22 +00:00
|
|
|
self,
|
|
|
|
data: TLObject,
|
|
|
|
retries: int = MAX_RETRIES,
|
|
|
|
timeout: float = WAIT_TIMEOUT,
|
|
|
|
sleep_threshold: float = SLEEP_THRESHOLD
|
|
|
|
):
|
2020-08-21 05:28:27 +00:00
|
|
|
try:
|
|
|
|
await asyncio.wait_for(self.is_connected.wait(), self.WAIT_TIMEOUT)
|
|
|
|
except asyncio.TimeoutError:
|
|
|
|
pass
|
2017-12-05 11:41:07 +00:00
|
|
|
|
2020-08-22 06:05:05 +00:00
|
|
|
if isinstance(data, (raw.functions.InvokeWithoutUpdates, raw.functions.InvokeWithTakeout)):
|
2020-05-07 11:38:22 +00:00
|
|
|
query = data.query
|
|
|
|
else:
|
|
|
|
query = data
|
|
|
|
|
|
|
|
query = ".".join(query.QUALNAME.split(".")[1:])
|
|
|
|
|
|
|
|
while True:
|
|
|
|
try:
|
2020-08-21 05:28:27 +00:00
|
|
|
return await self._send(data, timeout=timeout)
|
2020-05-07 11:38:22 +00:00
|
|
|
except FloodWait as e:
|
|
|
|
amount = e.x
|
|
|
|
|
2020-08-27 08:59:28 +00:00
|
|
|
if amount > sleep_threshold >= 0:
|
2020-05-07 11:38:22 +00:00
|
|
|
raise
|
|
|
|
|
2020-08-22 06:05:05 +00:00
|
|
|
log.warning(f'[{self.client.session_name}] Sleeping for {amount}s (required by "{query}")')
|
2020-05-07 11:38:22 +00:00
|
|
|
|
2020-08-21 05:28:27 +00:00
|
|
|
await asyncio.sleep(amount)
|
2021-04-12 07:21:20 +00:00
|
|
|
except (OSError, TimeoutError, InternalServerError, ServiceUnavailable) as e:
|
2020-05-07 11:38:22 +00:00
|
|
|
if retries == 0:
|
|
|
|
raise e from None
|
|
|
|
|
|
|
|
(log.warning if retries < 2 else log.info)(
|
2020-12-27 20:08:01 +00:00
|
|
|
f'[{Session.MAX_RETRIES - retries + 1}] Retrying "{query}" due to {repr(e)}')
|
2020-05-07 11:38:22 +00:00
|
|
|
|
2020-08-21 05:28:27 +00:00
|
|
|
await asyncio.sleep(0.5)
|
2020-05-07 11:38:22 +00:00
|
|
|
|
2020-08-21 05:28:27 +00:00
|
|
|
return await self.send(data, retries - 1, timeout)
|