Make more TLObject methods private

Even though raw API is somewhat necessary at times,
these methods should remain implementation details.
This commit is contained in:
Lonami Exo 2022-02-08 10:02:59 +01:00
parent 1f3ce07594
commit 84b016cf1c
9 changed files with 24 additions and 24 deletions

View File

@ -40,7 +40,7 @@ async def _call(self: 'TelegramClient', sender, request, ordered=False, flood_sl
for r in requests:
if not isinstance(r, _tl.TLRequest):
raise _NOT_A_REQUEST()
r = await r.resolve(self, utils)
r = await r._resolve(self, utils)
# Avoid making the request if it's already in a flood wait
if r.CONSTRUCTOR_ID in self._flood_waited_requests:

View File

@ -41,8 +41,8 @@ def _compute_fingerprint(key):
:param key: the Crypto.RSA key.
:return: its 8-bytes-long fingerprint.
"""
n = tlobject.TLObject.serialize_bytes(get_byte_array(key.n))
e = tlobject.TLObject.serialize_bytes(get_byte_array(key.e))
n = tlobject.TLObject._serialize_bytes(get_byte_array(key.n))
e = tlobject.TLObject._serialize_bytes(get_byte_array(key.e))
# Telegram uses the last 8 bytes as the fingerprint
return struct.unpack('<q', sha1(n + e).digest()[-8:])[0]

View File

@ -139,7 +139,7 @@ class BinaryReader:
self.set_position(pos)
raise error
return clazz.from_reader(self)
return clazz._from_reader(self)
def tgread_vector(self):
"""Reads a vector (a list) of Telegram objects."""

View File

@ -38,7 +38,7 @@ class TLObject:
SUBCLASS_OF_ID = None
@staticmethod
def serialize_bytes(data):
def _serialize_bytes(data):
"""Write bytes by using Telegram guidelines"""
if not isinstance(data, bytes):
if isinstance(data, str):
@ -73,7 +73,7 @@ class TLObject:
return b''.join(r)
@staticmethod
def serialize_datetime(dt):
def _serialize_datetime(dt):
if not dt and not isinstance(dt, timedelta):
return b'\0\0\0\0'
@ -133,7 +133,7 @@ class TLObject:
# provided) it will try to access `._bytes()`, which will fail
# with `AttributeError`. This occurs in fact because the type
# was wrong, so raise the correct error type.
raise TypeError('a TLObject was expected but found something else')
raise TypeError(f'a TLObject was expected but found {self!r}')
# Custom objects will call `(...)._bytes()` and not `bytes(...)` so that
# if the wrong type is used (e.g. `int`) we won't try allocating a huge
@ -142,7 +142,7 @@ class TLObject:
raise NotImplementedError
@classmethod
def from_reader(cls, reader):
def _from_reader(cls, reader):
raise NotImplementedError
@ -151,8 +151,8 @@ class TLRequest(TLObject):
Represents a content-related `TLObject` (a request that can be sent).
"""
@staticmethod
def read_result(reader):
def _read_result(reader):
return reader.tgread_object()
async def resolve(self, client, utils):
async def _resolve(self, client, utils):
return self

View File

@ -604,7 +604,7 @@ class MTProtoSender:
else:
try:
with BinaryReader(rpc_result.body) as reader:
result = state.request.read_result(reader)
result = state.request._read_result(reader)
except Exception as e:
# e.g. TypeNotFoundError, should be propagated to caller
if not state.future.cancelled():

View File

@ -26,7 +26,7 @@ class GzipPacked(tlobject.TLObject):
def __bytes__(self):
return struct.pack('<I', GzipPacked.CONSTRUCTOR_ID) + \
tlobject.TLObject.serialize_bytes(gzip.compress(self.data))
tlobject.TLObject._serialize_bytes(gzip.compress(self.data))
@staticmethod
def read(reader):
@ -35,7 +35,7 @@ class GzipPacked(tlobject.TLObject):
return gzip.decompress(reader.tgread_bytes())
@classmethod
def from_reader(cls, reader):
def _from_reader(cls, reader):
return GzipPacked(gzip.decompress(reader.tgread_bytes()))
def to_dict(self):

View File

@ -33,7 +33,7 @@ class MessageContainer(TLObject):
}
@classmethod
def from_reader(cls, reader):
def _from_reader(cls, reader):
# This assumes that .read_* calls are done in the order they appear
messages = []
for _ in range(reader.read_int()):

View File

@ -12,13 +12,13 @@ class RpcResult(TLObject):
self.error = error
@classmethod
def from_reader(cls, reader):
def _from_reader(cls, reader):
msg_id = reader.read_long()
inner_code = reader.read_int(signed=False)
if inner_code == _tl.RpcError.CONSTRUCTOR_ID:
return RpcResult(msg_id, None, _tl.RpcError.from_reader(reader))
return RpcResult(msg_id, None, _tl.RpcError._from_reader(reader))
if inner_code == GzipPacked.CONSTRUCTOR_ID:
return RpcResult(msg_id, GzipPacked.from_reader(reader).data, None)
return RpcResult(msg_id, GzipPacked._from_reader(reader).data, None)
reader.seek(-4)
# This reader.read() will read more than necessary, but it's okay.

View File

@ -259,7 +259,7 @@ def _write_resolve(tlobject, builder):
or ((arg.name, arg.type) in NAMED_AUTO_CASTS and tlobject.fullname not in NAMED_BLACKLIST))
for arg in tlobject.real_args
):
builder.writeln('async def resolve(self, client, utils):')
builder.writeln('async def _resolve(self, client, utils):')
builder.writeln('r = {}') # hold replacements
for arg in tlobject.real_args:
@ -352,7 +352,7 @@ def _write_to_bytes(tlobject, builder):
def _write_from_reader(tlobject, builder):
builder.writeln('@classmethod')
builder.writeln('def from_reader(cls, reader):')
builder.writeln('def _from_reader(cls, reader):')
for arg in tlobject.args:
_write_arg_read_code(builder, arg, tlobject, name='_' + arg.name)
@ -382,7 +382,7 @@ def _write_read_result(tlobject, builder):
builder.end_block()
builder.writeln('@staticmethod')
builder.writeln('def read_result(reader):')
builder.writeln('def _read_result(reader):')
builder.writeln('reader.read_int() # Vector ID')
builder.writeln('return [reader.read_{}() '
'for _ in range(reader.read_int())]', m.group(1))
@ -487,7 +487,7 @@ def _write_arg_to_bytes(builder, arg, tlobject, name=None):
builder.write("struct.pack('<d', {})", name)
elif 'string' == arg.type:
builder.write('self.serialize_bytes({})', name)
builder.write('self._serialize_bytes({})', name)
elif 'Bool' == arg.type:
# 0x997275b5 if boolean else 0xbc799737
@ -497,10 +497,10 @@ def _write_arg_to_bytes(builder, arg, tlobject, name=None):
pass # These are actually NOT written! Only used for flags
elif 'bytes' == arg.type:
builder.write('self.serialize_bytes({})', name)
builder.write('self._serialize_bytes({})', name)
elif 'date' == arg.type: # Custom format
builder.write('self.serialize_datetime({})', name)
builder.write('self._serialize_datetime({})', name)
else:
# Else it may be a custom type
@ -628,7 +628,7 @@ def _write_arg_read_code(builder, arg, tlobject, name):
# and we don't have information about such thing in the
# method we just ignore that case.
builder.writeln('from {} import {}', ns, class_name)
builder.writeln('{} = {}.from_reader(reader)',
builder.writeln('{} = {}._from_reader(reader)',
name, class_name)
# End vector and flag blocks if required (if we opened them before)