Don't start the updates thread until signed in

This commit is contained in:
Lonami Exo 2017-05-19 21:44:50 +02:00
parent 2f2ee15efd
commit 3c3946e6f1
2 changed files with 22 additions and 7 deletions

View File

@ -44,18 +44,13 @@ class MtProtoSender:
# Sleep amount on "must sleep" error for the updates thread to sleep too
self.updates_thread_sleep = None
self.updates_thread = Thread(
name='UpdatesThread', daemon=True,
target=self.updates_thread_method)
self.updates_thread = None # Set later
self.connect()
def connect(self):
"""Connects to the server"""
self.transport.connect()
# The "updates" thread must also be running to make periodic ping requests.
self.set_updates_thread(running=True)
def disconnect(self):
"""Disconnects and **stops all the running threads** if any"""
@ -67,6 +62,15 @@ class MtProtoSender:
self.disconnect()
self.connect()
def setup_ping_thread(self):
"""Sets up the Ping's thread, so that a connection can be kept
alive for a longer time without Telegram disconnecting us"""
self.updates_thread = Thread(
name='UpdatesThread', daemon=True,
target=self.updates_thread_method)
self.set_updates_thread(running=True)
def add_update_handler(self, handler):
"""Adds an update handler (a method with one argument, the received
TLObject) that is fired when there are updates available"""
@ -395,7 +399,8 @@ class MtProtoSender:
def set_updates_thread(self, running):
"""Sets the updates thread status (running or not)"""
if running == self.updates_thread_running.is_set():
if not self.updates_thread or \
running == self.updates_thread_running.is_set():
return
# Different state, update the saved value and behave as required

View File

@ -118,6 +118,10 @@ class TelegramClient:
# although many other options are available!
self.dc_options = result.dc_options
# Once we know we're authorized, we can setup the ping thread
if self.is_user_authorized():
self.sender.setup_ping_thread()
return True
except RPCError as error:
print('Could not stabilise initial connection: {}'.format(error))
@ -236,6 +240,12 @@ class TelegramClient:
self.session.user = result.user
self.session.save()
# If we want the connection to stay alive for a long time, we need
# to start the pings thread once we're already authorized and not
# before to avoid the updates thread trying to read anything while
# we haven't yet connected.
self.sender.setup_ping_thread()
return True
def sign_up(self, phone_number, code, first_name, last_name=''):