From 3d09219269df65b387ae9a1e9b1273a2f6d4ba86 Mon Sep 17 00:00:00 2001 From: Krille Date: Tue, 12 Mar 2024 09:00:04 +0100 Subject: [PATCH] feat: Offers client.ensureNotSoftLoggedOut() to fix using client with stopped sync loop This also makes sure that the access token is refreshed when calling client.getEventByPushNotification() which is porbably the most common case for a client with a stopped sync loop doing network requests. --- lib/src/client.dart | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/lib/src/client.dart b/lib/src/client.dart index c11d6c9c..03971d8c 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -1382,6 +1382,8 @@ class Client extends MatrixApi { accessToken = token; } + await ensureNotSoftLoggedOut(); + // Check if the notification contains an event at all: final eventId = notification.eventId; final roomId = notification.roomId; @@ -1793,6 +1795,10 @@ class Client extends MatrixApi { bool get syncPending => _currentSync != null; /// Controls the background sync (automatically looping forever if turned on). + /// If you use soft logout, you need to manually call + /// `ensureNotSoftLoggedOut()` before doing any API request after setting + /// the background sync to false, as the soft logout is handeld automatically + /// in the sync loop. set backgroundSync(bool enabled) { _backgroundSync = enabled; if (_backgroundSync) { @@ -1847,6 +1853,19 @@ class Client extends MatrixApi { } } + /// Checks if the token expires in under [expiresIn] time and calls the + /// given `onSoftLogout()` if so. You have to provide `onSoftLogout` in the + /// Client constructor. Otherwise this will do nothing. + Future ensureNotSoftLoggedOut( + [Duration expiresIn = const Duration(minutes: 1)]) async { + final tokenExpiresAt = accessTokenExpiresAt; + if (onSoftLogout != null && + tokenExpiresAt != null && + tokenExpiresAt.difference(DateTime.now()) <= expiresIn) { + await _handleSoftLogout(); + } + } + /// Pass a timeout to set how long the server waits before sending an empty response. /// (Corresponds to the timeout param on the /sync request.) Future _innerSync({Duration? timeout}) async { @@ -1866,14 +1885,7 @@ class Client extends MatrixApi { // amount of time if nothing happens. timeout ??= const Duration(seconds: 30); - // Call onSoftLogout 5 minutes before access token expires to prevent - // failing network requests. - final tokenExpiresAt = accessTokenExpiresAt; - if (onSoftLogout != null && - tokenExpiresAt != null && - tokenExpiresAt.difference(DateTime.now()) <= timeout * 2) { - await _handleSoftLogout(); - } + await ensureNotSoftLoggedOut(timeout * 2); final syncRequest = sync( filter: syncFilterId,