Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Add book date editing and improve account switching, playback, and Android Auto

Barnabas95ff19814013
diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb
index b5268760..60ebb9b4 100644
--- a/lib/l10n/app_de.arb
+++ b/lib/l10n/app_de.arb
@@ -1165,7 +1165,7 @@
},
"resetToDefault": "Auf Standard zurücksetzen",
"resetToDefaultStorage": "Auf Standardspeicher zurücksetzen",
- "legacyDownloadsNotice": "{count, plural, one {}=1{1 Download liegt in einem alten benutzerdefinierten Ordner, der nicht mehr geöffnet werden kann. Lade ihn erneut herunter oder schließe diese Mitteilung.} other{{count} Downloads liegen in einem alten benutzerdefinierten Ordner, der nicht mehr geöffnet werden kann. Lade die Dateien erneut herunter oder schließe diese Mitteilung.}}",
+ "legacyDownloadsNotice": "{count, plural, one {1 Download liegt in einem alten benutzerdefinierten Ordner, der nicht mehr geöffnet werden kann. Lade ihn erneut herunter oder schließe diese Mitteilung.} other{{count} Downloads liegen in einem alten benutzerdefinierten Ordner, der nicht mehr geöffnet werden kann. Lade die Dateien erneut herunter oder schließe diese Mitteilung.}}",
"@legacyDownloadsNotice": {
"placeholders": {
"count": {
@@ -1180,7 +1180,7 @@
"tipsSubtitle": "Hol das Beste aus Absorb heraus",
"adminTitle": "Server-Admin",
"adminTasksTitle": "Server-Aktivität",
- "adminTasksRunning": "{count, plural, one {}=1{1 Aufgabe läuft} other{{count} Aufgaben laufen}}",
+ "adminTasksRunning": "{count, plural, one {1 Aufgabe läuft} other{{count} Aufgaben laufen}}",
"@adminTasksRunning": {
"placeholders": {
"count": {
@@ -2104,7 +2104,7 @@
"adminLibraryFolders": "Ordner",
"adminLibrarySize": "Größe",
"adminLibraryDuration": "Dauer",
- "adminLibraryIssues": "{count, plural, one {}=1{1 fehlendes oder ungültiges Element} other{{count} fehlende oder ungültige Elemente}}",
+ "adminLibraryIssues": "{count, plural, one {1 fehlendes oder ungültiges Element} other{{count} fehlende oder ungültige Elemente}}",
"@adminLibraryIssues": {
"placeholders": {
"count": {
@@ -2158,7 +2158,7 @@
}
}
},
- "adminMissingRemovedMany": "{count, plural, one {}=1{1 Eintrag entfernt} other{{count} Einträge entfernt}}",
+ "adminMissingRemovedMany": "{count, plural, one {1 Eintrag entfernt} other{{count} Einträge entfernt}}",
"@adminMissingRemovedMany": {
"placeholders": {
"count": {
@@ -4051,7 +4051,7 @@
"adminUploadMetadataFailed": "Konnte nicht nach Metadaten suchen. Du kannst dieses Element trotzdem hochladen.",
"adminUploadDestinationPreview": "Server Ziel",
"adminUploadFiles": "Dateien",
- "adminUploadSelectedFiles": "{count, plural, one {}=1{1 Datei} other{{count} Dateien}}",
+ "adminUploadSelectedFiles": "{count, plural, one {1 Datei} other{{count} Dateien}}",
"@adminUploadSelectedFiles": {
"placeholders": {
"count": {
@@ -4164,7 +4164,7 @@
"libDeleteBody": "Dies entfernt die Bibliothek und alle Elemente dauerhaft vom Server.",
"libDeleted": "Bibliothek gelöscht",
"libDeleteFailed": "Bibliothek konnte nicht gelöscht werden",
- "libFolderCount": "{count, plural, one {}=1{1 Ordner} other{{count} Ordner}}",
+ "libFolderCount": "{count, plural, one {1 Ordner} other{{count} Ordner}}",
"@libFolderCount": {
"placeholders": {
"count": {
@@ -4292,4 +4292,4 @@
}
}
}
-}
\ No newline at end of file
+}
diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb
index e19917cb..05aa7c66 100644
--- a/lib/l10n/app_en.arb
+++ b/lib/l10n/app_en.arb
@@ -1683,6 +1683,14 @@
"admin": "Admin",
"serverAdmin": "Server Admin",
"serverAdminSubtitle": "Manage users, libraries & server settings",
+ "serverUpdateAvailable": "Server update {version} available",
+ "@serverUpdateAvailable": {
+ "placeholders": {
+ "version": {
+ "type": "String"
+ }
+ }
+ },
"justNow": "Just now",
"minutesAgo": "{count}m ago",
"@minutesAgo": {
diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart
index c74c9936..58449b80 100644
--- a/lib/l10n/app_localizations.dart
+++ b/lib/l10n/app_localizations.dart
@@ -6346,6 +6346,12 @@ abstract class AppLocalizations {
/// **'Manage users, libraries & server settings'**
String get serverAdminSubtitle;
+ /// No description provided for @serverUpdateAvailable.
+ ///
+ /// In en, this message translates to:
+ /// **'Server update {version} available'**
+ String serverUpdateAvailable(String version);
+
/// No description provided for @justNow.
///
/// In en, this message translates to:
diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart
index f93af3c2..569b7f4f 100644
--- a/lib/l10n/app_localizations_de.dart
+++ b/lib/l10n/app_localizations_de.dart
@@ -3507,6 +3507,11 @@ class AppLocalizationsDe extends AppLocalizations {
String get serverAdminSubtitle =>
'Benutzer, Bibliotheken & Server-Einstellungen verwalten';
+ @override
+ String serverUpdateAvailable(String version) {
+ return 'Server update $version available';
+ }
+
@override
String get justNow => 'Gerade eben';
diff --git a/lib/l10n/app_localizations_el.dart b/lib/l10n/app_localizations_el.dart
index e3d4d32f..718c4058 100644
--- a/lib/l10n/app_localizations_el.dart
+++ b/lib/l10n/app_localizations_el.dart
@@ -3466,6 +3466,11 @@ class AppLocalizationsEl extends AppLocalizations {
@override
String get serverAdminSubtitle => 'Manage users, libraries & server settings';
+ @override
+ String serverUpdateAvailable(String version) {
+ return 'Server update $version available';
+ }
+
@override
String get justNow => 'Just now';
diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart
index 9e93a0a4..006f437d 100644
--- a/lib/l10n/app_localizations_en.dart
+++ b/lib/l10n/app_localizations_en.dart
@@ -3466,6 +3466,11 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get serverAdminSubtitle => 'Manage users, libraries & server settings';
+ @override
+ String serverUpdateAvailable(String version) {
+ return 'Server update $version available';
+ }
+
@override
String get justNow => 'Just now';
diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart
index 8e35c18c..4f6c8b36 100644
--- a/lib/l10n/app_localizations_es.dart
+++ b/lib/l10n/app_localizations_es.dart
@@ -3468,6 +3468,11 @@ class AppLocalizationsEs extends AppLocalizations {
@override
String get serverAdminSubtitle => 'Manage users, libraries & server settings';
+ @override
+ String serverUpdateAvailable(String version) {
+ return 'Server update $version available';
+ }
+
@override
String get justNow => 'Just now';
diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart
index e178df08..522c71bf 100644
--- a/lib/l10n/app_localizations_fr.dart
+++ b/lib/l10n/app_localizations_fr.dart
@@ -3486,6 +3486,11 @@ class AppLocalizationsFr extends AppLocalizations {
@override
String get serverAdminSubtitle => 'Manage users, libraries & server settings';
+ @override
+ String serverUpdateAvailable(String version) {
+ return 'Server update $version available';
+ }
+
@override
String get justNow => 'Just now';
diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart
index 4a94b941..f8170cd1 100644
--- a/lib/l10n/app_localizations_it.dart
+++ b/lib/l10n/app_localizations_it.dart
@@ -3466,6 +3466,11 @@ class AppLocalizationsIt extends AppLocalizations {
@override
String get serverAdminSubtitle => 'Manage users, libraries & server settings';
+ @override
+ String serverUpdateAvailable(String version) {
+ return 'Server update $version available';
+ }
+
@override
String get justNow => 'Just now';
diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart
index 094ab596..7e86c536 100644
--- a/lib/l10n/app_localizations_ja.dart
+++ b/lib/l10n/app_localizations_ja.dart
@@ -3466,6 +3466,11 @@ class AppLocalizationsJa extends AppLocalizations {
@override
String get serverAdminSubtitle => 'Manage users, libraries & server settings';
+ @override
+ String serverUpdateAvailable(String version) {
+ return 'Server update $version available';
+ }
+
@override
String get justNow => 'Just now';
diff --git a/lib/l10n/app_localizations_no.dart b/lib/l10n/app_localizations_no.dart
index dac4ba5e..1f7fdc8f 100644
--- a/lib/l10n/app_localizations_no.dart
+++ b/lib/l10n/app_localizations_no.dart
@@ -3466,6 +3466,11 @@ class AppLocalizationsNo extends AppLocalizations {
@override
String get serverAdminSubtitle => 'Manage users, libraries & server settings';
+ @override
+ String serverUpdateAvailable(String version) {
+ return 'Server update $version available';
+ }
+
@override
String get justNow => 'Just now';
diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart
index f3093702..06474ad0 100644
--- a/lib/l10n/app_localizations_pt.dart
+++ b/lib/l10n/app_localizations_pt.dart
@@ -3466,6 +3466,11 @@ class AppLocalizationsPt extends AppLocalizations {
@override
String get serverAdminSubtitle => 'Manage users, libraries & server settings';
+ @override
+ String serverUpdateAvailable(String version) {
+ return 'Server update $version available';
+ }
+
@override
String get justNow => 'Just now';
diff --git a/lib/l10n/app_localizations_ro.dart b/lib/l10n/app_localizations_ro.dart
index 7071c150..4ab961d8 100644
--- a/lib/l10n/app_localizations_ro.dart
+++ b/lib/l10n/app_localizations_ro.dart
@@ -3466,6 +3466,11 @@ class AppLocalizationsRo extends AppLocalizations {
@override
String get serverAdminSubtitle => 'Manage users, libraries & server settings';
+ @override
+ String serverUpdateAvailable(String version) {
+ return 'Server update $version available';
+ }
+
@override
String get justNow => 'Just now';
diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart
index ba374bff..6e01cee5 100644
--- a/lib/l10n/app_localizations_ru.dart
+++ b/lib/l10n/app_localizations_ru.dart
@@ -3470,6 +3470,11 @@ class AppLocalizationsRu extends AppLocalizations {
@override
String get serverAdminSubtitle => 'Manage users, libraries & server settings';
+ @override
+ String serverUpdateAvailable(String version) {
+ return 'Server update $version available';
+ }
+
@override
String get justNow => 'Just now';
diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart
index 30806806..cec78051 100644
--- a/lib/l10n/app_localizations_zh.dart
+++ b/lib/l10n/app_localizations_zh.dart
@@ -3391,6 +3391,11 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get serverAdminSubtitle => '管理用户、媒体库和服务器设置';
+ @override
+ String serverUpdateAvailable(String version) {
+ return 'Server update $version available';
+ }
+
@override
String get justNow => '刚刚';
diff --git a/lib/main.dart b/lib/main.dart
index 04c0f525..d4e173c9 100644
--- a/lib/main.dart
+++ b/lib/main.dart
@@ -39,7 +39,7 @@ import 'services/setup_link_service.dart';
import 'services/wording.dart';
import 'screens/login_screen.dart';
import 'screens/app_shell.dart';
-import 'widgets/absorb_wave_icon.dart';
+import 'widgets/auth_loading_screen.dart';
import 'widgets/setup_link_login.dart';
/// Global notifier so any widget (e.g. settings) can change the theme instantly.
@@ -736,42 +736,14 @@ class _AuthGateState extends State<AuthGate> {
}
if (auth.isLoading) {
- return Scaffold(
- body: Center(
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- AbsorbWaveIcon(
- size: 48,
- color: Theme.of(context).colorScheme.primary,
- ),
- const SizedBox(height: 20),
- Text(
- 'A B S O R B',
- style: Theme.of(context).textTheme.headlineSmall?.copyWith(
- color: Theme.of(context).colorScheme.primary,
- letterSpacing: 6,
- fontWeight: FontWeight.w300,
- ),
- ),
- const SizedBox(height: 32),
- SizedBox(
- width: 24,
- height: 24,
- child: CircularProgressIndicator(
- strokeWidth: 2,
- color:
- Theme.of(context).colorScheme.primary.withValues(alpha: 0.5),
- ),
- ),
- ],
- ),
- ),
- );
+ return const AuthLoadingScreen();
}
if (auth.isAuthenticated) {
- return const AppShell();
+ return AppShell(
+ key: ValueKey(UserAccountService().activeScopeKey),
+ startOnAbsorbing: auth.startOnAbsorbingAfterAccountChange,
+ );
}
return const LoginScreen();
diff --git a/lib/providers/_lp_absorbing.dart b/lib/providers/_lp_absorbing.dart
index c3daa104..ef68b832 100644
--- a/lib/providers/_lp_absorbing.dart
+++ b/lib/providers/_lp_absorbing.dart
@@ -71,6 +71,22 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {
_absorbingItemCache.values.map((e) => jsonEncode(e)).toList());
}
+ void _pruneRemotelyFinishedBooks(Iterable<String> keys) {
+ var changed = false;
+ for (final key in keys) {
+ if (key.length > 36 ||
+ shouldIncludeBookInAbsorbing(
+ isFinished: (this as LibraryProvider).isItemFinishedByKey(key),
+ manuallyAdded: _manualAbsorbAdds.contains(key),
+ )) {
+ continue;
+ }
+ changed = _absorbingBookIds.remove(key) || changed;
+ changed = _absorbingItemCache.remove(key) != null || changed;
+ }
+ if (changed) unawaited(_saveManualAbsorbing());
+ }
+
Future<void> _updateAbsorbingCache() async {
final allowedKeys = <String>{};
final showEntities = <String, Map<String, dynamic>>{};
@@ -78,6 +94,10 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {
final continueSeriesKeys = <String>[];
final existingIds = Set<String>.from(_absorbingBookIds);
+ bool shouldIncludeBook(String key) => shouldIncludeBookInAbsorbing(
+ isFinished: (this as LibraryProvider).isItemFinishedByKey(key),
+ manuallyAdded: _manualAbsorbAdds.contains(key),
+ );
for (final section in _personalizedSections) {
final id = section['id'] as String? ?? '';
@@ -112,6 +132,7 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {
}
}
} else {
+ if (!shouldIncludeBook(itemId)) continue;
if (isDownloadedOnly &&
!_progressMap.containsKey(itemId) &&
!_manualAbsorbAdds.contains(itemId)) {
@@ -241,6 +262,10 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {
final toRemove = <String>[];
for (final key in _absorbingBookIds) {
+ if (key.length <= 36 && !shouldIncludeBook(key)) {
+ toRemove.add(key);
+ continue;
+ }
if (allowedKeys.contains(key)) continue;
if (_manualAbsorbAdds.contains(key)) continue;
final hasProgress = key.length > 36
diff --git a/lib/providers/_lp_core.dart b/lib/providers/_lp_core.dart
index a30e1b1c..34453911 100644
--- a/lib/providers/_lp_core.dart
+++ b/lib/providers/_lp_core.dart
@@ -482,6 +482,18 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
return data;
}
+ void applyLocalProgressDates(
+ String itemId, {
+ int? startedAt,
+ int? finishedAt,
+ }) {
+ final progress = Map<String, dynamic>.from(_progressMap[itemId] ?? {});
+ if (startedAt != null) progress['startedAt'] = startedAt;
+ if (finishedAt != null) progress['finishedAt'] = finishedAt;
+ _progressMap[itemId] = progress;
+ notifyListeners();
+ }
+
/// True if [itemId] currently appears in the personalized "Continue Listening"
/// shelf. Gates the "Remove from Continue Listening" book action.
bool isInContinueListeningShelf(String itemId) {
@@ -1201,6 +1213,7 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
_progressMap[key] = mp;
_localProgressOverrides.remove(key);
_resetItems.remove(key);
+ (this as _AbsorbingMixin)._pruneRemotelyFinishedBooks([key]);
notifyListeners();
_progressRefreshDebounce?.cancel();
@@ -1275,6 +1288,7 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
final progressList = data['mediaProgress'] as List<dynamic>?;
if (progressList != null) {
final player = AudioPlayerService();
+ final updatedKeys = <String>[];
final playingKey = player.currentEpisodeId != null
? '${player.currentItemId}-${player.currentEpisodeId}'
: player.currentItemId;
@@ -1288,9 +1302,11 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
if (key == playingKey && player.hasBook) continue;
_progressMap[key] = mp;
_localProgressOverrides.remove(key);
+ updatedKeys.add(key);
}
}
}
+ (this as _AbsorbingMixin)._pruneRemotelyFinishedBooks(updatedKeys);
notifyListeners();
} else {
_progressRefreshDebounce?.cancel();
@@ -1346,8 +1362,6 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
}
try {
- _lastPersonalizedFetchAt = DateTime.now();
- _lastPersonalizedFetchLibraryId = _selectedLibraryId;
await _refreshProgress();
_personalizedSections = await _api!.getPersonalizedView(
_selectedLibraryId!,
diff --git a/lib/providers/_lp_state.dart b/lib/providers/_lp_state.dart
index 5d907056..3c82dac5 100644
--- a/lib/providers/_lp_state.dart
+++ b/lib/providers/_lp_state.dart
@@ -33,8 +33,6 @@ mixin _StateMixin on ChangeNotifier {
Future<void>? _personalizedInFlight;
Future<void>? _progressShelvesInFlight;
- DateTime? _lastPersonalizedFetchAt;
- String? _lastPersonalizedFetchLibraryId;
DateTime? _lastProgressShelvesFetchAt;
String? _lastProgressShelvesLibraryId;
bool _rssHydrationInFlight = false;
diff --git a/lib/providers/auth_provider.dart b/lib/providers/auth_provider.dart
index be9d2c82..ae3dc40e 100644
--- a/lib/providers/auth_provider.dart
+++ b/lib/providers/auth_provider.dart
@@ -59,12 +59,15 @@ class AuthProvider extends ChangeNotifier {
bool _useLocalServer = false;
bool _isLoading = true;
+ bool _startOnAbsorbingAfterAccountChange = false;
String? _errorMessage;
bool _authExpiryInProgress = false;
// Getters
bool get isAuthenticated => _accessToken != null && _serverUrl != null;
bool get isLoading => _isLoading;
+ bool get startOnAbsorbingAfterAccountChange =>
+ _startOnAbsorbingAfterAccountChange;
bool get serverReachable => _serverReachable;
/// Current access token (or legacy token for old servers).
String? get token => _accessToken;
@@ -111,6 +114,21 @@ class AuthProvider extends ChangeNotifier {
return perms?['delete'] == true;
}
+ /// Replace the live app shell with the startup loading view while a saved
+ /// account is being activated and its library is prepared.
+ void beginAccountSwitch() {
+ _startOnAbsorbingAfterAccountChange = true;
+ if (_isLoading) return;
+ _isLoading = true;
+ notifyListeners();
+ }
+
+ void finishAccountSwitch() {
+ if (!_isLoading) return;
+ _isLoading = false;
+ notifyListeners();
+ }
+
/// Re-cache server settings after an admin saves them via PATCH /api/settings
/// (which echoes the updated serverSettings). Keeps cached values and the
/// shown server version fresh without forcing a re-login.
@@ -322,6 +340,7 @@ class AuthProvider extends ChangeNotifier {
final sw = Stopwatch()..start();
debugPrint('[Auth] tryRestoreSession started');
_isLoading = true;
+ _startOnAbsorbingAfterAccountChange = false;
_serverReachable = true;
notifyListeners();
@@ -648,6 +667,7 @@ class AuthProvider extends ChangeNotifier {
HomeWidgetService().refreshStats(force: true);
_pushSessionToWear();
+ _startOnAbsorbingAfterAccountChange = true;
_isLoading = false;
notifyListeners();
return true;
@@ -730,6 +750,7 @@ class AuthProvider extends ChangeNotifier {
HomeWidgetService().refreshStats(force: true);
_pushSessionToWear();
+ _startOnAbsorbingAfterAccountChange = true;
_isLoading = false;
notifyListeners();
return true;
@@ -829,6 +850,7 @@ class AuthProvider extends ChangeNotifier {
HomeWidgetService().refreshStats(force: true);
_pushSessionToWear();
+ _startOnAbsorbingAfterAccountChange = true;
_isLoading = false;
notifyListeners();
return true;
@@ -1003,6 +1025,7 @@ class AuthProvider extends ChangeNotifier {
_userJson = null;
_serverSettings = null;
_serverVersion = null;
+ _startOnAbsorbingAfterAccountChange = false;
_errorMessage = null;
_ereaderDevices = const [];
await _persistEreaderDevices();
@@ -1061,6 +1084,7 @@ class AuthProvider extends ChangeNotifier {
final selected =
UserAccountService().switchTo(account.serverUrl, account.username);
if (selected == null) return false;
+ _startOnAbsorbingAfterAccountChange = true;
// Notify widgets that read scoped settings (e.g. card button layout) so
// they reload from the new account's ScopedPrefs instead of keeping the
@@ -1098,8 +1122,18 @@ class AuthProvider extends ChangeNotifier {
final prefs = await SharedPreferences.getInstance();
await prefs.setString('server_url', _serverUrl!);
if (_accessToken != null) await prefs.setString('token', _accessToken!);
+ if (_refreshToken != null) {
+ await prefs.setString('refresh_token', _refreshToken!);
+ } else {
+ await prefs.remove('refresh_token');
+ }
if (_username != null) await prefs.setString('username', _username!);
- if (_userId != null) await prefs.setString('user_id', _userId!);
+ if (_userId != null) {
+ await prefs.setString('user_id', _userId!);
+ } else {
+ await prefs.remove('user_id');
+ }
+ await prefs.remove('default_library_id');
if (_customHeaders.isNotEmpty) {
await prefs.setString('custom_headers', jsonEncode(_customHeaders));
} else {
diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dart
index 125a4675..724052be 100644
--- a/lib/providers/library_provider.dart
+++ b/lib/providers/library_provider.dart
@@ -20,6 +20,7 @@ import '../services/session_cache.dart';
import '../services/socket_service.dart';
import '../services/book_search_index.dart';
import '../services/home_widget_service.dart';
+import '../utils/absorbing_inclusion.dart';
import '../l10n/app_localizations.dart';
import '../main.dart' show rootNavigatorKey;
import '../widgets/overlay_toast.dart';
@@ -30,6 +31,18 @@ part '_lp_absorbing.dart';
class LibraryProvider extends ChangeNotifier
with _StateMixin, _CoreMixin, _AbsorbingMixin {
+ int _accountLoadGeneration = 0;
+ Completer<void>? _accountReadyCompleter;
+
+ Future<void> waitForActiveAccountReady() =>
+ _accountReadyCompleter?.future ?? Future.value();
+
+ void _completeAccountLoad(int generation) {
+ if (generation != _accountLoadGeneration) return;
+ final completer = _accountReadyCompleter;
+ if (completer != null && !completer.isCompleted) completer.complete();
+ }
+
LibraryProvider() {
// Registered once at provider construction so the audio service can
// notify this provider on completion/playback events even when the
@@ -111,8 +124,16 @@ class LibraryProvider extends ChangeNotifier
}
_lastUseLocalServer = auth.useLocalServer;
+ final accountLoadGeneration = ++_accountLoadGeneration;
+ final previousCompleter = _accountReadyCompleter;
+ if (previousCompleter != null && !previousCompleter.isCompleted) {
+ previousCompleter.complete();
+ }
+ _accountReadyCompleter = Completer<void>();
+
if (isNewUser || isFreshLogin) {
_libraries = [];
+ _selectedLibraryId = null;
_personalizedSections = [];
_series = [];
_progressMap = {};
@@ -127,8 +148,6 @@ class LibraryProvider extends ChangeNotifier
_seriesBooksCache.clear();
_seriesTabCache.clear();
_personalizedInFlight = null;
- _lastPersonalizedFetchAt = null;
- _lastPersonalizedFetchLibraryId = null;
_rssHydrationInFlight = false;
_lastRssHydrationAt = null;
_lastRssHydrationLibraryId = null;
@@ -143,9 +162,12 @@ class LibraryProvider extends ChangeNotifier
// Refresh the local metadata cover overrides for this account so the
// grid/card covers reflect them, then repaint once loaded.
- MetadataOverrideService().loadAll().then((_) => notifyListeners());
+ MetadataOverrideService().loadAll().then((_) {
+ if (accountLoadGeneration == _accountLoadGeneration) notifyListeners();
+ });
restoreOfflineMode().then((_) async {
+ if (accountLoadGeneration != _accountLoadGeneration) return;
debugPrint(
'[Library] restoreOfflineMode done, serverReachable=${auth.serverReachable} api=${_api != null} offline=$isOffline');
_startConnectivityMonitoring();
@@ -170,6 +192,7 @@ class LibraryProvider extends ChangeNotifier
notifyListeners();
refreshLocalProgress();
if (_deviceHasConnectivity) _startServerPingTimer();
+ _completeAccountLoad(accountLoadGeneration);
return;
}
if (_api != null && !isOffline) {
@@ -201,13 +224,20 @@ class LibraryProvider extends ChangeNotifier
socket.connect(auth.serverUrl!, auth.token!, customHeaders: auth.customHeaders);
}
debugPrint('[Library] Calling loadLibraries()');
- loadLibraries();
+ await loadLibraries();
+ _completeAccountLoad(accountLoadGeneration);
}).catchError((e) {
+ if (accountLoadGeneration != _accountLoadGeneration) return;
debugPrint('[Library] restoreOfflineMode error: $e');
_isLoading = false;
notifyListeners();
+ _completeAccountLoad(accountLoadGeneration);
});
} else {
+ _accountLoadGeneration++;
+ final completer = _accountReadyCompleter;
+ if (completer != null && !completer.isCompleted) completer.complete();
+ _accountReadyCompleter = null;
_lastAuthKey = null;
_lastUseLocalServer = null;
_libraries = [];
@@ -225,8 +255,6 @@ class LibraryProvider extends ChangeNotifier
_stopHealthCheckTimer();
SocketService().disconnect();
_personalizedInFlight = null;
- _lastPersonalizedFetchAt = null;
- _lastPersonalizedFetchLibraryId = null;
_rssHydrationInFlight = false;
_lastRssHydrationAt = null;
_lastRssHydrationLibraryId = null;
diff --git a/lib/screens/app_shell.dart b/lib/screens/app_shell.dart
index d3668141..1884bcda 100644
--- a/lib/screens/app_shell.dart
+++ b/lib/screens/app_shell.dart
@@ -26,6 +26,7 @@ import 'home_screen.dart';
import 'library_screen.dart';
import 'stats_screen.dart';
import 'settings_screen.dart';
+import 'app_shell_navigation_policy.dart';
import '../widgets/library_picker_sheet.dart';
import '../widgets/welcome_sheet.dart';
import '../services/review_service.dart';
@@ -34,7 +35,9 @@ import '../widgets/update_dialog.dart';
import '../widgets/overlay_toast.dart';
class AppShell extends StatefulWidget {
- const AppShell({super.key});
+ final bool startOnAbsorbing;
+
+ const AppShell({super.key, this.startOnAbsorbing = false});
/// Navigate to the Absorbing tab using BuildContext (ancestor lookup).
static void goToAbsorbing(BuildContext context) {
@@ -313,6 +316,7 @@ class _AppShellState extends State<AppShell>
if (mounted && idx != _currentIndex && idx >= 0 && idx <= 4) {
setState(() => _currentIndex = idx);
_ensurePageBuilt(idx);
+ _restoreBookLibraryForCurrentTab(restoreLibraryPage: true);
}
});
}
@@ -321,7 +325,7 @@ class _AppShellState extends State<AppShell>
void initState() {
super.initState();
_instance = this;
- _loadStartScreen();
+ if (!widget.startOnAbsorbing) _loadStartScreen();
_ensurePageBuilt(_currentIndex);
_playerHadBook = _player.hasBook;
_wasPlaying = _player.isPlaying;
@@ -356,6 +360,7 @@ class _AppShellState extends State<AppShell>
_podcastTabLibraryId = libId;
});
}
+ _restoreBookLibraryForCurrentTab(restoreLibraryPage: true);
}
bool _podcastsShown(LibraryProvider lib) =>
@@ -363,6 +368,20 @@ class _AppShellState extends State<AppShell>
_podcastTabLibraryId.isNotEmpty &&
lib.libraries.any((l) => l['id'] == _podcastTabLibraryId);
+ void _restoreBookLibraryForCurrentTab({bool restoreLibraryPage = false}) {
+ final lib = context.read<LibraryProvider>();
+ final podcastsShown = _podcastsShown(lib);
+ if (shouldRestoreBookLibrary(
+ pageIndex: _currentIndex,
+ podcastsShown: podcastsShown,
+ selectedLibraryId: lib.selectedLibraryId,
+ podcastLibraryId: _podcastTabLibraryId,
+ restoreLibraryPage: restoreLibraryPage,
+ )) {
+ _syncTabLibrary(_currentIndex, podcastsShown);
+ }
+ }
+
// Display-destination index <-> stack page mapping when the Podcasts tab
// is shown (it sits at display slot 2 and shares stack page 1).
int _pageForDest(int dest, bool podcastsShown) {
@@ -435,14 +454,7 @@ class _AppShellState extends State<AppShell>
// Re-derive cover scheme whenever absorbing list changes so the app
// theme always reflects the current [0] book.
_deriveCoverScheme();
- // With the dedicated Podcasts tab, Home never shows the podcast library.
- // Covers the cold start restoring last_selected_library onto page 0.
- final lib = context.read<LibraryProvider>();
- if (_currentIndex == 0 &&
- _podcastsShown(lib) &&
- lib.selectedLibraryId == _podcastTabLibraryId) {
- _syncTabLibrary(0, true);
- }
+ _restoreBookLibraryForCurrentTab();
}
/// Attempt to derive cover scheme. Returns true if successful.
diff --git a/lib/screens/app_shell_navigation_policy.dart b/lib/screens/app_shell_navigation_policy.dart
new file mode 100644
index 00000000..cbd27636
--- /dev/null
+++ b/lib/screens/app_shell_navigation_policy.dart
@@ -0,0 +1,11 @@
+bool shouldRestoreBookLibrary({
+ required int pageIndex,
+ required bool podcastsShown,
+ required String? selectedLibraryId,
+ required String podcastLibraryId,
+ bool restoreLibraryPage = false,
+}) {
+ return (pageIndex == 0 || (restoreLibraryPage && pageIndex == 1)) &&
+ podcastsShown &&
+ selectedLibraryId == podcastLibraryId;
+}
diff --git a/lib/screens/book_edit_screen.dart b/lib/screens/book_edit_screen.dart
index a5158643..a6b5ca32 100644
--- a/lib/screens/book_edit_screen.dart
+++ b/lib/screens/book_edit_screen.dart
@@ -11,6 +11,7 @@ class BookEditScreen extends StatelessWidget {
final Map<String, dynamic> metadata;
final List<String> tags;
final List<dynamic> audioFiles;
+ final List<dynamic> libraryFiles;
final String relPath;
final bool isEbookOnly;
final bool isAdmin;
@@ -23,6 +24,7 @@ class BookEditScreen extends StatelessWidget {
required this.metadata,
required this.tags,
required this.audioFiles,
+ this.libraryFiles = const [],
required this.relPath,
required this.isEbookOnly,
required this.isAdmin,
@@ -53,6 +55,7 @@ class BookEditScreen extends StatelessWidget {
metadata: metadata,
tags: tags,
audioFiles: audioFiles,
+ libraryFiles: libraryFiles,
relPath: relPath,
isEbookOnly: isEbookOnly,
isAdmin: isAdmin,
diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart
index ecc73494..279704cf 100644
--- a/lib/screens/settings_screen.dart
+++ b/lib/screens/settings_screen.dart
@@ -24,6 +24,7 @@ import '../services/socket_service.dart';
import '../screens/login_screen.dart';
import '../screens/app_shell.dart';
import '../services/update_checker_service.dart';
+import '../services/audiobookshelf_update_service.dart';
import '../widgets/update_dialog.dart';
import '../screens/admin_screen.dart';
import '../screens/downloads_screen.dart';
@@ -44,6 +45,7 @@ import '../widgets/feature_hint.dart';
import '../widgets/welcome_sheet.dart';
import '../widgets/rmab_config_sheet.dart';
import '../widgets/server_connection_editor.dart';
+import '../widgets/server_admin_status_badges.dart';
import '../l10n/app_localizations.dart';
class SettingsScreen extends StatefulWidget {
@@ -170,6 +172,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
String? _rmabApiToken;
bool _loaded = false;
int _adminIssueCount = 0;
+ AudiobookshelfServerUpdate? _serverUpdate;
+ String? _serverUpdateCheckedFor;
+ bool _serverUpdateCheckRunning = false;
String _downloadLocationLabel = 'App Internal Storage (Default)';
bool _canPickDownloadLocation = false;
int _totalDownloadSizeBytes = 0;
@@ -247,6 +252,15 @@ class _SettingsScreenState extends State<SettingsScreen> {
setState(() => _adminIssueCount = counts.fold<int>(0, (a, b) => a + b));
}
+ Future<void> _loadServerUpdate(String currentVersion) async {
+ _serverUpdateCheckedFor = currentVersion;
+ _serverUpdateCheckRunning = true;
+ final update = await AudiobookshelfUpdateService.check(currentVersion: currentVersion);
+ _serverUpdateCheckRunning = false;
+ if (!mounted || _serverUpdateCheckedFor != currentVersion) return;
+ setState(() => _serverUpdate = update);
+ }
+
@override
void dispose() {
SocketService().removeItemsChangedListener(_onServerItemsChanged);
@@ -1168,6 +1182,13 @@ class _SettingsScreenState extends State<SettingsScreen> {
if (mounted) _loadAdminIssueCount();
});
}
+ final serverVersion = auth.serverVersion?.trim();
+ if (auth.isAdmin && serverVersion != null && serverVersion.isNotEmpty &&
+ !_serverUpdateCheckRunning && _serverUpdateCheckedFor != serverVersion) {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) _loadServerUpdate(serverVersion);
+ });
+ }
if (lib.selectedLibraryId != null && lib.selectedLibraryId != _curLibId) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) _loadCurrentLibraryOverrides(lib.selectedLibraryId!);
@@ -1326,19 +1347,13 @@ class _SettingsScreenState extends State<SettingsScreen> {
style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
],
)),
- if (_adminIssueCount > 0) ...[
- Container(
- padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
- decoration: BoxDecoration(
- color: Colors.orange.withValues(alpha: 0.15),
- borderRadius: BorderRadius.circular(10),
- ),
- child: Row(mainAxisSize: MainAxisSize.min, children: [
- Icon(Icons.report_problem_rounded, size: 12, color: Colors.orange.shade700),
- const SizedBox(width: 4),
- Text('$_adminIssueCount', style: tt.labelSmall?.copyWith(
- color: Colors.orange.shade700, fontWeight: FontWeight.w700)),
- ]),
+ if (_adminIssueCount > 0 || _serverUpdate != null) ...[
+ ServerAdminStatusBadges(
+ issueCount: _adminIssueCount,
+ updateVersion: _serverUpdate?.latestVersion,
+ updateTooltip: _serverUpdate == null
+ ? ''
+ : l.serverUpdateAvailable(_serverUpdate!.latestVersion),
),
const SizedBox(width: 10),
],
@@ -4587,24 +4602,22 @@ class _SettingsScreenState extends State<SettingsScreen> {
return;
}
- // Stop playback and sync before switching
- await _stopAndSyncPlayback();
- if (!context.mounted) return;
-
final auth = context.read<AuthProvider>();
final lib = context.read<LibraryProvider>();
-
- final switched = await auth.switchToAccount(account);
- if (!switched) return;
-
- // Re-init the library provider with the new user
- if (context.mounted) {
+ auth.beginAccountSwitch();
+ try {
+ // The startup view is visible now, so none of the previous account's
+ // Settings or Stats state remains on screen during the transition.
+ await _stopAndSyncPlayback();
+ final switched = await auth.switchToAccount(account);
+ if (!switched) return;
+
+ // Re-init the library provider with the new user and keep the startup
+ // view up until its first account-specific data refresh completes.
lib.updateAuth(auth);
- await lib.refresh();
- // Reload settings for the new account
- _loadSettings();
- // Jump to the absorbing screen
- AppShell.goToAbsorbingGlobal();
+ await lib.waitForActiveAccountReady();
+ } finally {
+ auth.finishAccountSwitch();
}
}
}
diff --git a/lib/screens/stats_screen.dart b/lib/screens/stats_screen.dart
index d33c897c..2481f704 100644
--- a/lib/screens/stats_screen.dart
+++ b/lib/screens/stats_screen.dart
@@ -7,6 +7,8 @@ import 'package:shared_preferences/shared_preferences.dart';
import '../providers/auth_provider.dart';
import '../providers/library_provider.dart';
import '../services/audio_player_service.dart';
+import '../services/scoped_prefs.dart';
+import '../services/user_account_service.dart';
import '../widgets/absorb_page_header.dart';
import '../widgets/finished_books_this_year_sheet.dart';
import '../widgets/stats_charts.dart';
@@ -283,14 +285,20 @@ class _StatsScreenState extends State<StatsScreen>
static const _kSessions = 'cached_sessions';
Future<void> _loadStats() async {
+ final accountScope = UserAccountService().activeScopeKey;
+ bool isActiveAccount() =>
+ UserAccountService().activeScopeKey == accountScope;
final api = context.read<AuthProvider>().apiService;
final lib = context.read<LibraryProvider>();
final prefs = await SharedPreferences.getInstance();
+ final statsCacheKey = ScopedPrefs.keyForScope(accountScope, _kStats);
+ final sessionsCacheKey = ScopedPrefs.keyForScope(accountScope, _kSessions);
// The saved-by-speed counter banks while listening, so re-read it on
// every load (incl. pull-to-refresh), not just at screen creation.
final timeSaved = await PlayerSettings.getStatsTimeSaved();
final timeSavedSince = await PlayerSettings.getStatsTimeSavedSince();
+ if (!isActiveAccount()) return;
if (mounted && (timeSaved != _timeSavedSeconds || timeSavedSince != _timeSavedSince)) {
setState(() {
_timeSavedSeconds = timeSaved;
@@ -300,8 +308,8 @@ class _StatsScreenState extends State<StatsScreen>
// Load cached data first so the page renders immediately even offline.
if (_isLoading) {
- final cachedStats = prefs.getString(_kStats);
- final cachedSessions = prefs.getString(_kSessions);
+ final cachedStats = prefs.getString(statsCacheKey);
+ final cachedSessions = prefs.getString(sessionsCacheKey);
if (cachedStats != null) {
final stats = jsonDecode(cachedStats) as Map<String, dynamic>;
final sessions = cachedSessions != null
@@ -330,13 +338,14 @@ class _StatsScreenState extends State<StatsScreen>
// Phase 1: load core stats from network and cache them.
final stats = await api.getListeningStats();
+ if (!mounted || !isActiveAccount()) return;
final finishedBooks = lib.finishedBooksCount;
final finishedEpisodes = lib.finishedEpisodesCount;
final finishedBooksYear = lib.finishedBooksThisYearCount;
final finishedEpisodesYear = lib.finishedEpisodesThisYearCount;
if (stats != null) {
- prefs.setString(_kStats, jsonEncode(stats));
+ prefs.setString(statsCacheKey, jsonEncode(stats));
}
if (mounted) {
@@ -358,9 +367,10 @@ class _StatsScreenState extends State<StatsScreen>
// Phase 2: load heavier sessions list in background and cache.
final sessionsData =
await api.getListeningSessions(page: 0, itemsPerPage: _sessionsPerPage);
+ if (!mounted || !isActiveAccount()) return;
final sessions = sessionsData?['sessions'] as List<dynamic>? ?? [];
if (sessions.isNotEmpty) {
- prefs.setString(_kSessions, jsonEncode(sessions));
+ prefs.setString(sessionsCacheKey, jsonEncode(sessions));
}
if (mounted) {
setState(() {
diff --git a/lib/services/android_auto_service.dart b/lib/services/android_auto_service.dart
index c2224dc9..7b2e5ac9 100644
--- a/lib/services/android_auto_service.dart
+++ b/lib/services/android_auto_service.dart
@@ -7,6 +7,7 @@ import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'api_service.dart';
import 'audio_player_service.dart';
+import 'book_search_index.dart';
import 'download_service.dart';
import 'progress_sync_service.dart';
import 'scoped_prefs.dart';
@@ -1646,9 +1647,29 @@ class AndroidAutoService {
final api = await getApi();
final libId = await getDefaultLibraryId();
if (api == null || libId == null) return [];
+ final trimmedQuery = query.trim();
+ if (trimmedQuery.isEmpty) return [];
try {
- final result = await api.searchLibrary(libId, query, limit: 20);
+ final library = _libraries.cast<AutoLibraryEntry?>().firstWhere(
+ (entry) => entry?.id == libId,
+ orElse: () => null,
+ );
+ if (library?.isPodcast != true) {
+ final index = BookSearchIndex();
+ await index.ensureIndex(api, libId);
+ if (index.isReady(libId)) {
+ final hits = index
+ .search(libId, trimmedQuery, limit: 20)
+ .where((hit) => hit.item['mediaType'] != 'podcast')
+ .map((hit) => _libraryItemToEntry(hit.item, api)?.toMediaItem())
+ .whereType<MediaItem>()
+ .toList();
+ if (library?.isBook == true || hits.isNotEmpty) return hits;
+ }
+ }
+
+ final result = await api.searchLibrary(libId, trimmedQuery, limit: 20);
if (result == null) return [];
final items = <MediaItem>[];
diff --git a/lib/services/api_service.dart b/lib/services/api_service.dart
index 90d0878c..f34d1c49 100644
--- a/lib/services/api_service.dart
+++ b/lib/services/api_service.dart
@@ -1531,6 +1531,108 @@ class ApiService {
return null;
}
+ Map<String, dynamic>? _progressRecreationBody(
+ Map<String, dynamic> progress, {
+ required int startedAt,
+ }) {
+ final originalStartedAt = progress['startedAt'];
+ if (progress['id'] is! String || originalStartedAt is! num) return null;
+
+ final body = <String, dynamic>{
+ 'createdAt': startedAt,
+ 'isFinished': progress['isFinished'] == true,
+ };
+ for (final key in [
+ 'currentTime',
+ 'duration',
+ 'progress',
+ 'hideFromContinueListening',
+ 'ebookLocation',
+ 'ebookProgress',
+ 'finishedAt',
+ ]) {
+ if (progress[key] != null) body[key] = progress[key];
+ }
+ return body;
+ }
+
+ /// Change a book's start date while preserving its listening progress.
+ /// Audiobookshelf stores the displayed start date as the progress record's
+ /// creation time, so changing it requires recreating that record.
+ Future<bool> updateProgressStartDate(String itemId, int startedAt) async {
+ try {
+ final progress = await getItemProgress(itemId);
+ if (progress == null) return false;
+ final progressId = progress['id'];
+ final originalStartedAt = progress['startedAt'];
+ if (progressId is! String || originalStartedAt is! num) return false;
+
+ final updatedBody = _progressRecreationBody(
+ progress,
+ startedAt: startedAt,
+ );
+ final originalBody = _progressRecreationBody(
+ progress,
+ startedAt: originalStartedAt.toInt(),
+ );
+ if (updatedBody == null || originalBody == null) return false;
+
+ final deleteResponse = await _authDelete(
+ Uri.parse('$_cleanBaseUrl/api/me/progress/$progressId'),
+ timeout: const Duration(seconds: 10),
+ );
+ if (deleteResponse.statusCode < 200 || deleteResponse.statusCode >= 300) {
+ return false;
+ }
+
+ await Future<void>.delayed(const Duration(milliseconds: 500));
+ int? updateStatus;
+ try {
+ final updateResponse = await _authPatch(
+ Uri.parse('$_cleanBaseUrl/api/me/progress/$itemId'),
+ body: jsonEncode(updatedBody),
+ timeout: const Duration(seconds: 10),
+ );
+ updateStatus = updateResponse.statusCode;
+ if (updateStatus >= 200 && updateStatus < 300) return true;
+ } catch (e) {
+ debugPrint('[API] updateProgressStartDate recreate error: $e');
+ }
+
+ try {
+ final restoreResponse = await _authPatch(
+ Uri.parse('$_cleanBaseUrl/api/me/progress/$itemId'),
+ body: jsonEncode(originalBody),
+ timeout: const Duration(seconds: 10),
+ );
+ debugPrint(
+ '[API] updateProgressStartDate failed ($updateStatus); '
+ 'restore=${restoreResponse.statusCode}',
+ );
+ } catch (e) {
+ debugPrint('[API] updateProgressStartDate restore error: $e');
+ }
+ } catch (e) {
+ debugPrint('[API] updateProgressStartDate error: $e');
+ }
+ return false;
+ }
+
+ /// Change the finish date on an existing progress record.
+ Future<bool> updateProgressFinishedDate(String itemId, int finishedAt) async {
+ try {
+ final response = await _authPatch(
+ Uri.parse('$_cleanBaseUrl/api/me/progress/$itemId'),
+ body: jsonEncode({'finishedAt': finishedAt, 'isFinished': true}),
+ timeout: const Duration(seconds: 10),
+ );
+ return response.statusCode >= 200 && response.statusCode < 300;
+ } catch (e) {
+ debugPrint('[API] updateProgressFinishedDate error: $e');
+ return false;
+ }
+ }
+
/// Update media progress directly (for offline sync).
/// PATCH /api/me/progress/:id
Future<void> updateProgress(
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index 77a699b1..41622e0c 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -16,6 +16,7 @@ import 'local_session_service.dart';
import 'sync_logic.dart';
import 'sleep_timer_service.dart';
import 'equalizer_service.dart';
+import 'external_audio_output_types.dart';
import 'android_auto_service.dart';
import 'chromecast_service.dart';
import 'chapter_lookup.dart';
@@ -416,6 +417,7 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
@override
Future<void> pause() async {
+ _service?._markPauseRequested();
debugPrint('[Handler] pause() called - routing to service');
await _logAbsorbDiag('pause');
final pauseEntryBt = await AudioPlayerService._isBluetoothAudioConnected();
@@ -2191,16 +2193,6 @@ class AudioPlayerService extends ChangeNotifier {
// speaker). With two outputs connected at once (e.g. car stereo + earbuds),
// dropping one just reroutes to the other and never fires it, so the book
// plays on silently. Watching device removal covers that gap.
- static const Set<AudioDeviceType> _externalOutputTypes = {
- AudioDeviceType.bluetoothA2dp,
- AudioDeviceType.bluetoothSco,
- AudioDeviceType.bluetoothLe,
- AudioDeviceType.wiredHeadset,
- AudioDeviceType.wiredHeadphones,
- AudioDeviceType.usbAudio,
- AudioDeviceType.hearingAid,
- AudioDeviceType.carAudio,
- };
// Set true when BT/headphones disconnect so the interruption handler
// won't auto-resume playback onto the phone speaker.
static bool _noisyPause = false;
@@ -2362,7 +2354,7 @@ class AudioPlayerService extends ChangeNotifier {
final service = _instance;
if (!service.isPlaying) return;
final lost = event.devicesRemoved
- .where((d) => d.isOutput && _externalOutputTypes.contains(d.type))
+ .where((d) => d.isOutput && externalAudioOutputTypes.contains(d.type))
.toSet();
if (lost.isEmpty) return;
// Settle re-check: some devices briefly drop and re-add a route when
@@ -2515,6 +2507,7 @@ class AudioPlayerService extends ChangeNotifier {
String? episodeTitle,
String? libraryId,
}) async {
+ _pauseRequested = false;
if (_handler == null) {
debugPrint('[Player] Handler not yet initialized, waiting…');
await _initCompleter.future;
@@ -4657,6 +4650,12 @@ class AudioPlayerService extends ChangeNotifier {
double _lastAutoRewindAmount = 0;
bool _seekedWhilePaused = false;
bool _wasPlayingBeforeInterrupt = false;
+ bool _pauseRequested = false;
+ bool get isPauseRequested => _pauseRequested;
+
+ void _markPauseRequested() {
+ _pauseRequested = true;
+ }
// Storm guard for the idle-on-resume re-init path. A book the player can't
// start (e.g. a thousands-of-files book the engine never leaves `idle` on)
@@ -4687,6 +4686,7 @@ class AudioPlayerService extends ChangeNotifier {
}
Future<void> play({String? logDetail}) async {
+ _pauseRequested = false;
debugPrint('[Service] play() called — lastPause=${_lastPauseTime != null}');
// Cold-start play guard. If the OS killed absorb during a long pause
@@ -4915,6 +4915,7 @@ class AudioPlayerService extends ChangeNotifier {
}
Future<void> pause() async {
+ _markPauseRequested();
debugPrint('[Service] pause() called');
_playVerifyTimer?.cancel();
_wasPlayingBeforeInterrupt = false;
diff --git a/lib/services/audiobookshelf_update_service.dart b/lib/services/audiobookshelf_update_service.dart
new file mode 100644
index 00000000..4d01f4e6
--- /dev/null
+++ b/lib/services/audiobookshelf_update_service.dart
@@ -0,0 +1,120 @@
+import 'dart:convert';
+
+import 'package:flutter/foundation.dart';
+import 'package:http/http.dart' as http;
+
+class AudiobookshelfServerUpdate {
+ final String currentVersion;
+ final String latestVersion;
+ final String releaseUrl;
+
+ const AudiobookshelfServerUpdate({
+ required this.currentVersion,
+ required this.latestVersion,
+ required this.releaseUrl,
+ });
+}
+
+class AudiobookshelfUpdateService {
+ static final Uri _releasesUri = Uri.parse(
+ 'https://api.github.com/repos/advplyr/audiobookshelf/releases?per_page=30',
+ );
+
+ static Future<AudiobookshelfServerUpdate?> check({
+ required String currentVersion,
+ http.Client? httpClient,
+ }) async {
+ final current = _ServerVersion.tryParse(currentVersion);
+ if (current == null) return null;
+
+ final client = httpClient ?? http.Client();
+ try {
+ final response = await client
+ .get(
+ _releasesUri,
+ headers: const {'Accept': 'application/vnd.github.v3+json'},
+ )
+ .timeout(const Duration(seconds: 10));
+ if (response.statusCode != 200) return null;
+
+ final decoded = jsonDecode(response.body);
+ if (decoded is! List) return null;
+
+ _ReleaseVersion? latest;
+ for (final value in decoded) {
+ if (value is! Map) continue;
+ final tagName = value['tag_name']?.toString() ?? '';
+ final version = _ServerVersion.tryParse(tagName);
+ if (version == null) continue;
+ if (latest == null || version.compareTo(latest.version) > 0) {
+ latest = _ReleaseVersion(
+ version: version,
+ releaseUrl:
+ value['html_url']?.toString() ??
+ 'https://github.com/advplyr/audiobookshelf/releases/tag/v${version.value}',
+ );
+ }
+ }
+
+ if (latest == null || latest.version.compareTo(current) <= 0) {
+ return null;
+ }
+ return AudiobookshelfServerUpdate(
+ currentVersion: current.value,
+ latestVersion: latest.version.value,
+ releaseUrl: latest.releaseUrl,
+ );
+ } catch (error) {
+ debugPrint('[AudiobookshelfUpdate] Check failed: $error');
+ return null;
+ } finally {
+ if (httpClient == null) client.close();
+ }
+ }
+}
+
+class _ReleaseVersion {
+ final _ServerVersion version;
+ final String releaseUrl;
+
+ const _ReleaseVersion({required this.version, required this.releaseUrl});
+}
+
+class _ServerVersion {
+ final int major;
+ final int minor;
+ final int patch;
+ final String value;
+
+ const _ServerVersion({
+ required this.major,
+ required this.minor,
+ required this.patch,
+ required this.value,
+ });
+
+ static _ServerVersion? tryParse(String value) {
+ final match = RegExp(
+ r'^v?(\d+)\.(\d+)\.(\d+)(?:[-+][0-9A-Za-z.-]+)?$',
+ ).firstMatch(value.trim());
+ if (match == null) return null;
+ final major = int.tryParse(match.group(1)!);
+ final minor = int.tryParse(match.group(2)!);
+ final patch = int.tryParse(match.group(3)!);
+ if (major == null || minor == null || patch == null) return null;
+ return _ServerVersion(
+ major: major,
+ minor: minor,
+ patch: patch,
+ value: '$major.$minor.$patch',
+ );
+ }
+
+ int compareTo(_ServerVersion other) {
+ final majorResult = major.compareTo(other.major);
+ if (majorResult != 0) return majorResult;
+ final minorResult = minor.compareTo(other.minor);
+ if (minorResult != 0) return minorResult;
+ return patch.compareTo(other.patch);
+ }
+}
diff --git a/lib/services/backup_service.dart b/lib/services/backup_service.dart
index 00a67a08..e35aca87 100644
--- a/lib/services/backup_service.dart
+++ b/lib/services/backup_service.dart
@@ -241,6 +241,21 @@ class BackupService {
collectHome('home_hidden_sections_', 'hidden');
collectHome('home_genre_sections_', 'genres');
+ final librarySettings = <String, Map<String, dynamic>>{};
+ void collectLibrarySetting(String shortPrefix, String field) {
+ final fullPrefix = '$scopePrefix$shortPrefix';
+ for (final key in prefs.getKeys()) {
+ if (!key.startsWith(fullPrefix)) continue;
+ final libraryId = key.substring(fullPrefix.length);
+ final value = prefs.get(key);
+ if (value is! String && value is! int) continue;
+ librarySettings.putIfAbsent(libraryId, () => {})[field] = value;
+ }
+ }
+ collectLibrarySetting('rectangleCovers_', 'coverShape');
+ collectLibrarySetting('skipOverrideForward_', 'skipForward');
+ collectLibrarySetting('skipOverrideBack_', 'skipBack');
+
// Per-item metadata overrides (scoped, keyed by itemId)
final metadataOverrides = <String, String>{};
final metaPrefix = '${scopePrefix}metadata_override_';
@@ -334,6 +349,7 @@ class BackupService {
'offlineListening': offlineListening,
'rmab': rmab,
'homeLayouts': homeLayouts,
+ 'librarySettings': librarySettings,
'metadataOverrides': metadataOverrides,
'ebookAnnotations': ebookAnnotations,
'ereader': ereader,
@@ -462,8 +478,18 @@ class BackupService {
if (s['rollingDownloadDeleteFinished'] != null) PlayerSettings.setRollingDownloadDeleteFinished(s['rollingDownloadDeleteFinished'] as bool);
if (s['queueAutoDownload'] != null) PlayerSettings.setQueueAutoDownload(s['queueAutoDownload'] as bool);
if (s['mergeAbsorbingLibraries'] != null) PlayerSettings.setMergeAbsorbingLibraries(s['mergeAbsorbingLibraries'] as bool);
- if (s['podcastTabEnabled'] != null) PlayerSettings.setPodcastTabEnabled(s['podcastTabEnabled'] as bool);
- if (s['podcastTabLibraryId'] != null) PlayerSettings.setPodcastTabLibraryId(s['podcastTabLibraryId'] as String);
+ if (s['podcastTabLibraryId'] != null) {
+ await ScopedPrefs.setString(
+ 'podcastTabLibraryId',
+ s['podcastTabLibraryId'] as String,
+ );
+ }
+ if (s['podcastTabEnabled'] != null) {
+ await ScopedPrefs.setBool(
+ 'podcastTabEnabled',
+ s['podcastTabEnabled'] as bool,
+ );
+ }
if (s['episodeNotifIntervalMinutes'] != null) PlayerSettings.setEpisodeNotifIntervalMinutes(s['episodeNotifIntervalMinutes'] as int);
if (s['maxConcurrentDownloads'] != null) PlayerSettings.setMaxConcurrentDownloads(s['maxConcurrentDownloads'] as int);
if (s['colorSource'] != null) PlayerSettings.setColorSource(s['colorSource'] as String);
@@ -683,6 +709,44 @@ class BackupService {
}
}
+ final librarySettings = data['librarySettings'] as Map<String, dynamic>?;
+ if (librarySettings != null) {
+ final scope = UserAccountService().activeScopeKey;
+ final scopePrefix = scope.isNotEmpty ? '$scope:' : '';
+ final prefixes = [
+ '${scopePrefix}rectangleCovers_',
+ '${scopePrefix}skipOverrideForward_',
+ '${scopePrefix}skipOverrideBack_',
+ ];
+ final oldKeys = prefs
+ .getKeys()
+ .where((key) => prefixes.any(key.startsWith))
+ .toList();
+ for (final key in oldKeys) {
+ await prefs.remove(key);
+ }
+ for (final entry in librarySettings.entries) {
+ final libraryId = entry.key;
+ final settings = entry.value as Map<String, dynamic>;
+ final coverShape = settings['coverShape'] as String?;
+ if (coverShape == 'rect' || coverShape == 'square') {
+ await PlayerSettings.setRectangleCoversOverride(
+ libraryId,
+ coverShape,
+ );
+ }
+ final skipForward = (settings['skipForward'] as num?)?.toInt();
+ final skipBack = (settings['skipBack'] as num?)?.toInt();
+ if (skipForward != null && skipBack != null) {
+ await PlayerSettings.setSkipOverride(
+ libraryId,
+ forward: skipForward,
+ back: skipBack,
+ );
+ }
+ }
+ }
+
// Per-item metadata overrides (scoped)
final metadataOverrides = data['metadataOverrides'] as Map<String, dynamic>?;
if (metadataOverrides != null) {
@@ -737,5 +801,7 @@ class BackupService {
if (customDownloadPath != null) {
await prefs.setString('custom_download_path', customDownloadPath);
}
+
+ PlayerSettings.notifySettingsChanged();
}
}
diff --git a/lib/services/external_audio_output_types.dart b/lib/services/external_audio_output_types.dart
new file mode 100644
index 00000000..c4ce3950
--- /dev/null
+++ b/lib/services/external_audio_output_types.dart
@@ -0,0 +1,14 @@
+// ignore_for_file: experimental_member_use
+
+import 'package:audio_session/audio_session.dart';
+
+const Set<AudioDeviceType> externalAudioOutputTypes = {
+ AudioDeviceType.bluetoothA2dp,
+ AudioDeviceType.bluetoothSco,
+ AudioDeviceType.bluetoothLe,
+ AudioDeviceType.wiredHeadset,
+ AudioDeviceType.wiredHeadphones,
+ AudioDeviceType.usbAudio,
+ AudioDeviceType.hearingAid,
+ AudioDeviceType.carAudio,
+};
diff --git a/lib/services/scoped_prefs.dart b/lib/services/scoped_prefs.dart
index f8542dd5..6a1026ad 100644
--- a/lib/services/scoped_prefs.dart
+++ b/lib/services/scoped_prefs.dart
@@ -11,7 +11,11 @@ import 'user_account_service.dart';
class ScopedPrefs {
ScopedPrefs._();
- static String _scope(String key) => UserAccountService().scopedKey(key);
+ static String keyForScope(String scope, String key) =>
+ scope.isEmpty ? key : '$scope:$key';
+
+ static String _scope(String key) =>
+ keyForScope(UserAccountService().activeScopeKey, key);
/// Only fall back to un-scoped data when there is no active scope
/// (i.e. pre-multi-user migration). Once scoped, a missing key means
diff --git a/lib/services/sleep_timer_service.dart b/lib/services/sleep_timer_service.dart
index cca1e47d..faa073d6 100644
--- a/lib/services/sleep_timer_service.dart
+++ b/lib/services/sleep_timer_service.dart
@@ -7,6 +7,7 @@ import 'package:vibration/vibration.dart';
import 'scoped_prefs.dart';
import 'audio_player_service.dart';
import 'chromecast_service.dart';
+import 'sleep_timer_tick_policy.dart';
enum SleepTimerMode { off, time, chapters, episodes }
@@ -126,6 +127,8 @@ class SleepTimerService extends ChangeNotifier {
bool _warningSent = false;
Duration _fadeThreshold = const Duration(seconds: 30);
double _fadeStartVolume = 1.0; // volume when fade begins
+ bool _tickInProgress = false;
+ bool _isTriggeringSleep = false;
// Reset on pause/play
bool _wasPlaying = false; // tracks play state transitions
@@ -195,31 +198,53 @@ class SleepTimerService extends ChangeNotifier {
}
void _onTimerTick(Timer timer) async {
- if (_timeRemaining.inSeconds <= 0) {
- _triggerSleep();
- return;
- }
- final isPlaying = _isPlaybackActive;
+ if (_tickInProgress) return;
+ _tickInProgress = true;
+ try {
+ if (_mode != SleepTimerMode.time) return;
+ final isPlaying = _isPlaybackActive;
+ final pauseRequested = !_cast.isCasting && _player.isPauseRequested;
+ var action = sleepTimerTickAction(
+ timeRemaining: _timeRemaining,
+ isPlaybackActive: isPlaying,
+ isPauseRequested: pauseRequested,
+ );
+ if (action == SleepTimerTickAction.wait) {
+ _wasPlaying = false;
+ return;
+ }
- // Detect pause->play transition and reset if setting is on
- if (isPlaying && !_wasPlaying) {
- final resetOnPause = await PlayerSettings.getResetSleepOnPause();
- if (resetOnPause) {
- _timeRemaining = _initialDuration;
- _warningSent = false;
- if (_isFadingOut) {
- _isFadingOut = false;
- _player.setVolume(_fadeStartVolume);
+ // Detect pause->play transition and reset if setting is on
+ if (!_wasPlaying) {
+ final resetOnPause = await PlayerSettings.getResetSleepOnPause();
+ if (resetOnPause) {
+ _timeRemaining = _initialDuration;
+ _warningSent = false;
+ if (_isFadingOut) {
+ _isFadingOut = false;
+ _player.setVolume(_fadeStartVolume);
+ }
+ debugPrint('[SleepTimer] Reset to ${_initialDuration.inMinutes}m on resume');
+ onToast?.call('Sleep timer reset: ${_initialDuration.inMinutes}m');
+ _scheduleNextTick();
}
- debugPrint('[SleepTimer] Reset to ${_initialDuration.inMinutes}m on resume');
- onToast?.call('Sleep timer reset: ${_initialDuration.inMinutes}m');
- _scheduleNextTick();
}
- }
- _wasPlaying = isPlaying;
+ _wasPlaying = true;
+
+ action = sleepTimerTickAction(
+ timeRemaining: _timeRemaining,
+ isPlaybackActive: _isPlaybackActive,
+ isPauseRequested: !_cast.isCasting && _player.isPauseRequested,
+ );
+ if (action == SleepTimerTickAction.wait) {
+ _wasPlaying = false;
+ return;
+ }
+ if (action == SleepTimerTickAction.trigger) {
+ await _triggerSleep();
+ return;
+ }
- // Only count down when playing
- if (isPlaying) {
_timeRemaining -= Duration(seconds: _tickIntervalSeconds);
// Switch to fast ticks when approaching fade threshold
if (_tickIntervalSeconds > 1 &&
@@ -251,6 +276,8 @@ class SleepTimerService extends ChangeNotifier {
}
notifyListeners();
+ } finally {
+ _tickInProgress = false;
}
}
@@ -315,7 +342,7 @@ class SleepTimerService extends ChangeNotifier {
// Check if we've reached the end of the target chapter
if (currentIdx >= _targetChapterIndex) {
- _triggerSleep();
+ unawaited(_triggerSleep());
}
}
});
@@ -359,7 +386,7 @@ class SleepTimerService extends ChangeNotifier {
if (totalSec <= 0) return;
final posSec = _player.position.inMilliseconds / 1000.0;
if (posSec >= totalSec - _episodeEndGuardSec) {
- _triggerSleep();
+ unawaited(_triggerSleep());
}
});
}
@@ -385,23 +412,34 @@ class SleepTimerService extends ChangeNotifier {
bool _isFadingOut = false;
bool get isFadingOut => _isFadingOut;
- void _triggerSleep() async {
+ Future<void> _triggerSleep() async {
+ if (_isTriggeringSleep) return;
+ final pauseRequested = !_cast.isCasting && _player.isPauseRequested;
+ if (!_isPlaybackActive || pauseRequested) {
+ _wasPlaying = false;
+ return;
+ }
+ _isTriggeringSleep = true;
debugPrint('[SleepTimer] Triggering sleep — pausing playback');
- if (_cast.isCasting) {
- _cast.pause();
- } else {
- _player.pause();
- // Restore volume so next playback starts at normal level
- _player.setVolume(_fadeStartVolume);
- // Auto-rewind so the user resumes from a few seconds back
- final rewindSeconds = await PlayerSettings.getEffectiveSleepRewindSeconds(_player.currentItemId);
- if (rewindSeconds > 0) {
- await _player.sleepTimerRewind(rewindSeconds);
- debugPrint('[SleepTimer] Rewound ${rewindSeconds}s');
+ try {
+ if (_cast.isCasting) {
+ await _cast.pause();
+ } else {
+ await _player.pause();
+ // Restore volume so next playback starts at normal level
+ _player.setVolume(_fadeStartVolume);
+ // Auto-rewind so the user resumes from a few seconds back
+ final rewindSeconds = await PlayerSettings.getEffectiveSleepRewindSeconds(_player.currentItemId);
+ if (rewindSeconds > 0) {
+ await _player.sleepTimerRewind(rewindSeconds);
+ debugPrint('[SleepTimer] Rewound ${rewindSeconds}s');
+ }
}
+ _isFadingOut = false;
+ cancel();
+ } finally {
+ _isTriggeringSleep = false;
}
- _isFadingOut = false;
- cancel();
}
void cancel() {
diff --git a/lib/services/sleep_timer_tick_policy.dart b/lib/services/sleep_timer_tick_policy.dart
new file mode 100644
index 00000000..2ae42102
--- /dev/null
+++ b/lib/services/sleep_timer_tick_policy.dart
@@ -0,0 +1,15 @@
+enum SleepTimerTickAction { wait, countDown, trigger }
+
+SleepTimerTickAction sleepTimerTickAction({
+ required Duration timeRemaining,
+ required bool isPlaybackActive,
+ required bool isPauseRequested,
+}) {
+ if (!isPlaybackActive || isPauseRequested) {
+ return SleepTimerTickAction.wait;
+ }
+ if (timeRemaining <= Duration.zero) {
+ return SleepTimerTickAction.trigger;
+ }
+ return SleepTimerTickAction.countDown;
+}
diff --git a/lib/utils/absorbing_inclusion.dart b/lib/utils/absorbing_inclusion.dart
new file mode 100644
index 00000000..4a198338
--- /dev/null
+++ b/lib/utils/absorbing_inclusion.dart
@@ -0,0 +1,6 @@
+bool shouldIncludeBookInAbsorbing({
+ required bool isFinished,
+ required bool manuallyAdded,
+}) {
+ return !isFinished || manuallyAdded;
+}
diff --git a/lib/widgets/auth_loading_screen.dart b/lib/widgets/auth_loading_screen.dart
new file mode 100644
index 00000000..cf1fde73
--- /dev/null
+++ b/lib/widgets/auth_loading_screen.dart
@@ -0,0 +1,43 @@
+import 'package:flutter/material.dart';
+
+import 'absorb_wave_icon.dart';
+
+class AuthLoadingScreen extends StatelessWidget {
+ static const screenKey = Key('authLoadingScreen');
+
+ const AuthLoadingScreen({super.key});
+
+ @override
+ Widget build(BuildContext context) {
+ final primary = Theme.of(context).colorScheme.primary;
+ return Scaffold(
+ key: screenKey,
+ body: Center(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ AbsorbWaveIcon(size: 48, color: primary),
+ const SizedBox(height: 20),
+ Text(
+ 'A B S O R B',
+ style: Theme.of(context).textTheme.headlineSmall?.copyWith(
+ color: primary,
+ letterSpacing: 6,
+ fontWeight: FontWeight.w300,
+ ),
+ ),
+ const SizedBox(height: 32),
+ SizedBox(
+ width: 24,
+ height: 24,
+ child: CircularProgressIndicator(
+ strokeWidth: 2,
+ color: primary.withValues(alpha: 0.5),
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
diff --git a/lib/widgets/book_detail_sheet.dart b/lib/widgets/book_detail_sheet.dart
index f0d6a73f..e56f34b2 100644
--- a/lib/widgets/book_detail_sheet.dart
+++ b/lib/widgets/book_detail_sheet.dart
@@ -78,6 +78,65 @@ void showQuickActionsSheet(BuildContext context, String itemId, {Map<String, dyn
);
}
+class BookDetailInfoChip extends StatelessWidget {
+ final IconData icon;
+ final String label;
+ final VoidCallback? onTap;
+
+ const BookDetailInfoChip({
+ super.key,
+ required this.icon,
+ required this.label,
+ this.onTap,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final pill = Container(
+ constraints: const BoxConstraints(maxWidth: 200),
+ padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
+ decoration: BoxDecoration(
+ color: onTap != null
+ ? cs.tertiary.withValues(alpha: 0.10)
+ : cs.onSurface.withValues(alpha: 0.06),
+ borderRadius: BorderRadius.circular(20),
+ border: Border.all(
+ color: onTap != null
+ ? cs.tertiary.withValues(alpha: 0.30)
+ : cs.onSurface.withValues(alpha: 0.08),
+ ),
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(
+ icon,
+ size: 12,
+ color: onTap != null
+ ? cs.tertiary
+ : cs.onSurface.withValues(alpha: 0.3),
+ ),
+ const SizedBox(width: 4),
+ Flexible(
+ child: Text(
+ label,
+ overflow: TextOverflow.ellipsis,
+ maxLines: 1,
+ style: TextStyle(
+ color: onTap != null ? cs.tertiary : cs.onSurfaceVariant,
+ fontSize: 11,
+ ),
+ ),
+ ),
+ ],
+ ),
+ );
+ if (onTap == null) return pill;
+ return GestureDetector(onTap: onTap, child: pill);
+ }
+}
+
class _BookDetailSheetContent extends StatefulWidget {
final String itemId;
final ScrollController scrollController;
@@ -99,8 +158,6 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
bool _isLoading = true;
bool _chaptersExpanded = false;
bool _bookmarksExpanded = false;
- bool _tracksExpanded = false;
- bool _filesExpanded = false;
BookmarkPreviewPlayer? _preview;
List<Bookmark> _bookmarks = [];
bool _isAbsorbing = false;
@@ -111,6 +168,7 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
bool _authorsExpanded = false;
bool _narratorsExpanded = false;
bool _squareCovers = false;
+ bool _isUpdatingProgressDate = false;
ColorScheme? _rawCoverScheme;
String? _coverSchemeUrl; // URL the current scheme was derived from
@@ -419,8 +477,6 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
final media = _item!['media'] as Map<String, dynamic>? ?? {};
final metadata = media['metadata'] as Map<String, dynamic>? ?? {};
final chapters = media['chapters'] as List<dynamic>? ?? [];
- final audioFiles = media['audioFiles'] as List<dynamic>? ?? [];
- final libraryFiles = _item!['libraryFiles'] as List<dynamic>? ?? [];
final title = metadata['title'] as String? ?? l.unknown;
final authorName = metadata['authorName'] as String? ?? '';
final descRaw = metadata['description'] as String? ?? '';
@@ -436,7 +492,6 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
final tags = tagsRaw.cast<String>();
final publisher = metadata['publisher'] as String? ?? '';
final year = metadata['publishedYear'] as String? ?? '';
- final serverPath = _item!['path'] as String? ?? _item!['relPath'] as String? ?? '';
final lib = context.watch<LibraryProvider>();
final progress = lib.getProgress(widget.itemId);
final auth = context.read<AuthProvider>();
@@ -740,7 +795,8 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
// More button below primary row
const SizedBox(height: 8),
GestureDetector(
- onTap: () => _showMoreSheet(context, auth, lib, title, authorName, progress, isFinished, duration, ebookFile, isEbookOnly, serverPath),
+ onTap: () => _showMoreSheet(context, auth, lib, title, authorName, progress, isFinished, duration, ebookFile, isEbookOnly,
+ ),
child: Container(
height: 36,
decoration: BoxDecoration(
@@ -779,9 +835,26 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
},
)),
if (progressData?['startedAt'] is num)
- _chip(Icons.play_circle_outline_rounded, l.startedDate(_fmtDate((progressData!['startedAt'] as num).toInt()))),
+ _chip(Icons.play_circle_outline_rounded, l.startedDate(_fmtDate((progressData!['startedAt'] as num).toInt())),
+ key: ValueKey('book-started-date-${widget.itemId}'),
+ onTap: () => _editProgressDate(
+ auth: auth,
+ lib: lib,
+ editingFinishedDate: false,
+ startedAt: (progressData['startedAt'] as num).toInt(),
+ finishedAt: (progressData['finishedAt'] as num?)?.toInt(),
+ ),
+ ),
if (progressData?['finishedAt'] is num)
- _chip(Icons.check_circle_outline_rounded, l.finishedDate(_fmtDate((progressData!['finishedAt'] as num).toInt()))),
+ _chip(Icons.check_circle_outline_rounded, l.finishedDate(_fmtDate((progressData!['finishedAt'] as num).toInt()),
+ ),
+ key: ValueKey('book-finished-date-${widget.itemId}'),
+ onTap: () => _editProgressDate(
+ auth: auth,
+ lib: lib,
+ editingFinishedDate: true,
+ startedAt: (progressData['startedAt'] as num).toInt(),
+ finishedAt: (progressData['finishedAt'] as num).toInt())),
]),
if (seriesEntries.isNotEmpty) ...[const SizedBox(height: 16),
...seriesEntries.map((s) {
@@ -850,46 +923,7 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
])),
]));
})]],
- if (audioFiles.isNotEmpty) ...[const SizedBox(height: 16),
- GestureDetector(onTap: () => setState(() => _tracksExpanded = !_tracksExpanded),
- child: Row(children: [
- Text(l.audioTracksCount(audioFiles.length), style: tt.titleSmall?.copyWith(color: cs.onSurfaceVariant, fontWeight: FontWeight.w600)),
- const Spacer(), Icon(_tracksExpanded ? Icons.expand_less : Icons.expand_more, color: cs.onSurface.withValues(alpha: 0.3), size: 20)])),
- if (_tracksExpanded) ...[const SizedBox(height: 8),
- ...audioFiles.asMap().entries.map((e) {
- final af = e.value as Map<String, dynamic>;
- final afMeta = af['metadata'] as Map<String, dynamic>? ?? {};
- final trackDuration = (af['duration'] as num?)?.toDouble() ?? 0;
- return Padding(padding: const EdgeInsets.symmetric(vertical: 3),
- child: Row(children: [
- SizedBox(width: 28, child: Text('${(af['index'] as num?)?.toInt() ?? e.key + 1}', style: tt.labelSmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.3)))),
- Expanded(child: Text(afMeta['filename'] as String? ?? '', maxLines: 1, overflow: TextOverflow.ellipsis, style: tt.bodySmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.6)))),
- if (trackDuration > 0)
- Text(formatHm(trackDuration), style: tt.labelSmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.3))),
- ]));
- })]],
- if (libraryFiles.isNotEmpty) ...[const SizedBox(height: 16),
- GestureDetector(onTap: () => setState(() => _filesExpanded = !_filesExpanded),
- child: Row(children: [
- Text(l.libraryFilesCount(libraryFiles.length), style: tt.titleSmall?.copyWith(color: cs.onSurfaceVariant, fontWeight: FontWeight.w600)),
- const Spacer(), Icon(_filesExpanded ? Icons.expand_less : Icons.expand_more, color: cs.onSurface.withValues(alpha: 0.3), size: 20)])),
- if (_filesExpanded) ...[const SizedBox(height: 8),
- ...libraryFiles.map((f) {
- final lf = f as Map<String, dynamic>;
- final lfMeta = lf['metadata'] as Map<String, dynamic>? ?? {};
- final size = (lfMeta['size'] as num?)?.toInt() ?? 0;
- return Padding(padding: const EdgeInsets.symmetric(vertical: 3),
- child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
- Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
- Text(lfMeta['relPath'] as String? ?? lfMeta['filename'] as String? ?? '', maxLines: 2, overflow: TextOverflow.ellipsis, style: tt.bodySmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.6))),
- if ((lf['fileType'] as String?)?.isNotEmpty ?? false)
- Text(lf['fileType'] as String, style: tt.labelSmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.35))),
- ])),
- if (size > 0) ...[const SizedBox(width: 8),
- Text(_fmtSize(size), style: tt.labelSmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.3)))],
- ]));
- })]],
- ]);
+ ]);
}
// ─── QUICK ACTIONS (long-press) ─────────────────────────────
@@ -906,7 +940,6 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
final title = metadata['title'] as String? ?? l.unknown;
final authorName = metadata['authorName'] as String? ?? '';
final duration = (media['duration'] as num?)?.toDouble() ?? 0;
- final serverPath = _item!['path'] as String? ?? _item!['relPath'] as String? ?? '';
final ebookFile = resolveEbookFile(_item);
final isEbookOnly = PlayerSettings.isEbookOnly(_item!);
@@ -971,7 +1004,8 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
// Secondary actions as the shared responsive pill grid. The quick sheet
// stays open behind navigation actions, so dismiss is a no-op here.
_actionPillGrid(context, cs, tt, l, auth, lib, title, authorName, progress,
- isFinished, duration, ebookFile, isEbookOnly, serverPath, inContinueListening,
+ isFinished, duration, ebookFile, isEbookOnly,
+ inContinueListening,
continueSeriesId, dismiss: () {}, includeOpenDetails: true),
],
);
@@ -986,7 +1020,7 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
Widget _actionPillGrid(BuildContext context, ColorScheme cs, TextTheme tt, AppLocalizations l,
AuthProvider auth, LibraryProvider lib, String title, String authorName, double progress,
bool isFinished, double duration, Map<String, dynamic>? ebookFile, bool isEbookOnly,
- String serverPath, bool inContinueListening, String? continueSeriesId,
+ bool inContinueListening, String? continueSeriesId,
{required VoidCallback dismiss, bool includeOpenDetails = false}) {
final onAbsorbing = lib.isOnAbsorbingList(widget.itemId);
return Column(mainAxisSize: MainAxisSize.min, children: [
@@ -1089,19 +1123,7 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
child: Wrap(spacing: gap, runSpacing: gap, children: pills),
);
}),
- if (auth.isAdmin && serverPath.isNotEmpty) ...[
- const SizedBox(height: 10),
- GestureDetector(
- onTap: () {
- dismiss();
- Clipboard.setData(ClipboardData(text: serverPath));
- HapticFeedback.lightImpact();
- },
- child: Text(serverPath, maxLines: 1, overflow: TextOverflow.ellipsis, textAlign: TextAlign.center,
- style: TextStyle(color: cs.onSurface.withValues(alpha: 0.25), fontSize: 11)),
- ),
- ],
- ]);
+ ]);
}
Widget _quickThumb(double size, Map<String, String> headers, ColorScheme cs) {
@@ -1219,7 +1241,8 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
void _showMoreSheet(BuildContext context, AuthProvider auth, LibraryProvider lib,
String title, String authorName, double progress, bool isFinished,
- double duration, Map<String, dynamic>? ebookFile, bool isEbookOnly, String serverPath) {
+ double duration, Map<String, dynamic>? ebookFile, bool isEbookOnly,
+ ) {
final cs = Theme.of(context).colorScheme;
final tt = Theme.of(context).textTheme;
final l = AppLocalizations.of(context)!;
@@ -1256,7 +1279,7 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
Flexible(
child: SingleChildScrollView(
child: _actionPillGrid(context, cs, tt, l, auth, lib, title, authorName,
- progress, isFinished, duration, ebookFile, isEbookOnly, serverPath,
+ progress, isFinished, duration, ebookFile, isEbookOnly,
inContinueListening, continueSeriesId, dismiss: () => Navigator.pop(ctx)),
),
),
@@ -1317,6 +1340,7 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
final meta = media['metadata'] as Map<String, dynamic>? ?? {};
final mediaTags = ((media['tags'] as List<dynamic>?) ?? const []).cast<String>();
final audioFiles = (media['audioFiles'] as List<dynamic>?) ?? const [];
+ final libraryFiles = (_item!['libraryFiles'] as List<dynamic>?) ?? const [];
final rel = _item!['relPath'] as String? ?? '';
Navigator.of(context, rootNavigator: true).push(MaterialPageRoute(
builder: (_) => BookEditScreen(
@@ -1325,7 +1349,8 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
metadata: meta,
tags: mediaTags,
audioFiles: audioFiles,
- relPath: rel,
+ libraryFiles: libraryFiles,
+ relPath: rel,
isEbookOnly: isEbookOnly,
isAdmin: auth.isAdmin,
libraryId: _item!['libraryId'] as String?,
@@ -1362,41 +1387,8 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
return '${(bytes / 1073741824).toStringAsFixed(2)} GB';
}
- Widget _chip(IconData icon, String text, {VoidCallback? onTap}) {
- final cs = Theme.of(context).colorScheme;
- final pill = Container(
- constraints: const BoxConstraints(maxWidth: 200),
- padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
- decoration: BoxDecoration(
- color: onTap != null
- ? cs.tertiary.withValues(alpha: 0.10)
- : cs.onSurface.withValues(alpha: 0.06),
- borderRadius: BorderRadius.circular(20),
- border: Border.all(
- color: onTap != null
- ? cs.tertiary.withValues(alpha: 0.30)
- : cs.onSurface.withValues(alpha: 0.08),
- ),
- ),
- child: Row(mainAxisSize: MainAxisSize.min, children: [
- Icon(icon,
- size: 12,
- color: onTap != null
- ? cs.tertiary
- : cs.onSurface.withValues(alpha: 0.3)),
- const SizedBox(width: 4),
- Flexible(
- child: Text(text,
- overflow: TextOverflow.ellipsis,
- maxLines: 1,
- style: TextStyle(
- color: onTap != null ? cs.tertiary : cs.onSurfaceVariant,
- fontSize: 11)),
- ),
- ]),
- );
- if (onTap == null) return pill;
- return GestureDetector(onTap: onTap, child: pill);
+ Widget _chip(IconData icon, String text, {Key? key, VoidCallback? onTap}) {
+ return BookDetailInfoChip(key: key, icon: icon, label: text, onTap: onTap);
}
String _fmtDate(int ms) {
@@ -1405,6 +1397,95 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
return '${months[d.month - 1]} ${d.day}, ${d.year}';
}
+ Future<void> _editProgressDate({
+ required AuthProvider auth,
+ required LibraryProvider lib,
+ required bool editingFinishedDate,
+ required int startedAt,
+ int? finishedAt,
+ }) async {
+ if (_isUpdatingProgressDate) return;
+ final l = AppLocalizations.of(context)!;
+ final api = auth.apiService;
+ if (api == null || lib.isOffline) {
+ showOverlayToast(
+ context,
+ l.failedToUpdateCheckConnection,
+ icon: Icons.cloud_off_rounded,
+ );
+ return;
+ }
+
+ final currentTimestamp = editingFinishedDate ? finishedAt : startedAt;
+ if (currentTimestamp == null) return;
+ final initialDate = DateUtils.dateOnly(
+ DateTime.fromMillisecondsSinceEpoch(currentTimestamp),
+ );
+ var firstDate = DateTime(1900);
+ var lastDate = DateUtils.dateOnly(DateTime.now());
+ if (editingFinishedDate) {
+ final startedDate = DateUtils.dateOnly(
+ DateTime.fromMillisecondsSinceEpoch(startedAt),
+ );
+ if (startedDate.isAfter(firstDate)) firstDate = startedDate;
+ } else if (finishedAt != null) {
+ final finishedDate = DateUtils.dateOnly(
+ DateTime.fromMillisecondsSinceEpoch(finishedAt),
+ );
+ if (finishedDate.isBefore(lastDate)) lastDate = finishedDate;
+ }
+ if (initialDate.isBefore(firstDate)) firstDate = initialDate;
+ if (initialDate.isAfter(lastDate)) lastDate = initialDate;
+
+ final picked = await showDatePicker(
+ context: context,
+ initialDate: initialDate,
+ firstDate: firstDate,
+ lastDate: lastDate,
+ helpText: editingFinishedDate ? l.dateFinished : l.dateStarted,
+ cancelText: l.cancel,
+ confirmText: l.save,
+ );
+ if (picked == null || !mounted) return;
+ if (picked.year == initialDate.year &&
+ picked.month == initialDate.month &&
+ picked.day == initialDate.day) {
+ return;
+ }
+
+ final timestamp = DateTime.utc(
+ picked.year,
+ picked.month,
+ picked.day,
+ 12,
+ ).millisecondsSinceEpoch;
+ setState(() => _isUpdatingProgressDate = true);
+ final updated = editingFinishedDate
+ ? await api.updateProgressFinishedDate(widget.itemId, timestamp)
+ : await api.updateProgressStartDate(widget.itemId, timestamp);
+ if (!mounted) return;
+ setState(() => _isUpdatingProgressDate = false);
+
+ if (updated) {
+ lib.applyLocalProgressDates(
+ widget.itemId,
+ startedAt: editingFinishedDate ? null : timestamp,
+ finishedAt: editingFinishedDate ? timestamp : null,
+ );
+ showOverlayToast(
+ context,
+ l.sessionSaved,
+ icon: Icons.event_available_rounded,
+ );
+ } else {
+ showOverlayToast(
+ context,
+ l.sessionSaveFailed,
+ icon: Icons.error_outline_rounded,
+ );
+ }
+ }
+
List<Widget> _buildStars(double rating, Color accent) {
final cs = Theme.of(context).colorScheme;
diff --git a/lib/widgets/edit_metadata_sheet.dart b/lib/widgets/edit_metadata_sheet.dart
index 4658e4ec..a900aabc 100644
--- a/lib/widgets/edit_metadata_sheet.dart
+++ b/lib/widgets/edit_metadata_sheet.dart
@@ -19,12 +19,14 @@ enum _ETab { details, cover, chapters, match, encode, embed }
/// adjacent tabs never double-attaches one controller.
class MetadataEditView extends StatefulWidget {
static const quickMatchButtonKey = Key('metadataQuickMatchButton');
+ static const filePathsSectionKey = Key('metadataFilePathsSection');
final String itemId;
final String bookTitle;
final Map<String, dynamic> metadata;
final List<String> tags;
final List<dynamic> audioFiles;
+ final List<dynamic> libraryFiles;
final String relPath;
final bool isEbookOnly;
final bool isAdmin;
@@ -37,6 +39,7 @@ class MetadataEditView extends StatefulWidget {
required this.metadata,
this.tags = const [],
this.audioFiles = const [],
+ this.libraryFiles = const [],
this.relPath = '',
this.isEbookOnly = false,
this.isAdmin = false,
@@ -1309,6 +1312,7 @@ class _MetadataEditViewState extends State<MetadataEditView>
// ─── Custom Tab ─────────────────────────────────────────────
Widget _buildCustomTab(ColorScheme cs, TextTheme tt, AppLocalizations l) {
+ final filePaths = fullLibraryFilePaths(widget.libraryFiles);
return Column(children: [
// Save button bar
Padding(
@@ -1431,6 +1435,19 @@ class _MetadataEditViewState extends State<MetadataEditView>
),
),
]),
+ if (widget.isAdmin && filePaths.isNotEmpty) ...[
+ const SizedBox(height: 20),
+ Text(l.libraryFilesCount(filePaths.length),
+ key: MetadataEditView.filePathsSectionKey,
+ style: tt.titleSmall?.copyWith(fontWeight: FontWeight.w600)),
+ const SizedBox(height: 8),
+ for (final path in filePaths)
+ Padding(
+ padding: const EdgeInsets.only(bottom: 8),
+ child: SelectableText(path, style: tt.bodySmall?.copyWith(
+ color: cs.onSurfaceVariant, height: 1.35)),
+ ),
+ ],
],
),
@@ -1858,3 +1875,15 @@ class _MetadataEditViewState extends State<MetadataEditView>
);
}
}
+
+List<String> fullLibraryFilePaths(List<dynamic> libraryFiles) {
+ final paths = <String>[];
+ for (final file in libraryFiles) {
+ if (file is! Map) continue;
+ final metadata = file['metadata'];
+ if (metadata is! Map) continue;
+ final path = metadata['path']?.toString().trim() ?? '';
+ if (path.isNotEmpty && !paths.contains(path)) paths.add(path);
+ }
+ return paths;
+}
diff --git a/lib/widgets/server_admin_status_badges.dart b/lib/widgets/server_admin_status_badges.dart
new file mode 100644
index 00000000..c01dfcce
--- /dev/null
+++ b/lib/widgets/server_admin_status_badges.dart
@@ -0,0 +1,85 @@
+import 'package:flutter/material.dart';
+
+class ServerAdminStatusBadges extends StatelessWidget {
+ final int issueCount;
+ final String? updateVersion;
+ final String updateTooltip;
+
+ const ServerAdminStatusBadges({
+ super.key,
+ required this.issueCount,
+ required this.updateVersion,
+ required this.updateTooltip,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ return Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ if (updateVersion case final version?) ...[
+ Tooltip(
+ message: updateTooltip,
+ child: Semantics(
+ label: updateTooltip,
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
+ decoration: BoxDecoration(
+ color: cs.primary.withValues(alpha: 0.14),
+ borderRadius: BorderRadius.circular(10),
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(
+ Icons.system_update_alt_rounded,
+ size: 12,
+ color: cs.primary,
+ ),
+ const SizedBox(width: 4),
+ Text(
+ 'v$version',
+ style: tt.labelSmall?.copyWith(
+ color: cs.primary,
+ fontWeight: FontWeight.w700,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ if (issueCount > 0) const SizedBox(width: 6),
+ ],
+ if (issueCount > 0)
+ Container(
+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
+ decoration: BoxDecoration(
+ color: Colors.orange.withValues(alpha: 0.15),
+ borderRadius: BorderRadius.circular(10),
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(
+ Icons.report_problem_rounded,
+ size: 12,
+ color: Colors.orange.shade700,
+ ),
+ const SizedBox(width: 4),
+ Text(
+ '$issueCount',
+ style: tt.labelSmall?.copyWith(
+ color: Colors.orange.shade700,
+ fontWeight: FontWeight.w700,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ],
+ );
+ }
+}
diff --git a/packages/audio_service/android/build.gradle b/packages/audio_service/android/build.gradle
index 86bd5167..028102e2 100644
--- a/packages/audio_service/android/build.gradle
+++ b/packages/audio_service/android/build.gradle
@@ -1,5 +1,5 @@
group = "com.ryanheise.audioservice"
-version "1.0-SNAPSHOT"
+version = "1.0-SNAPSHOT"
def args = ["-Xlint:deprecation","-Xlint:unchecked"]
buildscript {
@@ -30,7 +30,7 @@ project.getTasks().withType(JavaCompile) {
apply plugin: "com.android.library"
android {
- namespace "com.ryanheise.audioservice"
+ namespace = "com.ryanheise.audioservice"
compileSdk = 35
compileOptions {
diff --git a/packages/audio_service/example/lib/example_playlist.dart b/packages/audio_service/example/lib/example_playlist.dart
index 29ad4498..b0ebbc78 100644
--- a/packages/audio_service/example/lib/example_playlist.dart
+++ b/packages/audio_service/example/lib/example_playlist.dart
@@ -184,8 +184,7 @@ class MainScreen extends StatelessWidget {
final queueState = snapshot.data ?? QueueState.empty;
final queue = queueState.queue;
return ReorderableListView(
- onReorder: (int oldIndex, int newIndex) {
- if (oldIndex < newIndex) newIndex--;
+ onReorderItem: (int oldIndex, int newIndex) {
_audioHandler.moveQueueItem(oldIndex, newIndex);
},
children: [
diff --git a/packages/flutter_carplay/android/src/main/kotlin/com/oguzhnatly/flutter_android_auto/FlutterAndroidAutoPlugin.kt b/packages/flutter_carplay/android/src/main/kotlin/com/oguzhnatly/flutter_android_auto/FlutterAndroidAutoPlugin.kt
index c900db9b..98744dcc 100644
--- a/packages/flutter_carplay/android/src/main/kotlin/com/oguzhnatly/flutter_android_auto/FlutterAndroidAutoPlugin.kt
+++ b/packages/flutter_carplay/android/src/main/kotlin/com/oguzhnatly/flutter_android_auto/FlutterAndroidAutoPlugin.kt
@@ -4,11 +4,13 @@ import androidx.car.app.CarContext
import androidx.car.app.model.Action
import androidx.car.app.model.CarIcon
import androidx.car.app.model.CarText
+import androidx.car.app.model.Header
import androidx.car.app.model.ItemList
import androidx.car.app.model.ListTemplate
import androidx.car.app.model.SectionedItemList
import androidx.car.app.model.Row
import androidx.car.app.model.Template
+import androidx.car.app.versioning.CarAppApiLevels
import androidx.car.app.Screen
import androidx.car.app.ScreenManager
import io.flutter.embedding.engine.plugins.FlutterPlugin
@@ -242,6 +244,7 @@ class FlutterAndroidAutoPlugin : FlutterPlugin, EventChannel.StreamHandler {
}
}
+ @Suppress("DEPRECATION")
private suspend fun getListTemplate(
call: MethodCall,
result: MethodChannel.Result,
@@ -249,8 +252,21 @@ class FlutterAndroidAutoPlugin : FlutterPlugin, EventChannel.StreamHandler {
addBackButton: Boolean = true
): Template {
val template = FAAListTemplate.fromJson(data)
- val listTemplateBuilder =
- ListTemplate.Builder().setTitle(template.title)
+ val listTemplateBuilder = ListTemplate.Builder()
+ val carApiLevel = AndroidAutoService.session?.carContext?.carAppApiLevel
+
+ if (carApiLevel != null && carApiLevel >= CarAppApiLevels.LEVEL_7) {
+ val headerBuilder = Header.Builder().setTitle(template.title)
+ if (addBackButton) {
+ headerBuilder.setStartHeaderAction(Action.BACK)
+ }
+ listTemplateBuilder.setHeader(headerBuilder.build())
+ } else {
+ listTemplateBuilder.setTitle(template.title)
+ if (addBackButton) {
+ listTemplateBuilder.setHeaderAction(Action.BACK)
+ }
+ }
if (template.sections.size == 0) {
listTemplateBuilder.setLoading(true)
@@ -280,10 +296,6 @@ class FlutterAndroidAutoPlugin : FlutterPlugin, EventChannel.StreamHandler {
}
}
- if (addBackButton) {
- listTemplateBuilder.setHeaderAction(Action.BACK)
- }
-
return listTemplateBuilder.build()
}
diff --git a/packages/flutter_carplay/android/src/main/kotlin/com/oguzhnatly/flutter_android_auto/Screen.kt b/packages/flutter_carplay/android/src/main/kotlin/com/oguzhnatly/flutter_android_auto/Screen.kt
index f2058b6c..5e538ab7 100644
--- a/packages/flutter_carplay/android/src/main/kotlin/com/oguzhnatly/flutter_android_auto/Screen.kt
+++ b/packages/flutter_carplay/android/src/main/kotlin/com/oguzhnatly/flutter_android_auto/Screen.kt
@@ -20,17 +20,27 @@ import androidx.car.app.model.PlaceListMapTemplate
import androidx.car.app.model.PlaceMarker
import androidx.car.app.model.Row
import androidx.car.app.model.Template
+import androidx.car.app.model.Header
import androidx.car.app.model.ListTemplate
+import androidx.car.app.versioning.CarAppApiLevels
class MainScreen(carContext: CarContext) : Screen(carContext) {
init {}
+ @Suppress("DEPRECATION")
override fun onGetTemplate(): Template {
val appName =
carContext.applicationInfo.loadLabel(carContext.packageManager)
.toString() ?: ""
- return FlutterAndroidAutoPlugin.currentTemplate
- ?: ListTemplate.Builder().setTitle(appName).setLoading(true).build()
+ FlutterAndroidAutoPlugin.currentTemplate?.let { return it }
+
+ val templateBuilder = ListTemplate.Builder().setLoading(true)
+ if (carContext.carAppApiLevel >= CarAppApiLevels.LEVEL_7) {
+ templateBuilder.setHeader(Header.Builder().setTitle(appName).build())
+ } else {
+ templateBuilder.setTitle(appName)
+ }
+ return templateBuilder.build()
}
}
diff --git a/packages/just_audio/android/build.gradle b/packages/just_audio/android/build.gradle
index 22a1e0d4..5fc3835f 100644
--- a/packages/just_audio/android/build.gradle
+++ b/packages/just_audio/android/build.gradle
@@ -1,5 +1,5 @@
-group 'com.ryanheise.just_audio'
-version '1.0'
+group = 'com.ryanheise.just_audio'
+version = '1.0'
def args = ["-Xlint:deprecation","-Xlint:unchecked"]
buildscript {
@@ -29,13 +29,13 @@ apply plugin: 'com.android.library'
android {
// Conditional for compatibility with AGP <4.2.
if (project.android.hasProperty("namespace")) {
- namespace 'com.ryanheise.just_audio'
+ namespace = 'com.ryanheise.just_audio'
}
- compileSdk 34
+ compileSdk = 34
defaultConfig {
- minSdk 16
- testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
+ minSdk = 16
+ testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
lintOptions {
@@ -43,8 +43,8 @@ android {
}
compileOptions {
- sourceCompatibility JavaVersion.VERSION_11
- targetCompatibility JavaVersion.VERSION_11
+ sourceCompatibility = JavaVersion.VERSION_11
+ targetCompatibility = JavaVersion.VERSION_11
}
dependencies {
diff --git a/packages/just_audio/lib/just_audio.dart b/packages/just_audio/lib/just_audio.dart
index 93408c01..453834db 100644
--- a/packages/just_audio/lib/just_audio.dart
+++ b/packages/just_audio/lib/just_audio.dart
@@ -4203,7 +4203,9 @@ Future<void> _serveCachedFile(HttpRequest request, File cachedFile,
final lower = name.toLowerCase();
if (lower == 'content-length' ||
lower == 'content-range' ||
- lower == 'transfer-encoding') return;
+ lower == 'transfer-encoding') {
+ return;
+ }
try {
request.response.headers.set(name, value);
} catch (_) {}
diff --git a/pubspec.yaml b/pubspec.yaml
index fe2c9e80..f8a888a1 100644
--- a/pubspec.yaml
+++ b/pubspec.yaml
@@ -1,7 +1,7 @@
name: absorb
description: An Audiobookshelf Client
publish_to: 'none'
-version: 1.9.3+224
+version: 1.9.3+226
environment:
sdk: '>=3.10.0 <4.0.0'