Reuse some more code from MTProtoState

This commit is contained in:
Lonami Exo 2018-06-09 11:36:59 +02:00
parent adfe861e9f
commit 1e66cea9b7

View File

@ -3,8 +3,8 @@ This module contains the class used to communicate with Telegram's servers
in plain text, when no authorization key has been created yet.
"""
import struct
import time
from .mtprotostate import MTProtoState
from ..errors import BrokenAuthKeyError
from ..extensions import BinaryReader
@ -20,9 +20,7 @@ class MTProtoPlainSender:
:param connection: the Connection to be used.
"""
self._sequence = 0
self._time_offset = 0
self._last_msg_id = 0
self._state = MTProtoState(auth_key=None)
self._connection = connection
async def send(self, request):
@ -30,7 +28,7 @@ class MTProtoPlainSender:
Sends and receives the result for the given request.
"""
body = bytes(request)
msg_id = self._get_new_msg_id()
msg_id = self._state._get_new_msg_id()
await self._connection.send(
struct.pack('<QQi', 0, msg_id, len(body)) + body
)
@ -46,16 +44,3 @@ class MTProtoPlainSender:
assert reader.read_int() # length
# No need to read "length" bytes first, just read the object
return reader.tgread_object()
def _get_new_msg_id(self):
"""Generates a new message ID based on the current time since epoch."""
# See core.telegram.org/mtproto/description#message-identifier-msg-id
now = time.time()
nanoseconds = int((now - int(now)) * 1e+9)
# "message identifiers are divisible by 4"
new_msg_id = (int(now) << 32) | (nanoseconds << 2)
if self._last_msg_id >= new_msg_id:
new_msg_id = self._last_msg_id + 4
self._last_msg_id = new_msg_id
return new_msg_id