Fix confusing names "MtProtoRequest" and ".confirmed" (#176)

This also fixes the annoyingly confusing message:
"Odd msg_seqno expected (relevant message), but even received."
This commit is contained in:
Lonami Exo 2017-07-24 16:54:48 +02:00
parent 773376ee21
commit 160a3699ac
6 changed files with 26 additions and 32 deletions

View File

@ -143,7 +143,7 @@ class MtProtoSender:
plain_writer.write_long(self.session.id, signed=False) plain_writer.write_long(self.session.id, signed=False)
plain_writer.write_long(request.request_msg_id) plain_writer.write_long(request.request_msg_id)
plain_writer.write_int( plain_writer.write_int(
self.session.generate_sequence(request.confirmed)) self.session.generate_sequence(request.content_related))
plain_writer.write_int(len(packet)) plain_writer.write_int(len(packet))
plain_writer.write(packet) plain_writer.write(packet)

View File

@ -10,7 +10,7 @@ from .network import authenticator, MtProtoSender, TcpTransport
from .utils import get_appropriated_part_size from .utils import get_appropriated_part_size
# For sending and receiving requests # For sending and receiving requests
from .tl import MTProtoRequest, JsonSession from .tl import TLObject, JsonSession
from .tl.all_tlobjects import layer from .tl.all_tlobjects import layer
from .tl.functions import (InitConnectionRequest, InvokeWithLayerRequest) from .tl.functions import (InitConnectionRequest, InvokeWithLayerRequest)
@ -265,8 +265,8 @@ class TelegramBareClient:
If 'updates' is not None, all read update object will be put If 'updates' is not None, all read update object will be put
in such list. Otherwise, update objects will be ignored. in such list. Otherwise, update objects will be ignored.
""" """
if not isinstance(request, MTProtoRequest): if not isinstance(request, TLObject) and not request.content_related:
raise ValueError('You can only invoke MtProtoRequests') raise ValueError('You can only invoke requests, not types!')
if not self._sender: if not self._sender:
raise ValueError('You must be connected to invoke requests!') raise ValueError('You must be connected to invoke requests!')

View File

@ -14,7 +14,7 @@ from .errors import (RPCError, UnauthorizedError, InvalidParameterError,
PhoneCodeInvalidError, InvalidChecksumError) PhoneCodeInvalidError, InvalidChecksumError)
# For sending and receiving requests # For sending and receiving requests
from .tl import MTProtoRequest, Session, JsonSession from .tl import Session, JsonSession
# Required to get the password salt # Required to get the password salt
from .tl.functions.account import GetPasswordRequest from .tl.functions.account import GetPasswordRequest
@ -188,12 +188,6 @@ class TelegramClient(TelegramBareClient):
*args will be ignored. *args will be ignored.
""" """
if not issubclass(type(request), MTProtoRequest):
raise ValueError('You can only invoke MtProtoRequests')
if not self._sender:
raise ValueError('You must be connected to invoke requests!')
if self._updates_thread_receiving.is_set(): if self._updates_thread_receiving.is_set():
self._sender.cancel_receive() self._sender.cancel_receive()

View File

@ -1,2 +1,2 @@
from .mtproto_request import MTProtoRequest from .tlobject import TLObject
from .session import Session, JsonSession from .session import Session, JsonSession

View File

@ -1,7 +1,7 @@
from datetime import datetime, timedelta from datetime import datetime, timedelta
class MTProtoRequest: class TLObject:
def __init__(self): def __init__(self):
self.sent = False self.sent = False
@ -14,7 +14,7 @@ class MTProtoRequest:
# These should be overrode # These should be overrode
self.constructor_id = 0 self.constructor_id = 0
self.confirmed = False self.content_related = False # Only requests/functions/queries are
self.responded = False self.responded = False
# These should not be overrode # These should not be overrode
@ -27,7 +27,7 @@ class MTProtoRequest:
def need_resend(self): def need_resend(self):
return self.dirty or ( return self.dirty or (
self.confirmed and not self.confirm_received and self.content_related and not self.confirm_received and
datetime.now() - self.send_time > timedelta(seconds=3)) datetime.now() - self.send_time > timedelta(seconds=3))
@staticmethod @staticmethod
@ -36,32 +36,32 @@ class MTProtoRequest:
If indent is None, a single line will be returned. If indent is None, a single line will be returned.
""" """
if indent is None: if indent is None:
if isinstance(obj, MTProtoRequest): if isinstance(obj, TLObject):
return '{{{}: {}}}'.format( return '{{{}: {}}}'.format(
type(obj).__name__, type(obj).__name__,
MTProtoRequest.pretty_format(obj.to_dict()) TLObject.pretty_format(obj.to_dict())
) )
if isinstance(obj, dict): if isinstance(obj, dict):
return '{{{}}}'.format(', '.join( return '{{{}}}'.format(', '.join(
'{}: {}'.format( '{}: {}'.format(
k, MTProtoRequest.pretty_format(v) k, TLObject.pretty_format(v)
) for k, v in obj.items() ) for k, v in obj.items()
)) ))
elif isinstance(obj, str): elif isinstance(obj, str):
return '"{}"'.format(obj) return '"{}"'.format(obj)
elif hasattr(obj, '__iter__'): elif hasattr(obj, '__iter__'):
return '[{}]'.format( return '[{}]'.format(
', '.join(MTProtoRequest.pretty_format(x) for x in obj) ', '.join(TLObject.pretty_format(x) for x in obj)
) )
else: else:
return str(obj) return str(obj)
else: else:
result = [] result = []
if isinstance(obj, MTProtoRequest): if isinstance(obj, TLObject):
result.append('{') result.append('{')
result.append(type(obj).__name__) result.append(type(obj).__name__)
result.append(': ') result.append(': ')
result.append(MTProtoRequest.pretty_format( result.append(TLObject.pretty_format(
obj.to_dict(), indent obj.to_dict(), indent
)) ))
@ -72,7 +72,7 @@ class MTProtoRequest:
result.append('\t' * indent) result.append('\t' * indent)
result.append(k) result.append(k)
result.append(': ') result.append(': ')
result.append(MTProtoRequest.pretty_format(v, indent)) result.append(TLObject.pretty_format(v, indent))
result.append(',\n') result.append(',\n')
indent -= 1 indent -= 1
result.append('\t' * indent) result.append('\t' * indent)
@ -88,7 +88,7 @@ class MTProtoRequest:
indent += 1 indent += 1
for x in obj: for x in obj:
result.append('\t' * indent) result.append('\t' * indent)
result.append(MTProtoRequest.pretty_format(x, indent)) result.append(TLObject.pretty_format(x, indent))
result.append(',\n') result.append(',\n')
indent -= 1 indent -= 1
result.append('\t' * indent) result.append('\t' * indent)

View File

@ -177,10 +177,10 @@ class TLGenerator:
importing and documentation strings. importing and documentation strings.
'""" '"""
# Both types and functions inherit from # Both types and functions inherit from the TLObject class so they
# MTProtoRequest so they all can be sent # all can be serialized and sent, however, only the functions are
# TODO MTProtoRequest is not the best name for a type # "content_related".
builder.writeln('from {}.tl.mtproto_request import MTProtoRequest' builder.writeln('from {}.tl.tlobject import TLObject'
.format('.' * depth)) .format('.' * depth))
if tlobject.is_function: if tlobject.is_function:
@ -205,7 +205,7 @@ class TLGenerator:
builder.writeln() builder.writeln()
builder.writeln() builder.writeln()
builder.writeln('class {}(MTProtoRequest):'.format( builder.writeln('class {}(TLObject):'.format(
TLGenerator.get_class_name(tlobject))) TLGenerator.get_class_name(tlobject)))
# Write the original .tl definition, # Write the original .tl definition,
@ -269,7 +269,7 @@ class TLGenerator:
builder.write(' Must be a list.'.format(arg.name)) builder.write(' Must be a list.'.format(arg.name))
if arg.is_generic: if arg.is_generic:
builder.write(' Must be another MTProtoRequest.') builder.write(' Must be another TLObject request.')
builder.writeln() builder.writeln()
@ -301,7 +301,7 @@ class TLGenerator:
if tlobject.is_function: if tlobject.is_function:
builder.writeln('self.result = None') builder.writeln('self.result = None')
builder.writeln( builder.writeln(
'self.confirmed = True # Confirmed by default') 'self.content_related = True')
# Set the arguments # Set the arguments
if args: if args:
@ -423,11 +423,11 @@ class TLGenerator:
builder.end_block() builder.end_block()
builder.writeln('def __str__(self):') builder.writeln('def __str__(self):')
builder.writeln('return MTProtoRequest.pretty_format(self)') builder.writeln('return TLObject.pretty_format(self)')
builder.end_block() builder.end_block()
builder.writeln('def stringify(self):') builder.writeln('def stringify(self):')
builder.writeln('return MTProtoRequest.pretty_format(self, indent=0)') builder.writeln('return TLObject.pretty_format(self, indent=0)')
# builder.end_block() # No need to end the last block # builder.end_block() # No need to end the last block
@staticmethod @staticmethod