core (xmpp): new networkEnabled() and networkDisabled() methods:

those methods can be called by platform specific plugins when network is known to be (un)available. This way, connection attempts can be cancelled when no network is available, saving resources (notably battery on mobile devices), or attempts can be restarted immediately when network is known to be available again.
This commit is contained in:
Goffi 2019-04-06 19:05:57 +02:00
commit c2c7dbddfe
2 changed files with 45 additions and 1 deletions

View file

@ -418,7 +418,7 @@ class SAT(service.Service):
def connectProfile(__=None):
if self.isConnected(profile):
log.info(_("already connected !"))
log.info(_(u"already connected !"))
return True
if self.memory.isComponent(profile):

View file

@ -320,6 +320,43 @@ class SatXMPPEntity(object):
return
return cb(connector, reason)
def networkDisabled(self):
"""Indicate that network has been completely disabled
In other words, internet is not available anymore and transport must be stopped.
Retrying is disabled too, as it makes no sense to try without network, and it may
use resources (notably battery on mobiles).
"""
log.info(_(u"stopping connection because of network disabled"))
self.factory.continueTrying = 0
self._network_disabled = True
if self.xmlstream is not None:
self.xmlstream.transport.abortConnection()
def networkEnabled(self):
"""Indicate that network has been (re)enabled
This happens when e.g. user activate WIFI connection.
"""
try:
connector = self._saved_connector
network_disabled = self._network_disabled
except AttributeError:
# connection has not been stopped by networkDisabled
# we don't have to restart it
log.debug(u"no connection to restart")
return
else:
del self._network_disabled
if not network_disabled:
raise exceptions.InternalError(u"network_disabled should be True")
log.info(_(u"network is available, trying to connect"))
# we want to be sure to start fresh
self.factory.resetDelay()
# we have a saved connector, meaning the connection has been stopped previously
# we can now try to reconnect
connector.connect()
def _connected(self, xs):
send_hooks = []
receive_hooks = []
@ -359,6 +396,13 @@ class SatXMPPEntity(object):
u"somebody is trying to spy on you.\n"
u"Please contact your server administrator."))
self.factory.stopTrying()
try:
# with invalid certificate, we should not retry to connect
# so we delete saved connector to avoid reconnection if
# networkEnabled is called.
del self._saved_connector
except AttributeError:
pass
except (IndexError, TypeError):
pass
self.conn_deferred.errback(err)