Refactor exit-offline code

This commit is contained in:
miruka 2020-07-16 23:34:35 -04:00
parent f316a24550
commit 4784c80ed9
3 changed files with 22 additions and 17 deletions

View File

@ -198,16 +198,6 @@ class Backend:
)) ))
async def logoff_all(self) -> None:
"""Stop syncing and end all clients registered."""
await asyncio.gather(*[
client.set_presence("offline", save=False)
for client in self.clients.values()
if client._presence != "offline"
])
async def logout_client(self, user_id: str) -> None: async def logout_client(self, user_id: str) -> None:
"""Log a `MatrixClient` out and unregister it from our models.""" """Log a `MatrixClient` out and unregister it from our models."""
@ -231,6 +221,14 @@ class Backend:
await self.saved_accounts.delete(user_id) await self.saved_accounts.delete(user_id)
async def terminate_clients(self) -> None:
"""Call every `MatrixClient`'s `terminate()` method."""
log.info("Setting clients offline...")
tasks = [client.terminate() for client in self.clients.values()]
await asyncio.gather(*tasks)
async def get_client(self, user_id: str) -> MatrixClient: async def get_client(self, user_id: str) -> MatrixClient:
"""Wait until a `MatrixClient` is registered in model and return it.""" """Wait until a `MatrixClient` is registered in model and return it."""

View File

@ -305,6 +305,17 @@ class MatrixClient(nio.AsyncClient):
await self.close() await self.close()
async def terminate(self) -> None:
"""Stop tasks, Set our presence offline and close HTTP connections."""
await self._stop()
if self._presence != "offline":
await self.set_presence("offline", save=False)
await self.close()
log.info("%s termined", self.user_id)
@property @property
def syncing(self) -> bool: def syncing(self) -> bool:
"""Return whether this client is currently syncing with the server.""" """Return whether this client is currently syncing with the server."""

View File

@ -146,14 +146,10 @@ class QMLBridge:
remote_pdb.RemotePdb("127.0.0.1", 4444).set_trace() remote_pdb.RemotePdb("127.0.0.1", 4444).set_trace()
def exit_mirage(self) -> None: def exit(self) -> None:
"""Used to end some tasks before closing"""
try: try:
# Set accounts presence to offline
asyncio.run_coroutine_threadsafe( asyncio.run_coroutine_threadsafe(
self.backend.logoff_all(), self.backend.terminate_clients(), self._loop,
self._loop,
).result() ).result()
except Exception as e: except Exception as e:
print(e) print(e)
@ -179,4 +175,4 @@ except ValueError:
BRIDGE = QMLBridge() BRIDGE = QMLBridge()
pyotherside.atexit(BRIDGE.exit_mirage) pyotherside.atexit(BRIDGE.exit)