Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Keep playing in the app when you get signed out, with a red cloud that takes you back to sign in

Barnabas7119ccd4294e
diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb
index 87a17bf9..2c448bfc 100644
--- a/lib/l10n/app_en.arb
+++ b/lib/l10n/app_en.arb
@@ -5088,5 +5088,18 @@
"cardButtonFillSubtitle": "How the buttons on the player card are filled",
"cardButtonFillClear": "Clear",
"cardButtonFillSubtle": "Subtle",
- "cardButtonFillSolid": "Solid"
+ "cardButtonFillSolid": "Solid",
+ "signedOutTapToSignIn": "Signed out. Tap to sign in again.",
+ "authSignedOutKeepListening": "You've been signed out. Downloads still play. Tap the red cloud to sign in again.",
+ "signedOutSyncNote": "What you listen to while signed out is kept on this phone and syncs when you sign back in as {username} on {server}. Any way of signing in to that account works.",
+ "@signedOutSyncNote": {
+ "placeholders": {
+ "username": {
+ "type": "String"
+ },
+ "server": {
+ "type": "String"
+ }
+ }
+ }
}
diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart
index af68a8aa..06f6a056 100644
--- a/lib/l10n/app_localizations.dart
+++ b/lib/l10n/app_localizations.dart
@@ -15704,6 +15704,24 @@ abstract class AppLocalizations {
/// In en, this message translates to:
/// **'Solid'**
String get cardButtonFillSolid;
+
+ /// No description provided for @signedOutTapToSignIn.
+ ///
+ /// In en, this message translates to:
+ /// **'Signed out. Tap to sign in again.'**
+ String get signedOutTapToSignIn;
+
+ /// No description provided for @authSignedOutKeepListening.
+ ///
+ /// In en, this message translates to:
+ /// **'You\'ve been signed out. Downloads still play. Tap the red cloud to sign in again.'**
+ String get authSignedOutKeepListening;
+
+ /// No description provided for @signedOutSyncNote.
+ ///
+ /// In en, this message translates to:
+ /// **'What you listen to while signed out is kept on this phone and syncs when you sign back in as {username} on {server}. Any way of signing in to that account works.'**
+ String signedOutSyncNote(String username, String server);
}
class _AppLocalizationsDelegate
diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart
index f8467eb4..df074604 100644
--- a/lib/l10n/app_localizations_de.dart
+++ b/lib/l10n/app_localizations_de.dart
@@ -9235,4 +9235,16 @@ class AppLocalizationsDe extends AppLocalizations {
@override
String get cardButtonFillSolid => 'Solid';
+
+ @override
+ String get signedOutTapToSignIn => 'Signed out. Tap to sign in again.';
+
+ @override
+ String get authSignedOutKeepListening =>
+ 'You\'ve been signed out. Downloads still play. Tap the red cloud to sign in again.';
+
+ @override
+ String signedOutSyncNote(String username, String server) {
+ return 'What you listen to while signed out is kept on this phone and syncs when you sign back in as $username on $server. Any way of signing in to that account works.';
+ }
}
diff --git a/lib/l10n/app_localizations_el.dart b/lib/l10n/app_localizations_el.dart
index f0f30dc0..06f7e36f 100644
--- a/lib/l10n/app_localizations_el.dart
+++ b/lib/l10n/app_localizations_el.dart
@@ -9114,4 +9114,16 @@ class AppLocalizationsEl extends AppLocalizations {
@override
String get cardButtonFillSolid => 'Solid';
+
+ @override
+ String get signedOutTapToSignIn => 'Signed out. Tap to sign in again.';
+
+ @override
+ String get authSignedOutKeepListening =>
+ 'You\'ve been signed out. Downloads still play. Tap the red cloud to sign in again.';
+
+ @override
+ String signedOutSyncNote(String username, String server) {
+ return 'What you listen to while signed out is kept on this phone and syncs when you sign back in as $username on $server. Any way of signing in to that account works.';
+ }
}
diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart
index c1712075..9fc9cde6 100644
--- a/lib/l10n/app_localizations_en.dart
+++ b/lib/l10n/app_localizations_en.dart
@@ -9114,4 +9114,16 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get cardButtonFillSolid => 'Solid';
+
+ @override
+ String get signedOutTapToSignIn => 'Signed out. Tap to sign in again.';
+
+ @override
+ String get authSignedOutKeepListening =>
+ 'You\'ve been signed out. Downloads still play. Tap the red cloud to sign in again.';
+
+ @override
+ String signedOutSyncNote(String username, String server) {
+ return 'What you listen to while signed out is kept on this phone and syncs when you sign back in as $username on $server. Any way of signing in to that account works.';
+ }
}
diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart
index ec7d97e2..b6bcfb73 100644
--- a/lib/l10n/app_localizations_es.dart
+++ b/lib/l10n/app_localizations_es.dart
@@ -9116,4 +9116,16 @@ class AppLocalizationsEs extends AppLocalizations {
@override
String get cardButtonFillSolid => 'Solid';
+
+ @override
+ String get signedOutTapToSignIn => 'Signed out. Tap to sign in again.';
+
+ @override
+ String get authSignedOutKeepListening =>
+ 'You\'ve been signed out. Downloads still play. Tap the red cloud to sign in again.';
+
+ @override
+ String signedOutSyncNote(String username, String server) {
+ return 'What you listen to while signed out is kept on this phone and syncs when you sign back in as $username on $server. Any way of signing in to that account works.';
+ }
}
diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart
index 6c7ff9ce..03120f20 100644
--- a/lib/l10n/app_localizations_fr.dart
+++ b/lib/l10n/app_localizations_fr.dart
@@ -9167,4 +9167,16 @@ class AppLocalizationsFr extends AppLocalizations {
@override
String get cardButtonFillSolid => 'Solid';
+
+ @override
+ String get signedOutTapToSignIn => 'Signed out. Tap to sign in again.';
+
+ @override
+ String get authSignedOutKeepListening =>
+ 'You\'ve been signed out. Downloads still play. Tap the red cloud to sign in again.';
+
+ @override
+ String signedOutSyncNote(String username, String server) {
+ return 'What you listen to while signed out is kept on this phone and syncs when you sign back in as $username on $server. Any way of signing in to that account works.';
+ }
}
diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart
index 075cdbc6..337db24d 100644
--- a/lib/l10n/app_localizations_it.dart
+++ b/lib/l10n/app_localizations_it.dart
@@ -9114,4 +9114,16 @@ class AppLocalizationsIt extends AppLocalizations {
@override
String get cardButtonFillSolid => 'Solid';
+
+ @override
+ String get signedOutTapToSignIn => 'Signed out. Tap to sign in again.';
+
+ @override
+ String get authSignedOutKeepListening =>
+ 'You\'ve been signed out. Downloads still play. Tap the red cloud to sign in again.';
+
+ @override
+ String signedOutSyncNote(String username, String server) {
+ return 'What you listen to while signed out is kept on this phone and syncs when you sign back in as $username on $server. Any way of signing in to that account works.';
+ }
}
diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart
index f88b9c5c..a6c45b29 100644
--- a/lib/l10n/app_localizations_ja.dart
+++ b/lib/l10n/app_localizations_ja.dart
@@ -9114,4 +9114,16 @@ class AppLocalizationsJa extends AppLocalizations {
@override
String get cardButtonFillSolid => 'Solid';
+
+ @override
+ String get signedOutTapToSignIn => 'Signed out. Tap to sign in again.';
+
+ @override
+ String get authSignedOutKeepListening =>
+ 'You\'ve been signed out. Downloads still play. Tap the red cloud to sign in again.';
+
+ @override
+ String signedOutSyncNote(String username, String server) {
+ return 'What you listen to while signed out is kept on this phone and syncs when you sign back in as $username on $server. Any way of signing in to that account works.';
+ }
}
diff --git a/lib/l10n/app_localizations_no.dart b/lib/l10n/app_localizations_no.dart
index 1f5e86d0..fd291286 100644
--- a/lib/l10n/app_localizations_no.dart
+++ b/lib/l10n/app_localizations_no.dart
@@ -9114,4 +9114,16 @@ class AppLocalizationsNo extends AppLocalizations {
@override
String get cardButtonFillSolid => 'Solid';
+
+ @override
+ String get signedOutTapToSignIn => 'Signed out. Tap to sign in again.';
+
+ @override
+ String get authSignedOutKeepListening =>
+ 'You\'ve been signed out. Downloads still play. Tap the red cloud to sign in again.';
+
+ @override
+ String signedOutSyncNote(String username, String server) {
+ return 'What you listen to while signed out is kept on this phone and syncs when you sign back in as $username on $server. Any way of signing in to that account works.';
+ }
}
diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart
index 628805fc..a22b097f 100644
--- a/lib/l10n/app_localizations_pt.dart
+++ b/lib/l10n/app_localizations_pt.dart
@@ -9114,4 +9114,16 @@ class AppLocalizationsPt extends AppLocalizations {
@override
String get cardButtonFillSolid => 'Solid';
+
+ @override
+ String get signedOutTapToSignIn => 'Signed out. Tap to sign in again.';
+
+ @override
+ String get authSignedOutKeepListening =>
+ 'You\'ve been signed out. Downloads still play. Tap the red cloud to sign in again.';
+
+ @override
+ String signedOutSyncNote(String username, String server) {
+ return 'What you listen to while signed out is kept on this phone and syncs when you sign back in as $username on $server. Any way of signing in to that account works.';
+ }
}
diff --git a/lib/l10n/app_localizations_ro.dart b/lib/l10n/app_localizations_ro.dart
index 57e6a969..b6959e1e 100644
--- a/lib/l10n/app_localizations_ro.dart
+++ b/lib/l10n/app_localizations_ro.dart
@@ -9114,4 +9114,16 @@ class AppLocalizationsRo extends AppLocalizations {
@override
String get cardButtonFillSolid => 'Solid';
+
+ @override
+ String get signedOutTapToSignIn => 'Signed out. Tap to sign in again.';
+
+ @override
+ String get authSignedOutKeepListening =>
+ 'You\'ve been signed out. Downloads still play. Tap the red cloud to sign in again.';
+
+ @override
+ String signedOutSyncNote(String username, String server) {
+ return 'What you listen to while signed out is kept on this phone and syncs when you sign back in as $username on $server. Any way of signing in to that account works.';
+ }
}
diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart
index d812327e..0138400d 100644
--- a/lib/l10n/app_localizations_ru.dart
+++ b/lib/l10n/app_localizations_ru.dart
@@ -9119,4 +9119,16 @@ class AppLocalizationsRu extends AppLocalizations {
@override
String get cardButtonFillSolid => 'Solid';
+
+ @override
+ String get signedOutTapToSignIn => 'Signed out. Tap to sign in again.';
+
+ @override
+ String get authSignedOutKeepListening =>
+ 'You\'ve been signed out. Downloads still play. Tap the red cloud to sign in again.';
+
+ @override
+ String signedOutSyncNote(String username, String server) {
+ return 'What you listen to while signed out is kept on this phone and syncs when you sign back in as $username on $server. Any way of signing in to that account works.';
+ }
}
diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart
index 25c6b32b..3ebc098e 100644
--- a/lib/l10n/app_localizations_zh.dart
+++ b/lib/l10n/app_localizations_zh.dart
@@ -9022,4 +9022,16 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get cardButtonFillSolid => 'Solid';
+
+ @override
+ String get signedOutTapToSignIn => 'Signed out. Tap to sign in again.';
+
+ @override
+ String get authSignedOutKeepListening =>
+ 'You\'ve been signed out. Downloads still play. Tap the red cloud to sign in again.';
+
+ @override
+ String signedOutSyncNote(String username, String server) {
+ return 'What you listen to while signed out is kept on this phone and syncs when you sign back in as $username on $server. Any way of signing in to that account works.';
+ }
}
diff --git a/lib/main.dart b/lib/main.dart
index 00994ebb..ad1e6ed7 100644
--- a/lib/main.dart
+++ b/lib/main.dart
@@ -858,7 +858,7 @@ class _AuthGateState extends State<AuthGate> {
return const AuthLoadingScreen();
}
- if (auth.isAuthenticated) {
+ if (auth.isAuthenticated || auth.isSignedOut) {
return AppShell(
key: ValueKey(UserAccountService().activeScopeKey),
startOnAbsorbing: auth.startOnAbsorbingAfterAccountChange,
diff --git a/lib/providers/_lp_state.dart b/lib/providers/_lp_state.dart
index 1469f635..50720e1d 100644
--- a/lib/providers/_lp_state.dart
+++ b/lib/providers/_lp_state.dart
@@ -2,7 +2,10 @@ part of 'library_provider.dart';
mixin _StateMixin on ChangeNotifier {
AuthProvider? _auth;
- ApiService? get _api => _auth?.apiService;
+ // Signed out, the library makes no server calls and shows what is on the
+ // phone, like offline.
+ ApiService? get _api => _signedOut ? null : _auth?.apiService;
+ bool get _signedOut => _auth?.isSignedOut ?? false;
List<dynamic> _libraries = [];
bool _librariesFromCache = false;
@@ -136,7 +139,7 @@ mixin _StateMixin on ChangeNotifier {
bool get isLoadingCollections => _isLoadingCollections;
List<String> get sectionOrder => _sectionOrder;
Set<String> get hiddenSectionIds => _hiddenSectionIds;
- bool get isOffline => _manualOffline || _networkOffline;
+ bool get isOffline => _manualOffline || _networkOffline || _signedOut;
bool get isManualOffline => _manualOffline;
bool get isReconnecting => _isReconnecting;
Set<String> get manualAbsorbAdds => _manualAbsorbAdds;
diff --git a/lib/providers/auth_provider.dart b/lib/providers/auth_provider.dart
index 013fcc89..98008697 100644
--- a/lib/providers/auth_provider.dart
+++ b/lib/providers/auth_provider.dart
@@ -12,6 +12,7 @@ import '../services/audio_player_service.dart';
import '../services/equalizer_service.dart';
import '../services/session_cache.dart';
import '../services/socket_service.dart';
+import '../services/signed_out_playback.dart';
import '../services/user_account_service.dart';
import '../services/home_widget_service.dart';
import '../services/wear_auth_service.dart';
@@ -63,9 +64,13 @@ class AuthProvider extends ChangeNotifier {
bool _startOnAbsorbingAfterAccountChange = false;
String? _errorMessage;
bool _authExpiryInProgress = false;
+ // The session ended but the account is kept and the app stays usable on
+ // what is on the phone until the user signs back in.
+ bool _signedOut = false;
// Getters
bool get isAuthenticated => _accessToken != null && _serverUrl != null;
+ bool get isSignedOut => _signedOut && _accessToken == null && _serverUrl != null;
bool get isLoading => _isLoading;
bool get startOnAbsorbingAfterAccountChange =>
_startOnAbsorbingAfterAccountChange;
@@ -233,6 +238,9 @@ class AuthProvider extends ChangeNotifier {
}
ApiService? get apiService {
+ // Signed out, every server call fails straight away as unreachable,
+ // which playback and sync already treat as offline.
+ if (isSignedOut) return SignedOutPlayback.api();
final url = activeServerUrl;
if (url != null && _accessToken != null) {
return _createSessionApi(
@@ -405,17 +413,63 @@ class AuthProvider extends ChangeNotifier {
// Show a message to the user
final ctx = rootNavigatorKey.currentContext;
final l = ctx != null ? AppLocalizations.of(ctx) : null;
- final msg =
- l?.authSessionExpired ?? 'Session expired. Please log in again.';
+ final msg = l?.authSignedOutKeepListening ??
+ 'You have been signed out. Downloads still play. Tap the red cloud to sign in again.';
if (ctx != null)
- showOverlayToast(ctx, msg, icon: Icons.error_outline_rounded);
+ showOverlayToast(ctx, msg, icon: Icons.cloud_off_rounded);
unawaited(
- logout(forgetAccount: false).whenComplete(() {
+ _signOutKeepingAccount().whenComplete(() {
_authExpiryInProgress = false;
}),
);
}
+ /// The session ran out: keep the account and the app running, drop the
+ /// tokens, and carry on with what is on the phone. Playback keeps going;
+ /// listening queues like offline and goes up after the next sign-in.
+ Future<void> _signOutKeepingAccount() async {
+ final server = _serverUrl;
+ final user = _username;
+ _accessToken = null;
+ _refreshToken = null;
+ _isLegacyToken = false;
+ _userJson = null;
+ _signedOut = true;
+ AudioPlayerService().useApi(SignedOutPlayback.api());
+ SignedOutPlayback.started();
+ AndroidAutoService().clearCache();
+ CarPlayService().clearAndRefresh();
+ WearAuthService.instance.clear();
+ try {
+ if (server != null && user != null) {
+ await UserAccountService().clearTokens(server, user);
+ }
+ final prefs = await SharedPreferences.getInstance();
+ await prefs.remove('token');
+ await prefs.remove('refresh_token');
+ } catch (e) {
+ debugPrint('[Auth] Clearing the expired session failed: $e');
+ }
+ notifyListeners();
+ }
+
+ /// Open the app signed out on [account], whose session already ended, to
+ /// listen to what is on the phone (the sign-in screen's play downloads).
+ void continueSignedOut(SavedAccount account) {
+ _serverUrl = account.serverUrl;
+ _username = account.username;
+ _userId = account.userId;
+ _customHeaders = account.customHeaders;
+ _useLocalServer = false;
+ _accessToken = null;
+ _refreshToken = null;
+ _userJson = null;
+ _signedOut = true;
+ SignedOutPlayback.started();
+ debugPrint('[Auth] Continuing signed out as ${account.username}@${account.serverUrl}');
+ notifyListeners();
+ }
+
/// Try to restore a saved session from SharedPreferences.
/// If the server is unreachable, still restore credentials so offline mode works.
Future<void> tryRestoreSession() async {
@@ -1182,6 +1236,7 @@ class AuthProvider extends ChangeNotifier {
bool allDevices = false,
}) async {
if (revokeServerSession) await adoptCompanionTokens();
+ _signedOut = false;
// Stop any active playback
try {
diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dart
index a30974b3..c644861b 100644
--- a/lib/providers/library_provider.dart
+++ b/lib/providers/library_provider.dart
@@ -179,6 +179,10 @@ class LibraryProvider extends ChangeNotifier
_stopServerPingTimer();
_stopHealthCheckTimer();
_isLoading = true;
+ // Signing back in after a lapsed session hands the still-playing
+ // book its new connection.
+ final freshApi = auth.apiService;
+ if (freshApi != null) AudioPlayerService().useApi(freshApi);
notifyListeners();
}
@@ -263,6 +267,39 @@ class LibraryProvider extends ChangeNotifier
notifyListeners();
_completeAccountLoad(accountLoadGeneration);
});
+ } else if (auth.isSignedOut) {
+ // The session ended but the account stays: show what is on the phone
+ // until the user signs back in, which then loads like a fresh login.
+ final key = 'signed-out:${auth.username}@${auth.serverUrl}';
+ if (_lastAuthKey == key) return;
+ _lastAuthKey = key;
+ _lastUseLocalServer = null;
+ final generation = ++_accountLoadGeneration;
+ final completer = _accountReadyCompleter;
+ if (completer != null && !completer.isCompleted) completer.complete();
+ _accountReadyCompleter = null;
+ _connectivitySub?.cancel();
+ _connectivityDebounce?.cancel();
+ _stopServerPingTimer();
+ _stopHealthCheckTimer();
+ SocketService().disconnect();
+ _personalizedInFlight = null;
+ _networkOffline = false;
+ debugPrint('[Library] Signed out - showing what is on the phone');
+ () async {
+ await _loadManualAbsorbing();
+ await _loadRollingDownloadSeries();
+ await _loadSubscribedPodcasts();
+ await _loadYearHidden();
+ await _loadKnownEpisodeIds();
+ await _restoreCachedLibraries();
+ if (generation != _accountLoadGeneration) return;
+ _buildOfflineSections();
+ _isLoading = false;
+ notifyListeners();
+ refreshLocalProgress();
+ }();
+ notifyListeners();
} else {
_accountLoadGeneration++;
final completer = _accountReadyCompleter;
diff --git a/lib/screens/downloads_screen.dart b/lib/screens/downloads_screen.dart
index dd8844df..9075acaa 100644
--- a/lib/screens/downloads_screen.dart
+++ b/lib/screens/downloads_screen.dart
@@ -9,7 +9,6 @@ import '../services/audio_player_service.dart';
import '../services/download_service.dart';
import '../services/ebook_cache.dart';
import '../widgets/ebook_router.dart';
-import '../services/signed_out_playback.dart';
import '../services/wording.dart';
import '../widgets/absorb_page_header.dart';
import '../widgets/card_buttons.dart' show showErrorToast;
@@ -18,11 +17,7 @@ import '../widgets/overlay_toast.dart';
import '../l10n/app_localizations.dart';
class DownloadsScreen extends StatefulWidget {
- /// Opened from the sign-in screen after the session expired: plays without
- /// a server and keeps the user here instead of heading into the app.
- final bool signedOut;
-
- const DownloadsScreen({super.key, this.signedOut = false});
+ const DownloadsScreen({super.key});
@override
State<DownloadsScreen> createState() => _DownloadsScreenState();
}
@@ -224,13 +219,10 @@ class _DownloadsScreenState extends State<DownloadsScreen> {
/// any library - the one way to reach a downloaded podcast when the app
/// started offline stuck in a book library.
Future<void> _play(DownloadInfo info) async {
- final api = widget.signedOut
- ? SignedOutPlayback.api()
- : context.read<AuthProvider>().apiService;
+ final api = context.read<AuthProvider>().apiService;
if (api == null || info.localPaths.isEmpty) return;
- if (widget.signedOut) SignedOutPlayback.started();
debugPrint(
- '[Downloads] Play ${info.itemId} from the downloads list (signedOut=${widget.signedOut} library=${info.libraryId})');
+ '[Downloads] Play ${info.itemId} from the downloads list (library=${info.libraryId})');
final isEpisode = info.itemId.length > 36;
final itemId = isEpisode ? info.itemId.substring(0, 36) : info.itemId;
final episodeId = isEpisode ? info.itemId.substring(37) : null;
@@ -265,7 +257,6 @@ class _DownloadsScreenState extends State<DownloadsScreen> {
showErrorToast(context, error);
return;
}
- if (widget.signedOut) return;
context.read<LibraryProvider>().addToAbsorbing(info.itemId);
Navigator.of(context).popUntil((route) => route.isFirst);
AppShell.goToAbsorbingGlobal();
@@ -345,16 +336,6 @@ class _DownloadsScreenState extends State<DownloadsScreen> {
],
]),
),
- if (widget.signedOut)
- Padding(
- padding: const EdgeInsets.fromLTRB(20, 8, 20, 0),
- child: Text(
- l.signedOutDownloadsNote(
- SignedOutPlayback.expiredAccount()?.username ?? ''),
- style: tt.bodySmall
- ?.copyWith(color: cs.onSurfaceVariant),
- ),
- ),
const SizedBox(height: 12),
// Content
@@ -501,9 +482,6 @@ class _DownloadsScreenState extends State<DownloadsScreen> {
),
),
- if (widget.signedOut && !_selecting)
- const _SignedOutPlayerBar(),
-
// Bottom delete bar
if (_selecting && _selected.isNotEmpty)
Container(
@@ -854,98 +832,3 @@ class _ActiveDownloadCard extends StatelessWidget {
);
}
}
-
-/// A small player for signed-out listening, where the main app with its
-/// cards isn't reachable. The notification and lock screen controls work as
-/// usual on top of this.
-class _SignedOutPlayerBar extends StatelessWidget {
- const _SignedOutPlayerBar();
-
- @override
- Widget build(BuildContext context) {
- final cs = Theme.of(context).colorScheme;
- final tt = Theme.of(context).textTheme;
- final player = AudioPlayerService();
- return ListenableBuilder(
- listenable: player,
- builder: (context, _) {
- if (!player.hasBook) return const SizedBox.shrink();
- final total = player.totalDuration;
- return Container(
- padding: const EdgeInsets.fromLTRB(16, 8, 8, 8),
- decoration: BoxDecoration(
- color: cs.surfaceContainerHigh,
- border: Border(
- top: BorderSide(color: cs.outlineVariant.withValues(alpha: 0.3)),
- ),
- ),
- child: SafeArea(
- top: false,
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- Row(children: [
- Expanded(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- player.currentEpisodeTitle ?? player.currentTitle ?? '',
- style: tt.titleSmall
- ?.copyWith(fontWeight: FontWeight.w600),
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- ),
- Text(
- player.currentAuthor ?? '',
- style: tt.bodySmall
- ?.copyWith(color: cs.onSurfaceVariant),
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- ),
- ],
- ),
- ),
- IconButton(
- icon: const Icon(Icons.fast_rewind_rounded),
- onPressed: () async => player
- .skipBackward(await PlayerSettings.getBackSkip()),
- ),
- IconButton.filled(
- icon: Icon(player.isPlaying
- ? Icons.pause_rounded
- : Icons.play_arrow_rounded),
- onPressed: () => player.togglePlayPause(fromUi: true),
- ),
- IconButton(
- icon: const Icon(Icons.fast_forward_rounded),
- onPressed: () async => player
- .skipForward(await PlayerSettings.getForwardSkip()),
- ),
- ]),
- if (total > 0)
- StreamBuilder<Duration>(
- stream: player.absolutePositionStream,
- builder: (context, _) {
- final pos = player.position.inMilliseconds / 1000;
- return Padding(
- padding: const EdgeInsets.only(top: 6, right: 8),
- child: ClipRRect(
- borderRadius: BorderRadius.circular(4),
- child: LinearProgressIndicator(
- value: (pos / total).clamp(0.0, 1.0),
- minHeight: 4,
- backgroundColor: cs.surfaceContainerHighest,
- ),
- ),
- );
- },
- ),
- ],
- ),
- ),
- );
- },
- );
- }
-}
diff --git a/lib/screens/login_screen.dart b/lib/screens/login_screen.dart
index a87f3a65..58c26539 100644
--- a/lib/screens/login_screen.dart
+++ b/lib/screens/login_screen.dart
@@ -18,7 +18,6 @@ import '../widgets/absorb_wave_icon.dart';
import '../widgets/overlay_toast.dart';
import '../widgets/setup_link_login.dart';
import '../services/signed_out_playback.dart';
-import 'downloads_screen.dart';
import '../services/audio_player_service.dart';
import '../main.dart' show applyTrustAllCerts, flatNotifier;
import '../l10n/app_localizations.dart';
@@ -526,6 +525,10 @@ class _LoginScreenState extends State<LoginScreen>
),
),
+ if (context.watch<AuthProvider>().isSignedOut) ...[
+ _buildSignedOutSyncNote(cs),
+ const SizedBox(height: 12),
+ ],
// Server URL
_buildInputField(
controller: _serverController,
@@ -778,7 +781,7 @@ class _LoginScreenState extends State<LoginScreen>
),
),
- if (SignedOutPlayback.available) ...[
+ if (SignedOutPlayback.available && !context.watch<AuthProvider>().isSignedOut) ...[
const SizedBox(height: 16),
SizedBox(
width: double.infinity,
@@ -792,12 +795,12 @@ class _LoginScreenState extends State<LoginScreen>
borderRadius: BorderRadius.circular(14),
),
),
- onPressed: () => Navigator.of(context).push(
- MaterialPageRoute(
- builder: (_) =>
- const DownloadsScreen(signedOut: true),
- ),
- ),
+ onPressed: () {
+ final account = SignedOutPlayback.expiredAccount();
+ if (account != null) {
+ context.read<AuthProvider>().continueSignedOut(account);
+ }
+ },
),
),
],
@@ -1139,6 +1142,36 @@ class _LoginScreenState extends State<LoginScreen>
}
}
+ /// Signing back in after the session ended: say which account the
+ /// listening done since then belongs to, since only that one sends it up.
+ Widget _buildSignedOutSyncNote(ColorScheme cs) {
+ final l = AppLocalizations.of(context)!;
+ final tt = Theme.of(context).textTheme;
+ final auth = context.read<AuthProvider>();
+ final server = (auth.serverUrl ?? '')
+ .replaceAll(RegExp(r'^https?://'), '')
+ .replaceAll(RegExp(r'/+$'), '');
+ return Container(
+ width: double.infinity,
+ padding: const EdgeInsets.all(12),
+ decoration: BoxDecoration(
+ color: cs.primary.withValues(alpha: 0.08),
+ borderRadius: BorderRadius.circular(12),
+ border: Border.all(color: cs.primary.withValues(alpha: 0.25)),
+ ),
+ child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Icon(Icons.sync_rounded, size: 18, color: cs.primary),
+ const SizedBox(width: 10),
+ Expanded(
+ child: Text(
+ l.signedOutSyncNote(auth.username ?? '', server),
+ style: tt.bodySmall?.copyWith(color: cs.onSurface, height: 1.4),
+ ),
+ ),
+ ]),
+ );
+ }
+
Widget _buildInputField({
required TextEditingController controller,
required String label,
diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart
index 3002ca87..245a5f0f 100644
--- a/lib/screens/settings_screen.dart
+++ b/lib/screens/settings_screen.dart
@@ -52,6 +52,7 @@ import '../widgets/rmab_config_sheet.dart';
import '../widgets/server_connection_editor.dart';
import '../widgets/server_admin_status_badges.dart';
import '../l10n/app_localizations.dart';
+import '../widgets/sign_in_again.dart';
class SettingsScreen extends StatefulWidget {
const SettingsScreen({super.key});
@@ -1723,7 +1724,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),
child: GestureDetector(
- onTap: () => _showAccountSheet(context),
+ onTap: () => auth.isSignedOut ? openSignInAgain(context) : _showAccountSheet(context),
child: Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
@@ -1770,6 +1771,11 @@ class _SettingsScreenState extends State<SettingsScreen> {
auth.serverUrl?.replaceAll(RegExp(r'^https?://'), '').replaceAll(RegExp(r'/+$'), '') ?? '',
maxLines: 1, overflow: TextOverflow.ellipsis,
style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant.withValues(alpha: 0.6))),
+ if (auth.isSignedOut) ...[
+ const SizedBox(height: 2),
+ Text(l.signedOutTapToSignIn,
+ style: tt.labelSmall?.copyWith(color: cs.error, fontWeight: FontWeight.w600)),
+ ],
])),
Icon(Icons.chevron_right_rounded, size: 20, color: cs.primary.withValues(alpha: 0.5)),
]),
diff --git a/lib/services/api_service.dart b/lib/services/api_service.dart
index 4cb3e1e9..53e07d79 100644
--- a/lib/services/api_service.dart
+++ b/lib/services/api_service.dart
@@ -447,6 +447,33 @@ class ApiService {
}
}
+ /// An API key can't be refreshed, so a 401 on one may mean it was revoked.
+ /// Ask the server once whether it still knows the key before signing out,
+ /// so a stray 401 from something in between doesn't end the session.
+ static DateTime? _apiKeyCheckedAt;
+ static bool _apiKeyCheckRunning = false;
+
+ void _checkRevokedApiKey() {
+ if (_apiKeyCheckRunning) return;
+ final last = _apiKeyCheckedAt;
+ if (last != null && DateTime.now().difference(last) < const Duration(minutes: 1)) return;
+ _apiKeyCheckedAt = DateTime.now();
+ _apiKeyCheckRunning = true;
+ () async {
+ try {
+ final r = await _get(Uri.parse('$_cleanBaseUrl/api/me'), headers: _headers)
+ .timeout(const Duration(seconds: 15));
+ if (r.statusCode == 401) {
+ debugPrint('[API] The server no longer accepts this API key');
+ onAuthExpired?.call();
+ }
+ } catch (_) {
+ } finally {
+ _apiKeyCheckRunning = false;
+ }
+ }();
+ }
+
/// Attempt to refresh the access token using the refresh token. A rejected
/// refresh is kept distinct from a temporary network/server failure so only
/// an explicit 401/403 can expire the local session.
@@ -578,7 +605,11 @@ class ApiService {
/// Static state outlives a single test, so a test that trips the cooldown
/// would otherwise silently disable the pre-flight for whatever runs next.
@visibleForTesting
- static void resetPreflightCooldown() => _preflightCooldownUntil = null;
+ static void resetPreflightCooldown() {
+ _preflightCooldownUntil = null;
+ _apiKeyCheckedAt = null;
+ _apiKeyCheckRunning = false;
+ }
/// Refresh BEFORE spending a known-expired access token, rather than firing
/// the request, taking a 401, and recovering afterwards.
@@ -646,6 +677,8 @@ class ApiService {
response = await _get(url, headers: refreshedHeaders).timeout(timeout);
}
if (outcome == _RefreshOutcome.rejected) onAuthExpired?.call();
+ } else if (response.statusCode == 401) {
+ _checkRevokedApiKey();
}
return response;
}
@@ -663,6 +696,8 @@ class ApiService {
response = await _post(url, headers: refreshedHeaders, body: body).timeout(timeout);
}
if (outcome == _RefreshOutcome.rejected) onAuthExpired?.call();
+ } else if (response.statusCode == 401) {
+ _checkRevokedApiKey();
}
return response;
}
@@ -680,6 +715,8 @@ class ApiService {
response = await _patch(url, headers: refreshedHeaders, body: body).timeout(timeout);
}
if (outcome == _RefreshOutcome.rejected) onAuthExpired?.call();
+ } else if (response.statusCode == 401) {
+ _checkRevokedApiKey();
}
return response;
}
@@ -697,6 +734,8 @@ class ApiService {
response = await _delete(url, headers: refreshedHeaders).timeout(timeout);
}
if (outcome == _RefreshOutcome.rejected) onAuthExpired?.call();
+ } else if (response.statusCode == 401) {
+ _checkRevokedApiKey();
}
return response;
}
diff --git a/lib/services/signed_out_playback.dart b/lib/services/signed_out_playback.dart
index 057c1fdc..b083a1ed 100644
--- a/lib/services/signed_out_playback.dart
+++ b/lib/services/signed_out_playback.dart
@@ -4,10 +4,10 @@ import 'audio_player_service.dart';
import 'download_service.dart';
import 'user_account_service.dart';
-/// Listening to downloads after the session expired. The account stays saved
-/// with its token cleared and remains the active scope, so progress and
-/// listening sessions queue under it exactly like offline listening, and
-/// signing back into it sends them up.
+/// Using the app after the session expired. The account stays saved with its
+/// token cleared and remains the active scope, so progress and listening
+/// sessions queue under it exactly like offline listening, and signing back
+/// into it sends them up.
class SignedOutPlayback {
SignedOutPlayback._();
@@ -43,13 +43,18 @@ class SignedOutPlayback {
UserAccountService.beforeAccountChange = end;
}
- /// Stops signed-out playback before another sign-in changes the active
- /// account, so its listening is saved under the account it belongs to.
- static Future<void> end() async {
+ /// Runs before a sign-in changes the active account. Signing back into the
+ /// same account carries on playing; any other account stops playback
+ /// first, so its listening is saved under the account it belongs to.
+ static Future<void> end(SavedAccount next) async {
if (!_active) return;
_active = false;
- debugPrint('[SignedOut] Signing in, stopping signed-out playback first');
UserAccountService.beforeAccountChange = null;
+ if (expiredAccount()?.scopeKey == next.scopeKey) {
+ debugPrint('[SignedOut] Signed back in, playback carries on');
+ return;
+ }
+ debugPrint('[SignedOut] Signing in to another account, stopping signed-out playback first');
try {
final player = AudioPlayerService();
if (player.hasBook) {
diff --git a/lib/services/user_account_service.dart b/lib/services/user_account_service.dart
index a068ae6f..4b181b66 100644
--- a/lib/services/user_account_service.dart
+++ b/lib/services/user_account_service.dart
@@ -87,7 +87,7 @@ class UserAccountService {
/// Runs before a sign-in changes the active account, so anything still
/// being recorded for the old one is saved under it first.
- static Future<void> Function()? beforeAccountChange;
+ static Future<void> Function(SavedAccount next)? beforeAccountChange;
List<SavedAccount> _accounts = [];
String? _activeScopeKey;
@@ -159,7 +159,7 @@ class UserAccountService {
// this far has already written the new session, and bailing out now
// leaves the old account's scope active under it.
try {
- await beforeAccountChange?.call();
+ await beforeAccountChange?.call(account);
} catch (e) {
debugPrint('[UserAccount] beforeAccountChange failed: $e');
}
diff --git a/lib/widgets/offline_status_icon.dart b/lib/widgets/offline_status_icon.dart
index 323bd520..62dd4b30 100644
--- a/lib/widgets/offline_status_icon.dart
+++ b/lib/widgets/offline_status_icon.dart
@@ -4,6 +4,7 @@ import '../l10n/app_localizations.dart';
import '../providers/auth_provider.dart';
import '../providers/library_provider.dart';
import 'overlay_toast.dart';
+import 'sign_in_again.dart';
/// Cloud icon in page headers showing online/offline state.
///
@@ -23,6 +24,20 @@ class OfflineStatusIcon extends StatelessWidget {
final offline = lib.isOffline;
final reconnecting = lib.isReconnecting;
final onLocal = !offline && auth.useLocalServer;
+ if (auth.isSignedOut) {
+ return Semantics(
+ button: true,
+ label: l.signedOutTapToSignIn,
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: () => openSignInAgain(context),
+ child: const Padding(
+ padding: EdgeInsets.all(8),
+ child: Icon(Icons.cloud_off_rounded, size: 20, color: Colors.redAccent),
+ ),
+ ),
+ );
+ }
return GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: reconnecting
diff --git a/lib/widgets/sign_in_again.dart b/lib/widgets/sign_in_again.dart
new file mode 100644
index 00000000..9b76dfef
--- /dev/null
+++ b/lib/widgets/sign_in_again.dart
@@ -0,0 +1,12 @@
+import 'package:flutter/material.dart';
+import '../screens/login_screen.dart';
+import '../services/signed_out_playback.dart';
+
+/// Sign-in for the account whose session ended, filled in. Signing in pops
+/// back to wherever the user was.
+Future<void> openSignInAgain(BuildContext context) =>
+ Navigator.of(context, rootNavigator: true).push(
+ MaterialPageRoute(
+ builder: (_) => LoginScreen(prefillAccount: SignedOutPlayback.expiredAccount()),
+ ),
+ );