Telethon/network/mtproto_plain_sender.py

52 lines
2.0 KiB
Python
Raw Normal View History

2016-08-28 14:43:00 +03:00
# This file is based on TLSharp
# https://github.com/sochix/TLSharp/blob/master/TLSharp.Core/Network/MtProtoPlainSender.cs
import time
import random
2016-09-04 13:42:11 +03:00
from utils import BinaryWriter, BinaryReader
class MtProtoPlainSender:
2016-08-28 14:43:00 +03:00
"""MTProto Mobile Protocol plain sender (https://core.telegram.org/mtproto/description#unencrypted-messages)"""
def __init__(self, transport):
self._sequence = 0
self._time_offset = 0
self._last_msg_id = 0
self._transport = transport
def send(self, data):
2016-08-28 14:43:00 +03:00
"""Sends a plain packet (auth_key_id = 0) containing the given message body (data)"""
with BinaryWriter() as writer:
writer.write_long(0)
writer.write_long(self.get_new_msg_id())
writer.write_int(len(data))
writer.write(data)
packet = writer.get_bytes()
self._transport.send(packet)
def receive(self):
2016-08-28 14:43:00 +03:00
"""Receives a plain packet, returning the body of the response"""
result = self._transport.receive()
with BinaryReader(result.body) as reader:
auth_key_id = reader.read_long()
2016-08-28 14:43:00 +03:00
msg_id = reader.read_long()
message_length = reader.read_int()
response = reader.read(message_length)
return response
def get_new_msg_id(self):
2016-08-28 14:43:00 +03:00
"""Generates a new message ID based on the current time (in ms) since epoch"""
# See https://core.telegram.org/mtproto/description#message-identifier-msg-id
ms_time = int(time.time() * 1000)
new_msg_id = (((ms_time // 1000) << 32) | # "must approximately equal unixtime*2^32"
((ms_time % 1000) << 22) | # "approximate moment in time the message was created"
random.randint(0, 524288) << 2) # "message identifiers are divisible by 4"
2016-08-28 14:43:00 +03:00
# Ensure that we always return a message ID which is higher than the previous one
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