Fixed revert by hand (I hope)

This commit is contained in:
Lonami 2016-09-26 13:13:11 +02:00
parent 4d5e11f4af
commit 36b8a9026f
4 changed files with 28 additions and 65 deletions

View File

@ -192,6 +192,16 @@ class MtProtoSender:
if code == 0xa7eff811: # bad_msg_notification if code == 0xa7eff811: # bad_msg_notification
return self.handle_bad_msg_notification(msg_id, sequence, reader) return self.handle_bad_msg_notification(msg_id, sequence, reader)
if code == 0x62d6b459: # msgs_ack, it may handle the request we wanted
ack = reader.tgread_object()
for message_id in ack.msg_ids:
if message_id in self.need_confirmation:
self.need_confirmation.remove(message_id)
if request and request.msg_id in ack.msg_ids:
request.confirm_received = True
return False
# If the code is not parsed manually, then it was parsed by the code generator! # If the code is not parsed manually, then it was parsed by the code generator!
# In this case, we will simply treat the incoming TLObject as an Update, # In this case, we will simply treat the incoming TLObject as an Update,
# if we can first find a matching TLObject # if we can first find a matching TLObject

View File

@ -1,7 +1,7 @@
import platform import platform
from datetime import datetime from datetime import datetime
from hashlib import md5 from hashlib import md5
from os import path from os import path, listdir
from mimetypes import guess_extension, guess_type from mimetypes import guess_extension, guess_type
# For sending and receiving requests # For sending and receiving requests
@ -35,7 +35,7 @@ from telethon.tl.all_tlobjects import layer
class TelegramClient: class TelegramClient:
# Current TelegramClient version # Current TelegramClient version
__version__ = '0.5' __version__ = '0.6'
# region Initialization # region Initialization
@ -182,8 +182,7 @@ class TelegramClient:
def log_out(self): def log_out(self):
"""Logs out and deletes the current session. Returns True if everything went OK""" """Logs out and deletes the current session. Returns True if everything went OK"""
try: try:
# This request is a bit special. Nothing is received after self.invoke(LogOutRequest())
self.sender.send(LogOutRequest())
if not self.session.delete(): if not self.session.delete():
return False return False
@ -191,6 +190,13 @@ class TelegramClient:
except: except:
return False return False
@staticmethod
def list_sessions():
"""Lists all the sessions of the users who have ever connected
using this client and never logged out"""
return [path.splitext(path.basename(f))[0] # splitext = split ext (not spli text!)
for f in listdir('.') if f.endswith('.session')]
# endregion # endregion
# region Dialogs ("chats") requests # region Dialogs ("chats") requests

View File

@ -117,8 +117,14 @@ class BinaryReader:
# If there was still no luck, give up # If there was still no luck, give up
raise TypeNotFoundError(constructor_id) raise TypeNotFoundError(constructor_id)
# Create an empty instance of the class, and read its values # Now we need to determine the number of parameters of the class, so we can
result = clazz.empty() # instantiate it with all of them set to None, and still, no need to write
# the default =None in all the classes, thus forcing the user to provide a real value
sig = inspect.signature(clazz.__init__)
params = [None] * (len(sig.parameters) - 1) # Subtract 1 (self)
result = clazz(*params) # https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists
# Finally, read the object and return the result
result.on_response(self) result.on_response(self)
return result return result

View File

@ -62,7 +62,6 @@ class TLGenerator:
with SourceBuilder(file) as builder: with SourceBuilder(file) as builder:
# Both types and functions inherit from MTProtoRequest so they all can be sent # Both types and functions inherit from MTProtoRequest so they all can be sent
builder.writeln('from telethon.tl.mtproto_request import MTProtoRequest') builder.writeln('from telethon.tl.mtproto_request import MTProtoRequest')
builder.writeln('import json')
builder.writeln() builder.writeln()
builder.writeln() builder.writeln()
builder.writeln('class {}(MTProtoRequest):'.format(TLGenerator.get_class_name(tlobject))) builder.writeln('class {}(MTProtoRequest):'.format(TLGenerator.get_class_name(tlobject)))
@ -133,17 +132,6 @@ class TLGenerator:
TLGenerator.write_onsend_code(builder, arg, tlobject.args) TLGenerator.write_onsend_code(builder, arg, tlobject.args)
builder.end_block() builder.end_block()
# Generate the empty() function, which returns an "empty"
# instance, in which all attributes are set to None
builder.writeln('@staticmethod')
builder.writeln('def empty():')
builder.writeln('"""Returns an "empty" instance (all attributes are None)"""')
builder.writeln('return {}({})'.format(
TLGenerator.get_class_name(tlobject),
', '.join('None' for _ in range(len(args)))
))
builder.end_block()
# Write the on_response(self, reader) function # Write the on_response(self, reader) function
builder.writeln('def on_response(self, reader):') builder.writeln('def on_response(self, reader):')
# Do not read constructor's ID, since that's already been read somewhere else # Do not read constructor's ID, since that's already been read somewhere else
@ -165,47 +153,6 @@ class TLGenerator:
builder.writeln('def __str__(self):') builder.writeln('def __str__(self):')
builder.writeln("return {}".format(str(tlobject))) builder.writeln("return {}".format(str(tlobject)))
builder.end_block()
# Write JSON encoding
builder.writeln('def json_encode(self):')
builder.writeln('return json.dumps({')
builder.current_indent += 1
for arg in args:
if TLGenerator.is_tlobject(arg.type):
if arg.is_vector:
builder.writeln("'{0}': [{0}_item.json_encode() "
"for {0}_item in self.{0}],".format(arg.name))
else:
builder.writeln("'{0}': self.{0}.json_encode(),".format(arg.name))
else:
builder.writeln("'{0}': self.{0},".format(arg.name))
builder.current_indent -= 1
builder.writeln('})')
builder.end_block()
# Write JSON decoding
builder.writeln('@staticmethod')
builder.writeln('def json_decode(json_string):')
builder.writeln('# Create an empty instance which will be filled with the JSON values')
builder.writeln('instance = {}.empty()'.format(TLGenerator.get_class_name(tlobject)))
builder.writeln('dictionary = json.loads(json_string)')
builder.writeln()
for arg in args:
if TLGenerator.is_tlobject(arg.type):
if arg.is_vector:
builder.writeln("instance.{0} = [{0}_item.json_decode() "
"for {0}_item in dictionary['{0}']]".format(arg.name))
else:
builder.writeln("instance.{0} = dictionary['{0}'].json_decode() if '{0}' in dictionary "
"and dictionary['{0}'] is not None else None".format(arg.name))
else:
builder.writeln("instance.{0} = dictionary.get('{0}', None)".format(arg.name))
builder.writeln()
builder.writeln('return instance')
# builder.end_block() # There is no need to end the last block # builder.end_block() # There is no need to end the last block
# Once all the objects have been generated, we can now group them in a single file # Once all the objects have been generated, we can now group them in a single file
@ -276,12 +223,6 @@ class TLGenerator:
else: else:
return result return result
@staticmethod
def is_tlobject(type):
"""Determines whether the type is a "basic" type or another TLObject"""
return type not in ['int', 'long', 'int128', 'int256', 'double',
'string', 'Bool', 'true', 'bytes', 'date']
@staticmethod @staticmethod
def write_onsend_code(builder, arg, args, name=None): def write_onsend_code(builder, arg, args, name=None):
""" """