2018-06-06 21:41:01 +03:00
|
|
|
import asyncio
|
|
|
|
import logging
|
|
|
|
|
2018-06-07 17:32:12 +03:00
|
|
|
from . import MTProtoPlainSender, authenticator
|
2018-06-09 12:34:01 +03:00
|
|
|
from .. import utils
|
2018-06-07 17:32:12 +03:00
|
|
|
from ..errors import (
|
|
|
|
BadMessageError, TypeNotFoundError, BrokenAuthKeyError, SecurityError,
|
|
|
|
rpc_message_to_error
|
|
|
|
)
|
2018-06-06 21:41:01 +03:00
|
|
|
from ..extensions import BinaryReader
|
2018-06-09 14:11:49 +03:00
|
|
|
from ..tl.core import RpcResult, MessageContainer, GzipPacked
|
2018-06-07 12:51:09 +03:00
|
|
|
from ..tl.functions.auth import LogOutRequest
|
2018-06-06 21:41:01 +03:00
|
|
|
from ..tl.types import (
|
|
|
|
MsgsAck, Pong, BadServerSalt, BadMsgNotification, FutureSalts,
|
2018-06-14 17:23:16 +03:00
|
|
|
MsgNewDetailedInfo, NewSessionCreated, MsgDetailedInfo, MsgsStateReq,
|
|
|
|
MsgsStateInfo, MsgsAllInfo, MsgResendReq
|
2018-06-06 21:41:01 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
__log__ = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
# TODO Create some kind of "ReconnectionPolicy" that allows specifying
|
|
|
|
# what should be done in case of some errors, with some sane defaults.
|
|
|
|
# For instance, should all messages be set with an error upon network
|
|
|
|
# loss? Should we try reconnecting forever? A certain amount of times?
|
|
|
|
# A timeout? What about recoverable errors, like connection reset?
|
|
|
|
class MTProtoSender:
|
2018-06-07 12:51:09 +03:00
|
|
|
"""
|
|
|
|
MTProto Mobile Protocol sender
|
|
|
|
(https://core.telegram.org/mtproto/description).
|
|
|
|
|
|
|
|
This class is responsible for wrapping requests into `TLMessage`'s,
|
|
|
|
sending them over the network and receiving them in a safe manner.
|
|
|
|
|
|
|
|
Automatic reconnection due to temporary network issues is a concern
|
|
|
|
for this class as well, including retry of messages that could not
|
|
|
|
be sent successfully.
|
|
|
|
|
|
|
|
A new authorization key will be generated on connection if no other
|
|
|
|
key exists yet.
|
|
|
|
"""
|
2018-06-09 22:03:48 +03:00
|
|
|
def __init__(self, state, connection, *, retries=5,
|
|
|
|
first_query=None, update_callback=None):
|
2018-06-09 12:34:01 +03:00
|
|
|
self.state = state
|
2018-06-09 22:03:48 +03:00
|
|
|
self._connection = connection
|
2018-06-08 21:41:48 +03:00
|
|
|
self._ip = None
|
|
|
|
self._port = None
|
2018-06-08 21:50:53 +03:00
|
|
|
self._retries = retries
|
2018-06-09 22:03:48 +03:00
|
|
|
self._first_query = first_query
|
|
|
|
self._is_first_query = bool(first_query)
|
|
|
|
self._update_callback = update_callback
|
2018-06-07 12:51:09 +03:00
|
|
|
|
|
|
|
# Whether the user has explicitly connected or disconnected.
|
|
|
|
#
|
|
|
|
# If a disconnection happens for any other reason and it
|
|
|
|
# was *not* user action then the pending messages won't
|
|
|
|
# be cleared but on explicit user disconnection all the
|
|
|
|
# pending futures should be cancelled.
|
2018-06-06 21:41:01 +03:00
|
|
|
self._user_connected = False
|
2018-06-08 21:41:48 +03:00
|
|
|
self._reconnecting = False
|
2018-06-06 21:41:01 +03:00
|
|
|
|
2018-06-06 22:42:48 +03:00
|
|
|
# We need to join the loops upon disconnection
|
|
|
|
self._send_loop_handle = None
|
|
|
|
self._recv_loop_handle = None
|
|
|
|
|
2018-06-06 21:41:01 +03:00
|
|
|
# Sending something shouldn't block
|
2018-06-07 14:51:19 +03:00
|
|
|
self._send_queue = _ContainerQueue()
|
2018-06-06 21:41:01 +03:00
|
|
|
|
|
|
|
# Telegram responds to messages out of order. Keep
|
|
|
|
# {id: Message} to set their Future result upon arrival.
|
|
|
|
self._pending_messages = {}
|
|
|
|
|
2018-06-07 14:33:32 +03:00
|
|
|
# Containers are accepted or rejected as a whole when any of
|
2018-06-07 19:01:18 +03:00
|
|
|
# its inner requests are acknowledged. For this purpose we
|
|
|
|
# all the sent containers here.
|
2018-06-07 14:33:32 +03:00
|
|
|
self._pending_containers = []
|
|
|
|
|
2018-06-06 21:41:01 +03:00
|
|
|
# We need to acknowledge every response from Telegram
|
|
|
|
self._pending_ack = set()
|
|
|
|
|
|
|
|
# Jump table from response ID to method that handles it
|
|
|
|
self._handlers = {
|
2018-06-09 14:11:49 +03:00
|
|
|
RpcResult.CONSTRUCTOR_ID: self._handle_rpc_result,
|
2018-06-06 21:41:01 +03:00
|
|
|
MessageContainer.CONSTRUCTOR_ID: self._handle_container,
|
|
|
|
GzipPacked.CONSTRUCTOR_ID: self._handle_gzip_packed,
|
|
|
|
Pong.CONSTRUCTOR_ID: self._handle_pong,
|
|
|
|
BadServerSalt.CONSTRUCTOR_ID: self._handle_bad_server_salt,
|
|
|
|
BadMsgNotification.CONSTRUCTOR_ID: self._handle_bad_notification,
|
|
|
|
MsgDetailedInfo.CONSTRUCTOR_ID: self._handle_detailed_info,
|
|
|
|
MsgNewDetailedInfo.CONSTRUCTOR_ID: self._handle_new_detailed_info,
|
|
|
|
NewSessionCreated.CONSTRUCTOR_ID: self._handle_new_session_created,
|
|
|
|
MsgsAck.CONSTRUCTOR_ID: self._handle_ack,
|
2018-06-14 17:23:16 +03:00
|
|
|
FutureSalts.CONSTRUCTOR_ID: self._handle_future_salts,
|
|
|
|
MsgsStateReq.CONSTRUCTOR_ID: self._handle_state_forgotten,
|
|
|
|
MsgResendReq.CONSTRUCTOR_ID: self._handle_state_forgotten,
|
|
|
|
MsgsAllInfo.CONSTRUCTOR_ID: self._handle_msg_all,
|
2018-06-06 21:41:01 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
# Public API
|
|
|
|
|
|
|
|
async def connect(self, ip, port):
|
2018-06-07 12:51:09 +03:00
|
|
|
"""
|
|
|
|
Connects to the specified ``ip:port``, and generates a new
|
|
|
|
authorization key for the `MTProtoSender.session` if it does
|
|
|
|
not exist yet.
|
|
|
|
"""
|
|
|
|
if self._user_connected:
|
2018-06-08 22:13:14 +03:00
|
|
|
__log__.info('User is already connected!')
|
2018-06-07 12:51:09 +03:00
|
|
|
return
|
|
|
|
|
2018-06-08 21:41:48 +03:00
|
|
|
self._ip = ip
|
|
|
|
self._port = port
|
2018-06-06 22:42:48 +03:00
|
|
|
self._user_connected = True
|
2018-06-08 21:41:48 +03:00
|
|
|
await self._connect()
|
|
|
|
|
2018-06-09 22:03:48 +03:00
|
|
|
def is_connected(self):
|
|
|
|
return self._user_connected
|
|
|
|
|
2018-06-06 21:41:01 +03:00
|
|
|
async def disconnect(self):
|
2018-06-07 12:51:09 +03:00
|
|
|
"""
|
|
|
|
Cleanly disconnects the instance from the network, cancels
|
|
|
|
all pending requests, and closes the send and receive loops.
|
|
|
|
"""
|
|
|
|
if not self._user_connected:
|
2018-06-08 22:13:14 +03:00
|
|
|
__log__.info('User is already disconnected!')
|
2018-06-07 12:51:09 +03:00
|
|
|
return
|
|
|
|
|
2018-06-08 22:13:14 +03:00
|
|
|
__log__.info('Disconnecting from {}...'.format(self._ip))
|
2018-06-06 21:41:01 +03:00
|
|
|
self._user_connected = False
|
|
|
|
try:
|
2018-06-08 22:13:14 +03:00
|
|
|
__log__.debug('Closing current connection...')
|
2018-06-13 11:04:27 +03:00
|
|
|
await self._connection.close()
|
2018-06-06 22:42:48 +03:00
|
|
|
finally:
|
2018-06-08 22:13:14 +03:00
|
|
|
__log__.debug('Cancelling {} pending message(s)...'
|
|
|
|
.format(len(self._pending_messages)))
|
2018-06-07 12:51:09 +03:00
|
|
|
for message in self._pending_messages.values():
|
|
|
|
message.future.cancel()
|
|
|
|
|
|
|
|
self._pending_messages.clear()
|
2018-06-07 15:16:47 +03:00
|
|
|
self._pending_ack.clear()
|
2018-06-08 22:13:14 +03:00
|
|
|
|
|
|
|
__log__.debug('Cancelling the send loop...')
|
2018-06-06 22:42:48 +03:00
|
|
|
self._send_loop_handle.cancel()
|
2018-06-08 22:13:14 +03:00
|
|
|
|
|
|
|
__log__.debug('Cancelling the receive loop...')
|
2018-06-06 22:42:48 +03:00
|
|
|
self._recv_loop_handle.cancel()
|
2018-06-06 21:41:01 +03:00
|
|
|
|
2018-06-08 22:13:14 +03:00
|
|
|
__log__.info('Disconnection from {} complete!'.format(self._ip))
|
|
|
|
|
2018-06-09 16:26:13 +03:00
|
|
|
def send(self, request, ordered=False):
|
2018-06-07 11:30:20 +03:00
|
|
|
"""
|
|
|
|
This method enqueues the given request to be sent.
|
|
|
|
|
|
|
|
The request will be wrapped inside a `TLMessage` until its
|
|
|
|
response arrives, and the `Future` response of the `TLMessage`
|
|
|
|
is immediately returned so that one can further ``await`` it:
|
|
|
|
|
|
|
|
.. code-block:: python
|
|
|
|
|
|
|
|
async def method():
|
|
|
|
# Sending (enqueued for the send loop)
|
2018-06-09 16:26:13 +03:00
|
|
|
future = sender.send(request)
|
2018-06-07 11:30:20 +03:00
|
|
|
# Receiving (waits for the receive loop to read the result)
|
|
|
|
result = await future
|
|
|
|
|
|
|
|
Designed like this because Telegram may send the response at
|
|
|
|
any point, and it can send other items while one waits for it.
|
|
|
|
Once the response for this future arrives, it is set with the
|
|
|
|
received result, quite similar to how a ``receive()`` call
|
|
|
|
would otherwise work.
|
|
|
|
|
|
|
|
Since the receiving part is "built in" the future, it's
|
|
|
|
impossible to await receive a result that was never sent.
|
|
|
|
"""
|
2018-06-07 15:02:55 +03:00
|
|
|
if utils.is_list_like(request):
|
|
|
|
result = []
|
2018-06-09 12:34:01 +03:00
|
|
|
after = None
|
2018-06-07 15:02:55 +03:00
|
|
|
for r in request:
|
2018-06-09 12:34:01 +03:00
|
|
|
message = self.state.create_message(r, after=after)
|
2018-06-07 15:02:55 +03:00
|
|
|
self._pending_messages[message.msg_id] = message
|
2018-06-09 16:26:13 +03:00
|
|
|
self._send_queue.put_nowait(message)
|
2018-06-07 15:02:55 +03:00
|
|
|
result.append(message.future)
|
2018-06-09 12:34:01 +03:00
|
|
|
after = ordered and message
|
2018-06-07 15:02:55 +03:00
|
|
|
return result
|
|
|
|
else:
|
2018-06-09 12:34:01 +03:00
|
|
|
message = self.state.create_message(request)
|
2018-06-07 15:02:55 +03:00
|
|
|
self._pending_messages[message.msg_id] = message
|
2018-06-09 16:26:13 +03:00
|
|
|
self._send_queue.put_nowait(message)
|
2018-06-07 15:02:55 +03:00
|
|
|
return message.future
|
2018-06-06 21:41:01 +03:00
|
|
|
|
2018-06-08 22:18:15 +03:00
|
|
|
# Private methods
|
|
|
|
|
|
|
|
async def _connect(self):
|
|
|
|
"""
|
|
|
|
Performs the actual connection, retrying, generating the
|
|
|
|
authorization key if necessary, and starting the send and
|
|
|
|
receive loops.
|
|
|
|
"""
|
|
|
|
__log__.info('Connecting to {}:{}...'.format(self._ip, self._port))
|
|
|
|
_last_error = ConnectionError()
|
|
|
|
for retry in range(1, self._retries + 1):
|
|
|
|
try:
|
|
|
|
__log__.debug('Connection attempt {}...'.format(retry))
|
2018-06-13 11:04:27 +03:00
|
|
|
await self._connection.connect(self._ip, self._port)
|
2018-06-08 22:18:15 +03:00
|
|
|
except OSError as e:
|
|
|
|
_last_error = e
|
|
|
|
__log__.warning('Attempt {} at connecting failed: {}'
|
|
|
|
.format(retry, e))
|
|
|
|
else:
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
raise _last_error
|
|
|
|
|
|
|
|
__log__.debug('Connection success!')
|
2018-06-09 12:34:01 +03:00
|
|
|
if self.state.auth_key is None:
|
2018-06-11 20:51:01 +03:00
|
|
|
self._is_first_query = bool(self._first_query)
|
2018-06-08 22:18:15 +03:00
|
|
|
_last_error = SecurityError()
|
|
|
|
plain = MTProtoPlainSender(self._connection)
|
|
|
|
for retry in range(1, self._retries + 1):
|
|
|
|
try:
|
|
|
|
__log__.debug('New auth_key attempt {}...'.format(retry))
|
2018-06-09 12:34:01 +03:00
|
|
|
self.state.auth_key, self.state.time_offset =\
|
2018-06-08 22:18:15 +03:00
|
|
|
await authenticator.do_authentication(plain)
|
|
|
|
except (SecurityError, AssertionError) as e:
|
|
|
|
_last_error = e
|
|
|
|
__log__.warning('Attempt {} at new auth_key failed: {}'
|
|
|
|
.format(retry, e))
|
|
|
|
else:
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
raise _last_error
|
|
|
|
|
|
|
|
__log__.debug('Starting send loop')
|
|
|
|
self._send_loop_handle = asyncio.ensure_future(self._send_loop())
|
2018-06-10 22:30:16 +03:00
|
|
|
__log__.debug('Starting receive loop')
|
|
|
|
self._recv_loop_handle = asyncio.ensure_future(self._recv_loop())
|
2018-06-09 22:03:48 +03:00
|
|
|
if self._is_first_query:
|
|
|
|
__log__.debug('Running first query')
|
|
|
|
self._is_first_query = False
|
2018-06-10 22:30:16 +03:00
|
|
|
await self.send(self._first_query)
|
2018-06-09 22:03:48 +03:00
|
|
|
|
2018-06-08 22:18:15 +03:00
|
|
|
__log__.info('Connection to {} complete!'.format(self._ip))
|
|
|
|
|
|
|
|
async def _reconnect(self):
|
|
|
|
"""
|
|
|
|
Cleanly disconnects and then reconnects.
|
|
|
|
"""
|
|
|
|
self._reconnecting = True
|
|
|
|
|
|
|
|
__log__.debug('Awaiting for the send loop before reconnecting...')
|
|
|
|
await self._send_loop_handle
|
|
|
|
|
|
|
|
__log__.debug('Awaiting for the receive loop before reconnecting...')
|
|
|
|
await self._recv_loop_handle
|
|
|
|
|
|
|
|
__log__.debug('Closing current connection...')
|
2018-06-13 11:04:27 +03:00
|
|
|
await self._connection.close()
|
2018-06-08 22:18:15 +03:00
|
|
|
|
|
|
|
self._reconnecting = False
|
|
|
|
await self._connect()
|
|
|
|
|
2018-06-09 16:42:10 +03:00
|
|
|
def _clean_containers(self, msg_ids):
|
|
|
|
"""
|
|
|
|
Helper method to clean containers from the pending messages
|
|
|
|
once a wrapped msg_id of them has been acknowledged.
|
|
|
|
|
|
|
|
This is the only way we can resend TLMessage(MessageContainer)
|
|
|
|
on bad notifications and also mark them as received once any
|
|
|
|
of their inner TLMessage is acknowledged.
|
|
|
|
"""
|
|
|
|
for i in reversed(range(len(self._pending_containers))):
|
|
|
|
message = self._pending_containers[i]
|
|
|
|
for msg in message.obj.messages:
|
|
|
|
if msg.msg_id in msg_ids:
|
|
|
|
del self._pending_containers[i]
|
|
|
|
del self._pending_messages[message.msg_id]
|
|
|
|
break
|
|
|
|
|
2018-06-06 21:41:01 +03:00
|
|
|
# Loops
|
|
|
|
|
|
|
|
async def _send_loop(self):
|
2018-06-07 12:51:09 +03:00
|
|
|
"""
|
|
|
|
This loop is responsible for popping items off the send
|
|
|
|
queue, encrypting them, and sending them over the network.
|
|
|
|
|
|
|
|
Besides `connect`, only this method ever sends data.
|
|
|
|
"""
|
2018-06-08 21:41:48 +03:00
|
|
|
while self._user_connected and not self._reconnecting:
|
2018-06-07 15:16:47 +03:00
|
|
|
if self._pending_ack:
|
2018-06-09 16:26:13 +03:00
|
|
|
self._send_queue.put_nowait(self.state.create_message(
|
2018-06-09 12:34:01 +03:00
|
|
|
MsgsAck(list(self._pending_ack))
|
|
|
|
))
|
2018-06-07 15:16:47 +03:00
|
|
|
self._pending_ack.clear()
|
|
|
|
|
2018-06-07 19:01:18 +03:00
|
|
|
messages = await self._send_queue.get()
|
|
|
|
if isinstance(messages, list):
|
2018-06-09 12:34:01 +03:00
|
|
|
message = self.state.create_message(MessageContainer(messages))
|
2018-06-07 14:33:32 +03:00
|
|
|
self._pending_messages[message.msg_id] = message
|
|
|
|
self._pending_containers.append(message)
|
2018-06-07 19:01:18 +03:00
|
|
|
else:
|
|
|
|
message = messages
|
|
|
|
messages = [message]
|
2018-06-07 14:33:32 +03:00
|
|
|
|
2018-06-08 22:13:14 +03:00
|
|
|
__log__.debug('Packing {} outgoing message(s)...'
|
|
|
|
.format(len(messages)))
|
2018-06-09 12:34:01 +03:00
|
|
|
body = self.state.pack_message(message)
|
2018-06-06 21:41:01 +03:00
|
|
|
|
2018-06-07 19:01:18 +03:00
|
|
|
while not any(m.future.cancelled() for m in messages):
|
|
|
|
try:
|
2018-06-13 11:04:27 +03:00
|
|
|
__log__.debug('Sending {} bytes...'.format(len(body)))
|
|
|
|
await self._connection.send(body)
|
2018-06-07 19:01:18 +03:00
|
|
|
break
|
|
|
|
except asyncio.TimeoutError:
|
|
|
|
continue
|
2018-06-14 17:16:11 +03:00
|
|
|
except OSError as e:
|
|
|
|
__log__.warning('OSError while sending %s', e)
|
2018-06-07 19:01:18 +03:00
|
|
|
else:
|
|
|
|
# Remove the cancelled messages from pending
|
2018-06-08 22:13:14 +03:00
|
|
|
__log__.info('Some futures were cancelled, aborted send')
|
2018-06-07 19:01:18 +03:00
|
|
|
self._clean_containers([m.msg_id for m in messages])
|
|
|
|
for m in messages:
|
|
|
|
if m.future.cancelled():
|
|
|
|
self._pending_messages.pop(m.msg_id, None)
|
|
|
|
else:
|
2018-06-09 16:26:13 +03:00
|
|
|
self._send_queue.put_nowait(m)
|
2018-06-06 21:41:01 +03:00
|
|
|
|
2018-06-10 22:30:16 +03:00
|
|
|
__log__.debug('Outgoing messages {} sent!'
|
|
|
|
.format(', '.join(str(m.msg_id) for m in messages)))
|
2018-06-08 22:13:14 +03:00
|
|
|
|
2018-06-06 21:41:01 +03:00
|
|
|
async def _recv_loop(self):
|
2018-06-07 12:51:09 +03:00
|
|
|
"""
|
|
|
|
This loop is responsible for reading all incoming responses
|
|
|
|
from the network, decrypting and handling or dispatching them.
|
|
|
|
|
|
|
|
Besides `connect`, only this method ever receives data.
|
|
|
|
"""
|
2018-06-08 21:41:48 +03:00
|
|
|
while self._user_connected and not self._reconnecting:
|
2018-06-07 19:01:18 +03:00
|
|
|
# TODO Are there more exceptions besides timeout?
|
|
|
|
# Disconnecting or switching off WiFi only resulted in
|
|
|
|
# timeouts, and once the network was back it continued
|
|
|
|
# on its own after a short delay.
|
|
|
|
try:
|
2018-06-08 22:13:14 +03:00
|
|
|
__log__.debug('Receiving items from the network...')
|
2018-06-13 11:04:27 +03:00
|
|
|
body = await self._connection.recv()
|
2018-06-07 19:01:18 +03:00
|
|
|
except asyncio.TimeoutError:
|
2018-06-08 22:13:14 +03:00
|
|
|
# TODO If nothing is received for a minute, send a request
|
2018-06-07 19:01:18 +03:00
|
|
|
continue
|
2018-06-08 22:13:14 +03:00
|
|
|
except ConnectionError as e:
|
2018-06-14 17:16:11 +03:00
|
|
|
__log__.info('Connection reset while receiving %s', e)
|
|
|
|
asyncio.ensure_future(self._reconnect())
|
|
|
|
break
|
|
|
|
except OSError as e:
|
|
|
|
__log__.warning('OSError while receiving %s', e)
|
2018-06-08 21:41:48 +03:00
|
|
|
asyncio.ensure_future(self._reconnect())
|
|
|
|
break
|
2018-06-06 21:41:01 +03:00
|
|
|
|
|
|
|
# TODO Check salt, session_id and sequence_number
|
2018-06-14 17:16:11 +03:00
|
|
|
__log__.debug('Decoding packet of %d bytes...', len(body))
|
2018-06-07 17:32:12 +03:00
|
|
|
try:
|
2018-06-09 12:34:01 +03:00
|
|
|
message = self.state.unpack_message(body)
|
2018-06-08 22:13:14 +03:00
|
|
|
except (BrokenAuthKeyError, BufferError) as e:
|
2018-06-08 21:41:48 +03:00
|
|
|
# The authorization key may be broken if a message was
|
|
|
|
# sent malformed, or if the authkey truly is corrupted.
|
|
|
|
#
|
|
|
|
# There may be a buffer error if Telegram's response was too
|
|
|
|
# short and hence not understood. Reset the authorization key
|
|
|
|
# and try again in either case.
|
|
|
|
#
|
|
|
|
# TODO Is it possible to detect malformed messages vs
|
|
|
|
# an actually broken authkey?
|
2018-06-08 22:13:14 +03:00
|
|
|
__log__.warning('Broken authorization key?: {}'.format(e))
|
2018-06-09 12:34:01 +03:00
|
|
|
self.state.auth_key = None
|
2018-06-08 21:41:48 +03:00
|
|
|
asyncio.ensure_future(self._reconnect())
|
|
|
|
break
|
2018-06-08 22:13:14 +03:00
|
|
|
except SecurityError as e:
|
2018-06-08 21:41:48 +03:00
|
|
|
# A step while decoding had the incorrect data. This message
|
|
|
|
# should not be considered safe and it should be ignored.
|
2018-06-08 22:13:14 +03:00
|
|
|
__log__.warning('Security error while unpacking a '
|
|
|
|
'received message:'.format(e))
|
2018-06-08 21:41:48 +03:00
|
|
|
continue
|
2018-06-09 14:48:27 +03:00
|
|
|
except TypeNotFoundError as e:
|
|
|
|
# The payload inside the message was not a known TLObject.
|
|
|
|
__log__.info('Server replied with an unknown type {:08x}: {!r}'
|
|
|
|
.format(e.invalid_constructor_id, e.remaining))
|
2018-06-07 17:32:12 +03:00
|
|
|
else:
|
2018-06-09 14:48:27 +03:00
|
|
|
await self._process_message(message)
|
2018-06-06 21:41:01 +03:00
|
|
|
|
|
|
|
# Response Handlers
|
|
|
|
|
2018-06-09 14:48:27 +03:00
|
|
|
async def _process_message(self, message):
|
2018-06-07 12:51:09 +03:00
|
|
|
"""
|
|
|
|
Adds the given message to the list of messages that must be
|
|
|
|
acknowledged and dispatches control to different ``_handle_*``
|
|
|
|
method based on its type.
|
|
|
|
"""
|
2018-06-09 12:34:01 +03:00
|
|
|
self._pending_ack.add(message.msg_id)
|
2018-06-09 14:48:27 +03:00
|
|
|
handler = self._handlers.get(message.obj.CONSTRUCTOR_ID,
|
|
|
|
self._handle_update)
|
|
|
|
await handler(message)
|
2018-06-06 22:42:48 +03:00
|
|
|
|
2018-06-09 14:48:27 +03:00
|
|
|
async def _handle_rpc_result(self, message):
|
2018-06-07 12:51:09 +03:00
|
|
|
"""
|
|
|
|
Handles the result for Remote Procedure Calls:
|
|
|
|
|
|
|
|
rpc_result#f35c6d01 req_msg_id:long result:bytes = RpcResult;
|
|
|
|
|
|
|
|
This is where the future results for sent requests are set.
|
|
|
|
"""
|
2018-06-09 14:48:27 +03:00
|
|
|
rpc_result = message.obj
|
2018-06-09 14:11:49 +03:00
|
|
|
message = self._pending_messages.pop(rpc_result.req_msg_id, None)
|
|
|
|
__log__.debug('Handling RPC result for message {}'
|
|
|
|
.format(rpc_result.req_msg_id))
|
2018-06-06 22:42:48 +03:00
|
|
|
|
2018-06-09 14:11:49 +03:00
|
|
|
if rpc_result.error:
|
2018-06-09 12:34:01 +03:00
|
|
|
# TODO Report errors if possible/enabled
|
2018-06-09 14:11:49 +03:00
|
|
|
error = rpc_message_to_error(rpc_result.error)
|
2018-06-09 16:26:13 +03:00
|
|
|
self._send_queue.put_nowait(self.state.create_message(
|
2018-06-09 12:34:01 +03:00
|
|
|
MsgsAck([message.msg_id])
|
|
|
|
))
|
2018-06-07 11:30:20 +03:00
|
|
|
|
|
|
|
if not message.future.cancelled():
|
|
|
|
message.future.set_exception(error)
|
|
|
|
return
|
2018-06-06 22:42:48 +03:00
|
|
|
elif message:
|
2018-06-09 14:11:49 +03:00
|
|
|
with BinaryReader(rpc_result.body) as reader:
|
2018-06-09 14:48:27 +03:00
|
|
|
result = message.obj.read_result(reader)
|
2018-06-06 22:42:48 +03:00
|
|
|
|
2018-06-09 12:34:01 +03:00
|
|
|
# TODO Process entities
|
2018-06-07 11:30:20 +03:00
|
|
|
if not message.future.cancelled():
|
|
|
|
message.future.set_result(result)
|
|
|
|
return
|
2018-06-07 15:32:22 +03:00
|
|
|
else:
|
|
|
|
# TODO We should not get responses to things we never sent
|
2018-06-08 22:13:14 +03:00
|
|
|
__log__.info('Received response without parent request: {}'
|
2018-06-09 14:11:49 +03:00
|
|
|
.format(rpc_result.body))
|
2018-06-06 22:42:48 +03:00
|
|
|
|
2018-06-09 14:48:27 +03:00
|
|
|
async def _handle_container(self, message):
|
2018-06-07 12:51:09 +03:00
|
|
|
"""
|
|
|
|
Processes the inner messages of a container with many of them:
|
|
|
|
|
|
|
|
msg_container#73f1f8dc messages:vector<%Message> = MessageContainer;
|
|
|
|
"""
|
2018-06-08 22:13:14 +03:00
|
|
|
__log__.debug('Handling container')
|
2018-06-09 14:48:27 +03:00
|
|
|
for inner_message in message.obj.messages:
|
|
|
|
await self._process_message(inner_message)
|
2018-06-06 22:42:48 +03:00
|
|
|
|
2018-06-09 14:48:27 +03:00
|
|
|
async def _handle_gzip_packed(self, message):
|
2018-06-07 12:51:09 +03:00
|
|
|
"""
|
|
|
|
Unpacks the data from a gzipped object and processes it:
|
|
|
|
|
|
|
|
gzip_packed#3072cfa1 packed_data:bytes = Object;
|
|
|
|
"""
|
2018-06-08 22:13:14 +03:00
|
|
|
__log__.debug('Handling gzipped data')
|
2018-06-09 14:48:27 +03:00
|
|
|
with BinaryReader(message.obj.data) as reader:
|
|
|
|
message.obj = reader.tgread_object()
|
|
|
|
await self._process_message(message)
|
2018-06-06 21:41:01 +03:00
|
|
|
|
2018-06-09 14:48:27 +03:00
|
|
|
async def _handle_update(self, message):
|
|
|
|
__log__.debug('Handling update {}'
|
|
|
|
.format(message.obj.__class__.__name__))
|
2018-06-09 22:03:48 +03:00
|
|
|
if self._update_callback:
|
|
|
|
self._update_callback(message.obj)
|
2018-06-07 15:32:22 +03:00
|
|
|
|
2018-06-09 14:48:27 +03:00
|
|
|
async def _handle_pong(self, message):
|
2018-06-07 12:51:09 +03:00
|
|
|
"""
|
|
|
|
Handles pong results, which don't come inside a ``rpc_result``
|
|
|
|
but are still sent through a request:
|
|
|
|
|
|
|
|
pong#347773c5 msg_id:long ping_id:long = Pong;
|
|
|
|
"""
|
2018-06-08 22:13:14 +03:00
|
|
|
__log__.debug('Handling pong')
|
2018-06-09 14:48:27 +03:00
|
|
|
pong = message.obj
|
2018-06-07 12:51:09 +03:00
|
|
|
message = self._pending_messages.pop(pong.msg_id, None)
|
|
|
|
if message:
|
2018-06-12 20:46:37 +03:00
|
|
|
message.future.set_result(pong)
|
2018-06-06 21:41:01 +03:00
|
|
|
|
2018-06-09 14:48:27 +03:00
|
|
|
async def _handle_bad_server_salt(self, message):
|
2018-06-07 12:51:09 +03:00
|
|
|
"""
|
|
|
|
Corrects the currently used server salt to use the right value
|
|
|
|
before enqueuing the rejected message to be re-sent:
|
|
|
|
|
|
|
|
bad_server_salt#edab447b bad_msg_id:long bad_msg_seqno:int
|
|
|
|
error_code:int new_server_salt:long = BadMsgNotification;
|
|
|
|
"""
|
2018-06-08 22:13:14 +03:00
|
|
|
__log__.debug('Handling bad salt')
|
2018-06-09 14:48:27 +03:00
|
|
|
bad_salt = message.obj
|
2018-06-09 12:34:01 +03:00
|
|
|
self.state.salt = bad_salt.new_server_salt
|
2018-06-09 16:26:13 +03:00
|
|
|
self._send_queue.put_nowait(self._pending_messages[bad_salt.bad_msg_id])
|
2018-06-06 21:41:01 +03:00
|
|
|
|
2018-06-09 14:48:27 +03:00
|
|
|
async def _handle_bad_notification(self, message):
|
2018-06-07 12:51:09 +03:00
|
|
|
"""
|
|
|
|
Adjusts the current state to be correct based on the
|
|
|
|
received bad message notification whenever possible:
|
|
|
|
|
|
|
|
bad_msg_notification#a7eff811 bad_msg_id:long bad_msg_seqno:int
|
|
|
|
error_code:int = BadMsgNotification;
|
|
|
|
"""
|
2018-06-08 22:13:14 +03:00
|
|
|
__log__.debug('Handling bad message')
|
2018-06-09 14:48:27 +03:00
|
|
|
bad_msg = message.obj
|
2018-06-07 12:51:09 +03:00
|
|
|
if bad_msg.error_code in (16, 17):
|
|
|
|
# Sent msg_id too low or too high (respectively).
|
|
|
|
# Use the current msg_id to determine the right time offset.
|
2018-06-09 12:34:01 +03:00
|
|
|
self.state.update_time_offset(correct_msg_id=message.msg_id)
|
2018-06-07 12:51:09 +03:00
|
|
|
elif bad_msg.error_code == 32:
|
|
|
|
# msg_seqno too low, so just pump it up by some "large" amount
|
|
|
|
# TODO A better fix would be to start with a new fresh session ID
|
2018-06-09 12:34:01 +03:00
|
|
|
self.state._sequence += 64
|
2018-06-07 12:51:09 +03:00
|
|
|
elif bad_msg.error_code == 33:
|
|
|
|
# msg_seqno too high never seems to happen but just in case
|
2018-06-09 12:34:01 +03:00
|
|
|
self.state._sequence -= 16
|
2018-06-07 12:51:09 +03:00
|
|
|
else:
|
|
|
|
msg = self._pending_messages.pop(bad_msg.bad_msg_id, None)
|
|
|
|
if msg:
|
|
|
|
msg.future.set_exception(BadMessageError(bad_msg.error_code))
|
|
|
|
return
|
|
|
|
|
|
|
|
# Messages are to be re-sent once we've corrected the issue
|
2018-06-09 16:26:13 +03:00
|
|
|
self._send_queue.put_nowait(self._pending_messages[bad_msg.bad_msg_id])
|
2018-06-06 21:41:01 +03:00
|
|
|
|
2018-06-09 14:48:27 +03:00
|
|
|
async def _handle_detailed_info(self, message):
|
2018-06-07 12:51:09 +03:00
|
|
|
"""
|
|
|
|
Updates the current status with the received detailed information:
|
|
|
|
|
|
|
|
msg_detailed_info#276d3ec6 msg_id:long answer_msg_id:long
|
|
|
|
bytes:int status:int = MsgDetailedInfo;
|
|
|
|
"""
|
|
|
|
# TODO https://goo.gl/VvpCC6
|
2018-06-08 22:13:14 +03:00
|
|
|
__log__.debug('Handling detailed info')
|
2018-06-09 14:48:27 +03:00
|
|
|
self._pending_ack.add(message.obj.answer_msg_id)
|
2018-06-06 21:41:01 +03:00
|
|
|
|
2018-06-09 14:48:27 +03:00
|
|
|
async def _handle_new_detailed_info(self, message):
|
2018-06-07 12:51:09 +03:00
|
|
|
"""
|
|
|
|
Updates the current status with the received detailed information:
|
|
|
|
|
|
|
|
msg_new_detailed_info#809db6df answer_msg_id:long
|
|
|
|
bytes:int status:int = MsgDetailedInfo;
|
|
|
|
"""
|
|
|
|
# TODO https://goo.gl/G7DPsR
|
2018-06-08 22:13:14 +03:00
|
|
|
__log__.debug('Handling new detailed info')
|
2018-06-09 14:48:27 +03:00
|
|
|
self._pending_ack.add(message.obj.answer_msg_id)
|
2018-06-06 21:41:01 +03:00
|
|
|
|
2018-06-09 14:48:27 +03:00
|
|
|
async def _handle_new_session_created(self, message):
|
2018-06-07 12:51:09 +03:00
|
|
|
"""
|
|
|
|
Updates the current status with the received session information:
|
|
|
|
|
|
|
|
new_session_created#9ec20908 first_msg_id:long unique_id:long
|
|
|
|
server_salt:long = NewSession;
|
|
|
|
"""
|
2018-06-06 22:42:48 +03:00
|
|
|
# TODO https://goo.gl/LMyN7A
|
2018-06-08 22:13:14 +03:00
|
|
|
__log__.debug('Handling new session created')
|
2018-06-09 14:48:27 +03:00
|
|
|
self.state.salt = message.obj.server_salt
|
2018-06-06 21:41:01 +03:00
|
|
|
|
2018-06-09 14:48:27 +03:00
|
|
|
async def _handle_ack(self, message):
|
2018-06-07 12:51:09 +03:00
|
|
|
"""
|
|
|
|
Handles a server acknowledge about our messages. Normally
|
|
|
|
these can be ignored except in the case of ``auth.logOut``:
|
|
|
|
|
|
|
|
auth.logOut#5717da40 = Bool;
|
2018-06-06 21:41:01 +03:00
|
|
|
|
2018-06-07 12:51:09 +03:00
|
|
|
Telegram doesn't seem to send its result so we need to confirm
|
|
|
|
it manually. No other request is known to have this behaviour.
|
2018-06-07 14:33:32 +03:00
|
|
|
|
|
|
|
Since the ID of sent messages consisting of a container is
|
|
|
|
never returned (unless on a bad notification), this method
|
|
|
|
also removes containers messages when any of their inner
|
|
|
|
messages are acknowledged.
|
2018-06-07 12:51:09 +03:00
|
|
|
"""
|
2018-06-08 22:13:14 +03:00
|
|
|
__log__.debug('Handling acknowledge')
|
2018-06-09 14:48:27 +03:00
|
|
|
ack = message.obj
|
2018-06-07 14:33:32 +03:00
|
|
|
if self._pending_containers:
|
|
|
|
self._clean_containers(ack.msg_ids)
|
|
|
|
|
|
|
|
for msg_id in ack.msg_ids:
|
2018-06-07 12:51:09 +03:00
|
|
|
msg = self._pending_messages.get(msg_id, None)
|
2018-06-09 14:48:27 +03:00
|
|
|
if msg and isinstance(msg.obj, LogOutRequest):
|
2018-06-07 12:51:09 +03:00
|
|
|
del self._pending_messages[msg_id]
|
|
|
|
msg.future.set_result(True)
|
2018-06-06 21:41:01 +03:00
|
|
|
|
2018-06-09 14:48:27 +03:00
|
|
|
async def _handle_future_salts(self, message):
|
2018-06-07 12:51:09 +03:00
|
|
|
"""
|
|
|
|
Handles future salt results, which don't come inside a
|
|
|
|
``rpc_result`` but are still sent through a request:
|
|
|
|
|
|
|
|
future_salts#ae500895 req_msg_id:long now:int
|
|
|
|
salts:vector<future_salt> = FutureSalts;
|
|
|
|
"""
|
|
|
|
# TODO save these salts and automatically adjust to the
|
|
|
|
# correct one whenever the salt in use expires.
|
2018-06-08 22:13:14 +03:00
|
|
|
__log__.debug('Handling future salts')
|
2018-06-09 12:34:01 +03:00
|
|
|
msg = self._pending_messages.pop(message.msg_id, None)
|
2018-06-07 12:51:09 +03:00
|
|
|
if msg:
|
2018-06-09 14:48:27 +03:00
|
|
|
msg.future.set_result(message.obj)
|
2018-06-07 14:51:19 +03:00
|
|
|
|
2018-06-14 17:23:16 +03:00
|
|
|
async def _handle_state_forgotten(self, message):
|
|
|
|
"""
|
|
|
|
Handles both :tl:`MsgsStateReq` and :tl:`MsgResendReq` by
|
|
|
|
enqueuing a :tl:`MsgsStateInfo` to be sent at a later point.
|
|
|
|
"""
|
|
|
|
self.send(MsgsStateInfo(req_msg_id=message.msg_id,
|
|
|
|
info=chr(1) * len(message.obj.msg_ids)))
|
|
|
|
|
|
|
|
async def _handle_msg_all(self, message):
|
|
|
|
"""
|
|
|
|
Handles :tl:`MsgsAllInfo` by doing nothing (yet).
|
|
|
|
"""
|
|
|
|
|
2018-06-07 14:51:19 +03:00
|
|
|
|
|
|
|
class _ContainerQueue(asyncio.Queue):
|
|
|
|
"""
|
|
|
|
An asyncio queue that's aware of `MessageContainer` instances.
|
|
|
|
|
|
|
|
The `get` method returns either a single `TLMessage` or a list
|
|
|
|
of them that should be turned into a new `MessageContainer`.
|
|
|
|
|
|
|
|
Instances of this class can be replaced with the simpler
|
|
|
|
``asyncio.Queue`` when needed for testing purposes, and
|
|
|
|
a list won't be returned in said case.
|
|
|
|
"""
|
|
|
|
async def get(self):
|
|
|
|
result = await super().get()
|
2018-06-09 14:48:27 +03:00
|
|
|
if self.empty() or isinstance(result.obj, MessageContainer):
|
2018-06-07 14:51:19 +03:00
|
|
|
return result
|
|
|
|
|
|
|
|
result = [result]
|
|
|
|
while not self.empty():
|
|
|
|
item = self.get_nowait()
|
2018-06-09 14:48:27 +03:00
|
|
|
if isinstance(item.obj, MessageContainer):
|
2018-06-09 16:26:13 +03:00
|
|
|
self.put_nowait(item)
|
2018-06-07 14:51:19 +03:00
|
|
|
break
|
|
|
|
else:
|
|
|
|
result.append(item)
|
|
|
|
|
|
|
|
return result
|