A cross platform Audiobookshelf client for Android and iOS
Dart
Add initial BookOrbit support
Barnabas5cbe225d5b0b
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xmlindex 8856e392..24810c5b 100644--- a/android/app/src/main/AndroidManifest.xml+++ b/android/app/src/main/AndroidManifest.xml@@ -59,6 +59,7 @@<category android:name="android.intent.category.DEFAULT" /><category android:name="android.intent.category.BROWSABLE" /><data android:scheme="audiobookshelf" />+ <data android:scheme="bookorbit" /></intent-filter></activity>diff --git a/android/app/src/main/kotlin/com/barnabas/absorb/CoverContentProvider.kt b/android/app/src/main/kotlin/com/barnabas/absorb/CoverContentProvider.ktindex 2557f048..b0bb8b40 100644--- a/android/app/src/main/kotlin/com/barnabas/absorb/CoverContentProvider.kt+++ b/android/app/src/main/kotlin/com/barnabas/absorb/CoverContentProvider.kt@@ -105,6 +105,9 @@ class CoverContentProvider : ContentProvider() {val prefs = context.getSharedPreferences("FlutterSharedPreferences", android.content.Context.MODE_PRIVATE)+ if (prefs.getString("flutter.server_backend", null) == "bookorbit") {+ return fetchViaBookOrbitProxy(context, prefs, itemId)+ }val serverUrl = prefs.getString("flutter.server_url", null)var token = prefs.getString("flutter.token", null)if (serverUrl.isNullOrEmpty() || token.isNullOrEmpty()) {@@ -140,6 +143,49 @@ class CoverContentProvider : ContentProvider() {}}+ // BookOrbit covers need a Bearer header and its refresh tokens are single+ // use, so they come through the app's loopback proxy, which owns the+ // session. Nothing here touches the tokens.+ private fun fetchViaBookOrbitProxy(+ context: android.content.Context,+ prefs: android.content.SharedPreferences,+ itemId: String,+ ): File? {+ val port = try {+ prefs.getLong("flutter.bookorbit_proxy_port", 0L)+ } catch (e: ClassCastException) {+ 0L+ }+ val secret = prefs.getString("flutter.bookorbit_proxy_secret", null)+ if (port <= 0L || secret.isNullOrEmpty()) {+ Log.w(TAG, "BookOrbit proxy not set up - cannot fetch cover")+ return null+ }+ val cacheDir = File(context.cacheDir, "aa_covers")+ if (!cacheDir.exists()) cacheDir.mkdirs()+ val cacheFile = File(cacheDir, "$itemId.jpg")+ val connection = URL("http://127.0.0.1:$port/$secret/api/v1/books/$itemId/cover?medium=audio")+ .openConnection() as HttpURLConnection+ connection.connectTimeout = 3000+ connection.readTimeout = 8000+ try {+ if (connection.responseCode != 200) {+ Log.w(TAG, "BookOrbit cover fetch failed: HTTP ${connection.responseCode} for $itemId")+ return null+ }+ connection.inputStream.use { input ->+ cacheFile.outputStream().use { output -> input.copyTo(output) }+ }+ } catch (e: Exception) {+ Log.w(TAG, "BookOrbit cover fetch error for $itemId: ${e.message}")+ cacheFile.delete()+ return null+ } finally {+ connection.disconnect()+ }+ return if (cacheFile.length() > 0) cacheFile else null+ }+private fun fetchCover(serverUrl: String,itemId: String,diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arbindex 22588e8a..0fa89439 100644--- a/lib/l10n/app_en.arb+++ b/lib/l10n/app_en.arb@@ -5079,11 +5079,48 @@"keepScreenOnPlayerSubtitle": "The screen stays on while the player is open","keepScreenOnCarMode": "Keep the screen on in car mode","keepScreenOnCarModeSubtitle": "The screen stays on while car mode is open",+ "loginServerType": "Server type",+ "authBookOrbitDefaultPassword": "This account still has its default password. Change it in BookOrbit, then sign in again.",+ "authServerIsBookOrbit": "This is a BookOrbit server. Choose BookOrbit above the server address.",+ "authServerIsAudiobookshelf": "This is an Audiobookshelf server. Choose Audiobookshelf above the server address.",+ "castNotAvailableBookOrbit": "Casting is not available with BookOrbit servers",+ "loginMagicLink": "Magic link",+ "loginMagicLinkDescription": "Sign in with a BookOrbit magic link instead of a password.",+ "collectionPublicTitle": "Public",+ "collectionPublicSubtitle": "Everyone on this server can see this collection",+ "loginSignInWithProvider": "Sign in with {provider}",+ "@loginSignInWithProvider": {+ "placeholders": {+ "provider": {+ "type": "String"+ }+ }+ },+ "loginSignInWithSso": "Sign in with SSO",+ "loginChooseSsoProvider": "Choose how to sign in",+ "loginRedirectUriBookOrbit": "Redirect URI: bookorbit://oauth2-callback",+ "readStatusTitle": "Reading status",+ "readStatusHint": "BookOrbit keeps a status you pick here until you change it.",+ "readStatusUnread": "Unread",+ "readStatusWantToRead": "Want to read",+ "readStatusReading": "Reading",+ "readStatusOnHold": "On hold",+ "readStatusRereading": "Rereading",+ "readStatusRead": "Read",+ "readStatusSkimmed": "Skimmed",+ "readStatusAbandoned": "Abandoned",+ "personalNoteTitle": "Your note",+ "personalNoteAdd": "Add a private note",+ "personalNoteHint": "Only you can see this note.",+ "moreLikeThis": "More like this",+ "coverSlotAudiobook": "Audiobook cover",+ "coverSlotBook": "Book cover","cardButtonFill": "Button background","cardButtonFillSubtitle": "How the buttons on the player card are filled","cardButtonFillClear": "Clear","cardButtonFillSubtle": "Subtle","cardButtonFillSolid": "Solid",+ "loginBookOrbitPreview": "BookOrbit support is new. Playback, downloads and browsing work, but some screens may still look or act like Audiobookshelf. Follow the progress on GitHub, and let us know if something seems off.","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.",@@ -5096,5 +5133,10 @@"type": "String"}}- }+ },+ "comicReadingDirection": "Reading direction",+ "comicLeftToRight": "Left to right",+ "comicRightToLeft": "Right to left (manga)",+ "comicNeedsConnection": "This comic opens page by page from your server, so it needs a connection.",+ "comicNoPages": "No pages found in this comic."}diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dartindex 0366594a..cd9026ec 100644--- a/lib/l10n/app_localizations.dart+++ b/lib/l10n/app_localizations.dart@@ -15651,6 +15651,180 @@ abstract class AppLocalizations {/// **'The screen stays on while car mode is open'**String get keepScreenOnCarModeSubtitle;+ /// No description provided for @loginServerType.+ ///+ /// In en, this message translates to:+ /// **'Server type'**+ String get loginServerType;++ /// No description provided for @authBookOrbitDefaultPassword.+ ///+ /// In en, this message translates to:+ /// **'This account still has its default password. Change it in BookOrbit, then sign in again.'**+ String get authBookOrbitDefaultPassword;++ /// No description provided for @authServerIsBookOrbit.+ ///+ /// In en, this message translates to:+ /// **'This is a BookOrbit server. Choose BookOrbit above the server address.'**+ String get authServerIsBookOrbit;++ /// No description provided for @authServerIsAudiobookshelf.+ ///+ /// In en, this message translates to:+ /// **'This is an Audiobookshelf server. Choose Audiobookshelf above the server address.'**+ String get authServerIsAudiobookshelf;++ /// No description provided for @castNotAvailableBookOrbit.+ ///+ /// In en, this message translates to:+ /// **'Casting is not available with BookOrbit servers'**+ String get castNotAvailableBookOrbit;++ /// No description provided for @loginMagicLink.+ ///+ /// In en, this message translates to:+ /// **'Magic link'**+ String get loginMagicLink;++ /// No description provided for @loginMagicLinkDescription.+ ///+ /// In en, this message translates to:+ /// **'Sign in with a BookOrbit magic link instead of a password.'**+ String get loginMagicLinkDescription;++ /// No description provided for @collectionPublicTitle.+ ///+ /// In en, this message translates to:+ /// **'Public'**+ String get collectionPublicTitle;++ /// No description provided for @collectionPublicSubtitle.+ ///+ /// In en, this message translates to:+ /// **'Everyone on this server can see this collection'**+ String get collectionPublicSubtitle;++ /// No description provided for @loginSignInWithProvider.+ ///+ /// In en, this message translates to:+ /// **'Sign in with {provider}'**+ String loginSignInWithProvider(String provider);++ /// No description provided for @loginSignInWithSso.+ ///+ /// In en, this message translates to:+ /// **'Sign in with SSO'**+ String get loginSignInWithSso;++ /// No description provided for @loginChooseSsoProvider.+ ///+ /// In en, this message translates to:+ /// **'Choose how to sign in'**+ String get loginChooseSsoProvider;++ /// No description provided for @loginRedirectUriBookOrbit.+ ///+ /// In en, this message translates to:+ /// **'Redirect URI: bookorbit://oauth2-callback'**+ String get loginRedirectUriBookOrbit;++ /// No description provided for @readStatusTitle.+ ///+ /// In en, this message translates to:+ /// **'Reading status'**+ String get readStatusTitle;++ /// No description provided for @readStatusHint.+ ///+ /// In en, this message translates to:+ /// **'BookOrbit keeps a status you pick here until you change it.'**+ String get readStatusHint;++ /// No description provided for @readStatusUnread.+ ///+ /// In en, this message translates to:+ /// **'Unread'**+ String get readStatusUnread;++ /// No description provided for @readStatusWantToRead.+ ///+ /// In en, this message translates to:+ /// **'Want to read'**+ String get readStatusWantToRead;++ /// No description provided for @readStatusReading.+ ///+ /// In en, this message translates to:+ /// **'Reading'**+ String get readStatusReading;++ /// No description provided for @readStatusOnHold.+ ///+ /// In en, this message translates to:+ /// **'On hold'**+ String get readStatusOnHold;++ /// No description provided for @readStatusRereading.+ ///+ /// In en, this message translates to:+ /// **'Rereading'**+ String get readStatusRereading;++ /// No description provided for @readStatusRead.+ ///+ /// In en, this message translates to:+ /// **'Read'**+ String get readStatusRead;++ /// No description provided for @readStatusSkimmed.+ ///+ /// In en, this message translates to:+ /// **'Skimmed'**+ String get readStatusSkimmed;++ /// No description provided for @readStatusAbandoned.+ ///+ /// In en, this message translates to:+ /// **'Abandoned'**+ String get readStatusAbandoned;++ /// No description provided for @personalNoteTitle.+ ///+ /// In en, this message translates to:+ /// **'Your note'**+ String get personalNoteTitle;++ /// No description provided for @personalNoteAdd.+ ///+ /// In en, this message translates to:+ /// **'Add a private note'**+ String get personalNoteAdd;++ /// No description provided for @personalNoteHint.+ ///+ /// In en, this message translates to:+ /// **'Only you can see this note.'**+ String get personalNoteHint;++ /// No description provided for @moreLikeThis.+ ///+ /// In en, this message translates to:+ /// **'More like this'**+ String get moreLikeThis;++ /// No description provided for @coverSlotAudiobook.+ ///+ /// In en, this message translates to:+ /// **'Audiobook cover'**+ String get coverSlotAudiobook;++ /// No description provided for @coverSlotBook.+ ///+ /// In en, this message translates to:+ /// **'Book cover'**+ String get coverSlotBook;+/// No description provided for @cardButtonFill.////// In en, this message translates to:@@ -15681,6 +15855,12 @@ abstract class AppLocalizations {/// **'Solid'**String get cardButtonFillSolid;+ /// No description provided for @loginBookOrbitPreview.+ ///+ /// In en, this message translates to:+ /// **'BookOrbit support is new. Playback, downloads and browsing work, but some screens may still look or act like Audiobookshelf. Follow the progress on GitHub, and let us know if something seems off.'**+ String get loginBookOrbitPreview;+/// No description provided for @signedOutTapToSignIn.////// In en, this message translates to:@@ -15698,6 +15878,36 @@ abstract class AppLocalizations {/// 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);++ /// No description provided for @comicReadingDirection.+ ///+ /// In en, this message translates to:+ /// **'Reading direction'**+ String get comicReadingDirection;++ /// No description provided for @comicLeftToRight.+ ///+ /// In en, this message translates to:+ /// **'Left to right'**+ String get comicLeftToRight;++ /// No description provided for @comicRightToLeft.+ ///+ /// In en, this message translates to:+ /// **'Right to left (manga)'**+ String get comicRightToLeft;++ /// No description provided for @comicNeedsConnection.+ ///+ /// In en, this message translates to:+ /// **'This comic opens page by page from your server, so it needs a connection.'**+ String get comicNeedsConnection;++ /// No description provided for @comicNoPages.+ ///+ /// In en, this message translates to:+ /// **'No pages found in this comic.'**+ String get comicNoPages;}class _AppLocalizationsDelegatediff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dartindex 5f00d057..765234e3 100644--- a/lib/l10n/app_localizations_de.dart+++ b/lib/l10n/app_localizations_de.dart@@ -9205,6 +9205,103 @@ class AppLocalizationsDe extends AppLocalizations {String get keepScreenOnCarModeSubtitle =>'The screen stays on while car mode is open';+ @override+ String get loginServerType => 'Server type';++ @override+ String get authBookOrbitDefaultPassword =>+ 'This account still has its default password. Change it in BookOrbit, then sign in again.';++ @override+ String get authServerIsBookOrbit =>+ 'This is a BookOrbit server. Choose BookOrbit above the server address.';++ @override+ String get authServerIsAudiobookshelf =>+ 'This is an Audiobookshelf server. Choose Audiobookshelf above the server address.';++ @override+ String get castNotAvailableBookOrbit =>+ 'Casting is not available with BookOrbit servers';++ @override+ String get loginMagicLink => 'Magic link';++ @override+ String get loginMagicLinkDescription =>+ 'Sign in with a BookOrbit magic link instead of a password.';++ @override+ String get collectionPublicTitle => 'Public';++ @override+ String get collectionPublicSubtitle =>+ 'Everyone on this server can see this collection';++ @override+ String loginSignInWithProvider(String provider) {+ return 'Sign in with $provider';+ }++ @override+ String get loginSignInWithSso => 'Sign in with SSO';++ @override+ String get loginChooseSsoProvider => 'Choose how to sign in';++ @override+ String get loginRedirectUriBookOrbit =>+ 'Redirect URI: bookorbit://oauth2-callback';++ @override+ String get readStatusTitle => 'Reading status';++ @override+ String get readStatusHint =>+ 'BookOrbit keeps a status you pick here until you change it.';++ @override+ String get readStatusUnread => 'Unread';++ @override+ String get readStatusWantToRead => 'Want to read';++ @override+ String get readStatusReading => 'Reading';++ @override+ String get readStatusOnHold => 'On hold';++ @override+ String get readStatusRereading => 'Rereading';++ @override+ String get readStatusRead => 'Read';++ @override+ String get readStatusSkimmed => 'Skimmed';++ @override+ String get readStatusAbandoned => 'Abandoned';++ @override+ String get personalNoteTitle => 'Your note';++ @override+ String get personalNoteAdd => 'Add a private note';++ @override+ String get personalNoteHint => 'Only you can see this note.';++ @override+ String get moreLikeThis => 'More like this';++ @override+ String get coverSlotAudiobook => 'Audiobook cover';++ @override+ String get coverSlotBook => 'Book cover';+@overrideString get cardButtonFill => 'Button background';@@ -9221,6 +9318,10 @@ class AppLocalizationsDe extends AppLocalizations {@overrideString get cardButtonFillSolid => 'Solid';+ @override+ String get loginBookOrbitPreview =>+ 'BookOrbit support is new. Playback, downloads and browsing work, but some screens may still look or act like Audiobookshelf. Follow the progress on GitHub, and let us know if something seems off.';+@overrideString get signedOutTapToSignIn => 'Signed out. Tap to sign in again.';@@ -9232,4 +9333,20 @@ class AppLocalizationsDe extends AppLocalizations {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.';}++ @override+ String get comicReadingDirection => 'Reading direction';++ @override+ String get comicLeftToRight => 'Left to right';++ @override+ String get comicRightToLeft => 'Right to left (manga)';++ @override+ String get comicNeedsConnection =>+ 'This comic opens page by page from your server, so it needs a connection.';++ @override+ String get comicNoPages => 'No pages found in this comic.';}diff --git a/lib/l10n/app_localizations_el.dart b/lib/l10n/app_localizations_el.dartindex 7c349884..9bc92a1b 100644--- a/lib/l10n/app_localizations_el.dart+++ b/lib/l10n/app_localizations_el.dart@@ -9084,6 +9084,103 @@ class AppLocalizationsEl extends AppLocalizations {String get keepScreenOnCarModeSubtitle =>'The screen stays on while car mode is open';+ @override+ String get loginServerType => 'Server type';++ @override+ String get authBookOrbitDefaultPassword =>+ 'This account still has its default password. Change it in BookOrbit, then sign in again.';++ @override+ String get authServerIsBookOrbit =>+ 'This is a BookOrbit server. Choose BookOrbit above the server address.';++ @override+ String get authServerIsAudiobookshelf =>+ 'This is an Audiobookshelf server. Choose Audiobookshelf above the server address.';++ @override+ String get castNotAvailableBookOrbit =>+ 'Casting is not available with BookOrbit servers';++ @override+ String get loginMagicLink => 'Magic link';++ @override+ String get loginMagicLinkDescription =>+ 'Sign in with a BookOrbit magic link instead of a password.';++ @override+ String get collectionPublicTitle => 'Public';++ @override+ String get collectionPublicSubtitle =>+ 'Everyone on this server can see this collection';++ @override+ String loginSignInWithProvider(String provider) {+ return 'Sign in with $provider';+ }++ @override+ String get loginSignInWithSso => 'Sign in with SSO';++ @override+ String get loginChooseSsoProvider => 'Choose how to sign in';++ @override+ String get loginRedirectUriBookOrbit =>+ 'Redirect URI: bookorbit://oauth2-callback';++ @override+ String get readStatusTitle => 'Reading status';++ @override+ String get readStatusHint =>+ 'BookOrbit keeps a status you pick here until you change it.';++ @override+ String get readStatusUnread => 'Unread';++ @override+ String get readStatusWantToRead => 'Want to read';++ @override+ String get readStatusReading => 'Reading';++ @override+ String get readStatusOnHold => 'On hold';++ @override+ String get readStatusRereading => 'Rereading';++ @override+ String get readStatusRead => 'Read';++ @override+ String get readStatusSkimmed => 'Skimmed';++ @override+ String get readStatusAbandoned => 'Abandoned';++ @override+ String get personalNoteTitle => 'Your note';++ @override+ String get personalNoteAdd => 'Add a private note';++ @override+ String get personalNoteHint => 'Only you can see this note.';++ @override+ String get moreLikeThis => 'More like this';++ @override+ String get coverSlotAudiobook => 'Audiobook cover';++ @override+ String get coverSlotBook => 'Book cover';+@overrideString get cardButtonFill => 'Button background';@@ -9100,6 +9197,10 @@ class AppLocalizationsEl extends AppLocalizations {@overrideString get cardButtonFillSolid => 'Solid';+ @override+ String get loginBookOrbitPreview =>+ 'BookOrbit support is new. Playback, downloads and browsing work, but some screens may still look or act like Audiobookshelf. Follow the progress on GitHub, and let us know if something seems off.';+@overrideString get signedOutTapToSignIn => 'Signed out. Tap to sign in again.';@@ -9111,4 +9212,20 @@ class AppLocalizationsEl extends AppLocalizations {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.';}++ @override+ String get comicReadingDirection => 'Reading direction';++ @override+ String get comicLeftToRight => 'Left to right';++ @override+ String get comicRightToLeft => 'Right to left (manga)';++ @override+ String get comicNeedsConnection =>+ 'This comic opens page by page from your server, so it needs a connection.';++ @override+ String get comicNoPages => 'No pages found in this comic.';}diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dartindex ccf9acb0..935653bf 100644--- a/lib/l10n/app_localizations_en.dart+++ b/lib/l10n/app_localizations_en.dart@@ -9084,6 +9084,103 @@ class AppLocalizationsEn extends AppLocalizations {String get keepScreenOnCarModeSubtitle =>'The screen stays on while car mode is open';+ @override+ String get loginServerType => 'Server type';++ @override+ String get authBookOrbitDefaultPassword =>+ 'This account still has its default password. Change it in BookOrbit, then sign in again.';++ @override+ String get authServerIsBookOrbit =>+ 'This is a BookOrbit server. Choose BookOrbit above the server address.';++ @override+ String get authServerIsAudiobookshelf =>+ 'This is an Audiobookshelf server. Choose Audiobookshelf above the server address.';++ @override+ String get castNotAvailableBookOrbit =>+ 'Casting is not available with BookOrbit servers';++ @override+ String get loginMagicLink => 'Magic link';++ @override+ String get loginMagicLinkDescription =>+ 'Sign in with a BookOrbit magic link instead of a password.';++ @override+ String get collectionPublicTitle => 'Public';++ @override+ String get collectionPublicSubtitle =>+ 'Everyone on this server can see this collection';++ @override+ String loginSignInWithProvider(String provider) {+ return 'Sign in with $provider';+ }++ @override+ String get loginSignInWithSso => 'Sign in with SSO';++ @override+ String get loginChooseSsoProvider => 'Choose how to sign in';++ @override+ String get loginRedirectUriBookOrbit =>+ 'Redirect URI: bookorbit://oauth2-callback';++ @override+ String get readStatusTitle => 'Reading status';++ @override+ String get readStatusHint =>+ 'BookOrbit keeps a status you pick here until you change it.';++ @override+ String get readStatusUnread => 'Unread';++ @override+ String get readStatusWantToRead => 'Want to read';++ @override+ String get readStatusReading => 'Reading';++ @override+ String get readStatusOnHold => 'On hold';++ @override+ String get readStatusRereading => 'Rereading';++ @override+ String get readStatusRead => 'Read';++ @override+ String get readStatusSkimmed => 'Skimmed';++ @override+ String get readStatusAbandoned => 'Abandoned';++ @override+ String get personalNoteTitle => 'Your note';++ @override+ String get personalNoteAdd => 'Add a private note';++ @override+ String get personalNoteHint => 'Only you can see this note.';++ @override+ String get moreLikeThis => 'More like this';++ @override+ String get coverSlotAudiobook => 'Audiobook cover';++ @override+ String get coverSlotBook => 'Book cover';+@overrideString get cardButtonFill => 'Button background';@@ -9100,6 +9197,10 @@ class AppLocalizationsEn extends AppLocalizations {@overrideString get cardButtonFillSolid => 'Solid';+ @override+ String get loginBookOrbitPreview =>+ 'BookOrbit support is new. Playback, downloads and browsing work, but some screens may still look or act like Audiobookshelf. Follow the progress on GitHub, and let us know if something seems off.';+@overrideString get signedOutTapToSignIn => 'Signed out. Tap to sign in again.';@@ -9111,4 +9212,20 @@ class AppLocalizationsEn extends AppLocalizations {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.';}++ @override+ String get comicReadingDirection => 'Reading direction';++ @override+ String get comicLeftToRight => 'Left to right';++ @override+ String get comicRightToLeft => 'Right to left (manga)';++ @override+ String get comicNeedsConnection =>+ 'This comic opens page by page from your server, so it needs a connection.';++ @override+ String get comicNoPages => 'No pages found in this comic.';}diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dartindex 599a58fc..83b91bc0 100644--- a/lib/l10n/app_localizations_es.dart+++ b/lib/l10n/app_localizations_es.dart@@ -9086,6 +9086,103 @@ class AppLocalizationsEs extends AppLocalizations {String get keepScreenOnCarModeSubtitle =>'The screen stays on while car mode is open';+ @override+ String get loginServerType => 'Server type';++ @override+ String get authBookOrbitDefaultPassword =>+ 'This account still has its default password. Change it in BookOrbit, then sign in again.';++ @override+ String get authServerIsBookOrbit =>+ 'This is a BookOrbit server. Choose BookOrbit above the server address.';++ @override+ String get authServerIsAudiobookshelf =>+ 'This is an Audiobookshelf server. Choose Audiobookshelf above the server address.';++ @override+ String get castNotAvailableBookOrbit =>+ 'Casting is not available with BookOrbit servers';++ @override+ String get loginMagicLink => 'Magic link';++ @override+ String get loginMagicLinkDescription =>+ 'Sign in with a BookOrbit magic link instead of a password.';++ @override+ String get collectionPublicTitle => 'Public';++ @override+ String get collectionPublicSubtitle =>+ 'Everyone on this server can see this collection';++ @override+ String loginSignInWithProvider(String provider) {+ return 'Sign in with $provider';+ }++ @override+ String get loginSignInWithSso => 'Sign in with SSO';++ @override+ String get loginChooseSsoProvider => 'Choose how to sign in';++ @override+ String get loginRedirectUriBookOrbit =>+ 'Redirect URI: bookorbit://oauth2-callback';++ @override+ String get readStatusTitle => 'Reading status';++ @override+ String get readStatusHint =>+ 'BookOrbit keeps a status you pick here until you change it.';++ @override+ String get readStatusUnread => 'Unread';++ @override+ String get readStatusWantToRead => 'Want to read';++ @override+ String get readStatusReading => 'Reading';++ @override+ String get readStatusOnHold => 'On hold';++ @override+ String get readStatusRereading => 'Rereading';++ @override+ String get readStatusRead => 'Read';++ @override+ String get readStatusSkimmed => 'Skimmed';++ @override+ String get readStatusAbandoned => 'Abandoned';++ @override+ String get personalNoteTitle => 'Your note';++ @override+ String get personalNoteAdd => 'Add a private note';++ @override+ String get personalNoteHint => 'Only you can see this note.';++ @override+ String get moreLikeThis => 'More like this';++ @override+ String get coverSlotAudiobook => 'Audiobook cover';++ @override+ String get coverSlotBook => 'Book cover';+@overrideString get cardButtonFill => 'Button background';@@ -9102,6 +9199,10 @@ class AppLocalizationsEs extends AppLocalizations {@overrideString get cardButtonFillSolid => 'Solid';+ @override+ String get loginBookOrbitPreview =>+ 'BookOrbit support is new. Playback, downloads and browsing work, but some screens may still look or act like Audiobookshelf. Follow the progress on GitHub, and let us know if something seems off.';+@overrideString get signedOutTapToSignIn => 'Signed out. Tap to sign in again.';@@ -9113,4 +9214,20 @@ class AppLocalizationsEs extends AppLocalizations {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.';}++ @override+ String get comicReadingDirection => 'Reading direction';++ @override+ String get comicLeftToRight => 'Left to right';++ @override+ String get comicRightToLeft => 'Right to left (manga)';++ @override+ String get comicNeedsConnection =>+ 'This comic opens page by page from your server, so it needs a connection.';++ @override+ String get comicNoPages => 'No pages found in this comic.';}diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dartindex 0c3ae71c..f17e71ce 100644--- a/lib/l10n/app_localizations_fr.dart+++ b/lib/l10n/app_localizations_fr.dart@@ -9137,6 +9137,103 @@ class AppLocalizationsFr extends AppLocalizations {String get keepScreenOnCarModeSubtitle =>'The screen stays on while car mode is open';+ @override+ String get loginServerType => 'Server type';++ @override+ String get authBookOrbitDefaultPassword =>+ 'This account still has its default password. Change it in BookOrbit, then sign in again.';++ @override+ String get authServerIsBookOrbit =>+ 'This is a BookOrbit server. Choose BookOrbit above the server address.';++ @override+ String get authServerIsAudiobookshelf =>+ 'This is an Audiobookshelf server. Choose Audiobookshelf above the server address.';++ @override+ String get castNotAvailableBookOrbit =>+ 'Casting is not available with BookOrbit servers';++ @override+ String get loginMagicLink => 'Magic link';++ @override+ String get loginMagicLinkDescription =>+ 'Sign in with a BookOrbit magic link instead of a password.';++ @override+ String get collectionPublicTitle => 'Public';++ @override+ String get collectionPublicSubtitle =>+ 'Everyone on this server can see this collection';++ @override+ String loginSignInWithProvider(String provider) {+ return 'Sign in with $provider';+ }++ @override+ String get loginSignInWithSso => 'Sign in with SSO';++ @override+ String get loginChooseSsoProvider => 'Choose how to sign in';++ @override+ String get loginRedirectUriBookOrbit =>+ 'Redirect URI: bookorbit://oauth2-callback';++ @override+ String get readStatusTitle => 'Reading status';++ @override+ String get readStatusHint =>+ 'BookOrbit keeps a status you pick here until you change it.';++ @override+ String get readStatusUnread => 'Unread';++ @override+ String get readStatusWantToRead => 'Want to read';++ @override+ String get readStatusReading => 'Reading';++ @override+ String get readStatusOnHold => 'On hold';++ @override+ String get readStatusRereading => 'Rereading';++ @override+ String get readStatusRead => 'Read';++ @override+ String get readStatusSkimmed => 'Skimmed';++ @override+ String get readStatusAbandoned => 'Abandoned';++ @override+ String get personalNoteTitle => 'Your note';++ @override+ String get personalNoteAdd => 'Add a private note';++ @override+ String get personalNoteHint => 'Only you can see this note.';++ @override+ String get moreLikeThis => 'More like this';++ @override+ String get coverSlotAudiobook => 'Audiobook cover';++ @override+ String get coverSlotBook => 'Book cover';+@overrideString get cardButtonFill => 'Button background';@@ -9153,6 +9250,10 @@ class AppLocalizationsFr extends AppLocalizations {@overrideString get cardButtonFillSolid => 'Solid';+ @override+ String get loginBookOrbitPreview =>+ 'BookOrbit support is new. Playback, downloads and browsing work, but some screens may still look or act like Audiobookshelf. Follow the progress on GitHub, and let us know if something seems off.';+@overrideString get signedOutTapToSignIn => 'Signed out. Tap to sign in again.';@@ -9164,4 +9265,20 @@ class AppLocalizationsFr extends AppLocalizations {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.';}++ @override+ String get comicReadingDirection => 'Reading direction';++ @override+ String get comicLeftToRight => 'Left to right';++ @override+ String get comicRightToLeft => 'Right to left (manga)';++ @override+ String get comicNeedsConnection =>+ 'This comic opens page by page from your server, so it needs a connection.';++ @override+ String get comicNoPages => 'No pages found in this comic.';}diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dartindex ec0b6974..6bcdb3f3 100644--- a/lib/l10n/app_localizations_it.dart+++ b/lib/l10n/app_localizations_it.dart@@ -9084,6 +9084,103 @@ class AppLocalizationsIt extends AppLocalizations {String get keepScreenOnCarModeSubtitle =>'The screen stays on while car mode is open';+ @override+ String get loginServerType => 'Server type';++ @override+ String get authBookOrbitDefaultPassword =>+ 'This account still has its default password. Change it in BookOrbit, then sign in again.';++ @override+ String get authServerIsBookOrbit =>+ 'This is a BookOrbit server. Choose BookOrbit above the server address.';++ @override+ String get authServerIsAudiobookshelf =>+ 'This is an Audiobookshelf server. Choose Audiobookshelf above the server address.';++ @override+ String get castNotAvailableBookOrbit =>+ 'Casting is not available with BookOrbit servers';++ @override+ String get loginMagicLink => 'Magic link';++ @override+ String get loginMagicLinkDescription =>+ 'Sign in with a BookOrbit magic link instead of a password.';++ @override+ String get collectionPublicTitle => 'Public';++ @override+ String get collectionPublicSubtitle =>+ 'Everyone on this server can see this collection';++ @override+ String loginSignInWithProvider(String provider) {+ return 'Sign in with $provider';+ }++ @override+ String get loginSignInWithSso => 'Sign in with SSO';++ @override+ String get loginChooseSsoProvider => 'Choose how to sign in';++ @override+ String get loginRedirectUriBookOrbit =>+ 'Redirect URI: bookorbit://oauth2-callback';++ @override+ String get readStatusTitle => 'Reading status';++ @override+ String get readStatusHint =>+ 'BookOrbit keeps a status you pick here until you change it.';++ @override+ String get readStatusUnread => 'Unread';++ @override+ String get readStatusWantToRead => 'Want to read';++ @override+ String get readStatusReading => 'Reading';++ @override+ String get readStatusOnHold => 'On hold';++ @override+ String get readStatusRereading => 'Rereading';++ @override+ String get readStatusRead => 'Read';++ @override+ String get readStatusSkimmed => 'Skimmed';++ @override+ String get readStatusAbandoned => 'Abandoned';++ @override+ String get personalNoteTitle => 'Your note';++ @override+ String get personalNoteAdd => 'Add a private note';++ @override+ String get personalNoteHint => 'Only you can see this note.';++ @override+ String get moreLikeThis => 'More like this';++ @override+ String get coverSlotAudiobook => 'Audiobook cover';++ @override+ String get coverSlotBook => 'Book cover';+@overrideString get cardButtonFill => 'Button background';@@ -9100,6 +9197,10 @@ class AppLocalizationsIt extends AppLocalizations {@overrideString get cardButtonFillSolid => 'Solid';+ @override+ String get loginBookOrbitPreview =>+ 'BookOrbit support is new. Playback, downloads and browsing work, but some screens may still look or act like Audiobookshelf. Follow the progress on GitHub, and let us know if something seems off.';+@overrideString get signedOutTapToSignIn => 'Signed out. Tap to sign in again.';@@ -9111,4 +9212,20 @@ class AppLocalizationsIt extends AppLocalizations {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.';}++ @override+ String get comicReadingDirection => 'Reading direction';++ @override+ String get comicLeftToRight => 'Left to right';++ @override+ String get comicRightToLeft => 'Right to left (manga)';++ @override+ String get comicNeedsConnection =>+ 'This comic opens page by page from your server, so it needs a connection.';++ @override+ String get comicNoPages => 'No pages found in this comic.';}diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dartindex 605e03a4..d69dc138 100644--- a/lib/l10n/app_localizations_ja.dart+++ b/lib/l10n/app_localizations_ja.dart@@ -9084,6 +9084,103 @@ class AppLocalizationsJa extends AppLocalizations {String get keepScreenOnCarModeSubtitle =>'The screen stays on while car mode is open';+ @override+ String get loginServerType => 'Server type';++ @override+ String get authBookOrbitDefaultPassword =>+ 'This account still has its default password. Change it in BookOrbit, then sign in again.';++ @override+ String get authServerIsBookOrbit =>+ 'This is a BookOrbit server. Choose BookOrbit above the server address.';++ @override+ String get authServerIsAudiobookshelf =>+ 'This is an Audiobookshelf server. Choose Audiobookshelf above the server address.';++ @override+ String get castNotAvailableBookOrbit =>+ 'Casting is not available with BookOrbit servers';++ @override+ String get loginMagicLink => 'Magic link';++ @override+ String get loginMagicLinkDescription =>+ 'Sign in with a BookOrbit magic link instead of a password.';++ @override+ String get collectionPublicTitle => 'Public';++ @override+ String get collectionPublicSubtitle =>+ 'Everyone on this server can see this collection';++ @override+ String loginSignInWithProvider(String provider) {+ return 'Sign in with $provider';+ }++ @override+ String get loginSignInWithSso => 'Sign in with SSO';++ @override+ String get loginChooseSsoProvider => 'Choose how to sign in';++ @override+ String get loginRedirectUriBookOrbit =>+ 'Redirect URI: bookorbit://oauth2-callback';++ @override+ String get readStatusTitle => 'Reading status';++ @override+ String get readStatusHint =>+ 'BookOrbit keeps a status you pick here until you change it.';++ @override+ String get readStatusUnread => 'Unread';++ @override+ String get readStatusWantToRead => 'Want to read';++ @override+ String get readStatusReading => 'Reading';++ @override+ String get readStatusOnHold => 'On hold';++ @override+ String get readStatusRereading => 'Rereading';++ @override+ String get readStatusRead => 'Read';++ @override+ String get readStatusSkimmed => 'Skimmed';++ @override+ String get readStatusAbandoned => 'Abandoned';++ @override+ String get personalNoteTitle => 'Your note';++ @override+ String get personalNoteAdd => 'Add a private note';++ @override+ String get personalNoteHint => 'Only you can see this note.';++ @override+ String get moreLikeThis => 'More like this';++ @override+ String get coverSlotAudiobook => 'Audiobook cover';++ @override+ String get coverSlotBook => 'Book cover';+@overrideString get cardButtonFill => 'Button background';@@ -9100,6 +9197,10 @@ class AppLocalizationsJa extends AppLocalizations {@overrideString get cardButtonFillSolid => 'Solid';+ @override+ String get loginBookOrbitPreview =>+ 'BookOrbit support is new. Playback, downloads and browsing work, but some screens may still look or act like Audiobookshelf. Follow the progress on GitHub, and let us know if something seems off.';+@overrideString get signedOutTapToSignIn => 'Signed out. Tap to sign in again.';@@ -9111,4 +9212,20 @@ class AppLocalizationsJa extends AppLocalizations {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.';}++ @override+ String get comicReadingDirection => 'Reading direction';++ @override+ String get comicLeftToRight => 'Left to right';++ @override+ String get comicRightToLeft => 'Right to left (manga)';++ @override+ String get comicNeedsConnection =>+ 'This comic opens page by page from your server, so it needs a connection.';++ @override+ String get comicNoPages => 'No pages found in this comic.';}diff --git a/lib/l10n/app_localizations_no.dart b/lib/l10n/app_localizations_no.dartindex fff06c4b..9b756e7c 100644--- a/lib/l10n/app_localizations_no.dart+++ b/lib/l10n/app_localizations_no.dart@@ -9084,6 +9084,103 @@ class AppLocalizationsNo extends AppLocalizations {String get keepScreenOnCarModeSubtitle =>'The screen stays on while car mode is open';+ @override+ String get loginServerType => 'Server type';++ @override+ String get authBookOrbitDefaultPassword =>+ 'This account still has its default password. Change it in BookOrbit, then sign in again.';++ @override+ String get authServerIsBookOrbit =>+ 'This is a BookOrbit server. Choose BookOrbit above the server address.';++ @override+ String get authServerIsAudiobookshelf =>+ 'This is an Audiobookshelf server. Choose Audiobookshelf above the server address.';++ @override+ String get castNotAvailableBookOrbit =>+ 'Casting is not available with BookOrbit servers';++ @override+ String get loginMagicLink => 'Magic link';++ @override+ String get loginMagicLinkDescription =>+ 'Sign in with a BookOrbit magic link instead of a password.';++ @override+ String get collectionPublicTitle => 'Public';++ @override+ String get collectionPublicSubtitle =>+ 'Everyone on this server can see this collection';++ @override+ String loginSignInWithProvider(String provider) {+ return 'Sign in with $provider';+ }++ @override+ String get loginSignInWithSso => 'Sign in with SSO';++ @override+ String get loginChooseSsoProvider => 'Choose how to sign in';++ @override+ String get loginRedirectUriBookOrbit =>+ 'Redirect URI: bookorbit://oauth2-callback';++ @override+ String get readStatusTitle => 'Reading status';++ @override+ String get readStatusHint =>+ 'BookOrbit keeps a status you pick here until you change it.';++ @override+ String get readStatusUnread => 'Unread';++ @override+ String get readStatusWantToRead => 'Want to read';++ @override+ String get readStatusReading => 'Reading';++ @override+ String get readStatusOnHold => 'On hold';++ @override+ String get readStatusRereading => 'Rereading';++ @override+ String get readStatusRead => 'Read';++ @override+ String get readStatusSkimmed => 'Skimmed';++ @override+ String get readStatusAbandoned => 'Abandoned';++ @override+ String get personalNoteTitle => 'Your note';++ @override+ String get personalNoteAdd => 'Add a private note';++ @override+ String get personalNoteHint => 'Only you can see this note.';++ @override+ String get moreLikeThis => 'More like this';++ @override+ String get coverSlotAudiobook => 'Audiobook cover';++ @override+ String get coverSlotBook => 'Book cover';+@overrideString get cardButtonFill => 'Button background';@@ -9100,6 +9197,10 @@ class AppLocalizationsNo extends AppLocalizations {@overrideString get cardButtonFillSolid => 'Solid';+ @override+ String get loginBookOrbitPreview =>+ 'BookOrbit support is new. Playback, downloads and browsing work, but some screens may still look or act like Audiobookshelf. Follow the progress on GitHub, and let us know if something seems off.';+@overrideString get signedOutTapToSignIn => 'Signed out. Tap to sign in again.';@@ -9111,4 +9212,20 @@ class AppLocalizationsNo extends AppLocalizations {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.';}++ @override+ String get comicReadingDirection => 'Reading direction';++ @override+ String get comicLeftToRight => 'Left to right';++ @override+ String get comicRightToLeft => 'Right to left (manga)';++ @override+ String get comicNeedsConnection =>+ 'This comic opens page by page from your server, so it needs a connection.';++ @override+ String get comicNoPages => 'No pages found in this comic.';}diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dartindex 70921bb3..f40a738d 100644--- a/lib/l10n/app_localizations_pt.dart+++ b/lib/l10n/app_localizations_pt.dart@@ -9084,6 +9084,103 @@ class AppLocalizationsPt extends AppLocalizations {String get keepScreenOnCarModeSubtitle =>'The screen stays on while car mode is open';+ @override+ String get loginServerType => 'Server type';++ @override+ String get authBookOrbitDefaultPassword =>+ 'This account still has its default password. Change it in BookOrbit, then sign in again.';++ @override+ String get authServerIsBookOrbit =>+ 'This is a BookOrbit server. Choose BookOrbit above the server address.';++ @override+ String get authServerIsAudiobookshelf =>+ 'This is an Audiobookshelf server. Choose Audiobookshelf above the server address.';++ @override+ String get castNotAvailableBookOrbit =>+ 'Casting is not available with BookOrbit servers';++ @override+ String get loginMagicLink => 'Magic link';++ @override+ String get loginMagicLinkDescription =>+ 'Sign in with a BookOrbit magic link instead of a password.';++ @override+ String get collectionPublicTitle => 'Public';++ @override+ String get collectionPublicSubtitle =>+ 'Everyone on this server can see this collection';++ @override+ String loginSignInWithProvider(String provider) {+ return 'Sign in with $provider';+ }++ @override+ String get loginSignInWithSso => 'Sign in with SSO';++ @override+ String get loginChooseSsoProvider => 'Choose how to sign in';++ @override+ String get loginRedirectUriBookOrbit =>+ 'Redirect URI: bookorbit://oauth2-callback';++ @override+ String get readStatusTitle => 'Reading status';++ @override+ String get readStatusHint =>+ 'BookOrbit keeps a status you pick here until you change it.';++ @override+ String get readStatusUnread => 'Unread';++ @override+ String get readStatusWantToRead => 'Want to read';++ @override+ String get readStatusReading => 'Reading';++ @override+ String get readStatusOnHold => 'On hold';++ @override+ String get readStatusRereading => 'Rereading';++ @override+ String get readStatusRead => 'Read';++ @override+ String get readStatusSkimmed => 'Skimmed';++ @override+ String get readStatusAbandoned => 'Abandoned';++ @override+ String get personalNoteTitle => 'Your note';++ @override+ String get personalNoteAdd => 'Add a private note';++ @override+ String get personalNoteHint => 'Only you can see this note.';++ @override+ String get moreLikeThis => 'More like this';++ @override+ String get coverSlotAudiobook => 'Audiobook cover';++ @override+ String get coverSlotBook => 'Book cover';+@overrideString get cardButtonFill => 'Button background';@@ -9100,6 +9197,10 @@ class AppLocalizationsPt extends AppLocalizations {@overrideString get cardButtonFillSolid => 'Solid';+ @override+ String get loginBookOrbitPreview =>+ 'BookOrbit support is new. Playback, downloads and browsing work, but some screens may still look or act like Audiobookshelf. Follow the progress on GitHub, and let us know if something seems off.';+@overrideString get signedOutTapToSignIn => 'Signed out. Tap to sign in again.';@@ -9111,4 +9212,20 @@ class AppLocalizationsPt extends AppLocalizations {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.';}++ @override+ String get comicReadingDirection => 'Reading direction';++ @override+ String get comicLeftToRight => 'Left to right';++ @override+ String get comicRightToLeft => 'Right to left (manga)';++ @override+ String get comicNeedsConnection =>+ 'This comic opens page by page from your server, so it needs a connection.';++ @override+ String get comicNoPages => 'No pages found in this comic.';}diff --git a/lib/l10n/app_localizations_ro.dart b/lib/l10n/app_localizations_ro.dartindex e9021345..2244ca92 100644--- a/lib/l10n/app_localizations_ro.dart+++ b/lib/l10n/app_localizations_ro.dart@@ -9084,6 +9084,103 @@ class AppLocalizationsRo extends AppLocalizations {String get keepScreenOnCarModeSubtitle =>'The screen stays on while car mode is open';+ @override+ String get loginServerType => 'Server type';++ @override+ String get authBookOrbitDefaultPassword =>+ 'This account still has its default password. Change it in BookOrbit, then sign in again.';++ @override+ String get authServerIsBookOrbit =>+ 'This is a BookOrbit server. Choose BookOrbit above the server address.';++ @override+ String get authServerIsAudiobookshelf =>+ 'This is an Audiobookshelf server. Choose Audiobookshelf above the server address.';++ @override+ String get castNotAvailableBookOrbit =>+ 'Casting is not available with BookOrbit servers';++ @override+ String get loginMagicLink => 'Magic link';++ @override+ String get loginMagicLinkDescription =>+ 'Sign in with a BookOrbit magic link instead of a password.';++ @override+ String get collectionPublicTitle => 'Public';++ @override+ String get collectionPublicSubtitle =>+ 'Everyone on this server can see this collection';++ @override+ String loginSignInWithProvider(String provider) {+ return 'Sign in with $provider';+ }++ @override+ String get loginSignInWithSso => 'Sign in with SSO';++ @override+ String get loginChooseSsoProvider => 'Choose how to sign in';++ @override+ String get loginRedirectUriBookOrbit =>+ 'Redirect URI: bookorbit://oauth2-callback';++ @override+ String get readStatusTitle => 'Reading status';++ @override+ String get readStatusHint =>+ 'BookOrbit keeps a status you pick here until you change it.';++ @override+ String get readStatusUnread => 'Unread';++ @override+ String get readStatusWantToRead => 'Want to read';++ @override+ String get readStatusReading => 'Reading';++ @override+ String get readStatusOnHold => 'On hold';++ @override+ String get readStatusRereading => 'Rereading';++ @override+ String get readStatusRead => 'Read';++ @override+ String get readStatusSkimmed => 'Skimmed';++ @override+ String get readStatusAbandoned => 'Abandoned';++ @override+ String get personalNoteTitle => 'Your note';++ @override+ String get personalNoteAdd => 'Add a private note';++ @override+ String get personalNoteHint => 'Only you can see this note.';++ @override+ String get moreLikeThis => 'More like this';++ @override+ String get coverSlotAudiobook => 'Audiobook cover';++ @override+ String get coverSlotBook => 'Book cover';+@overrideString get cardButtonFill => 'Button background';@@ -9100,6 +9197,10 @@ class AppLocalizationsRo extends AppLocalizations {@overrideString get cardButtonFillSolid => 'Solid';+ @override+ String get loginBookOrbitPreview =>+ 'BookOrbit support is new. Playback, downloads and browsing work, but some screens may still look or act like Audiobookshelf. Follow the progress on GitHub, and let us know if something seems off.';+@overrideString get signedOutTapToSignIn => 'Signed out. Tap to sign in again.';@@ -9111,4 +9212,20 @@ class AppLocalizationsRo extends AppLocalizations {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.';}++ @override+ String get comicReadingDirection => 'Reading direction';++ @override+ String get comicLeftToRight => 'Left to right';++ @override+ String get comicRightToLeft => 'Right to left (manga)';++ @override+ String get comicNeedsConnection =>+ 'This comic opens page by page from your server, so it needs a connection.';++ @override+ String get comicNoPages => 'No pages found in this comic.';}diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dartindex 36d4f22f..d1ac132d 100644--- a/lib/l10n/app_localizations_ru.dart+++ b/lib/l10n/app_localizations_ru.dart@@ -9089,6 +9089,103 @@ class AppLocalizationsRu extends AppLocalizations {String get keepScreenOnCarModeSubtitle =>'The screen stays on while car mode is open';+ @override+ String get loginServerType => 'Server type';++ @override+ String get authBookOrbitDefaultPassword =>+ 'This account still has its default password. Change it in BookOrbit, then sign in again.';++ @override+ String get authServerIsBookOrbit =>+ 'This is a BookOrbit server. Choose BookOrbit above the server address.';++ @override+ String get authServerIsAudiobookshelf =>+ 'This is an Audiobookshelf server. Choose Audiobookshelf above the server address.';++ @override+ String get castNotAvailableBookOrbit =>+ 'Casting is not available with BookOrbit servers';++ @override+ String get loginMagicLink => 'Magic link';++ @override+ String get loginMagicLinkDescription =>+ 'Sign in with a BookOrbit magic link instead of a password.';++ @override+ String get collectionPublicTitle => 'Public';++ @override+ String get collectionPublicSubtitle =>+ 'Everyone on this server can see this collection';++ @override+ String loginSignInWithProvider(String provider) {+ return 'Sign in with $provider';+ }++ @override+ String get loginSignInWithSso => 'Sign in with SSO';++ @override+ String get loginChooseSsoProvider => 'Choose how to sign in';++ @override+ String get loginRedirectUriBookOrbit =>+ 'Redirect URI: bookorbit://oauth2-callback';++ @override+ String get readStatusTitle => 'Reading status';++ @override+ String get readStatusHint =>+ 'BookOrbit keeps a status you pick here until you change it.';++ @override+ String get readStatusUnread => 'Unread';++ @override+ String get readStatusWantToRead => 'Want to read';++ @override+ String get readStatusReading => 'Reading';++ @override+ String get readStatusOnHold => 'On hold';++ @override+ String get readStatusRereading => 'Rereading';++ @override+ String get readStatusRead => 'Read';++ @override+ String get readStatusSkimmed => 'Skimmed';++ @override+ String get readStatusAbandoned => 'Abandoned';++ @override+ String get personalNoteTitle => 'Your note';++ @override+ String get personalNoteAdd => 'Add a private note';++ @override+ String get personalNoteHint => 'Only you can see this note.';++ @override+ String get moreLikeThis => 'More like this';++ @override+ String get coverSlotAudiobook => 'Audiobook cover';++ @override+ String get coverSlotBook => 'Book cover';+@overrideString get cardButtonFill => 'Button background';@@ -9105,6 +9202,10 @@ class AppLocalizationsRu extends AppLocalizations {@overrideString get cardButtonFillSolid => 'Solid';+ @override+ String get loginBookOrbitPreview =>+ 'BookOrbit support is new. Playback, downloads and browsing work, but some screens may still look or act like Audiobookshelf. Follow the progress on GitHub, and let us know if something seems off.';+@overrideString get signedOutTapToSignIn => 'Signed out. Tap to sign in again.';@@ -9116,4 +9217,20 @@ class AppLocalizationsRu extends AppLocalizations {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.';}++ @override+ String get comicReadingDirection => 'Reading direction';++ @override+ String get comicLeftToRight => 'Left to right';++ @override+ String get comicRightToLeft => 'Right to left (manga)';++ @override+ String get comicNeedsConnection =>+ 'This comic opens page by page from your server, so it needs a connection.';++ @override+ String get comicNoPages => 'No pages found in this comic.';}diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dartindex f2118c40..ef3daffa 100644--- a/lib/l10n/app_localizations_zh.dart+++ b/lib/l10n/app_localizations_zh.dart@@ -8992,6 +8992,103 @@ class AppLocalizationsZh extends AppLocalizations {String get keepScreenOnCarModeSubtitle =>'The screen stays on while car mode is open';+ @override+ String get loginServerType => 'Server type';++ @override+ String get authBookOrbitDefaultPassword =>+ 'This account still has its default password. Change it in BookOrbit, then sign in again.';++ @override+ String get authServerIsBookOrbit =>+ 'This is a BookOrbit server. Choose BookOrbit above the server address.';++ @override+ String get authServerIsAudiobookshelf =>+ 'This is an Audiobookshelf server. Choose Audiobookshelf above the server address.';++ @override+ String get castNotAvailableBookOrbit =>+ 'Casting is not available with BookOrbit servers';++ @override+ String get loginMagicLink => 'Magic link';++ @override+ String get loginMagicLinkDescription =>+ 'Sign in with a BookOrbit magic link instead of a password.';++ @override+ String get collectionPublicTitle => 'Public';++ @override+ String get collectionPublicSubtitle =>+ 'Everyone on this server can see this collection';++ @override+ String loginSignInWithProvider(String provider) {+ return 'Sign in with $provider';+ }++ @override+ String get loginSignInWithSso => 'Sign in with SSO';++ @override+ String get loginChooseSsoProvider => 'Choose how to sign in';++ @override+ String get loginRedirectUriBookOrbit =>+ 'Redirect URI: bookorbit://oauth2-callback';++ @override+ String get readStatusTitle => 'Reading status';++ @override+ String get readStatusHint =>+ 'BookOrbit keeps a status you pick here until you change it.';++ @override+ String get readStatusUnread => 'Unread';++ @override+ String get readStatusWantToRead => 'Want to read';++ @override+ String get readStatusReading => 'Reading';++ @override+ String get readStatusOnHold => 'On hold';++ @override+ String get readStatusRereading => 'Rereading';++ @override+ String get readStatusRead => 'Read';++ @override+ String get readStatusSkimmed => 'Skimmed';++ @override+ String get readStatusAbandoned => 'Abandoned';++ @override+ String get personalNoteTitle => 'Your note';++ @override+ String get personalNoteAdd => 'Add a private note';++ @override+ String get personalNoteHint => 'Only you can see this note.';++ @override+ String get moreLikeThis => 'More like this';++ @override+ String get coverSlotAudiobook => 'Audiobook cover';++ @override+ String get coverSlotBook => 'Book cover';+@overrideString get cardButtonFill => 'Button background';@@ -9008,6 +9105,10 @@ class AppLocalizationsZh extends AppLocalizations {@overrideString get cardButtonFillSolid => 'Solid';+ @override+ String get loginBookOrbitPreview =>+ 'BookOrbit support is new. Playback, downloads and browsing work, but some screens may still look or act like Audiobookshelf. Follow the progress on GitHub, and let us know if something seems off.';+@overrideString get signedOutTapToSignIn => 'Signed out. Tap to sign in again.';@@ -9019,4 +9120,20 @@ class AppLocalizationsZh extends AppLocalizations {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.';}++ @override+ String get comicReadingDirection => 'Reading direction';++ @override+ String get comicLeftToRight => 'Left to right';++ @override+ String get comicRightToLeft => 'Right to left (manga)';++ @override+ String get comicNeedsConnection =>+ 'This comic opens page by page from your server, so it needs a connection.';++ @override+ String get comicNoPages => 'No pages found in this comic.';}diff --git a/lib/providers/_lp_core.dart b/lib/providers/_lp_core.dartindex 50fa00d4..07d2572d 100644--- a/lib/providers/_lp_core.dart+++ b/lib/providers/_lp_core.dart@@ -1396,6 +1396,43 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {_healthCheckTimer = null;}+ /// BookOrbit pushes no progress events, so while the app is open the book+ /// sitting paused in the player is checked against the server instead, and+ /// a newer position from another device goes through the same handler the+ /// Audiobookshelf socket feeds.+ void _startBookOrbitPoll() {+ _bookOrbitPollTimer?.cancel();+ _bookOrbitPollTimer = null;+ if (_auth?.isBookOrbit != true) return;+ if (_isBackgrounded || _readerQuiet || PlayerSettings.einkMode) return;+ _bookOrbitPollTimer = Timer.periodic(+ const Duration(seconds: 30), (_) => _pollPausedBookProgress());+ }++ void _stopBookOrbitPoll() {+ _bookOrbitPollTimer?.cancel();+ _bookOrbitPollTimer = null;+ }++ Future<void> _pollPausedBookProgress() async {+ final api = _api;+ if (api == null || !api.isBookOrbit || isOffline) return;+ final player = AudioPlayerService();+ final itemId = player.currentItemId;+ if (!player.hasBook || player.isPlaying || itemId == null) return;+ if (player.currentEpisodeId != null) return;+ try {+ final mp = await api.getItemProgress(itemId);+ if (mp == null || player.isPlaying || player.currentItemId != itemId) return;+ final serverUpd = (mp['lastUpdate'] as num?)?.toInt() ?? 0;+ if (serverUpd <= await ProgressSyncService().getSavedTimestamp(itemId)) return;+ debugPrint('[Sync] BookOrbit has a newer position for the paused book');+ _onRemoteProgressUpdated(mp);+ } catch (e) {+ debugPrint('[Sync] BookOrbit progress poll failed: $e');+ }+ }+// ── Battery-saving lifecycle ──void onAppBackgrounded() {@@ -1403,6 +1440,7 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {_backgroundedAt = DateTime.now();_stopServerPingTimer();_stopHealthCheckTimer();+ _stopBookOrbitPoll();if (!AudioPlayerService().isPlaying) {_stopLocalProbeTimer();}@@ -1440,6 +1478,7 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {debugPrint('[Library] Reader open - quieting live work');_stopServerPingTimer();_stopHealthCheckTimer();+ _stopBookOrbitPoll();if (!AudioPlayerService().isPlaying) _stopLocalProbeTimer();_softDisconnectSocket();return;@@ -1461,6 +1500,7 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {debugPrint('[Library] E-ink mode on - quieting live work');_stopServerPingTimer();_stopHealthCheckTimer();+ _stopBookOrbitPoll();if (!AudioPlayerService().isPlaying) _stopLocalProbeTimer();_softDisconnectSocket();return;@@ -1474,7 +1514,9 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {/// and awake. [quietSince] is when live work stopped, so a long gap can/// replay what the socket would have delivered.void _resumeLiveWork({DateTime? quietSince}) {+ if (_auth?.isBookOrbit == true) unawaited(_api?.ensureMediaReady());_softReconnectSocket();+ _startBookOrbitPoll();if (_networkOffline && _deviceHasConnectivity && !_manualOffline) {_startServerPingTimer();} else if (!_networkOffline && !_manualOffline) {@@ -1491,6 +1533,10 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {: DateTime.now().difference(quietSince);if (away != null && away > const Duration(seconds: 30)) {_catchUpAfterBackground();+ if (_auth?.isBookOrbit == true) {+ unawaited(_pollPausedBookProgress());+ unawaited(_catchUpRemoteProgress());+ }}}}@@ -2104,6 +2150,7 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {Future<Map<String, dynamic>?> createPlaylist(String name) async {if (_api == null || _selectedLibraryId == null) return null;+ if (_api!.isBookOrbit) return createCollection(name);final result = await _api!.createPlaylist(_selectedLibraryId!, name);if (result != null) {_playlists = [..._playlists, result];@@ -2118,6 +2165,7 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {String? episodeId,}) async {if (_api == null) return false;+ if (_api!.isBookOrbit) return addToCollection(playlistId, libraryItemId);final updated = await _api!.addItemToPlaylist(playlistId, libraryItemId, episodeId: episodeId,);@@ -2134,6 +2182,7 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {String? episodeId,}) async {if (_api == null) return false;+ if (_api!.isBookOrbit) return removeFromCollection(playlistId, libraryItemId);final updated = await _api!.removeItemFromPlaylist(playlistId, libraryItemId, episodeId: episodeId,);@@ -2165,6 +2214,7 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {Future<bool> deletePlaylist(String playlistId) async {if (_api == null) return false;+ if (_api!.isBookOrbit) return await deleteCollection(playlistId) == 200;final ok = await _api!.deletePlaylist(playlistId);if (ok) {_playlists = _playlists.where((p) => (p as Map)['id'] != playlistId).toList();@@ -2238,6 +2288,13 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {return false;}+ Future<bool> setCollectionPublic(String collectionId, bool isPublic) async {+ if (_api == null) return false;+ final ok = await _api!.setCollectionPublic(collectionId, isPublic);+ if (ok) await _doLoadCollections();+ return ok;+ }+Future<bool> reorderCollectionBooks(String collectionId,List<String> bookIds,diff --git a/lib/providers/_lp_state.dart b/lib/providers/_lp_state.dartindex 50720e1d..4abde298 100644--- a/lib/providers/_lp_state.dart+++ b/lib/providers/_lp_state.dart@@ -87,6 +87,7 @@ mixin _StateMixin on ChangeNotifier {bool _isReconnecting = false;Timer? _serverPingTimer;Timer? _healthCheckTimer;+ Timer? _bookOrbitPollTimer;Timer? _localProbeTimer;int _localProbeFailures = 0;DateTime? _localLastReachableAt;diff --git a/lib/providers/auth_provider.dart b/lib/providers/auth_provider.dartindex 98008697..2005a789 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/server_backend.dart';import '../services/signed_out_playback.dart';import '../services/user_account_service.dart';import '../services/home_widget_service.dart';@@ -32,6 +33,12 @@ class AuthProvider extends ChangeNotifier {Map<String, dynamic>? _userJson;Map<String, dynamic>? _serverSettings;String? _serverVersion;+ ServerBackend __backend = ServerBackend.audiobookshelf;+ ServerBackend get _backend => __backend;+ set _backend(ServerBackend value) {+ __backend = value;+ ServerBackend.active = value;+ }// Ereader devices come on the login response (top-level, NOT inside user).// /api/me doesn't include them, so cache to prefs so the list survives// cold restarts until the next login.@@ -93,6 +100,8 @@ class AuthProvider extends ChangeNotifier {Map<String, dynamic>? get serverSettings => _serverSettings;String? get serverVersion => _serverVersion;Map<String, String> get customHeaders => _customHeaders;+ ServerBackend get backend => _backend;+ bool get isBookOrbit => _backend.isBookOrbit;bool get isAdmin {final t = _userJson?['type'] as String?;return t == 'admin' || t == 'root';@@ -261,7 +270,8 @@ class AuthProvider extends ChangeNotifier {}) {final sessionServer = _serverUrl ?? baseUrl;final sessionUsername = _username;- return ApiService(+ return ApiService.forSession(+ backend: _backend,baseUrl: baseUrl,token: token,refreshToken: refreshToken,@@ -351,6 +361,10 @@ class AuthProvider extends ChangeNotifier {final url = _serverUrl;final token = _accessToken;if (url == null || token == null) return;+ if (_backend.isBookOrbit) {+ WearAuthService.instance.clear();+ return;+ }WearAuthService.instance.publish(serverUrl: url,accessToken: token,@@ -439,6 +453,7 @@ class AuthProvider extends ChangeNotifier {SignedOutPlayback.started();AndroidAutoService().clearCache();CarPlayService().clearAndRefresh();+ BookOrbitApiService.clearCaches();WearAuthService.instance.clear();try {if (server != null && user != null) {@@ -460,6 +475,7 @@ class AuthProvider extends ChangeNotifier {_username = account.username;_userId = account.userId;_customHeaders = account.customHeaders;+ _backend = account.backend;_useLocalServer = false;_accessToken = null;_refreshToken = null;@@ -491,6 +507,7 @@ class AuthProvider extends ChangeNotifier {final savedRefreshToken = prefs.getString('refresh_token');final savedUsername = prefs.getString('username');final savedLibraryId = prefs.getString('default_library_id');+ _backend = ServerBackend.loadActive(prefs);// Restore ereader devices alongside other session data. /api/me doesn't// return them, so without this they'd stay empty until next login.await _restoreEreaderDevices();@@ -670,7 +687,14 @@ class AuthProvider extends ChangeNotifier {debugPrint('[Auth] tryRestoreSession done, isAuthenticated=$isAuthenticated (${sw.elapsedMilliseconds}ms)',);- if (isAuthenticated) _pushSessionToWear();+ if (isAuthenticated) {+ try {+ await apiService?.ensureMediaReady();+ } catch (e) {+ debugPrint('[Auth] Media proxy did not start: $e');+ }+ _pushSessionToWear();+ }_isLoading = false;notifyListeners();}@@ -744,6 +768,8 @@ class AuthProvider extends ChangeNotifier {required String username,required String password,Map<String, String> customHeaders = const {},+ ServerBackend backend = ServerBackend.audiobookshelf,+ String? magicLink,AppLocalizations? l,}) async {_errorMessage = null;@@ -754,6 +780,7 @@ class AuthProvider extends ChangeNotifier {final reachable = await ApiService.pingServer(url,customHeaders: customHeaders,+ backend: backend,);if (!reachable) {_errorMessage =@@ -762,18 +789,31 @@ class AuthProvider extends ChangeNotifier {}// Attempt login- final (result, statusCode) = await ApiService.login(- serverUrl: url,- username: username,- password: password,- customHeaders: customHeaders,- );+ final (result, statusCode) = backend.isBookOrbit && magicLink != null+ ? await BookOrbitApiService.signInWithMagicLink(+ serverUrl: url,+ link: magicLink,+ customHeaders: customHeaders,+ )+ : await ApiService.login(+ serverUrl: url,+ username: username,+ password: password,+ customHeaders: customHeaders,+ backend: backend,+ );+ if (result?['bookOrbitDefaultPassword'] == true) {+ _errorMessage = l?.authBookOrbitDefaultPassword ??+ 'This account still has its default password. Change it in BookOrbit, then sign in again.';+ return false;+ }if (result == null) {_errorMessage = statusCode == 401? (l?.authInvalidUsernameOrPassword ?? 'Invalid username or password')- : (l?.authLoginFailedDetail ??- 'Login failed - check your server address and credentials');+ : await _wrongServerTypeMessage(url, backend, customHeaders, l) ??+ (l?.authLoginFailedDetail ??+ 'Login failed - check your server address and credentials');return false;}@@ -785,7 +825,12 @@ class AuthProvider extends ChangeNotifier {return false;}+ BookOrbitApiService.clearCaches();_serverUrl = url;+ // The old account's local address must not pair with the new+ // tokens while the rest of the switch is still awaiting.+ _useLocalServer = false;+ _backend = backend;// Prefer the JWTs returned inside user by current servers, while accepting// the top-level shape and legacy token used by older servers.final tokens = AuthTokens.fromResponse(result);@@ -835,6 +880,7 @@ class AuthProvider extends ChangeNotifier {try {final prefs = await SharedPreferences.getInstance();await prefs.setString('server_url', _serverUrl!);+ await prefs.setString(ServerBackend.prefsKey, _backend.key);// Refresh token first: a crash between the two writes then leaves the old// access token beside the NEW refresh token, which recovers itself. The// other order is the one that strands a spent refresh token.@@ -864,6 +910,7 @@ class AuthProvider extends ChangeNotifier {userId: _userId,isLegacyToken: _isLegacyToken,customHeaders: customHeaders,+ backend: _backend,),);} catch (e) {@@ -871,6 +918,7 @@ class AuthProvider extends ChangeNotifier {}await _onAccountActivated();+ await apiService?.ensureMediaReady();// Wipe any previous user's stats from the widget and pull this user's.await HomeWidgetService().clearStats();@@ -883,6 +931,40 @@ class AuthProvider extends ChangeNotifier {return true;}+ /// When a sign-in fails for a reason other than bad credentials, check+ /// whether the server is the other kind and say so.+ Future<String?> _wrongServerTypeMessage(+ String url,+ ServerBackend tried,+ Map<String, String> customHeaders,+ AppLocalizations? l,+ ) async {+ try {+ if (!tried.isBookOrbit) {+ final probe = await BookOrbitApiService.probe(+ url,+ customHeaders: customHeaders,+ timeout: const Duration(seconds: 5),+ );+ if (probe.ok) {+ return l?.authServerIsBookOrbit ??+ 'This is a BookOrbit server. Choose BookOrbit above the server address.';+ }+ } else {+ final version = await ApiService.getServerVersion(+ url,+ customHeaders: customHeaders,+ backend: ServerBackend.audiobookshelf,+ );+ if (version != null) {+ return l?.authServerIsAudiobookshelf ??+ 'This is an Audiobookshelf server. Choose Audiobookshelf above the server address.';+ }+ }+ } catch (_) {}+ return null;+ }+/// Login with an admin-generated API key. Skips `/login` entirely - the key/// is just a bearer token. Treated as a legacy token (no refresh) since API/// keys don't expire and don't have a refresh-token counterpart.@@ -890,6 +972,7 @@ class AuthProvider extends ChangeNotifier {required String serverUrl,required String apiKey,Map<String, String> customHeaders = const {},+ ServerBackend backend = ServerBackend.audiobookshelf,AppLocalizations? l,}) async {_errorMessage = null;@@ -899,6 +982,7 @@ class AuthProvider extends ChangeNotifier {final reachable = await ApiService.pingServer(url,customHeaders: customHeaders,+ backend: backend,);if (!reachable) {_errorMessage =@@ -910,6 +994,7 @@ class AuthProvider extends ChangeNotifier {serverUrl: url,apiKey: apiKey,customHeaders: customHeaders,+ backend: backend,);if (user == null) {@@ -921,6 +1006,8 @@ class AuthProvider extends ChangeNotifier {}_serverUrl = url;+ _useLocalServer = false;+ _backend = backend;_accessToken = apiKey;_refreshToken = null;_isLegacyToken = true;@@ -936,6 +1023,7 @@ class AuthProvider extends ChangeNotifier {try {final prefs = await SharedPreferences.getInstance();await prefs.setString('server_url', _serverUrl!);+ await prefs.setString(ServerBackend.prefsKey, _backend.key);await prefs.setString('token', _accessToken!);await prefs.remove('refresh_token');if (_username != null) await prefs.setString('username', _username!);@@ -957,6 +1045,7 @@ class AuthProvider extends ChangeNotifier {userId: _userId,isLegacyToken: true,customHeaders: customHeaders,+ backend: _backend,),);} catch (e) {@@ -984,6 +1073,7 @@ class AuthProvider extends ChangeNotifier {required String serverUrl,required Map<String, dynamic> result,Map<String, String> customHeaders = const {},+ ServerBackend backend = ServerBackend.audiobookshelf,AppLocalizations? l,}) async {_errorMessage = null;@@ -998,7 +1088,10 @@ class AuthProvider extends ChangeNotifier {return false;}+ BookOrbitApiService.clearCaches();_serverUrl = url;+ _useLocalServer = false;+ _backend = backend;final tokens = AuthTokens.fromResponse(result);if (tokens.token == null) {_errorMessage =@@ -1043,6 +1136,7 @@ class AuthProvider extends ChangeNotifier {try {final prefs = await SharedPreferences.getInstance();await prefs.setString('server_url', _serverUrl!);+ await prefs.setString(ServerBackend.prefsKey, _backend.key);// Refresh token first: a crash between the two writes then leaves the old// access token beside the NEW refresh token, which recovers itself. The// other order is the one that strands a spent refresh token.@@ -1072,6 +1166,7 @@ class AuthProvider extends ChangeNotifier {userId: _userId,isLegacyToken: _isLegacyToken,customHeaders: customHeaders,+ backend: _backend,),);} catch (e) {@@ -1079,6 +1174,7 @@ class AuthProvider extends ChangeNotifier {}await _onAccountActivated();+ await apiService?.ensureMediaReady();// Wipe any previous user's stats from the widget and pull this user's.await HomeWidgetService().clearStats();@@ -1221,6 +1317,7 @@ class AuthProvider extends ChangeNotifier {final version = await ApiService.getServerVersion(url,customHeaders: _customHeaders,+ backend: _backend,);if (version != null) {_serverVersion = version;@@ -1260,6 +1357,7 @@ class AuthProvider extends ChangeNotifier {// Clear cached session metadata for this user (track URLs would be invalid// on next login anyway)await SessionCache.clearAll();+ BookOrbitApiService.clearCaches();// Remove account from saved accounts listfinal logoutServer = _serverUrl;@@ -1345,6 +1443,7 @@ class AuthProvider extends ChangeNotifier {// Clear Android Auto / CarPlay browse tree cache so it refreshes for the new userAndroidAutoService().clearCache();CarPlayService().clearAndRefresh();+ BookOrbitApiService.clearCaches();// Set the new account as active in the account service. It may have been// removed since the caller loaded its saved-account row.@@ -1377,6 +1476,8 @@ class AuthProvider extends ChangeNotifier {// Set credentials_serverUrl = selected.serverUrl;+ _useLocalServer = false;+ _backend = selected.backend;_accessToken = selected.token;_refreshToken = selected.refreshToken;_isLegacyToken = selected.isLegacyToken;@@ -1394,6 +1495,7 @@ class AuthProvider extends ChangeNotifier {try {final prefs = await SharedPreferences.getInstance();await prefs.setString('server_url', _serverUrl!);+ await prefs.setString(ServerBackend.prefsKey, _backend.key);// Refresh token first, for the same reason as the other persist sites.if (_refreshToken != null) {await prefs.setString('refresh_token', _refreshToken!);@@ -1471,6 +1573,7 @@ class AuthProvider extends ChangeNotifier {}}_fetchServerVersion(activeServerUrl!);+ await apiService?.ensureMediaReady();_pushSessionToWear();notifyListeners();return true;diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dartindex c644861b..d3552621 100644--- a/lib/providers/library_provider.dart+++ b/lib/providers/library_provider.dart@@ -256,6 +256,7 @@ class LibraryProvider extends ChangeNotifierauth.setEreaderDevices(auth.filterDevicesForCurrentUser(devices));};socket.connect(auth.serverUrl!, auth.token!, customHeaders: auth.customHeaders);+ _startBookOrbitPoll();}debugPrint('[Library] Calling loadLibraries()');await loadLibraries();@@ -282,6 +283,7 @@ class LibraryProvider extends ChangeNotifier_connectivityDebounce?.cancel();_stopServerPingTimer();_stopHealthCheckTimer();+ _stopBookOrbitPoll();SocketService().disconnect();_personalizedInFlight = null;_networkOffline = false;diff --git a/lib/screens/absorbing_screen.dart b/lib/screens/absorbing_screen.dartindex 2a4ec7db..d22f60d8 100644--- a/lib/screens/absorbing_screen.dart+++ b/lib/screens/absorbing_screen.dart@@ -1560,7 +1560,9 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {ButtonSegment(value: 'manual', icon: const Icon(Icons.queue_music_rounded, size: 16), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModeManual, maxLines: 1))),ButtonSegment(value: 'auto_next', icon: const Icon(Icons.skip_next_rounded, size: 16),label: FittedBox(fit: BoxFit.scaleDown, child: Text(widget.isMerged ? l.queueModeAuto : _currentIsPodcast ? l.queueModeShowLabel : l.queueModeSeriesLabel, maxLines: 1))),- ButtonSegment(value: 'playlist', icon: const Icon(Icons.playlist_play_rounded, size: 16), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModePlaylist, maxLines: 1))),+ // BookOrbit has no playlists.+ if (!context.read<AuthProvider>().isBookOrbit || _queueMode == 'playlist')+ ButtonSegment(value: 'playlist', icon: const Icon(Icons.playlist_play_rounded, size: 16), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModePlaylist, maxLines: 1))),// Collection mode is entered via a collection's Play button, not// picked here - shown only while active so the selection is valid.if (_queueMode == 'collection')diff --git a/lib/screens/library_screen.dart b/lib/screens/library_screen.dartindex 11b6b17c..6750866c 100644--- a/lib/screens/library_screen.dart+++ b/lib/screens/library_screen.dart@@ -40,6 +40,7 @@ import '../widgets/rmab_config_sheet.dart'import '../widgets/rmab_search_results_sheet.dart';import '../widgets/scroll_reveal.dart';import '../services/scoped_prefs.dart';+import '../services/server_backend.dart';import '../services/user_account_service.dart';import '../l10n/app_localizations.dart';@@ -241,6 +242,48 @@ bool libraryFilterSupportsMediaType(};}+/// The sort a BookOrbit server actually runs for [sort]. It has no duration+/// sort, only one author order, file dates are its date added, and it keeps+/// no last-listened time to sort progress by.+LibrarySort librarySortForServer(LibrarySort sort) {+ if (!ServerBackend.active.isBookOrbit) return sort;+ return switch (sort) {+ LibrarySort.authorFirstLast => LibrarySort.authorName,+ LibrarySort.progress => LibrarySort.dateStarted,+ LibrarySort.duration ||+ LibrarySort.fileCreated ||+ LibrarySort.lastModified => LibrarySort.recentlyAdded,+ _ => sort,+ };+}++/// BookOrbit has no supplementary ebooks, track counts, abridged or explicit+/// flags, or RSS feeds to filter on.+bool libraryFilterSupportedOnServer(LibraryFilter filter) {+ if (!ServerBackend.active.isBookOrbit) return true;+ return switch (filter) {+ LibraryFilter.hasSupplementaryEbook ||+ LibraryFilter.noSupplementaryEbook ||+ LibraryFilter.singleTrack ||+ LibraryFilter.multipleTracks ||+ LibraryFilter.abridged ||+ LibraryFilter.feedOpen ||+ LibraryFilter.explicit => false,+ _ => true,+ };+}++bool missingMetadataSupportedOnServer(MissingMetadataField field) {+ if (!ServerBackend.active.isBookOrbit) return true;+ return switch (field) {+ MissingMetadataField.asin ||+ MissingMetadataField.subtitle ||+ MissingMetadataField.narrators ||+ MissingMetadataField.chapters => false,+ _ => true,+ };+}+bool libraryFilterRequiresValue(LibraryFilter filter) => switch (filter) {LibraryFilter.series ||LibraryFilter.author ||@@ -763,10 +806,10 @@ class LibraryScreenState extends State<LibraryScreen>if (!mounted) return;setState(() {// Book library sort/filter- _sort = LibrarySort.values.firstWhere(+ _sort = librarySortForServer(LibrarySort.values.firstWhere((s) => s.name == sortName,orElse: () => LibrarySort.recentlyAdded,- );+ ));_sortAsc = sortAsc;if (_sort == LibrarySort.random) _randomSeed = Random().nextInt(100000);// Don't restore filter from prefs if the user (typically via a@@ -780,9 +823,10 @@ class LibraryScreenState extends State<LibraryScreen>orElse: () => LibraryFilter.none,);if (!libraryFilterSupportsMediaType(- _filter,- isPodcast: isPodcast,- )) {+ _filter,+ isPodcast: isPodcast,+ ) ||+ !libraryFilterSupportedOnServer(_filter)) {_filter = LibraryFilter.none;}final restoredGenre = isPodcast ? podcastGenreFilter : genreFilter;@@ -813,6 +857,10 @@ class LibraryScreenState extends State<LibraryScreen>: MissingMetadataField.values.where((field) => field.name == missingMetadataFilterName).firstOrNull;+ if (_missingMetadataFilter != null &&+ !missingMetadataSupportedOnServer(_missingMetadataFilter!)) {+ _missingMetadataFilter = null;+ }if (_filter == LibraryFilter.missingMetadata &&_missingMetadataFilter == null) {_filter = LibraryFilter.none;diff --git a/lib/screens/login_screen.dart b/lib/screens/login_screen.dartindex 58c26539..e29bc5e9 100644--- a/lib/screens/login_screen.dart+++ b/lib/screens/login_screen.dart@@ -1,1413 +1,1581 @@-import 'dart:async';-import 'dart:convert';-import 'dart:io';-import 'dart:ui';-import 'package:flutter/material.dart';-import 'package:flutter/services.dart';-import 'package:file_picker/file_picker.dart';-import 'package:package_info_plus/package_info_plus.dart';-import 'package:provider/provider.dart';-import '../providers/auth_provider.dart';-import '../services/api_service.dart';-import '../services/backup_service.dart';-import '../services/oidc_service.dart';-import '../services/settings_sync_service.dart';-import '../services/setup_link_service.dart';-import '../services/user_account_service.dart';-import '../widgets/absorb_wave_icon.dart';-import '../widgets/overlay_toast.dart';-import '../widgets/setup_link_login.dart';-import '../services/signed_out_playback.dart';-import '../services/audio_player_service.dart';-import '../main.dart' show applyTrustAllCerts, flatNotifier;-import '../l10n/app_localizations.dart';-import '../services/wording.dart';--class LoginScreen extends StatefulWidget {- final SavedAccount? prefillAccount;- final String? prefillServerUrl;-- const LoginScreen({- super.key,- this.prefillAccount,- this.prefillServerUrl,- });-- @override- State<LoginScreen> createState() => _LoginScreenState();-}-class _LoginScreenState extends State<LoginScreen>- with SingleTickerProviderStateMixin {- final _formKey = GlobalKey<FormState>();- final _serverController = TextEditingController();- final _usernameController = TextEditingController();- final _passwordController = TextEditingController();- final _apiKeyController = TextEditingController();- final _usernameFocus = FocusNode();-- bool _obscurePassword = true;- bool _obscureApiKey = true;- bool _isConnecting = false;- String _protocol = 'https://';-- // Server validation state- bool _serverValid = false;- bool _serverChecking = false;- String? _serverError;- // Technical reason the last check failed (TLS, timeout, HTTP status, etc.),- // shown beneath the field so unreachable-in-app-but-fine-in-browser servers- // are diagnosable instead of just "could not reach server".- String? _serverErrorDetail;- Timer? _debounce;-- // Login error- String? _loginError;-- // OIDC state- OidcConfig? _oidcConfig;- bool _isOidcLoading = false;-- // Custom headers (advanced)- bool _showAdvanced = false;- bool _trustAllCerts = false;- final List<(TextEditingController, TextEditingController)> _headerControllers = [];-- // App version- String _appVersion = '';-- late AnimationController _animController;- late Animation<double> _fadeAnim;- late Animation<double> _slideAnim;-- @override- void initState() {- super.initState();- _animController = AnimationController(- vsync: this,- duration: const Duration(milliseconds: 1200),- );- _fadeAnim = CurvedAnimation(- parent: _animController,- curve: const Interval(0.0, 0.5, curve: Curves.easeOut),- );- _slideAnim = CurvedAnimation(- parent: _animController,- curve: const Interval(0.3, 1.0, curve: Curves.easeOutCubic),- );- _animController.forward();- _serverController.addListener(_onServerChanged);- _loadVersion();- WidgetsBinding.instance.addPostFrameCallback((_) {- if (!mounted) return;- final auth = context.read<AuthProvider>();- final account = widget.prefillAccount;- if (account != null) {- _setInitialHeaders(account.customHeaders);- _prefillLogin(account.serverUrl, account.username);- return;- }- final requestedServer = widget.prefillServerUrl;- if (requestedServer != null && requestedServer.isNotEmpty) {- _setInitialHeaders(auth.customHeaders);- _prefillLogin(requestedServer, '');- return;- }- final serverUrl = auth.serverUrl;- if (!auth.isAuthenticated && serverUrl != null && serverUrl.isNotEmpty) {- _prefillLogin(serverUrl, auth.username ?? '');- }- });- }-- void _prefillLogin(String serverUrl, String username) {- final uri = Uri.tryParse(serverUrl);- final protocol = uri?.scheme == 'http' || uri?.scheme == 'https'- ? '${uri!.scheme}://'- : _protocol;- setState(() => _protocol = protocol);- _serverController.text = serverUrl.startsWith(protocol)- ? serverUrl.substring(protocol.length)- : serverUrl;- _usernameController.text = username;- }-- void _setInitialHeaders(Map<String, String> headers) {- for (final (key, value) in _headerControllers) {- key.dispose();- value.dispose();- }- _headerControllers- ..clear()- ..addAll(headers.entries.map(- (entry) => (- TextEditingController(text: entry.key),- TextEditingController(text: entry.value),- ),- ));- if (headers.isNotEmpty) _showAdvanced = true;- }-- Future<void> _loadVersion() async {- try {- final info = await PackageInfo.fromPlatform();- if (mounted) setState(() => _appVersion = 'v${info.version}');- } catch (_) {}- try {- final trust = await PlayerSettings.getTrustAllCerts();- if (mounted) setState(() => _trustAllCerts = trust);- } catch (_) {}- }-- @override- void dispose() {- _debounce?.cancel();- _animController.dispose();- _serverController.dispose();- _usernameController.dispose();- _passwordController.dispose();- _apiKeyController.dispose();- _usernameFocus.dispose();- for (final (k, v) in _headerControllers) { k.dispose(); v.dispose(); }- OidcService().cancel();- super.dispose();- }-- String _lastValidatedServer = '';-- /// Re-trigger server validation when custom headers change.- void _revalidateServer() {- if (_serverController.text.trim().isEmpty) return;- _lastValidatedServer = ''; // Force re-check- _debounce?.cancel();- _debounce = Timer(const Duration(milliseconds: 800), () => _checkServer());- }-- void _onServerChanged() {- final text = _serverController.text.trim();- if (text.isEmpty) {- setState(() {- _serverValid = false;- _serverChecking = false;- _serverError = null;- _serverErrorDetail = null;- _lastValidatedServer = '';- });- _debounce?.cancel();- return;- }-- // Only invalidate if the server text actually changed from what we validated- final cleanUrl = text.replaceAll(RegExp(r'^https?://'), '');- final fullUrl = '$_protocol$cleanUrl';- if (fullUrl != _lastValidatedServer) {- setState(() {- _serverValid = false;- _serverChecking = true;- _serverError = null;- });- } else {- // Same server, just re-checking — keep fields visible- setState(() {- _serverChecking = true;- _serverError = null;- });- }-- _debounce?.cancel();- _debounce = Timer(const Duration(milliseconds: 800), () => _checkServer());- }-- Map<String, String> _collectHeaders() {- final headers = <String, String>{};- for (final (keyCtrl, valCtrl) in _headerControllers) {- final k = keyCtrl.text.trim();- final v = valCtrl.text.trim();- if (k.isNotEmpty && v.isNotEmpty) headers[k] = v;- }- return headers;- }-- Future<void> _checkServer() async {- final text = _serverController.text.trim();- if (text.isEmpty) return;-- final cleanUrl = text.replaceAll(RegExp(r'^https?://'), '');- final fullUrl = '$_protocol$cleanUrl';-- try {- final headers = _collectHeaders();- final result = await ApiService.pingServerDetailed(fullUrl, customHeaders: headers);- final ok = result.ok;- if (!mounted) return;- if (_serverController.text.trim() != text) return;-- setState(() {- _serverChecking = false;- _serverValid = ok;- _serverError = ok ? null : AppLocalizations.of(context)!.loginCouldNotReachServer;- _serverErrorDetail = ok ? null : result.detail;- if (ok) {- _lastValidatedServer = fullUrl;- } else {- _oidcConfig = null;- _lastValidatedServer = '';- }- });-- if (ok) {- // Also check if OIDC is available- OidcService.checkOidcEnabled(fullUrl, customHeaders: headers).then((config) {- if (mounted && _serverController.text.trim() == text) {- setState(() => _oidcConfig = config);- }- });-- // Don't auto-focus — user may still be typing IP:port- }- } catch (e) {- if (!mounted) return;- setState(() {- _serverChecking = false;- _serverValid = false;- _serverError = AppLocalizations.of(context)!.loginCouldNotReachServer;- _serverErrorDetail = e.toString();- _oidcConfig = null;- });- }- }-- Future<void> _handleLogin() async {- final apiKey = _apiKeyController.text.trim();-- // Skip form validation when an API key is supplied — the username- // field's required-validator would otherwise block the submit.- if (apiKey.isEmpty && !_formKey.currentState!.validate()) return;-- // Validate server first if not yet checked- if (!_serverValid) {- await _checkServer();- if (!_serverValid) {- setState(() => _loginError = _serverError ?? AppLocalizations.of(context)!.loginCouldNotReachServer);- return;- }- }-- setState(() {- _isConnecting = true;- _loginError = null;- });-- final auth = context.read<AuthProvider>();- final serverText = _serverController.text.trim();- final cleanUrl = serverText.replaceAll(RegExp(r'^https?://'), '');- final fullUrl = '$_protocol$cleanUrl';-- final headers = _collectHeaders();-- final success = apiKey.isNotEmpty- ? await auth.loginWithApiKey(- serverUrl: fullUrl,- apiKey: apiKey,- customHeaders: headers,- l: AppLocalizations.of(context),- )- : await auth.login(- serverUrl: fullUrl,- username: _usernameController.text.trim(),- password: _passwordController.text,- customHeaders: headers,- l: AppLocalizations.of(context),- );-- if (mounted) {- setState(() => _isConnecting = false);-- if (!success) {- setState(() {- _loginError = auth.errorMessage ?? AppLocalizations.of(context)!.loginFailed;- });- } else {- TextInput.finishAutofillContext();- FocusManager.instance.primaryFocus?.unfocus();- if (Navigator.of(context).canPop()) {- // If pushed as a route (e.g. Add Account), pop back- Navigator.of(context).pop();- }- }- }- }-- Future<void> _handleOidcLogin() async {- if (!_serverValid) return;-- setState(() {- _isOidcLoading = true;- _loginError = null;- });-- final serverText = _serverController.text.trim();- final cleanUrl = serverText.replaceAll(RegExp(r'^https?://'), '');- final fullUrl = '$_protocol$cleanUrl';-- final headers = _collectHeaders();- final oidc = OidcService();- final callbackUri = await oidc.startLogin(fullUrl, customHeaders: headers);- if (callbackUri == null) {- if (!mounted) return;- // Quiet path: user just dismissed the popup. Don't surface an error.- if (oidc.lastWasUserCancel) {- setState(() => _isOidcLoading = false);- return;- }- final base = AppLocalizations.of(context)!.loginSsoFailed;- final detail = oidc.lastError;- setState(() {- _isOidcLoading = false;- _loginError = detail != null ? '$base\n\n$detail' : base;- });- return;- }-- final result = await oidc.handleCallback(callbackUri);- if (result != null && mounted) {- FocusManager.instance.primaryFocus?.unfocus();- final auth = context.read<AuthProvider>();- final success = await auth.loginWithOidc(- serverUrl: fullUrl,- result: result,- customHeaders: headers,- l: AppLocalizations.of(context),- );- if (mounted) {- setState(() => _isOidcLoading = false);- if (!success) {- setState(() => _loginError = auth.errorMessage ?? AppLocalizations.of(context)!.loginSsoFailed);- } else if (Navigator.of(context).canPop()) {- Navigator.of(context).pop();- }- }- } else if (mounted) {- final base = AppLocalizations.of(context)!.loginSsoAuthFailed;- final detail = oidc.lastError;- setState(() {- _isOidcLoading = false;- _loginError = detail != null ? '$base\n\n$detail' : base;- });- }- }-- @override- Widget build(BuildContext context) {- final cs = Theme.of(context).colorScheme;- final tt = Theme.of(context).textTheme;- final l = AppLocalizations.of(context)!;-- return Scaffold(- resizeToAvoidBottomInset: true,- body: Container(- decoration: flatNotifier.value ? null : BoxDecoration(- gradient: LinearGradient(- begin: Alignment.topLeft,- end: Alignment.bottomRight,- stops: const [0.0, 0.4, 0.7, 1.0],- colors: [- cs.primary.withValues(alpha: 0.15),- cs.primary.withValues(alpha: 0.05),- cs.surface,- cs.surface,- ],- ),- ),- child: SafeArea(- child: LayoutBuilder(- builder: (context, constraints) => SingleChildScrollView(- padding: const EdgeInsets.symmetric(horizontal: 28, vertical: 24),- child: ConstrainedBox(- constraints: BoxConstraints(minHeight: constraints.maxHeight - 48),- child: Column(- mainAxisAlignment: MainAxisAlignment.center,- mainAxisSize: MainAxisSize.min,- children: [- // ── Logo + Tagline ──- FadeTransition(- opacity: _fadeAnim,- child: Column(- children: [- // Wave icon with glow- Container(- width: 100,- height: 100,- decoration: BoxDecoration(- shape: BoxShape.circle,- boxShadow: [- BoxShadow(- color: cs.primary.withValues(alpha: 0.3),- blurRadius: 40,- spreadRadius: 8,- ),- ],- ),- child: Container(- decoration: BoxDecoration(- shape: BoxShape.circle,- color: cs.primary.withValues(alpha: 0.1),- border: Border.all(- color: cs.primary.withValues(alpha: 0.15),- width: 1.5,- ),- ),- child: Center(- child: AbsorbWaveIcon(- size: 44,- color: cs.primary,- ),- ),- ),- ),- const SizedBox(height: 28),- Text(- l.appTitle,- style: tt.headlineMedium?.copyWith(- fontWeight: FontWeight.w200,- color: cs.onSurface,- letterSpacing: 10,- ),- ),- const SizedBox(height: 10),- Text(- Wording.of(context).loginTagline,- style: tt.bodyLarge?.copyWith(- color: cs.onSurfaceVariant.withValues(alpha: 0.6),- fontWeight: FontWeight.w400,- letterSpacing: 0.5,- ),- ),- ],- ),- ),- const SizedBox(height: 40),-- // ── Glass form card ──- SlideTransition(- position: Tween<Offset>(- begin: const Offset(0, 0.12),- end: Offset.zero,- ).animate(_slideAnim),- child: FadeTransition(- opacity: _slideAnim,- child: ClipRRect(- borderRadius: BorderRadius.circular(24),- child: BackdropFilter(- filter: ImageFilter.blur(sigmaX: 20, sigmaY: 20),- child: Container(- padding: const EdgeInsets.all(24),- decoration: BoxDecoration(- color: cs.surfaceContainerHighest.withValues(alpha: 0.35),- borderRadius: BorderRadius.circular(24),- border: Border.all(- color: cs.outlineVariant.withValues(alpha: 0.15),- ),- ),- child: Form(- key: _formKey,- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- // Section label- Padding(- padding: const EdgeInsets.only(left: 4, bottom: 16),- child: Text(- l.loginConnectToServer,- style: tt.titleSmall?.copyWith(- color: cs.onSurfaceVariant.withValues(alpha: 0.7),- fontWeight: FontWeight.w500,- ),- ),- ),-- if (context.watch<AuthProvider>().isSignedOut) ...[- _buildSignedOutSyncNote(cs),- const SizedBox(height: 12),- ],- // Server URL- _buildInputField(- controller: _serverController,- label: l.loginServerAddress,- hint: l.loginServerHint,- helperText: l.loginServerHelper,- keyboardType: TextInputType.url,- textInputAction: TextInputAction.next,- onFieldSubmitted: (_) {- if (!_serverValid && !_serverChecking) {- _checkServer().then((_) {- if (mounted && _serverValid) _usernameFocus.requestFocus();- });- } else if (_serverValid) {- _usernameFocus.requestFocus();- }- },- cs: cs,- prefixIcon: Padding(- padding: const EdgeInsets.only(left: 8),- child: DropdownButtonHideUnderline(- child: DropdownButton<String>(- value: _protocol,- isDense: true,- style: TextStyle(- color: cs.primary,- fontSize: 13,- fontWeight: FontWeight.w600,- ),- items: const [- DropdownMenuItem(- value: 'https://',- child: Text('https://'),- ),- DropdownMenuItem(- value: 'http://',- child: Text('http://'),- ),- ],- onChanged: (v) {- if (v != null) {- setState(() {- _protocol = v;- _serverValid = false;- });- _onServerChanged();- }- },- ),- ),- ),- suffixIcon: _serverChecking- ? const Padding(- padding: EdgeInsets.all(14),- child: SizedBox(- width: 18, height: 18,- child: CircularProgressIndicator(strokeWidth: 2),- ),- )- : _serverValid- ? Icon(Icons.check_circle_rounded,- color: Colors.green.shade400, size: 22)- : _serverError != null- ? Icon(Icons.error_outline_rounded,- color: cs.error, size: 22)- : null,- borderColor: _serverValid- ? Colors.green.shade400.withValues(alpha: 0.4)- : _serverError != null- ? cs.error.withValues(alpha: 0.4)- : null,- errorText: _serverError,- ),-- if (_serverErrorDetail != null) ...[- const SizedBox(height: 6),- Padding(- padding: const EdgeInsets.symmetric(horizontal: 4),- child: Text(- _serverErrorDetail!,- style: TextStyle(- fontSize: 11,- color: cs.onSurfaceVariant.withValues(alpha: 0.6),- ),- ),- ),- ],-- // Advanced: Custom Headers — must be before server validation- const SizedBox(height: 8),- GestureDetector(- onTap: () => setState(() => _showAdvanced = !_showAdvanced),- child: Row(- children: [- Icon(_showAdvanced ? Icons.expand_less_rounded : Icons.expand_more_rounded,- size: 18, color: cs.onSurfaceVariant.withValues(alpha: 0.5)),- const SizedBox(width: 4),- Text(l.loginAdvanced, style: TextStyle(fontSize: 13, color: cs.onSurfaceVariant.withValues(alpha: 0.5))),- ],- ),- ),- if (_showAdvanced) ...[- const SizedBox(height: 8),- Text(l.loginCustomHttpHeaders, style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: cs.onSurfaceVariant.withValues(alpha: 0.7))),- const SizedBox(height: 4),- Text(l.loginCustomHeadersDescription,- style: TextStyle(fontSize: 11, color: cs.onSurfaceVariant.withValues(alpha: 0.4))),- const SizedBox(height: 8),- ..._headerControllers.asMap().entries.map((entry) {- final i = entry.key;- final (keyCtrl, valCtrl) = entry.value;- return Padding(- padding: const EdgeInsets.only(bottom: 8),- child: Row(- children: [- Expanded(- flex: 2,- child: TextField(- controller: keyCtrl,- style: TextStyle(fontSize: 13, color: cs.onSurface),- onChanged: (_) => _revalidateServer(),- decoration: InputDecoration(- hintText: l.loginHeaderName,- hintStyle: TextStyle(color: cs.onSurfaceVariant.withValues(alpha: 0.3), fontSize: 13),- filled: true,- fillColor: cs.surfaceContainerHighest.withValues(alpha: 0.5),- border: OutlineInputBorder(borderRadius: BorderRadius.circular(10), borderSide: BorderSide.none),- contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),- ),- ),- ),- const SizedBox(width: 8),- Expanded(- flex: 3,- child: TextField(- controller: valCtrl,- style: TextStyle(fontSize: 13, color: cs.onSurface),- onChanged: (_) => _revalidateServer(),- decoration: InputDecoration(- hintText: l.loginHeaderValue,- hintStyle: TextStyle(color: cs.onSurfaceVariant.withValues(alpha: 0.3), fontSize: 13),- filled: true,- fillColor: cs.surfaceContainerHighest.withValues(alpha: 0.5),- border: OutlineInputBorder(borderRadius: BorderRadius.circular(10), borderSide: BorderSide.none),- contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),- ),- ),- ),- const SizedBox(width: 4),- GestureDetector(- onTap: () {- setState(() {- _headerControllers[i].$1.dispose();- _headerControllers[i].$2.dispose();- _headerControllers.removeAt(i);- });- _revalidateServer();- },- child: Icon(Icons.close_rounded, size: 18, color: cs.error.withValues(alpha: 0.6)),- ),- ],- ),- );- }),- GestureDetector(- onTap: () => setState(() {- _headerControllers.add((TextEditingController(), TextEditingController()));- }),- child: Container(- padding: const EdgeInsets.symmetric(vertical: 8),- child: Row(- mainAxisAlignment: MainAxisAlignment.center,- children: [- Icon(Icons.add_rounded, size: 16, color: cs.primary),- const SizedBox(width: 4),- Text(l.loginAddHeader, style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600, color: cs.primary)),- ],- ),- ),- ),- const SizedBox(height: 8),- const Divider(height: 1),- const SizedBox(height: 4),- Text(l.loginSelfSignedCertificates, style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: cs.onSurfaceVariant.withValues(alpha: 0.7))),- Row(- children: [- Expanded(- child: Text(- l.loginTrustAllCertificates,- style: TextStyle(fontSize: 11, color: cs.onSurfaceVariant.withValues(alpha: 0.4)),- ),- ),- Transform.scale(- scale: 0.8,- child: Switch(- value: _trustAllCerts,- onChanged: (v) async {- setState(() => _trustAllCerts = v);- await PlayerSettings.setTrustAllCerts(v);- applyTrustAllCerts(v);- _revalidateServer();- },- ),- ),- ],- ),- const SizedBox(height: 8),- const Divider(height: 1),- const SizedBox(height: 8),- Text(l.loginApiKey, style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: cs.onSurfaceVariant.withValues(alpha: 0.7))),- const SizedBox(height: 4),- Text(l.loginApiKeyDescription,- style: TextStyle(fontSize: 11, color: cs.onSurfaceVariant.withValues(alpha: 0.4))),- const SizedBox(height: 8),- TextField(- controller: _apiKeyController,- obscureText: _obscureApiKey,- autocorrect: false,- enableSuggestions: false,- style: TextStyle(fontSize: 13, color: cs.onSurface),- onChanged: (_) => setState(() {}),- decoration: InputDecoration(- hintText: l.loginApiKey,- hintStyle: TextStyle(color: cs.onSurfaceVariant.withValues(alpha: 0.3), fontSize: 13),- filled: true,- fillColor: cs.surfaceContainerHighest.withValues(alpha: 0.5),- border: OutlineInputBorder(borderRadius: BorderRadius.circular(10), borderSide: BorderSide.none),- contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),- prefixIcon: Icon(Icons.vpn_key_rounded, size: 18, color: cs.onSurfaceVariant.withValues(alpha: 0.5)),- suffixIcon: IconButton(- icon: Icon(- _obscureApiKey ? Icons.visibility_outlined : Icons.visibility_off_outlined,- size: 18,- color: cs.onSurfaceVariant.withValues(alpha: 0.5),- ),- onPressed: () => setState(() => _obscureApiKey = !_obscureApiKey),- ),- ),- ),- ],-- // Credentials — always visible- _buildCredentialFields(cs, tt),- ],- ),- ),- ),- ),- ),- ),- ),-- if (SignedOutPlayback.available && !context.watch<AuthProvider>().isSignedOut) ...[- const SizedBox(height: 16),- SizedBox(- width: double.infinity,- height: 48,- child: FilledButton.tonalIcon(- key: const Key('play-downloads-signed-out'),- icon: const Icon(Icons.download_done_rounded),- label: Text(l.loginPlayDownloads),- style: FilledButton.styleFrom(- shape: RoundedRectangleBorder(- borderRadius: BorderRadius.circular(14),- ),- ),- onPressed: () {- final account = SignedOutPlayback.expiredAccount();- if (account != null) {- context.read<AuthProvider>().continueSignedOut(account);- }- },- ),- ),- ],-- // ── Version + Restore pill ──- const SizedBox(height: 32),- FadeTransition(- opacity: _fadeAnim,- child: Column(- children: [- Text(- _appVersion,- style: tt.labelSmall?.copyWith(- color: cs.onSurfaceVariant.withValues(alpha: 0.3),- letterSpacing: 1,- ),- ),- const SizedBox(height: 12),- Wrap(- alignment: WrapAlignment.center,- spacing: 8,- runSpacing: 8,- children: [- ActionChip(- avatar: Icon(Icons.restore_rounded, size: 16,- color: cs.onSurfaceVariant.withValues(alpha: 0.6)),- label: Text(l.loginRestoreFromBackup,- style: tt.labelSmall?.copyWith(- color: cs.onSurfaceVariant.withValues(alpha: 0.6),- )),- backgroundColor: cs.surfaceContainerHighest.withValues(alpha: 0.3),- side: BorderSide(color: cs.outlineVariant.withValues(alpha: 0.15)),- shape: RoundedRectangleBorder(- borderRadius: BorderRadius.circular(20),- ),- onPressed: _restoreFromBackup,- ),- ActionChip(- key: const Key('paste-login-link'),- avatar: Icon(Icons.content_paste_rounded, size: 16,- color: cs.onSurfaceVariant.withValues(alpha: 0.6)),- label: Text(l.loginPasteLink,- style: tt.labelSmall?.copyWith(- color: cs.onSurfaceVariant.withValues(alpha: 0.6),- )),- backgroundColor: cs.surfaceContainerHighest.withValues(alpha: 0.3),- side: BorderSide(color: cs.outlineVariant.withValues(alpha: 0.15)),- shape: RoundedRectangleBorder(- borderRadius: BorderRadius.circular(20),- ),- onPressed: _pasteLoginLink,- ),- ],- )- ],- ),- ),-- // ── Saved accounts quick-switch ──- _buildSavedAccounts(cs, tt),- ],- ),- ),- ),- ),- ),- ),- );- }-- Widget _buildSavedAccounts(ColorScheme cs, TextTheme tt) {- final accounts = UserAccountService().accounts;- if (accounts.isEmpty) return const SizedBox.shrink();- final l = AppLocalizations.of(context)!;-- return FadeTransition(- opacity: _fadeAnim,- child: Padding(- padding: const EdgeInsets.only(top: 32),- child: Column(- children: [- Row(- children: [- Expanded(child: Divider(color: cs.outlineVariant.withValues(alpha: 0.15))),- Padding(- padding: const EdgeInsets.symmetric(horizontal: 14),- child: Text(l.loginSavedAccounts,- style: tt.bodySmall?.copyWith(- color: cs.onSurfaceVariant.withValues(alpha: 0.4))),- ),- Expanded(child: Divider(color: cs.outlineVariant.withValues(alpha: 0.15))),- ],- ),- const SizedBox(height: 12),- ...accounts.map((account) {- final shortUrl = account.serverUrl- .replaceAll(RegExp(r'^https?://'), '')- .replaceAll(RegExp(r'/+$'), '');- return Padding(- padding: const EdgeInsets.only(bottom: 8),- child: Material(- color: cs.surface.withValues(alpha: 0.3),- borderRadius: BorderRadius.circular(14),- child: InkWell(- borderRadius: BorderRadius.circular(14),- onTap: () => _quickSwitch(account),- child: Padding(- padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),- child: Row(- children: [- CircleAvatar(- radius: 18,- backgroundColor: cs.primary.withValues(alpha: 0.15),- child: Text(- account.username.isNotEmpty- ? account.username[0].toUpperCase()- : '?',- style: TextStyle(- color: cs.primary,- fontWeight: FontWeight.w600,- ),- ),- ),- const SizedBox(width: 12),- Expanded(- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Text(account.username,- style: tt.bodyMedium?.copyWith(- fontWeight: FontWeight.w600,- color: cs.onSurface)),- Text(shortUrl,- style: tt.labelSmall?.copyWith(- color: cs.onSurfaceVariant.withValues(alpha: 0.5)),- maxLines: 1,- overflow: TextOverflow.ellipsis),- ],- ),- ),- Icon(Icons.arrow_forward_ios_rounded,- size: 14, color: cs.onSurfaceVariant.withValues(alpha: 0.3)),- ],- ),- ),- ),- ),- );- }),- ],- ),- ),- );- }-- Future<void> _restoreFromBackup() async {- try {- final result = await FilePicker.platform.pickFiles(type: FileType.any);- if (result == null || result.files.isEmpty) return;-- final file = File(result.files.single.path!);- final jsonStr = await file.readAsString();- final data = jsonDecode(jsonStr) as Map<String, dynamic>;-- if (!data.containsKey('version')) {- if (mounted) {- final l = AppLocalizations.of(context)!;- showOverlayToast(context, l.loginInvalidBackupFile,- icon: Icons.error_outline_rounded);- }- return;- }-- final accounts = data['accounts'] as List<dynamic>?;- final accountCount = accounts?.length ?? 0;- final hasAccounts = accountCount > 0;- // A setup/login file carries an account but no settings payload, so it- // should read as a sign-in rather than a backup restore.- final isSetup = data['setup'] == true || (hasAccounts && data['settings'] == null);- final firstUsername = hasAccounts ? ((accounts!.first as Map)['username'] as String? ?? '') : '';-- if (!mounted) return;- final l = AppLocalizations.of(context)!;- final confirm = await showDialog<bool>(- context: context,- builder: (ctx) => AlertDialog(- title: Text(isSetup ? l.loginSignIn : l.loginRestoreBackupTitle),- content: Text(isSetup- ? (firstUsername.isNotEmpty ? l.loginSignInAs(firstUsername) : l.loginSignInToServer)- : (hasAccounts- ? l.loginRestoreBackupWithAccounts(accountCount)- : l.loginRestoreBackupNoAccounts)),- actions: [- TextButton(- onPressed: () => Navigator.pop(ctx, false),- child: Text(l.cancel),- ),- FilledButton(- onPressed: () => Navigator.pop(ctx, true),- child: Text(isSetup ? l.loginSignIn : l.loginRestore),- ),- ],- ),- );-- if (confirm != true) return;-- await BackupService.importSettings(data);-- // Auto-login with the first restored account- if (hasAccounts && mounted) {- final restoredAccounts = UserAccountService().accounts;- if (restoredAccounts.isNotEmpty) {- final auth = context.read<AuthProvider>();- await auth.switchToAccount(restoredAccounts.first);-- if (mounted) {- final l2 = AppLocalizations.of(context)!;- if (auth.isAuthenticated && auth.serverReachable) {- showOverlayToast(- context,- isSetup- ? l2.loginSignedInAs(restoredAccounts.first.username)- : l2.loginRestoredAndSignedIn(restoredAccounts.first.username),- icon: Icons.check_circle_outline_rounded,- );- } else {- // Token expired — accounts are saved but need re-auth- showOverlayToast(context, l2.loginSessionExpired, icon: Icons.error_outline_rounded);- setState(() {}); // Refresh to show saved accounts list- }- }- }- } else if (mounted) {- final l3 = AppLocalizations.of(context)!;- showOverlayToast(context, l3.loginSettingsRestored, icon: Icons.check_circle_outline_rounded);- }-- await SettingsSyncService().resolveSourceAfterRestore();- } catch (e) {- if (mounted) {- final l4 = AppLocalizations.of(context)!;- showOverlayToast(context, l4.loginRestoreFailed(e.toString()), icon: Icons.error_outline_rounded);- }- }- }-- Future<void> _pasteLoginLink() async {- final l = AppLocalizations.of(context)!;- final controller = TextEditingController();- String? errorText;- final link = await showDialog<Uri>(- context: context,- builder: (dialogContext) => StatefulBuilder(- builder: (context, setDialogState) {- void submit() {- final uri = Uri.tryParse(controller.text.trim());- try {- if (uri == null) throw const SetupLinkException('Invalid link');- SetupLinkService.parseLink(uri);- Navigator.pop(dialogContext, uri);- } on SetupLinkException {- setDialogState(() => errorText = l.setupLinkInvalid);- }- }-- return AlertDialog(- title: Text(l.loginPasteLink),- content: Column(- mainAxisSize: MainAxisSize.min,- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Text(l.loginPasteLinkHelp),- const SizedBox(height: 16),- TextField(- key: const Key('login-link-field'),- controller: controller,- autofocus: true,- autocorrect: false,- enableSuggestions: false,- keyboardType: TextInputType.url,- minLines: 2,- maxLines: 4,- decoration: InputDecoration(- hintText: 'absorb://setup/...',- errorText: errorText,- suffixIcon: IconButton(- tooltip: l.loginPasteLink,- icon: const Icon(Icons.content_paste_rounded),- onPressed: () async {- final data = await Clipboard.getData('text/plain');- controller.text = data?.text ?? '';- setDialogState(() => errorText = null);- },- ),- ),- ),- ],- ),- actions: [- TextButton(- onPressed: () => Navigator.pop(dialogContext),- child: Text(l.cancel),- ),- FilledButton(- key: const Key('submit-login-link'),- onPressed: submit,- child: Text(l.loginSignIn),- ),- ],- );- },- ),- );- controller.dispose();- if (link == null || !mounted) return;- await handleSetupLinkLogin(context, link);- }-- Future<void> _quickSwitch(SavedAccount account) async {- if (account.token.isEmpty) {- _setInitialHeaders(account.customHeaders);- _prefillLogin(account.serverUrl, account.username);- _passwordController.clear();- _usernameFocus.unfocus();- return;- }- setState(() => _isConnecting = true);-- final auth = context.read<AuthProvider>();- await auth.switchToAccount(account);-- if (mounted) {- setState(() => _isConnecting = false);- if (auth.isAuthenticated && Navigator.of(context).canPop()) {- Navigator.of(context).pop();- }- // If this is the root login screen, AuthGate will react to the state change- }- }-- /// 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,- required ColorScheme cs,- String? hint,- String? helperText,- TextInputType? keyboardType,- TextInputAction? textInputAction,- FocusNode? focusNode,- Widget? prefixIcon,- Widget? suffixIcon,- Color? borderColor,- String? errorText,- bool obscureText = false,- void Function(String)? onFieldSubmitted,- String? Function(String?)? validator,- Iterable<String>? autofillHints,- }) {- final isUrl = keyboardType == TextInputType.url;- return TextFormField(- controller: controller,- focusNode: focusNode,- keyboardType: keyboardType,- textInputAction: textInputAction,- obscureText: obscureText,- autocorrect: !isUrl,- enableSuggestions: !isUrl,- autofillHints: autofillHints,- onFieldSubmitted: onFieldSubmitted,- validator: validator,- style: TextStyle(color: cs.onSurface),- decoration: InputDecoration(- labelText: label,- hintText: hint,- helperText: helperText,- helperStyle: TextStyle(color: cs.onSurfaceVariant.withValues(alpha: 0.5), fontSize: 11),- helperMaxLines: 2,- prefixIcon: prefixIcon,- suffixIcon: suffixIcon,- errorText: errorText,- border: OutlineInputBorder(- borderRadius: BorderRadius.circular(14),- borderSide: BorderSide(color: cs.outlineVariant.withValues(alpha: 0.2)),- ),- enabledBorder: OutlineInputBorder(- borderRadius: BorderRadius.circular(14),- borderSide: BorderSide(- color: borderColor ?? cs.outlineVariant.withValues(alpha: 0.15),- ),- ),- focusedBorder: OutlineInputBorder(- borderRadius: BorderRadius.circular(14),- borderSide: BorderSide(color: cs.primary.withValues(alpha: 0.6), width: 1.5),- ),- filled: true,- fillColor: cs.surface.withValues(alpha: 0.4),- contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),- ),- );- }-- Widget _buildOidcButton(ColorScheme cs, TextTheme tt) {- final l = AppLocalizations.of(context)!;- return Column(- children: [- const SizedBox(height: 12),- SizedBox(- width: double.infinity,- height: 44,- child: OutlinedButton.icon(- onPressed: _isConnecting || _isOidcLoading ? null : _handleOidcLogin,- icon: _isOidcLoading- ? SizedBox(- width: 18, height: 18,- child: CircularProgressIndicator(strokeWidth: 2, color: cs.primary),- )- : Icon(Icons.login_rounded, size: 20, color: cs.primary),- label: Text(- _isOidcLoading ? l.loginWaitingForSso : _oidcConfig!.buttonText,- style: tt.titleMedium?.copyWith(- fontWeight: FontWeight.w600,- color: cs.primary,- ),- ),- style: OutlinedButton.styleFrom(- side: BorderSide(color: cs.primary.withValues(alpha: 0.3)),- shape: RoundedRectangleBorder(- borderRadius: BorderRadius.circular(12),- ),- ),- ),- ),- const SizedBox(height: 6),- Text(- l.loginRedirectUri,- style: tt.labelSmall?.copyWith(- color: cs.onSurfaceVariant.withValues(alpha: 0.4),- letterSpacing: 0.3,- ),- ),- ],- );- }-- Widget _buildCredentialFields(ColorScheme cs, TextTheme tt) {- final l = AppLocalizations.of(context)!;- final usingApiKey = _apiKeyController.text.trim().isNotEmpty;- return AutofillGroup(- child: Column(- children: [- const SizedBox(height: 16),-- // Login error message- if (_loginError != null)- Padding(- padding: const EdgeInsets.only(bottom: 12),- child: Container(- width: double.infinity,- padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),- decoration: BoxDecoration(- color: cs.error.withValues(alpha: 0.1),- borderRadius: BorderRadius.circular(12),- border: Border.all(color: cs.error.withValues(alpha: 0.3)),- ),- child: Row(- children: [- Icon(Icons.warning_amber_rounded, size: 18, color: cs.error),- const SizedBox(width: 10),- Expanded(- child: Text(- _loginError!,- style: tt.bodySmall?.copyWith(color: cs.error),- ),- ),- ],- ),- ),- ),-- if (!usingApiKey) ...[- // Username- _buildInputField(- controller: _usernameController,- focusNode: _usernameFocus,- label: l.loginUsername,- cs: cs,- textInputAction: TextInputAction.next,- autofillHints: const [AutofillHints.username],- prefixIcon: Icon(Icons.person_outline_rounded, size: 20,- color: cs.onSurfaceVariant.withValues(alpha: 0.5)),- validator: (v) {- if (v == null || v.trim().isEmpty) {- return l.loginUsernameRequired;- }- return null;- },- ),- const SizedBox(height: 14),-- // Password- _buildInputField(- controller: _passwordController,- label: l.loginPassword,- cs: cs,- obscureText: _obscurePassword,- textInputAction: TextInputAction.done,- autofillHints: const [AutofillHints.password],- onFieldSubmitted: (_) => _handleLogin(),- prefixIcon: Icon(Icons.lock_outline_rounded, size: 20,- color: cs.onSurfaceVariant.withValues(alpha: 0.5)),- suffixIcon: IconButton(- icon: Icon(- _obscurePassword- ? Icons.visibility_outlined- : Icons.visibility_off_outlined,- size: 20,- color: cs.onSurfaceVariant.withValues(alpha: 0.5),- ),- onPressed: () {- setState(() => _obscurePassword = !_obscurePassword);- },- ),- // No validator — ABS allows passwordless accounts- ),- ],- const SizedBox(height: 24),-- // Sign In button- SizedBox(- width: double.infinity,- height: 52,- child: FilledButton(- onPressed: _isConnecting || _isOidcLoading ? null : _handleLogin,- style: FilledButton.styleFrom(- backgroundColor: cs.primary,- foregroundColor: cs.onPrimary,- shape: RoundedRectangleBorder(- borderRadius: BorderRadius.circular(14),- ),- elevation: 0,- ),- child: AnimatedSwitcher(- duration: const Duration(milliseconds: 200),- child: _isConnecting- ? SizedBox(- key: const ValueKey('loading'),- width: 22,- height: 22,- child: CircularProgressIndicator(- strokeWidth: 2.5,- color: cs.onPrimary,- ),- )- : Text(- l.loginSignIn,- key: const ValueKey('text'),- style: tt.titleMedium?.copyWith(- fontWeight: FontWeight.w600,- color: cs.onPrimary,- ),- ),- ),- ),- ),- AnimatedSize(- duration: const Duration(milliseconds: 350),- curve: Curves.easeOutCubic,- alignment: Alignment.topCenter,- child: _serverValid && _oidcConfig != null && _oidcConfig!.enabled- ? _buildOidcButton(cs, tt)- : const SizedBox.shrink(),- ),--- ],- ),- );- }-}+import 'dart:async';+import 'dart:convert';+import 'dart:io';+import 'dart:ui';+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:file_picker/file_picker.dart';+import 'package:package_info_plus/package_info_plus.dart';+import 'package:provider/provider.dart';+import 'package:url_launcher/url_launcher.dart';+import '../providers/auth_provider.dart';+import '../services/api_service.dart';+import '../services/backup_service.dart';+import '../services/log_service.dart';+import '../services/oidc_service.dart';+import '../services/server_backend.dart';+import '../services/settings_sync_service.dart';+import '../services/setup_link_service.dart';+import '../services/user_account_service.dart';+import '../widgets/absorb_wave_icon.dart';+import '../widgets/overlay_toast.dart';+import '../widgets/setup_link_login.dart';+import '../services/signed_out_playback.dart';+import '../services/audio_player_service.dart';+import '../main.dart' show applyTrustAllCerts, flatNotifier;+import '../l10n/app_localizations.dart';+import '../services/wording.dart';++class LoginScreen extends StatefulWidget {+ final SavedAccount? prefillAccount;+ final String? prefillServerUrl;++ const LoginScreen({+ super.key,+ this.prefillAccount,+ this.prefillServerUrl,+ });++ @override+ State<LoginScreen> createState() => _LoginScreenState();+}+class _LoginScreenState extends State<LoginScreen>+ with SingleTickerProviderStateMixin {+ final _formKey = GlobalKey<FormState>();+ final _serverController = TextEditingController();+ final _usernameController = TextEditingController();+ final _passwordController = TextEditingController();+ final _apiKeyController = TextEditingController();+ final _usernameFocus = FocusNode();++ bool _obscurePassword = true;+ bool _obscureApiKey = true;+ bool _isConnecting = false;+ String _protocol = 'https://';+ ServerBackend _backend = ServerBackend.audiobookshelf;++ // Server validation state+ bool _serverValid = false;+ bool _serverChecking = false;+ String? _serverError;+ // Technical reason the last check failed (TLS, timeout, HTTP status, etc.),+ // shown beneath the field so unreachable-in-app-but-fine-in-browser servers+ // are diagnosable instead of just "could not reach server".+ String? _serverErrorDetail;+ Timer? _debounce;++ // Login error+ String? _loginError;++ // OIDC state+ OidcConfig? _oidcConfig;+ bool _isOidcLoading = false;++ // Custom headers (advanced)+ bool _showAdvanced = false;+ bool _trustAllCerts = false;+ final List<(TextEditingController, TextEditingController)> _headerControllers = [];++ // App version+ String _appVersion = '';++ late AnimationController _animController;+ late Animation<double> _fadeAnim;+ late Animation<double> _slideAnim;++ @override+ void initState() {+ super.initState();+ _animController = AnimationController(+ vsync: this,+ duration: const Duration(milliseconds: 1200),+ );+ _fadeAnim = CurvedAnimation(+ parent: _animController,+ curve: const Interval(0.0, 0.5, curve: Curves.easeOut),+ );+ _slideAnim = CurvedAnimation(+ parent: _animController,+ curve: const Interval(0.3, 1.0, curve: Curves.easeOutCubic),+ );+ _animController.forward();+ _serverController.addListener(_onServerChanged);+ _loadVersion();+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (!mounted) return;+ final auth = context.read<AuthProvider>();+ final account = widget.prefillAccount;+ if (account != null) {+ _setInitialHeaders(account.customHeaders);+ setState(() => _backend = account.backend);+ _prefillLogin(account.serverUrl, account.username);+ return;+ }+ final requestedServer = widget.prefillServerUrl;+ if (requestedServer != null && requestedServer.isNotEmpty) {+ _setInitialHeaders(auth.customHeaders);+ _prefillLogin(requestedServer, '');+ return;+ }+ final serverUrl = auth.serverUrl;+ if (!auth.isAuthenticated && serverUrl != null && serverUrl.isNotEmpty) {+ setState(() => _backend = auth.backend);+ _prefillLogin(serverUrl, auth.username ?? '');+ }+ });+ }++ void _prefillLogin(String serverUrl, String username) {+ final uri = Uri.tryParse(serverUrl);+ final protocol = uri?.scheme == 'http' || uri?.scheme == 'https'+ ? '${uri!.scheme}://'+ : _protocol;+ setState(() => _protocol = protocol);+ _serverController.text = serverUrl.startsWith(protocol)+ ? serverUrl.substring(protocol.length)+ : serverUrl;+ _usernameController.text = username;+ }++ void _setInitialHeaders(Map<String, String> headers) {+ for (final (key, value) in _headerControllers) {+ key.dispose();+ value.dispose();+ }+ _headerControllers+ ..clear()+ ..addAll(headers.entries.map(+ (entry) => (+ TextEditingController(text: entry.key),+ TextEditingController(text: entry.value),+ ),+ ));+ if (headers.isNotEmpty) _showAdvanced = true;+ }++ Future<void> _loadVersion() async {+ try {+ final info = await PackageInfo.fromPlatform();+ if (mounted) setState(() => _appVersion = 'v${info.version}');+ } catch (_) {}+ try {+ final trust = await PlayerSettings.getTrustAllCerts();+ if (mounted) setState(() => _trustAllCerts = trust);+ } catch (_) {}+ }++ @override+ void dispose() {+ _debounce?.cancel();+ _animController.dispose();+ _serverController.dispose();+ _usernameController.dispose();+ _passwordController.dispose();+ _apiKeyController.dispose();+ _usernameFocus.dispose();+ for (final (k, v) in _headerControllers) { k.dispose(); v.dispose(); }+ OidcService().cancel();+ super.dispose();+ }++ String _lastValidatedServer = '';++ /// Re-trigger server validation when custom headers change.+ void _revalidateServer() {+ if (_serverController.text.trim().isEmpty) return;+ _lastValidatedServer = ''; // Force re-check+ _debounce?.cancel();+ _debounce = Timer(const Duration(milliseconds: 800), () => _checkServer());+ }++ void _onServerChanged() {+ final text = _serverController.text.trim();+ if (text.isEmpty) {+ setState(() {+ _serverValid = false;+ _serverChecking = false;+ _serverError = null;+ _serverErrorDetail = null;+ _lastValidatedServer = '';+ });+ _debounce?.cancel();+ return;+ }++ // Only invalidate if the server text actually changed from what we validated+ final cleanUrl = text.replaceAll(RegExp(r'^https?://'), '');+ final fullUrl = '$_protocol$cleanUrl';+ if (fullUrl != _lastValidatedServer) {+ setState(() {+ _serverValid = false;+ _serverChecking = true;+ _serverError = null;+ });+ } else {+ // Same server, just re-checking — keep fields visible+ setState(() {+ _serverChecking = true;+ _serverError = null;+ });+ }++ _debounce?.cancel();+ _debounce = Timer(const Duration(milliseconds: 800), () => _checkServer());+ }++ Map<String, String> _collectHeaders() {+ final headers = <String, String>{};+ for (final (keyCtrl, valCtrl) in _headerControllers) {+ final k = keyCtrl.text.trim();+ final v = valCtrl.text.trim();+ if (k.isNotEmpty && v.isNotEmpty) headers[k] = v;+ }+ return headers;+ }++ Future<void> _checkServer() async {+ final text = _serverController.text.trim();+ if (text.isEmpty) return;++ final cleanUrl = text.replaceAll(RegExp(r'^https?://'), '');+ final fullUrl = '$_protocol$cleanUrl';++ try {+ final headers = _collectHeaders();+ final backend = _backend;+ final result = await ApiService.pingServerDetailed(+ fullUrl,+ customHeaders: headers,+ backend: backend,+ );+ final ok = result.ok;+ if (!mounted) return;+ if (_serverController.text.trim() != text || _backend != backend) return;++ setState(() {+ _serverChecking = false;+ _serverValid = ok;+ _serverError = ok ? null : AppLocalizations.of(context)!.loginCouldNotReachServer;+ _serverErrorDetail = ok ? null : result.detail;+ if (ok) {+ _lastValidatedServer = fullUrl;+ } else {+ _oidcConfig = null;+ _lastValidatedServer = '';+ }+ });++ if (ok) {+ // Also check if OIDC is available+ final check = backend.isBookOrbit+ ? OidcService.checkBookOrbitOidc(fullUrl, customHeaders: headers)+ : OidcService.checkOidcEnabled(fullUrl, customHeaders: headers);+ check.then((config) {+ if (mounted && _serverController.text.trim() == text && _backend == backend) {+ setState(() => _oidcConfig = config);+ }+ });++ // Don't auto-focus — user may still be typing IP:port+ }+ } catch (e) {+ if (!mounted) return;+ setState(() {+ _serverChecking = false;+ _serverValid = false;+ _serverError = AppLocalizations.of(context)!.loginCouldNotReachServer;+ _serverErrorDetail = e.toString();+ _oidcConfig = null;+ });+ }+ }++ Future<void> _handleLogin() async {+ final apiKey = _apiKeyController.text.trim();++ // Skip form validation when an API key is supplied — the username+ // field's required-validator would otherwise block the submit.+ if (apiKey.isEmpty && !_formKey.currentState!.validate()) return;++ // Validate server first if not yet checked+ if (!_serverValid) {+ await _checkServer();+ if (!_serverValid) {+ setState(() => _loginError = _serverError ?? AppLocalizations.of(context)!.loginCouldNotReachServer);+ return;+ }+ }++ setState(() {+ _isConnecting = true;+ _loginError = null;+ });++ final auth = context.read<AuthProvider>();+ final serverText = _serverController.text.trim();+ final cleanUrl = serverText.replaceAll(RegExp(r'^https?://'), '');+ final fullUrl = '$_protocol$cleanUrl';++ final headers = _collectHeaders();++ final success = apiKey.isNotEmpty && _backend.isBookOrbit+ ? await auth.login(+ serverUrl: fullUrl,+ username: '',+ password: '',+ customHeaders: headers,+ backend: _backend,+ magicLink: apiKey,+ l: AppLocalizations.of(context),+ )+ : apiKey.isNotEmpty+ ? await auth.loginWithApiKey(+ serverUrl: fullUrl,+ apiKey: apiKey,+ customHeaders: headers,+ backend: _backend,+ l: AppLocalizations.of(context),+ )+ : await auth.login(+ serverUrl: fullUrl,+ username: _usernameController.text.trim(),+ password: _passwordController.text,+ customHeaders: headers,+ backend: _backend,+ l: AppLocalizations.of(context),+ );++ if (mounted) {+ setState(() => _isConnecting = false);++ if (!success) {+ setState(() {+ _loginError = auth.errorMessage ?? AppLocalizations.of(context)!.loginFailed;+ });+ } else {+ TextInput.finishAutofillContext();+ FocusManager.instance.primaryFocus?.unfocus();+ if (Navigator.of(context).canPop()) {+ // If pushed as a route (e.g. Add Account), pop back+ Navigator.of(context).pop();+ }+ }+ }+ }++ Future<void> _handleOidcLogin() async {+ if (!_serverValid) return;++ setState(() {+ _isOidcLoading = true;+ _loginError = null;+ });++ final serverText = _serverController.text.trim();+ final cleanUrl = serverText.replaceAll(RegExp(r'^https?://'), '');+ final fullUrl = '$_protocol$cleanUrl';++ final headers = _collectHeaders();+ final oidc = OidcService();+ BookOrbitOidcProvider? provider;+ if (_backend.isBookOrbit) {+ final providers = _oidcConfig?.bookOrbitProviders ?? const <BookOrbitOidcProvider>[];+ provider = providers.length == 1 ? providers.single : await _pickOidcProvider(providers);+ if (!mounted) return;+ if (provider == null) {+ setState(() => _isOidcLoading = false);+ return;+ }+ }+ final callbackUri = provider != null+ ? await oidc.startBookOrbitLogin(fullUrl, provider, customHeaders: headers)+ : await oidc.startLogin(fullUrl, customHeaders: headers);+ if (callbackUri == null) {+ if (!mounted) return;+ // Quiet path: user just dismissed the popup. Don't surface an error.+ if (oidc.lastWasUserCancel) {+ setState(() => _isOidcLoading = false);+ return;+ }+ final base = AppLocalizations.of(context)!.loginSsoFailed;+ final detail = oidc.lastError;+ setState(() {+ _isOidcLoading = false;+ _loginError = detail != null ? '$base\n\n$detail' : base;+ });+ return;+ }++ final result = provider != null+ ? await oidc.handleBookOrbitCallback(callbackUri)+ : await oidc.handleCallback(callbackUri);+ if (result != null && mounted) {+ FocusManager.instance.primaryFocus?.unfocus();+ final auth = context.read<AuthProvider>();+ final success = await auth.loginWithOidc(+ serverUrl: fullUrl,+ result: result,+ customHeaders: headers,+ backend: provider != null ? ServerBackend.bookorbit : ServerBackend.audiobookshelf,+ l: AppLocalizations.of(context),+ );+ if (mounted) {+ setState(() => _isOidcLoading = false);+ if (!success) {+ setState(() => _loginError = auth.errorMessage ?? AppLocalizations.of(context)!.loginSsoFailed);+ } else if (Navigator.of(context).canPop()) {+ Navigator.of(context).pop();+ }+ }+ } else if (mounted) {+ final base = AppLocalizations.of(context)!.loginSsoAuthFailed;+ final detail = oidc.lastError;+ setState(() {+ _isOidcLoading = false;+ _loginError = detail != null ? '$base\n\n$detail' : base;+ });+ }+ }++ Future<BookOrbitOidcProvider?> _pickOidcProvider(List<BookOrbitOidcProvider> providers) {+ if (providers.isEmpty) return Future.value(null);+ final l = AppLocalizations.of(context)!;+ return showDialog<BookOrbitOidcProvider>(+ context: context,+ builder: (ctx) => SimpleDialog(+ title: Text(l.loginChooseSsoProvider),+ children: [+ for (final p in providers)+ SimpleDialogOption(+ onPressed: () => Navigator.pop(ctx, p),+ child: Text(p.displayName),+ ),+ ],+ ),+ );+ }++ String _oidcButtonText(AppLocalizations l) {+ final providers = _oidcConfig!.bookOrbitProviders;+ if (providers.isEmpty) return _oidcConfig!.buttonText;+ return providers.length == 1+ ? l.loginSignInWithProvider(providers.single.displayName)+ : l.loginSignInWithSso;+ }++ @override+ Widget build(BuildContext context) {+ final cs = Theme.of(context).colorScheme;+ final tt = Theme.of(context).textTheme;+ final l = AppLocalizations.of(context)!;++ return Scaffold(+ resizeToAvoidBottomInset: true,+ body: Container(+ decoration: flatNotifier.value ? null : BoxDecoration(+ gradient: LinearGradient(+ begin: Alignment.topLeft,+ end: Alignment.bottomRight,+ stops: const [0.0, 0.4, 0.7, 1.0],+ colors: [+ cs.primary.withValues(alpha: 0.15),+ cs.primary.withValues(alpha: 0.05),+ cs.surface,+ cs.surface,+ ],+ ),+ ),+ child: SafeArea(+ child: LayoutBuilder(+ builder: (context, constraints) => SingleChildScrollView(+ padding: const EdgeInsets.symmetric(horizontal: 28, vertical: 24),+ child: ConstrainedBox(+ constraints: BoxConstraints(minHeight: constraints.maxHeight - 48),+ child: Column(+ mainAxisAlignment: MainAxisAlignment.center,+ mainAxisSize: MainAxisSize.min,+ children: [+ // ── Logo + Tagline ──+ FadeTransition(+ opacity: _fadeAnim,+ child: Column(+ children: [+ // Wave icon with glow+ Container(+ width: 100,+ height: 100,+ decoration: BoxDecoration(+ shape: BoxShape.circle,+ boxShadow: [+ BoxShadow(+ color: cs.primary.withValues(alpha: 0.3),+ blurRadius: 40,+ spreadRadius: 8,+ ),+ ],+ ),+ child: Container(+ decoration: BoxDecoration(+ shape: BoxShape.circle,+ color: cs.primary.withValues(alpha: 0.1),+ border: Border.all(+ color: cs.primary.withValues(alpha: 0.15),+ width: 1.5,+ ),+ ),+ child: Center(+ child: AbsorbWaveIcon(+ size: 44,+ color: cs.primary,+ ),+ ),+ ),+ ),+ const SizedBox(height: 28),+ Text(+ l.appTitle,+ style: tt.headlineMedium?.copyWith(+ fontWeight: FontWeight.w200,+ color: cs.onSurface,+ letterSpacing: 10,+ ),+ ),+ const SizedBox(height: 10),+ Text(+ Wording.of(context).loginTagline,+ style: tt.bodyLarge?.copyWith(+ color: cs.onSurfaceVariant.withValues(alpha: 0.6),+ fontWeight: FontWeight.w400,+ letterSpacing: 0.5,+ ),+ ),+ ],+ ),+ ),+ const SizedBox(height: 40),++ // ── Glass form card ──+ SlideTransition(+ position: Tween<Offset>(+ begin: const Offset(0, 0.12),+ end: Offset.zero,+ ).animate(_slideAnim),+ child: FadeTransition(+ opacity: _slideAnim,+ child: ClipRRect(+ borderRadius: BorderRadius.circular(24),+ child: BackdropFilter(+ filter: ImageFilter.blur(sigmaX: 20, sigmaY: 20),+ child: Container(+ padding: const EdgeInsets.all(24),+ decoration: BoxDecoration(+ color: cs.surfaceContainerHighest.withValues(alpha: 0.35),+ borderRadius: BorderRadius.circular(24),+ border: Border.all(+ color: cs.outlineVariant.withValues(alpha: 0.15),+ ),+ ),+ child: Form(+ key: _formKey,+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ // Section label+ Padding(+ padding: const EdgeInsets.only(left: 4, bottom: 16),+ child: Text(+ l.loginConnectToServer,+ style: tt.titleSmall?.copyWith(+ color: cs.onSurfaceVariant.withValues(alpha: 0.7),+ fontWeight: FontWeight.w500,+ ),+ ),+ ),++ if (context.watch<AuthProvider>().isSignedOut) ...[+ _buildSignedOutSyncNote(cs),+ const SizedBox(height: 12),+ ],+ _buildBackendPicker(cs),+ if (_backend.isBookOrbit) ...[+ const SizedBox(height: 10),+ _buildBookOrbitNotice(cs),+ ],+ const SizedBox(height: 14),++ _buildInputField(+ controller: _serverController,+ label: l.loginServerAddress,+ hint: l.loginServerHint,+ helperText: l.loginServerHelper,+ keyboardType: TextInputType.url,+ textInputAction: TextInputAction.next,+ onFieldSubmitted: (_) {+ if (!_serverValid && !_serverChecking) {+ _checkServer().then((_) {+ if (mounted && _serverValid) _usernameFocus.requestFocus();+ });+ } else if (_serverValid) {+ _usernameFocus.requestFocus();+ }+ },+ cs: cs,+ prefixIcon: Padding(+ padding: const EdgeInsets.only(left: 8),+ child: DropdownButtonHideUnderline(+ child: DropdownButton<String>(+ value: _protocol,+ isDense: true,+ style: TextStyle(+ color: cs.primary,+ fontSize: 13,+ fontWeight: FontWeight.w600,+ ),+ items: const [+ DropdownMenuItem(+ value: 'https://',+ child: Text('https://'),+ ),+ DropdownMenuItem(+ value: 'http://',+ child: Text('http://'),+ ),+ ],+ onChanged: (v) {+ if (v != null) {+ setState(() {+ _protocol = v;+ _serverValid = false;+ });+ _onServerChanged();+ }+ },+ ),+ ),+ ),+ suffixIcon: _serverChecking+ ? const Padding(+ padding: EdgeInsets.all(14),+ child: SizedBox(+ width: 18, height: 18,+ child: CircularProgressIndicator(strokeWidth: 2),+ ),+ )+ : _serverValid+ ? Icon(Icons.check_circle_rounded,+ color: Colors.green.shade400, size: 22)+ : _serverError != null+ ? Icon(Icons.error_outline_rounded,+ color: cs.error, size: 22)+ : null,+ borderColor: _serverValid+ ? Colors.green.shade400.withValues(alpha: 0.4)+ : _serverError != null+ ? cs.error.withValues(alpha: 0.4)+ : null,+ errorText: _serverError,+ ),++ if (_serverErrorDetail != null) ...[+ const SizedBox(height: 6),+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: 4),+ child: Text(+ _serverErrorDetail!,+ style: TextStyle(+ fontSize: 11,+ color: cs.onSurfaceVariant.withValues(alpha: 0.6),+ ),+ ),+ ),+ ],++ // Advanced: Custom Headers — must be before server validation+ const SizedBox(height: 8),+ GestureDetector(+ onTap: () => setState(() => _showAdvanced = !_showAdvanced),+ child: Row(+ children: [+ Icon(_showAdvanced ? Icons.expand_less_rounded : Icons.expand_more_rounded,+ size: 18, color: cs.onSurfaceVariant.withValues(alpha: 0.5)),+ const SizedBox(width: 4),+ Text(l.loginAdvanced, style: TextStyle(fontSize: 13, color: cs.onSurfaceVariant.withValues(alpha: 0.5))),+ ],+ ),+ ),+ if (_showAdvanced) ...[+ const SizedBox(height: 8),+ Text(l.loginCustomHttpHeaders, style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: cs.onSurfaceVariant.withValues(alpha: 0.7))),+ const SizedBox(height: 4),+ Text(l.loginCustomHeadersDescription,+ style: TextStyle(fontSize: 11, color: cs.onSurfaceVariant.withValues(alpha: 0.4))),+ const SizedBox(height: 8),+ ..._headerControllers.asMap().entries.map((entry) {+ final i = entry.key;+ final (keyCtrl, valCtrl) = entry.value;+ return Padding(+ padding: const EdgeInsets.only(bottom: 8),+ child: Row(+ children: [+ Expanded(+ flex: 2,+ child: TextField(+ controller: keyCtrl,+ style: TextStyle(fontSize: 13, color: cs.onSurface),+ onChanged: (_) => _revalidateServer(),+ decoration: InputDecoration(+ hintText: l.loginHeaderName,+ hintStyle: TextStyle(color: cs.onSurfaceVariant.withValues(alpha: 0.3), fontSize: 13),+ filled: true,+ fillColor: cs.surfaceContainerHighest.withValues(alpha: 0.5),+ border: OutlineInputBorder(borderRadius: BorderRadius.circular(10), borderSide: BorderSide.none),+ contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),+ ),+ ),+ ),+ const SizedBox(width: 8),+ Expanded(+ flex: 3,+ child: TextField(+ controller: valCtrl,+ style: TextStyle(fontSize: 13, color: cs.onSurface),+ onChanged: (_) => _revalidateServer(),+ decoration: InputDecoration(+ hintText: l.loginHeaderValue,+ hintStyle: TextStyle(color: cs.onSurfaceVariant.withValues(alpha: 0.3), fontSize: 13),+ filled: true,+ fillColor: cs.surfaceContainerHighest.withValues(alpha: 0.5),+ border: OutlineInputBorder(borderRadius: BorderRadius.circular(10), borderSide: BorderSide.none),+ contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),+ ),+ ),+ ),+ const SizedBox(width: 4),+ GestureDetector(+ onTap: () {+ setState(() {+ _headerControllers[i].$1.dispose();+ _headerControllers[i].$2.dispose();+ _headerControllers.removeAt(i);+ });+ _revalidateServer();+ },+ child: Icon(Icons.close_rounded, size: 18, color: cs.error.withValues(alpha: 0.6)),+ ),+ ],+ ),+ );+ }),+ GestureDetector(+ onTap: () => setState(() {+ _headerControllers.add((TextEditingController(), TextEditingController()));+ }),+ child: Container(+ padding: const EdgeInsets.symmetric(vertical: 8),+ child: Row(+ mainAxisAlignment: MainAxisAlignment.center,+ children: [+ Icon(Icons.add_rounded, size: 16, color: cs.primary),+ const SizedBox(width: 4),+ Text(l.loginAddHeader, style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600, color: cs.primary)),+ ],+ ),+ ),+ ),+ const SizedBox(height: 8),+ const Divider(height: 1),+ const SizedBox(height: 4),+ Text(l.loginSelfSignedCertificates, style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: cs.onSurfaceVariant.withValues(alpha: 0.7))),+ Row(+ children: [+ Expanded(+ child: Text(+ l.loginTrustAllCertificates,+ style: TextStyle(fontSize: 11, color: cs.onSurfaceVariant.withValues(alpha: 0.4)),+ ),+ ),+ Transform.scale(+ scale: 0.8,+ child: Switch(+ value: _trustAllCerts,+ onChanged: (v) async {+ setState(() => _trustAllCerts = v);+ await PlayerSettings.setTrustAllCerts(v);+ applyTrustAllCerts(v);+ _revalidateServer();+ },+ ),+ ),+ ],+ ),+ const SizedBox(height: 8),+ const Divider(height: 1),+ const SizedBox(height: 8),+ Text(_backend.isBookOrbit ? l.loginMagicLink : l.loginApiKey, style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: cs.onSurfaceVariant.withValues(alpha: 0.7))),+ const SizedBox(height: 4),+ Text(_backend.isBookOrbit ? l.loginMagicLinkDescription : l.loginApiKeyDescription,+ style: TextStyle(fontSize: 11, color: cs.onSurfaceVariant.withValues(alpha: 0.4))),+ const SizedBox(height: 8),+ TextField(+ controller: _apiKeyController,+ obscureText: _obscureApiKey,+ autocorrect: false,+ enableSuggestions: false,+ style: TextStyle(fontSize: 13, color: cs.onSurface),+ onChanged: (_) => setState(() {}),+ decoration: InputDecoration(+ hintText: _backend.isBookOrbit ? l.loginMagicLink : l.loginApiKey,+ hintStyle: TextStyle(color: cs.onSurfaceVariant.withValues(alpha: 0.3), fontSize: 13),+ filled: true,+ fillColor: cs.surfaceContainerHighest.withValues(alpha: 0.5),+ border: OutlineInputBorder(borderRadius: BorderRadius.circular(10), borderSide: BorderSide.none),+ contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),+ prefixIcon: Icon(Icons.vpn_key_rounded, size: 18, color: cs.onSurfaceVariant.withValues(alpha: 0.5)),+ suffixIcon: IconButton(+ icon: Icon(+ _obscureApiKey ? Icons.visibility_outlined : Icons.visibility_off_outlined,+ size: 18,+ color: cs.onSurfaceVariant.withValues(alpha: 0.5),+ ),+ onPressed: () => setState(() => _obscureApiKey = !_obscureApiKey),+ ),+ ),+ ),+ ],++ // Credentials — always visible+ _buildCredentialFields(cs, tt),+ ],+ ),+ ),+ ),+ ),+ ),+ ),+ ),++ if (SignedOutPlayback.available && !context.watch<AuthProvider>().isSignedOut) ...[+ const SizedBox(height: 16),+ SizedBox(+ width: double.infinity,+ height: 48,+ child: FilledButton.tonalIcon(+ key: const Key('play-downloads-signed-out'),+ icon: const Icon(Icons.download_done_rounded),+ label: Text(l.loginPlayDownloads),+ style: FilledButton.styleFrom(+ shape: RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(14),+ ),+ ),+ onPressed: () {+ final account = SignedOutPlayback.expiredAccount();+ if (account != null) {+ context.read<AuthProvider>().continueSignedOut(account);+ }+ },+ ),+ ),+ ],++ // ── Version + Restore pill ──+ const SizedBox(height: 32),+ FadeTransition(+ opacity: _fadeAnim,+ child: Column(+ children: [+ Text(+ _appVersion,+ style: tt.labelSmall?.copyWith(+ color: cs.onSurfaceVariant.withValues(alpha: 0.3),+ letterSpacing: 1,+ ),+ ),+ const SizedBox(height: 12),+ Wrap(+ alignment: WrapAlignment.center,+ spacing: 8,+ runSpacing: 8,+ children: [+ ActionChip(+ avatar: Icon(Icons.restore_rounded, size: 16,+ color: cs.onSurfaceVariant.withValues(alpha: 0.6)),+ label: Text(l.loginRestoreFromBackup,+ style: tt.labelSmall?.copyWith(+ color: cs.onSurfaceVariant.withValues(alpha: 0.6),+ )),+ backgroundColor: cs.surfaceContainerHighest.withValues(alpha: 0.3),+ side: BorderSide(color: cs.outlineVariant.withValues(alpha: 0.15)),+ shape: RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(20),+ ),+ onPressed: _restoreFromBackup,+ ),+ ActionChip(+ key: const Key('paste-login-link'),+ avatar: Icon(Icons.content_paste_rounded, size: 16,+ color: cs.onSurfaceVariant.withValues(alpha: 0.6)),+ label: Text(l.loginPasteLink,+ style: tt.labelSmall?.copyWith(+ color: cs.onSurfaceVariant.withValues(alpha: 0.6),+ )),+ backgroundColor: cs.surfaceContainerHighest.withValues(alpha: 0.3),+ side: BorderSide(color: cs.outlineVariant.withValues(alpha: 0.15)),+ shape: RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(20),+ ),+ onPressed: _pasteLoginLink,+ ),+ ],+ )+ ],+ ),+ ),++ // ── Saved accounts quick-switch ──+ _buildSavedAccounts(cs, tt),+ ],+ ),+ ),+ ),+ ),+ ),+ ),+ );+ }++ /// 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),+ ),+ ),+ ]),+ );+ }++ /// BookOrbit support is new; say so before anyone signs in.+ Widget _buildBookOrbitNotice(ColorScheme cs) {+ final l = AppLocalizations.of(context)!;+ final tt = Theme.of(context).textTheme;+ return Container(+ width: double.infinity,+ padding: const EdgeInsets.fromLTRB(12, 10, 12, 4),+ decoration: BoxDecoration(+ color: cs.error.withValues(alpha: 0.08),+ borderRadius: BorderRadius.circular(12),+ border: Border.all(color: cs.error.withValues(alpha: 0.3)),+ ),+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [+ Text(l.loginBookOrbitPreview, style: tt.bodySmall?.copyWith(color: cs.error, height: 1.4)),+ Wrap(children: [+ TextButton.icon(+ onPressed: () => launchUrl(+ Uri.parse('https://github.com/pounat/absorb'),+ mode: LaunchMode.externalApplication,+ ),+ icon: const Icon(Icons.code_rounded, size: 16),+ label: const Text('GitHub'),+ style: TextButton.styleFrom(+ foregroundColor: cs.error,+ visualDensity: VisualDensity.compact,+ padding: const EdgeInsets.symmetric(horizontal: 8),+ ),+ ),+ TextButton.icon(+ onPressed: () => LogService().contactEmail(),+ icon: const Icon(Icons.email_outlined, size: 16),+ label: Text(l.contact),+ style: TextButton.styleFrom(+ foregroundColor: cs.error,+ visualDensity: VisualDensity.compact,+ padding: const EdgeInsets.symmetric(horizontal: 8),+ ),+ ),+ TextButton.icon(+ onPressed: () => launchUrl(+ Uri.parse('https://discord.gg/bwH6hdvzZ4'),+ mode: LaunchMode.externalApplication,+ ),+ icon: const Icon(Icons.discord, size: 16),+ label: Text(l.joinDiscord),+ style: TextButton.styleFrom(+ foregroundColor: cs.error,+ visualDensity: VisualDensity.compact,+ padding: const EdgeInsets.symmetric(horizontal: 8),+ ),+ ),+ ]),+ ]),+ );+ }++ Widget _buildBackendPicker(ColorScheme cs) {+ return Semantics(+ label: AppLocalizations.of(context)!.loginServerType,+ child: SizedBox(+ width: double.infinity,+ child: SegmentedButton<ServerBackend>(+ key: const Key('login-backend-picker'),+ showSelectedIcon: false,+ style: SegmentedButton.styleFrom(+ visualDensity: VisualDensity.compact,+ textStyle: const TextStyle(fontSize: 13, fontWeight: FontWeight.w600),+ ),+ segments: [+ for (final b in ServerBackend.values)+ ButtonSegment(value: b, label: Text(b.displayName)),+ ],+ selected: {_backend},+ onSelectionChanged: _isConnecting || _isOidcLoading+ ? null+ : (selection) {+ final picked = selection.first;+ if (picked == _backend) return;+ setState(() {+ _backend = picked;+ _oidcConfig = null;+ _loginError = null;+ _apiKeyController.clear();+ });+ _revalidateServer();+ },+ ),+ ),+ );+ }++ Widget _buildSavedAccounts(ColorScheme cs, TextTheme tt) {+ final accounts = UserAccountService().accounts;+ if (accounts.isEmpty) return const SizedBox.shrink();+ final l = AppLocalizations.of(context)!;++ return FadeTransition(+ opacity: _fadeAnim,+ child: Padding(+ padding: const EdgeInsets.only(top: 32),+ child: Column(+ children: [+ Row(+ children: [+ Expanded(child: Divider(color: cs.outlineVariant.withValues(alpha: 0.15))),+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: 14),+ child: Text(l.loginSavedAccounts,+ style: tt.bodySmall?.copyWith(+ color: cs.onSurfaceVariant.withValues(alpha: 0.4))),+ ),+ Expanded(child: Divider(color: cs.outlineVariant.withValues(alpha: 0.15))),+ ],+ ),+ const SizedBox(height: 12),+ ...accounts.map((account) {+ final host = account.serverUrl+ .replaceAll(RegExp(r'^https?://'), '')+ .replaceAll(RegExp(r'/+$'), '');+ final shortUrl = account.backend.isBookOrbit+ ? '$host - ${account.backend.displayName}'+ : host;+ return Padding(+ padding: const EdgeInsets.only(bottom: 8),+ child: Material(+ color: cs.surface.withValues(alpha: 0.3),+ borderRadius: BorderRadius.circular(14),+ child: InkWell(+ borderRadius: BorderRadius.circular(14),+ onTap: () => _quickSwitch(account),+ child: Padding(+ padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),+ child: Row(+ children: [+ CircleAvatar(+ radius: 18,+ backgroundColor: cs.primary.withValues(alpha: 0.15),+ child: Text(+ account.username.isNotEmpty+ ? account.username[0].toUpperCase()+ : '?',+ style: TextStyle(+ color: cs.primary,+ fontWeight: FontWeight.w600,+ ),+ ),+ ),+ const SizedBox(width: 12),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(account.username,+ style: tt.bodyMedium?.copyWith(+ fontWeight: FontWeight.w600,+ color: cs.onSurface)),+ Text(shortUrl,+ style: tt.labelSmall?.copyWith(+ color: cs.onSurfaceVariant.withValues(alpha: 0.5)),+ maxLines: 1,+ overflow: TextOverflow.ellipsis),+ ],+ ),+ ),+ Icon(Icons.arrow_forward_ios_rounded,+ size: 14, color: cs.onSurfaceVariant.withValues(alpha: 0.3)),+ ],+ ),+ ),+ ),+ ),+ );+ }),+ ],+ ),+ ),+ );+ }++ Future<void> _restoreFromBackup() async {+ try {+ final result = await FilePicker.platform.pickFiles(type: FileType.any);+ if (result == null || result.files.isEmpty) return;++ final file = File(result.files.single.path!);+ final jsonStr = await file.readAsString();+ final data = jsonDecode(jsonStr) as Map<String, dynamic>;++ if (!data.containsKey('version')) {+ if (mounted) {+ final l = AppLocalizations.of(context)!;+ showOverlayToast(context, l.loginInvalidBackupFile,+ icon: Icons.error_outline_rounded);+ }+ return;+ }++ final accounts = data['accounts'] as List<dynamic>?;+ final accountCount = accounts?.length ?? 0;+ final hasAccounts = accountCount > 0;+ // A setup/login file carries an account but no settings payload, so it+ // should read as a sign-in rather than a backup restore.+ final isSetup = data['setup'] == true || (hasAccounts && data['settings'] == null);+ final firstUsername = hasAccounts ? ((accounts!.first as Map)['username'] as String? ?? '') : '';++ if (!mounted) return;+ final l = AppLocalizations.of(context)!;+ final confirm = await showDialog<bool>(+ context: context,+ builder: (ctx) => AlertDialog(+ title: Text(isSetup ? l.loginSignIn : l.loginRestoreBackupTitle),+ content: Text(isSetup+ ? (firstUsername.isNotEmpty ? l.loginSignInAs(firstUsername) : l.loginSignInToServer)+ : (hasAccounts+ ? l.loginRestoreBackupWithAccounts(accountCount)+ : l.loginRestoreBackupNoAccounts)),+ actions: [+ TextButton(+ onPressed: () => Navigator.pop(ctx, false),+ child: Text(l.cancel),+ ),+ FilledButton(+ onPressed: () => Navigator.pop(ctx, true),+ child: Text(isSetup ? l.loginSignIn : l.loginRestore),+ ),+ ],+ ),+ );++ if (confirm != true) return;++ await BackupService.importSettings(data);++ // Auto-login with the first restored account+ if (hasAccounts && mounted) {+ final restoredAccounts = UserAccountService().accounts;+ if (restoredAccounts.isNotEmpty) {+ final auth = context.read<AuthProvider>();+ await auth.switchToAccount(restoredAccounts.first);++ if (mounted) {+ final l2 = AppLocalizations.of(context)!;+ if (auth.isAuthenticated && auth.serverReachable) {+ showOverlayToast(+ context,+ isSetup+ ? l2.loginSignedInAs(restoredAccounts.first.username)+ : l2.loginRestoredAndSignedIn(restoredAccounts.first.username),+ icon: Icons.check_circle_outline_rounded,+ );+ } else {+ // Token expired — accounts are saved but need re-auth+ showOverlayToast(context, l2.loginSessionExpired, icon: Icons.error_outline_rounded);+ setState(() {}); // Refresh to show saved accounts list+ }+ }+ }+ } else if (mounted) {+ final l3 = AppLocalizations.of(context)!;+ showOverlayToast(context, l3.loginSettingsRestored, icon: Icons.check_circle_outline_rounded);+ }++ await SettingsSyncService().resolveSourceAfterRestore();+ } catch (e) {+ if (mounted) {+ final l4 = AppLocalizations.of(context)!;+ showOverlayToast(context, l4.loginRestoreFailed(e.toString()), icon: Icons.error_outline_rounded);+ }+ }+ }++ Future<void> _pasteLoginLink() async {+ final l = AppLocalizations.of(context)!;+ final controller = TextEditingController();+ String? errorText;+ final link = await showDialog<Uri>(+ context: context,+ builder: (dialogContext) => StatefulBuilder(+ builder: (context, setDialogState) {+ void submit() {+ final uri = Uri.tryParse(controller.text.trim());+ try {+ if (uri == null) throw const SetupLinkException('Invalid link');+ SetupLinkService.parseLink(uri);+ Navigator.pop(dialogContext, uri);+ } on SetupLinkException {+ setDialogState(() => errorText = l.setupLinkInvalid);+ }+ }++ return AlertDialog(+ title: Text(l.loginPasteLink),+ content: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(l.loginPasteLinkHelp),+ const SizedBox(height: 16),+ TextField(+ key: const Key('login-link-field'),+ controller: controller,+ autofocus: true,+ autocorrect: false,+ enableSuggestions: false,+ keyboardType: TextInputType.url,+ minLines: 2,+ maxLines: 4,+ decoration: InputDecoration(+ hintText: 'absorb://setup/...',+ errorText: errorText,+ suffixIcon: IconButton(+ tooltip: l.loginPasteLink,+ icon: const Icon(Icons.content_paste_rounded),+ onPressed: () async {+ final data = await Clipboard.getData('text/plain');+ controller.text = data?.text ?? '';+ setDialogState(() => errorText = null);+ },+ ),+ ),+ ),+ ],+ ),+ actions: [+ TextButton(+ onPressed: () => Navigator.pop(dialogContext),+ child: Text(l.cancel),+ ),+ FilledButton(+ key: const Key('submit-login-link'),+ onPressed: submit,+ child: Text(l.loginSignIn),+ ),+ ],+ );+ },+ ),+ );+ controller.dispose();+ if (link == null || !mounted) return;+ await handleSetupLinkLogin(context, link);+ }++ Future<void> _quickSwitch(SavedAccount account) async {+ if (account.token.isEmpty) {+ _setInitialHeaders(account.customHeaders);+ setState(() => _backend = account.backend);+ _prefillLogin(account.serverUrl, account.username);+ _passwordController.clear();+ _usernameFocus.unfocus();+ return;+ }+ setState(() => _isConnecting = true);++ final auth = context.read<AuthProvider>();+ await auth.switchToAccount(account);++ if (mounted) {+ setState(() => _isConnecting = false);+ if (auth.isAuthenticated && Navigator.of(context).canPop()) {+ Navigator.of(context).pop();+ }+ // If this is the root login screen, AuthGate will react to the state change+ }+ }++ Widget _buildInputField({+ required TextEditingController controller,+ required String label,+ required ColorScheme cs,+ String? hint,+ String? helperText,+ TextInputType? keyboardType,+ TextInputAction? textInputAction,+ FocusNode? focusNode,+ Widget? prefixIcon,+ Widget? suffixIcon,+ Color? borderColor,+ String? errorText,+ bool obscureText = false,+ void Function(String)? onFieldSubmitted,+ String? Function(String?)? validator,+ Iterable<String>? autofillHints,+ }) {+ final isUrl = keyboardType == TextInputType.url;+ return TextFormField(+ controller: controller,+ focusNode: focusNode,+ keyboardType: keyboardType,+ textInputAction: textInputAction,+ obscureText: obscureText,+ autocorrect: !isUrl,+ enableSuggestions: !isUrl,+ autofillHints: autofillHints,+ onFieldSubmitted: onFieldSubmitted,+ validator: validator,+ style: TextStyle(color: cs.onSurface),+ decoration: InputDecoration(+ labelText: label,+ hintText: hint,+ helperText: helperText,+ helperStyle: TextStyle(color: cs.onSurfaceVariant.withValues(alpha: 0.5), fontSize: 11),+ helperMaxLines: 2,+ prefixIcon: prefixIcon,+ suffixIcon: suffixIcon,+ errorText: errorText,+ border: OutlineInputBorder(+ borderRadius: BorderRadius.circular(14),+ borderSide: BorderSide(color: cs.outlineVariant.withValues(alpha: 0.2)),+ ),+ enabledBorder: OutlineInputBorder(+ borderRadius: BorderRadius.circular(14),+ borderSide: BorderSide(+ color: borderColor ?? cs.outlineVariant.withValues(alpha: 0.15),+ ),+ ),+ focusedBorder: OutlineInputBorder(+ borderRadius: BorderRadius.circular(14),+ borderSide: BorderSide(color: cs.primary.withValues(alpha: 0.6), width: 1.5),+ ),+ filled: true,+ fillColor: cs.surface.withValues(alpha: 0.4),+ contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),+ ),+ );+ }++ Widget _buildOidcButton(ColorScheme cs, TextTheme tt) {+ final l = AppLocalizations.of(context)!;+ return Column(+ children: [+ const SizedBox(height: 12),+ SizedBox(+ width: double.infinity,+ height: 44,+ child: OutlinedButton.icon(+ onPressed: _isConnecting || _isOidcLoading ? null : _handleOidcLogin,+ icon: _isOidcLoading+ ? SizedBox(+ width: 18, height: 18,+ child: CircularProgressIndicator(strokeWidth: 2, color: cs.primary),+ )+ : Icon(Icons.login_rounded, size: 20, color: cs.primary),+ label: Text(+ _isOidcLoading ? l.loginWaitingForSso : _oidcButtonText(l),+ style: tt.titleMedium?.copyWith(+ fontWeight: FontWeight.w600,+ color: cs.primary,+ ),+ ),+ style: OutlinedButton.styleFrom(+ side: BorderSide(color: cs.primary.withValues(alpha: 0.3)),+ shape: RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(12),+ ),+ ),+ ),+ ),+ const SizedBox(height: 6),+ Text(+ _backend.isBookOrbit ? l.loginRedirectUriBookOrbit : l.loginRedirectUri,+ style: tt.labelSmall?.copyWith(+ color: cs.onSurfaceVariant.withValues(alpha: 0.4),+ letterSpacing: 0.3,+ ),+ ),+ ],+ );+ }++ Widget _buildCredentialFields(ColorScheme cs, TextTheme tt) {+ final l = AppLocalizations.of(context)!;+ final usingApiKey = _apiKeyController.text.trim().isNotEmpty;+ return AutofillGroup(+ child: Column(+ children: [+ const SizedBox(height: 16),++ // Login error message+ if (_loginError != null)+ Padding(+ padding: const EdgeInsets.only(bottom: 12),+ child: Container(+ width: double.infinity,+ padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),+ decoration: BoxDecoration(+ color: cs.error.withValues(alpha: 0.1),+ borderRadius: BorderRadius.circular(12),+ border: Border.all(color: cs.error.withValues(alpha: 0.3)),+ ),+ child: Row(+ children: [+ Icon(Icons.warning_amber_rounded, size: 18, color: cs.error),+ const SizedBox(width: 10),+ Expanded(+ child: Text(+ _loginError!,+ style: tt.bodySmall?.copyWith(color: cs.error),+ ),+ ),+ ],+ ),+ ),+ ),++ if (!usingApiKey) ...[+ // Username+ _buildInputField(+ controller: _usernameController,+ focusNode: _usernameFocus,+ label: l.loginUsername,+ cs: cs,+ textInputAction: TextInputAction.next,+ autofillHints: const [AutofillHints.username],+ prefixIcon: Icon(Icons.person_outline_rounded, size: 20,+ color: cs.onSurfaceVariant.withValues(alpha: 0.5)),+ validator: (v) {+ if (v == null || v.trim().isEmpty) {+ return l.loginUsernameRequired;+ }+ return null;+ },+ ),+ const SizedBox(height: 14),++ // Password+ _buildInputField(+ controller: _passwordController,+ label: l.loginPassword,+ cs: cs,+ obscureText: _obscurePassword,+ textInputAction: TextInputAction.done,+ autofillHints: const [AutofillHints.password],+ onFieldSubmitted: (_) => _handleLogin(),+ prefixIcon: Icon(Icons.lock_outline_rounded, size: 20,+ color: cs.onSurfaceVariant.withValues(alpha: 0.5)),+ suffixIcon: IconButton(+ icon: Icon(+ _obscurePassword+ ? Icons.visibility_outlined+ : Icons.visibility_off_outlined,+ size: 20,+ color: cs.onSurfaceVariant.withValues(alpha: 0.5),+ ),+ onPressed: () {+ setState(() => _obscurePassword = !_obscurePassword);+ },+ ),+ // No validator — ABS allows passwordless accounts+ ),+ ],+ const SizedBox(height: 24),++ // Sign In button+ SizedBox(+ width: double.infinity,+ height: 52,+ child: FilledButton(+ onPressed: _isConnecting || _isOidcLoading ? null : _handleLogin,+ style: FilledButton.styleFrom(+ backgroundColor: cs.primary,+ foregroundColor: cs.onPrimary,+ shape: RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(14),+ ),+ elevation: 0,+ ),+ child: AnimatedSwitcher(+ duration: const Duration(milliseconds: 200),+ child: _isConnecting+ ? SizedBox(+ key: const ValueKey('loading'),+ width: 22,+ height: 22,+ child: CircularProgressIndicator(+ strokeWidth: 2.5,+ color: cs.onPrimary,+ ),+ )+ : Text(+ l.loginSignIn,+ key: const ValueKey('text'),+ style: tt.titleMedium?.copyWith(+ fontWeight: FontWeight.w600,+ color: cs.onPrimary,+ ),+ ),+ ),+ ),+ ),+ AnimatedSize(+ duration: const Duration(milliseconds: 350),+ curve: Curves.easeOutCubic,+ alignment: Alignment.topCenter,+ child: _serverValid && _oidcConfig != null && _oidcConfig!.enabled+ ? _buildOidcButton(cs, tt)+ : const SizedBox.shrink(),+ ),+++ ],+ ),+ );+ }+}diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dartindex ac6fc81b..60c771dd 100644--- a/lib/screens/settings_screen.dart+++ b/lib/screens/settings_screen.dart@@ -1750,6 +1750,8 @@ class _SettingsScreenState extends State<SettingsScreen> {Row(children: [Flexible(child: Text(auth.username ?? l.userFallback, style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w700),overflow: TextOverflow.ellipsis)),+ const SizedBox(width: 8),+ _serverKindTag(cs, tt, auth.isBookOrbit),if (auth.isAdmin) ...[const SizedBox(width: 8),Container(@@ -2582,7 +2584,8 @@ class _SettingsScreenState extends State<SettingsScreen> {ButtonSegment(value: 'off', icon: const Icon(Icons.stop_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModeOff))),ButtonSegment(value: 'manual', icon: const Icon(Icons.queue_music_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModeManual))),ButtonSegment(value: 'auto_next', icon: const Icon(Icons.skip_next_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModeAuto))),- ButtonSegment(value: 'playlist', icon: const Icon(Icons.playlist_play_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModePlaylist))),+ if (!context.read<AuthProvider>().isBookOrbit || _mergedQueueMode == 'playlist')+ ButtonSegment(value: 'playlist', icon: const Icon(Icons.playlist_play_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModePlaylist))),],selected: {_mergedQueueMode},onSelectionChanged: _loaded@@ -2600,7 +2603,8 @@ class _SettingsScreenState extends State<SettingsScreen> {ButtonSegment(value: 'off', icon: const Icon(Icons.stop_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModeOff))),ButtonSegment(value: 'manual', icon: const Icon(Icons.queue_music_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModeManual))),ButtonSegment(value: 'auto_next', icon: const Icon(Icons.skip_next_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModeSeriesLabel))),- ButtonSegment(value: 'playlist', icon: const Icon(Icons.playlist_play_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModePlaylist))),+ if (!context.read<AuthProvider>().isBookOrbit || _bookQueueMode == 'playlist')+ ButtonSegment(value: 'playlist', icon: const Icon(Icons.playlist_play_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModePlaylist))),],selected: {_bookQueueMode},onSelectionChanged: _loaded@@ -2618,7 +2622,8 @@ class _SettingsScreenState extends State<SettingsScreen> {ButtonSegment(value: 'off', icon: const Icon(Icons.stop_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModeOff))),ButtonSegment(value: 'manual', icon: const Icon(Icons.queue_music_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModeManual))),ButtonSegment(value: 'auto_next', icon: const Icon(Icons.skip_next_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModeShowLabel))),- ButtonSegment(value: 'playlist', icon: const Icon(Icons.playlist_play_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModePlaylist))),+ if (!context.read<AuthProvider>().isBookOrbit || _podcastQueueMode == 'playlist')+ ButtonSegment(value: 'playlist', icon: const Icon(Icons.playlist_play_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModePlaylist))),],selected: {_podcastQueueMode},onSelectionChanged: _loaded@@ -4929,7 +4934,12 @@ class _SettingsScreenState extends State<SettingsScreen> {Padding(padding: const EdgeInsets.symmetric(horizontal: 20),child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [- Text(auth.username ?? l.userFallback, style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w700)),+ Row(children: [+ Flexible(child: Text(auth.username ?? l.userFallback, style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w700),+ overflow: TextOverflow.ellipsis)),+ const SizedBox(width: 8),+ _serverKindTag(cs, tt, auth.isBookOrbit),+ ]),const SizedBox(height: 6),Row(children: [Icon(Icons.dns_rounded, size: 13, color: cs.onSurfaceVariant.withValues(alpha: 0.4)),@@ -4968,6 +4978,7 @@ class _SettingsScreenState extends State<SettingsScreen> {),const SizedBox(height: 12),Divider(height: 1, indent: 20, endIndent: 20, color: cs.onSurface.withValues(alpha: 0.06)),+ if (!auth.isBookOrbit) ...[InkWell(onTap: () {Navigator.pop(ctx);@@ -5009,6 +5020,7 @@ class _SettingsScreenState extends State<SettingsScreen> {),),Divider(height: 1, indent: 20, endIndent: 20, color: cs.onSurface.withValues(alpha: 0.06)),+ ],// Other accountsif (otherAccounts.isNotEmpty) ...[const SizedBox(height: 4),@@ -5019,9 +5031,12 @@ class _SettingsScreenState extends State<SettingsScreen> {color: cs.onSurfaceVariant.withValues(alpha: 0.4), fontWeight: FontWeight.w600, letterSpacing: 0.5))),),...otherAccounts.map((account) {- final shortUrl = account.serverUrl+ final host = account.serverUrl.replaceAll(RegExp(r'^https?://'), '').replaceAll(RegExp(r'/+$'), '');+ final shortUrl = account.backend.isBookOrbit+ ? '$host - ${account.backend.displayName}'+ : host;return InkWell(onTap: () { Navigator.pop(ctx); _switchAccount(context, account); },onLongPress: () { Navigator.pop(ctx); _accountOptions(context, account); },@@ -5308,3 +5323,22 @@ class _SettingsScreenState extends State<SettingsScreen> {}}}++/// The kind of server the account is on, spelled to show where the app's+/// name comes from: ABS and orb, or abs and BookOrbit's ORB.+Widget _serverKindTag(ColorScheme cs, TextTheme tt, bool bookOrbit) => Container(+ padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1),+ decoration: BoxDecoration(+ color: cs.onSurface.withValues(alpha: 0.08),+ borderRadius: BorderRadius.circular(4),+ ),+ child: Text(+ bookOrbit ? 'absORB' : 'ABSorb',+ style: tt.labelSmall?.copyWith(+ color: cs.onSurfaceVariant,+ fontWeight: FontWeight.w600,+ fontSize: 9,+ letterSpacing: 0.4,+ ),+ ),+ );diff --git a/lib/services/android_auto_service.dart b/lib/services/android_auto_service.dartindex e301f9ec..3cf70697 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:home_widget/home_widget.dart';import 'package:shared_preferences/shared_preferences.dart';import 'api_service.dart';+import 'server_backend.dart';import 'audio_player_service.dart';import 'book_search_index.dart';import 'download_service.dart';@@ -335,7 +336,8 @@ class AndroidAutoService {customHeaders = Map<String, String>.from(jsonDecode(headersJson) as Map);} catch (_) {}}- return ApiService(+ return ApiService.forSession(+ backend: ServerBackend.loadActive(prefs),baseUrl: url,token: token,refreshToken: refreshToken,@@ -350,7 +352,7 @@ class AndroidAutoService {serverUrl: url,username: username,),- );+ ).withMediaReady();}Future<String?> getDefaultLibraryId() async {@@ -983,11 +985,12 @@ class AndroidAutoService {title: l?.androidAutoCatCollections ?? 'Collections',playable: false,),- MediaItem(- id: AutoMediaIds.libPlaylists(libraryId),- title: l?.androidAutoCatPlaylists ?? 'Playlists',- playable: false,- ),+ if (!ServerBackend.active.isBookOrbit)+ MediaItem(+ id: AutoMediaIds.libPlaylists(libraryId),+ title: l?.androidAutoCatPlaylists ?? 'Playlists',+ playable: false,+ ),];}diff --git a/lib/services/api_service.dart b/lib/services/api_service.dartindex 53e07d79..2265a309 100644--- a/lib/services/api_service.dart+++ b/lib/services/api_service.dart@@ -1,13 +1,22 @@import 'dart:async';import 'dart:convert';+import 'dart:math' as math;import 'package:flutter/foundation.dart';import 'package:http/http.dart' as http;import 'package:shared_preferences/shared_preferences.dart';import 'package:package_info_plus/package_info_plus.dart';import 'auth_tokens.dart';+import 'bookorbit_mapper.dart';+import 'bookorbit_media_proxy_stub.dart'+ if (dart.library.io) 'bookorbit_media_proxy.dart';+import 'player_settings.dart';+import 'server_backend.dart';+import 'socket_service.dart';import '../models/auth_session.dart';import '../utils/server_url.dart';+part 'bookorbit_api_service.dart';+/// Outcome of a local-session upsert. [serverTooOld] flags a 404/501 (the/// server predates /api/session/local) so the caller can fall back to the/// legacy /play flush instead of stranding the session in the replay queue.@@ -298,6 +307,104 @@ class ApiService {_loadCachedServerVersion(baseUrl);}+ /// The ApiService for a signed-in session: the plain Audiobookshelf client,+ /// or the BookOrbit one that answers in Audiobookshelf shapes. [backend]+ /// defaults to the active session's.+ factory ApiService.forSession({+ required String baseUrl,+ required String token,+ String? refreshToken,+ bool isLegacyToken = false,+ Map<String, String> customHeaders = const {},+ FutureOr<bool> Function(String newAccessToken, String? newRefreshToken)?+ onTokensRefreshed,+ Future<AuthTokens?> Function()? loadPersistedTokens,+ VoidCallback? onAuthExpired,+ ServerBackend? backend,+ }) {+ if ((backend ?? ServerBackend.active).isBookOrbit) {+ return BookOrbitApiService(+ baseUrl: baseUrl,+ token: token,+ refreshToken: refreshToken,+ isLegacyToken: isLegacyToken,+ customHeaders: customHeaders,+ onTokensRefreshed: onTokensRefreshed,+ loadPersistedTokens: loadPersistedTokens,+ onAuthExpired: onAuthExpired,+ );+ }+ return ApiService(+ baseUrl: baseUrl,+ token: token,+ refreshToken: refreshToken,+ isLegacyToken: isLegacyToken,+ customHeaders: customHeaders,+ onTokensRefreshed: onTokensRefreshed,+ loadPersistedTokens: loadPersistedTokens,+ onAuthExpired: onAuthExpired,+ );+ }++ ServerBackend get backend => ServerBackend.audiobookshelf;+ bool get isBookOrbit => backend.isBookOrbit;++ /// Await before handing media URLs to something that fetches them right+ /// away. Only BookOrbit has anything to wait for (its media proxy).+ Future<void> ensureMediaReady() async {}++ Future<ApiService> withMediaReady() async {+ await ensureMediaReady();+ return this;+ }++ /// URL for downloading an ebook file for the reader.+ String buildEbookUrl(String itemId, String ino) =>+ '$_cleanBaseUrl/api/items/$itemId/file/$ino?token=$token';++ /// How many pages a comic file has, when the server hands them out one at+ /// a time (BookOrbit, which opens CBR and CB7 too). Null means the archive+ /// has to be opened on the phone.+ Future<int?> comicPageCount(String fileId) async => null;++ /// Image of comic page [index] (from 0), when [comicPageCount] answered.+ String? comicPageUrl(String fileId, int index) => null;++ /// The cover slots a book uses on BookOrbit ('audio', 'ebook'). Empty on+ /// Audiobookshelf, which has one cover per item.+ Future<List<String>> coverSlots(String itemId) async => const [];++ /// The cover search source the user picked as default on the server.+ Future<String?> defaultCoverSearchProvider() async => null;++ /// Books the server thinks are like [itemId], as {id, title, authorName,+ /// hasCover, isAudiobook, finished}. Only BookOrbit has this.+ Future<List<Map<String, dynamic>>> getSimilarBooks(String itemId) async => const [];++ /// BookOrbit's per-user reading status (want_to_read, on_hold, ...).+ Future<bool> setReadStatus(String itemId, String status) async => false;++ /// A private note on a book, or null to remove it. Only BookOrbit has this.+ Future<bool> setPersonalNote(String itemId, String? note) async => false;++ /// The metadata providers the server has turned on, as {key, label}, when+ /// it can say. Null means the app's own list applies.+ Future<List<Map<String, String>>?> bookMatchProviders() async => null;++ /// URL a background download fetches [ino] from. Same as [buildFileUrl]+ /// on Audiobookshelf.+ String buildDownloadFileUrl(String itemId, String ino) => buildFileUrl(itemId, ino);++ /// Headers for a download of [url] built by [buildDownloadFileUrl].+ Map<String, String> downloadHeadersFor(String url) => mediaHeaders;++ /// Called once before a book's files are queued for download.+ Future<void> prepareDownload(String itemId) async {}++ /// Show a collection to everyone on the server or only its owner. Only+ /// BookOrbit has this; Audiobookshelf collections are always shared.+ Future<bool> setCollectionPublic(String collectionId, bool isPublic) async => false;+/// Current access token (for external use like cover URLs, socket auth).String get token => _accessToken;@@ -412,18 +519,21 @@ class ApiService {if (!lock.isCompleted) lock.complete();}- Future<bool> _refreshTokenPairOnce() async {- final refreshToken = _refreshToken;- if (_isLegacyToken || refreshToken == null) return false;- try {- final response = await _post(+ Future<http.Response> _sendRefresh(String refreshToken) => _post(Uri.parse('$_cleanBaseUrl/auth/refresh'),headers: {...customHeaders,'x-refresh-token': refreshToken,if (!kIsWeb) 'User-Agent': userAgent,},- ).timeout(const Duration(seconds: 15));+ );++ Future<bool> _refreshTokenPairOnce() async {+ final refreshToken = _refreshToken;+ if (_isLegacyToken || refreshToken == null) return false;+ try {+ final response = await _sendRefresh(refreshToken)+ .timeout(const Duration(seconds: 15));if (response.statusCode != 200) {debugPrint('[API] Proactive token refresh failed: ${response.statusCode} '@@ -454,7 +564,7 @@ class ApiService {static bool _apiKeyCheckRunning = false;void _checkRevokedApiKey() {- if (_apiKeyCheckRunning) return;+ if (isBookOrbit || _apiKeyCheckRunning) return;final last = _apiKeyCheckedAt;if (last != null && DateTime.now().difference(last) < const Duration(minutes: 1)) return;_apiKeyCheckedAt = DateTime.now();@@ -509,14 +619,8 @@ class ApiService {// Timeout is load-bearing: this is awaited from tryRestoreSession via// the 401-retry path, and a stalled response here would otherwise hold// the splash screen forever.- final response = await _post(- Uri.parse('$_cleanBaseUrl/auth/refresh'),- headers: {- ...customHeaders,- 'x-refresh-token': refreshTokenSent,- if (!kIsWeb) 'User-Agent': userAgent,- },- ).timeout(const Duration(seconds: 15));+ final response = await _sendRefresh(refreshTokenSent)+ .timeout(const Duration(seconds: 15));if (response.statusCode == 200) {final data = jsonDecode(response.body) as Map<String, dynamic>;@@ -746,7 +850,16 @@ class ApiService {required String username,required String password,Map<String, String> customHeaders = const {},+ ServerBackend backend = ServerBackend.audiobookshelf,}) async {+ if (backend.isBookOrbit) {+ return BookOrbitApiService.signIn(+ serverUrl: serverUrl,+ username: username,+ password: password,+ customHeaders: customHeaders,+ );+ }final url = serverUrl.endsWith('/')? '${serverUrl}login': '$serverUrl/login';@@ -780,7 +893,9 @@ class ApiService {required String serverUrl,required String apiKey,Map<String, String> customHeaders = const {},+ ServerBackend backend = ServerBackend.audiobookshelf,}) async {+ if (backend.isBookOrbit) return (null, 0);final base = serverUrl.endsWith('/') ? serverUrl : '$serverUrl/';final url = '${base}api/me';@@ -800,7 +915,10 @@ class ApiService {}/// Ping the server to check connectivity.- static Future<bool> pingServer(String serverUrl, {Map<String, String> customHeaders = const {}}) async {+ static Future<bool> pingServer(String serverUrl, {Map<String, String> customHeaders = const {}, ServerBackend? backend}) async {+ if ((backend ?? ServerBackend.active).isBookOrbit) {+ return (await BookOrbitApiService.probe(serverUrl, customHeaders: customHeaders)).ok;+ }final url = serverUrl.endsWith('/')? '${serverUrl}ping': '$serverUrl/ping';@@ -822,7 +940,15 @@ class ApiService {static Future<({bool ok, String? detail})> pingServerDetailed(String serverUrl, {Map<String, String> customHeaders = const {},+ ServerBackend? backend,}) async {+ if ((backend ?? ServerBackend.active).isBookOrbit) {+ return BookOrbitApiService.probe(+ serverUrl,+ customHeaders: customHeaders,+ timeout: const Duration(seconds: 15),+ );+ }final url = serverUrl.endsWith('/') ? '${serverUrl}ping' : '$serverUrl/ping';try {final response = await http@@ -865,7 +991,9 @@ class ApiService {}/// Get the server version via the /status endpoint (no auth needed).- static Future<String?> getServerVersion(String serverUrl, {Map<String, String> customHeaders = const {}}) async {+ static Future<String?> getServerVersion(String serverUrl, {Map<String, String> customHeaders = const {}, ServerBackend? backend}) async {+ // BookOrbit only tells a signed-in client its version.+ if ((backend ?? ServerBackend.active).isBookOrbit) return null;final url = serverUrl.endsWith('/')? '${serverUrl}status': '$serverUrl/status';@@ -1078,7 +1206,9 @@ class ApiService {}/// Build a cover image URL for a library item.- String getCoverUrl(String itemId, {int? width = 400, int? updatedAt}) {+ /// [coverSlot] picks BookOrbit's 'audio' (square) or 'ebook' (portrait)+ /// cover and is ignored on Audiobookshelf, which has one.+ String getCoverUrl(String itemId, {int? width = 400, int? updatedAt, String? coverSlot}) {var url = '$_cleanBaseUrl/api/items/$itemId/cover?token=$token';if (width != null) url += '&width=$width';if (updatedAt != null) url += '&ts=$updatedAt';@@ -3881,7 +4011,7 @@ class ApiService {}/// Upload a cover image URL for a library item (admin only)- Future<bool> updateItemCoverUrl(String itemId, String url) async {+ Future<bool> updateItemCoverUrl(String itemId, String url, {String? coverSlot}) async {try {final r = await _authPost(Uri.parse('$_cleanBaseUrl/api/items/$itemId/cover'),@@ -3895,7 +4025,7 @@ class ApiService {/// Remove a library item's cover, leaving it with none (admin only)./// DELETE /api/items/:id/cover- Future<bool> removeItemCover(String itemId) async {+ Future<bool> removeItemCover(String itemId, {String? coverSlot}) async {try {final r = await _authDelete(Uri.parse('$_cleanBaseUrl/api/items/$itemId/cover'),@@ -3907,7 +4037,7 @@ class ApiService {}/// Upload a cover image file for a library item (admin only)- Future<bool> uploadItemCover(String itemId, String filePath) async {+ Future<bool> uploadItemCover(String itemId, String filePath, {String? coverSlot}) async {try {final req = http.MultipartRequest('POST',@@ -3924,7 +4054,7 @@ class ApiService {/// Search provider cover images for a book./// GET /api/search/covers?title=&author=&provider= -> { results: [url, ...] }Future<List<String>> searchCovers(String title,- {String? author, String provider = 'google'}) async {+ {String? author, String provider = 'google', String? coverSlot}) async {try {final uri = Uri.parse('$_cleanBaseUrl/api/search/covers').replace(queryParameters: {'title': title,diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dartindex b43300bb..5350b514 100644--- a/lib/services/audio_player_service.dart+++ b/lib/services/audio_player_service.dart@@ -6972,6 +6972,9 @@ class AudioPlayerService extends ChangeNotifier {_setupSync();}}+ // BookOrbit audio streams through the in-app proxy, which a long+ // suspension can take down; a lock screen play doesn't foreground the app.+ if (_api?.isBookOrbit == true) await _api!.ensureMediaReady();// A source streaming through a session the server no longer has (closed// by the pause timeout, or replaced since) would play from the cache// until that runs out, then die with a 404 and a five-second retry.@@ -7164,8 +7167,12 @@ class AudioPlayerService extends ChangeNotifier {if (_knownOffline || _isOfflineMode) return false;if (ChromecastService().isCasting) return false;final lastPause = _lastPauseTime;- if (lastPause == null ||- DateTime.now().difference(lastPause) < _serverPositionCheckMinPause) {+ // BookOrbit has no live progress push to cover a short pause, so check+ // after any pause long enough for someone to have listened elsewhere.+ final minPause = _api!.isBookOrbit+ ? const Duration(seconds: 10)+ : _serverPositionCheckMinPause;+ if (lastPause == null || DateTime.now().difference(lastPause) < minPause) {return false;}final manualOffline =diff --git a/lib/services/bookorbit_api_service.dart b/lib/services/bookorbit_api_service.dartnew file mode 100644index 00000000..87890026--- /dev/null+++ b/lib/services/bookorbit_api_service.dart@@ -0,0 +1,3196 @@+part of 'api_service.dart';++class _BoHttpError implements Exception {+ final int status;+ final String message;+ _BoHttpError(this.status, this.message);+ @override+ String toString() => 'BookOrbit HTTP $status: $message';+}++class _BoListenSession {+ final String bookId;+ final String sessionUuid;+ final DateTime startedAt;+ int? fileId;+ double listenedSeconds = 0;+ double? startPercent;+ double? lastPercent;+ bool deviceRemembered = false;++ _BoListenSession(this.bookId, this.sessionUuid, this.startedAt);+}++class _BoTicket {+ final String token;+ final DateTime expiresAt;+ final Set<String> fileIds;+ _BoTicket(this.token, this.expiresAt, this.fileIds);+}++/// ApiService for a BookOrbit server.+///+/// The rest of the app speaks Audiobookshelf, so this keeps every public+/// method and answers the Audiobookshelf routes they call from BookOrbit+/// instead: the authenticated request helpers are overridden and each+/// `/api/...` request is routed to a handler that calls `/api/v1/...` on the+/// BookOrbit server and returns an Audiobookshelf-shaped response. Routes+/// with no BookOrbit counterpart answer 404, which the callers already treat+/// as "not supported here".+class BookOrbitApiService extends ApiService implements BookOrbitTokenSource {+ BookOrbitApiService({+ required super.baseUrl,+ required super.token,+ super.refreshToken,+ super.isLegacyToken,+ super.customHeaders,+ super.onTokensRefreshed,+ super.loadPersistedTokens,+ super.onAuthExpired,+ super.httpClient,+ }) {+ if (token.isNotEmpty && baseUrl.isNotEmpty) {+ BookOrbitMediaProxy.instance.attach(this);+ unawaited(BookOrbitMediaProxy.instance.ensureRunning());+ }+ }++ @override+ ServerBackend get backend => ServerBackend.bookorbit;++ String get _basePath => Uri.parse(_cleanBaseUrl).path;+ String get _v1 => '$_cleanBaseUrl/api/v1';++ static String? _platformSource() {+ if (kIsWeb) return null;+ return switch (defaultTargetPlatform) {+ TargetPlatform.android => 'android',+ TargetPlatform.iOS => 'ios',+ _ => null,+ };+ }++ static final math.Random _rng = math.Random.secure();++ static String _uuid() {+ final b = List<int>.generate(16, (_) => _rng.nextInt(256));+ b[6] = (b[6] & 0x0f) | 0x40;+ b[8] = (b[8] & 0x3f) | 0x80;+ final h = b.map((x) => x.toRadixString(16).padLeft(2, '0')).join();+ return '${h.substring(0, 8)}-${h.substring(8, 12)}-${h.substring(12, 16)}-'+ '${h.substring(16, 20)}-${h.substring(20)}';+ }++ /// ISO-8601 in UTC to the millisecond, the precision the server keeps.+ static String _iso(DateTime t) {+ final u = t.toUtc();+ return DateTime.utc(u.year, u.month, u.day, u.hour, u.minute, u.second, u.millisecond)+ .toIso8601String();+ }++ static final Map<String, Map<String, dynamic>> _manifests = {};+ static final Map<String, DateTime> _manifestAt = {};+ static final Map<String, Map<String, dynamic>> _details = {};+ static final Map<String, DateTime> _detailAt = {};+ static final Map<String, int> _revisions = {};+ static final Map<String, _BoListenSession> _sessions = {};+ static final Map<String, String> _coverVersions = {};+ static final Map<String, String> _bookLibrary = {};+ static final Map<String, _BoTicket> _tickets = {};+ static final Map<String, String> _assetByFile = {};+ static final Map<String, String> _serverVersions = {};+ static List<Map<String, dynamic>>? _librariesCache;+ static DateTime? _librariesAt;+ static final Map<String, ({DateTime at, Future<Object?> value})> _recent = {};++ /// One answer per [key] for [ttl], shared by concurrent callers. Failures+ /// are not kept.+ Future<T> _cached<T>(String key, Duration ttl, Future<T> Function() load) {+ final k = _key(key);+ final hit = _recent[k];+ if (hit != null && DateTime.now().difference(hit.at) < ttl) return hit.value.then((v) => v as T);+ final future = load();+ _recent[k] = (at: DateTime.now(), value: future);+ future.then<void>((_) {}, onError: (Object _) {+ if (identical(_recent[k]?.value, future)) _recent.remove(k);+ });+ return future;+ }++ static const _manifestTtl = Duration(minutes: 10);+ static const _detailTtl = Duration(minutes: 2);++ /// Keyed by book alone so the local and remote address of one server share+ /// them (cover URLs stay the same and image caches keep hitting). They are+ /// cleared whenever the signed-in account changes.+ String _key(String id) => id;++ /// Forget everything cached for the signed-in account.+ static void clearCaches() {+ _manifests.clear();+ _manifestAt.clear();+ _details.clear();+ _detailAt.clear();+ _revisions.clear();+ _sessions.clear();+ _coverVersions.clear();+ _bookLibrary.clear();+ _tickets.clear();+ _assetByFile.clear();+ _librariesCache = null;+ _librariesAt = null;+ _recent.clear();+ }++ @override+ String get upstreamBaseUrl => _cleanBaseUrl;++ @override+ Map<String, String> get upstreamCustomHeaders => customHeaders;++ @override+ Future<String?> currentAccessToken() async {+ await _ensureFreshAccessToken();+ return _accessToken.isEmpty ? null : _accessToken;+ }++ @override+ Future<String?> tokenAfterRejection() async {+ final outcome = await _refreshAccessToken();+ if (outcome == _RefreshOutcome.rejected) onAuthExpired?.call();+ return outcome == _RefreshOutcome.refreshed ? _accessToken : null;+ }++ @override+ Future<void> ensureMediaReady() async {+ BookOrbitMediaProxy.instance.attach(this);+ await BookOrbitMediaProxy.instance.ensureRunning();+ if (!_watchingCoverShape) {+ _watchingCoverShape = true;+ PlayerSettings.settingsChanged.addListener(() => unawaited(loadCoverShape()));+ }+ await loadCoverShape();+ }++ /// The cover shape picked in settings, globally and per library. With+ /// rectangle covers a book shows BookOrbit's portrait book cover, falling+ /// back to the square one when it has none. Kept here because cover URLs+ /// are built synchronously during layout.+ static bool _rectCovers = false;+ static final Map<String, bool> _rectCoversByLibrary = {};+ static bool _watchingCoverShape = false;++ static Future<void> loadCoverShape() async {+ final global = await PlayerSettings.getRectangleCovers();+ final byLibrary = <String, bool>{};+ for (final lib in _librariesCache ?? const <Map<String, dynamic>>[]) {+ final id = '${lib['id']}';+ final v = await PlayerSettings.getRectangleCoversOverride(id);+ if (v != null) byLibrary[id] = v == 'rect';+ }+ final changed = global != _rectCovers ||+ byLibrary.length != _rectCoversByLibrary.length ||+ byLibrary.entries.any((e) => _rectCoversByLibrary[e.key] != e.value);+ if (!changed) return;+ _rectCovers = global;+ _rectCoversByLibrary+ ..clear()+ ..addAll(byLibrary);+ // Screens rebuilt on the settings change before this finished; once+ // more so they pick up the other cover.+ PlayerSettings.notifySettingsChanged();+ }++ String _listCoverSlot(String itemId) {+ final lib = _bookLibrary[_key(itemId)];+ final rect = (lib == null ? null : _rectCoversByLibrary[lib]) ?? _rectCovers;+ return rect ? 'ebook' : 'audio';+ }++ /// A magic-link sign-in is a browser-style session: its refresh token only+ /// travels as the `refresh_token` cookie. Stored with this prefix so the+ /// refresh and sign-out calls know to send it that way.+ static const _webRefreshPrefix = 'web:';++ static String? _refreshCookie(http.Response r) {+ final raw = r.headers['set-cookie'];+ if (raw == null) return null;+ return RegExp(r'refresh_token=([^;,\s]+)').firstMatch(raw)?.group(1);+ }++ Map<String, String> _refreshHeaders(String refreshToken) => {+ ...customHeaders,+ 'Content-Type': 'application/json',+ if (!kIsWeb) 'User-Agent': ApiService.userAgent,+ if (refreshToken.startsWith(_webRefreshPrefix))+ 'Cookie': 'refresh_token=${refreshToken.substring(_webRefreshPrefix.length)}',+ };++ String _refreshBody(String refreshToken) => refreshToken.startsWith(_webRefreshPrefix)+ ? '{}'+ : jsonEncode({'refreshToken': refreshToken});++ @override+ Future<http.Response> _sendRefresh(String refreshToken) async {+ final r = await _post(+ Uri.parse('$_v1/auth/refresh'),+ headers: _refreshHeaders(refreshToken),+ body: _refreshBody(refreshToken),+ );+ if (r.statusCode != 200 || !refreshToken.startsWith(_webRefreshPrefix)) return r;+ final data = jsonDecode(r.body) as Map<String, dynamic>;+ final next = _refreshCookie(r);+ if (next != null) data['refreshToken'] = '$_webRefreshPrefix$next';+ return http.Response.bytes(+ utf8.encode(jsonEncode(data)),+ 200,+ headers: {'content-type': 'application/json; charset=utf-8'},+ );+ }++ static String _deviceLabel() {+ final model = [ApiService.deviceManufacturer, ApiService.deviceModel]+ .where((s) => s.isNotEmpty)+ .join(' ');+ final label = model.isEmpty ? 'Absorb' : 'Absorb on $model';+ return label.length > 100 ? label.substring(0, 100) : label;+ }++ static String _v1Of(String serverUrl) => '${normalizeServerUrl(serverUrl)}/api/v1';++ /// A BookOrbit server answers its public login options with a JSON object+ /// carrying `passwordLoginEnabled`; nothing else does.+ static Future<({bool ok, String? detail})> probe(+ String serverUrl, {+ Map<String, String> customHeaders = const {},+ Duration timeout = const Duration(seconds: 10),+ }) async {+ try {+ final r = await http+ .get(Uri.parse('${_v1Of(serverUrl)}/auth/login-options'),+ headers: customHeaders.isNotEmpty ? customHeaders : null)+ .timeout(timeout);+ if (r.statusCode != 200) {+ return (ok: false, detail: 'Server returned HTTP ${r.statusCode} for the BookOrbit login options.');+ }+ final data = jsonDecode(r.body);+ if (data is Map && data.containsKey('passwordLoginEnabled')) {+ final sso = (data['oidcProviders'] as List<dynamic>? ?? const []).isNotEmpty;+ if (data['passwordLoginEnabled'] == false && !sso) {+ return (ok: false, detail: 'Password sign-in is turned off on this BookOrbit server.');+ }+ return (ok: true, detail: null);+ }+ return (ok: false, detail: 'The server answered, but it does not look like BookOrbit.');+ } on FormatException {+ return (ok: false, detail: 'The server answered, but it does not look like BookOrbit.');+ } catch (e) {+ return (ok: false, detail: ApiService._describePingError(e));+ }+ }++ /// Sign in and answer in the shape of an Audiobookshelf /login response.+ static Future<(Map<String, dynamic>?, int)> signIn({+ required String serverUrl,+ required String username,+ required String password,+ Map<String, String> customHeaders = const {},+ }) async {+ try {+ final r = await http+ .post(+ Uri.parse('${_v1Of(serverUrl)}/auth/login'),+ headers: {+ ...customHeaders,+ 'Content-Type': 'application/json',+ if (!kIsWeb) 'User-Agent': ApiService.userAgent,+ },+ body: jsonEncode({+ 'username': username,+ 'password': password,+ 'clientKind': 'native',+ 'deviceLabel': _deviceLabel(),+ }),+ )+ .timeout(const Duration(seconds: 20));+ if (r.statusCode != 200 && r.statusCode != 201) {+ debugPrint('[BookOrbit] login failed: ${r.statusCode} ${r.body}');+ return (null, r.statusCode);+ }+ final data = jsonDecode(r.body) as Map<String, dynamic>;+ final rawUser = data['user'] as Map<String, dynamic>? ?? const {};+ if (rawUser['isDefaultPassword'] == true) {+ return (<String, dynamic>{'bookOrbitDefaultPassword': true}, 403);+ }+ return (await _loginShape(serverUrl, data, customHeaders, data['refreshToken'] as String?), 200);+ } catch (e) {+ debugPrint('[BookOrbit] login error: $e');+ return (null, 0);+ }+ }++ /// A BookOrbit sign-in answer as an Audiobookshelf /login response, with+ /// the tokens inside `user` the way current Audiobookshelf servers put them.+ static Future<Map<String, dynamic>> _loginShape(+ String serverUrl,+ Map<String, dynamic> data,+ Map<String, String> customHeaders,+ String? refreshToken,+ ) async {+ final rawUser = data['user'] as Map<String, dynamic>? ?? const {};+ final access = data['accessToken'] as String?;+ final version = access == null ? null : await _fetchVersion(serverUrl, access, customHeaders);+ final user = BookOrbitMapper.user(rawUser)+ ..['accessToken'] = access+ ..['refreshToken'] = refreshToken;+ return {+ 'user': user,+ 'userDefaultLibraryId': null,+ 'serverSettings': {'version': version ?? ''},+ 'ereaderDevices': const [],+ 'Source': 'bookorbit',+ };+ }++ /// What a BookOrbit server offers before anyone signs in: whether+ /// passwords work and which single sign-on providers it has. Null when the+ /// server can't be read or isn't BookOrbit.+ static Future<({bool passwordLogin, List<Map<String, dynamic>> oidcProviders})?> loginOptions(+ String serverUrl, {+ Map<String, String> customHeaders = const {},+ }) async {+ try {+ final r = await http+ .get(Uri.parse('${_v1Of(serverUrl)}/auth/login-options'),+ headers: customHeaders.isNotEmpty ? customHeaders : null)+ .timeout(const Duration(seconds: 10));+ if (r.statusCode != 200) return null;+ final data = jsonDecode(r.body);+ if (data is! Map || !data.containsKey('passwordLoginEnabled')) return null;+ return (+ passwordLogin: data['passwordLoginEnabled'] != false,+ oidcProviders: (data['oidcProviders'] as List<dynamic>? ?? const [])+ .whereType<Map<String, dynamic>>()+ .where((p) => p['enabled'] != false && p['slug'] is String && p['clientId'] is String)+ .toList(),+ );+ } catch (e) {+ debugPrint('[BookOrbit] login options failed: $e');+ return null;+ }+ }++ static Map<String, String> _publicHeaders(Map<String, String> customHeaders) => {+ ...customHeaders,+ 'Content-Type': 'application/json',+ if (!kIsWeb) 'User-Agent': ApiService.userAgent,+ };++ static String _errorText(http.Response r) {+ try {+ final m = (jsonDecode(r.body) as Map)['message'];+ if (m != null) return '$m';+ } catch (_) {}+ return r.body.length > 200 ? r.body.substring(0, 200) : r.body;+ }++ /// The one-time state for an OIDC sign-in and the identity provider's+ /// sign-in page. The app sends the user there itself.+ static Future<({String state, String authorizationEndpoint})> oidcState(+ String serverUrl,+ String slug, {+ Map<String, String> customHeaders = const {},+ }) async {+ final r = await http+ .post(+ Uri.parse('${_v1Of(serverUrl)}/auth/oidc/${Uri.encodeComponent(slug)}/state'),+ headers: _publicHeaders(customHeaders),+ body: '{}',+ )+ .timeout(const Duration(seconds: 20));+ if (r.statusCode != 200 && r.statusCode != 201) {+ throw Exception('BookOrbit returned HTTP ${r.statusCode}: ${_errorText(r)}');+ }+ final data = jsonDecode(r.body) as Map<String, dynamic>;+ return (state: data['state'] as String, authorizationEndpoint: data['authorizationEndpoint'] as String);+ }++ /// Trade the identity provider's code for BookOrbit tokens and answer like+ /// [signIn], with the server's reason when it says no.+ static Future<(Map<String, dynamic>?, int, String?)> signInWithOidc({+ required String serverUrl,+ required String code,+ required String codeVerifier,+ required String redirectUri,+ required String nonce,+ required String state,+ Map<String, String> customHeaders = const {},+ }) async {+ try {+ final r = await http+ .post(+ Uri.parse('${_v1Of(serverUrl)}/auth/oidc/callback'),+ headers: _publicHeaders(customHeaders),+ body: jsonEncode({+ 'code': code,+ 'codeVerifier': codeVerifier,+ 'redirectUri': redirectUri,+ 'nonce': nonce,+ 'state': state,+ 'clientKind': 'native',+ 'deviceLabel': _deviceLabel(),+ }),+ )+ .timeout(const Duration(seconds: 30));+ if (r.statusCode != 200 && r.statusCode != 201) {+ debugPrint('[BookOrbit] OIDC callback failed: ${r.statusCode} ${r.body}');+ return (null, r.statusCode, _errorText(r));+ }+ final data = jsonDecode(r.body) as Map<String, dynamic>;+ if (data['accessToken'] is! String) return (null, r.statusCode, 'No sign-in tokens in the reply');+ final cookie = _refreshCookie(r);+ final refresh = data['refreshToken'] as String? ?? (cookie == null ? null : '$_webRefreshPrefix$cookie');+ return (await _loginShape(serverUrl, data, customHeaders, refresh), 200, null);+ } catch (e) {+ debugPrint('[BookOrbit] OIDC callback error: $e');+ return (null, 0, '$e');+ }+ }++ /// The token from a BookOrbit magic link (`https://host/magic?token=...`),+ /// or the token itself when that is what was pasted.+ static String? magicLinkToken(String input) {+ final text = input.trim();+ final fromUrl = Uri.tryParse(text)?.queryParameters['token'];+ if (fromUrl != null && fromUrl.isNotEmpty) return fromUrl;+ if (RegExp(r'^[A-Za-z0-9_-]{16,512}$').hasMatch(text)) return text;+ return null;+ }++ /// Sign in with a magic link and answer like [signIn].+ static Future<(Map<String, dynamic>?, int)> signInWithMagicLink({+ required String serverUrl,+ required String link,+ Map<String, String> customHeaders = const {},+ }) async {+ final token = magicLinkToken(link);+ if (token == null) return (null, 400);+ try {+ final r = await http+ .post(+ Uri.parse('${_v1Of(serverUrl)}/auth/magic-links/login'),+ headers: {+ ...customHeaders,+ 'Content-Type': 'application/json',+ if (!kIsWeb) 'User-Agent': ApiService.userAgent,+ },+ body: jsonEncode({'token': token}),+ )+ .timeout(const Duration(seconds: 20));+ if (r.statusCode != 200 && r.statusCode != 201) {+ debugPrint('[BookOrbit] magic link login failed: ${r.statusCode} ${r.body}');+ return (null, r.statusCode);+ }+ final data = jsonDecode(r.body) as Map<String, dynamic>;+ final cookie = _refreshCookie(r);+ return (+ await _loginShape(serverUrl, data, customHeaders, cookie == null ? null : '$_webRefreshPrefix$cookie'),+ 200,+ );+ } catch (e) {+ debugPrint('[BookOrbit] magic link login error: $e');+ return (null, 0);+ }+ }++ static Future<String?> _fetchVersion(+ String serverUrl,+ String accessToken,+ Map<String, String> customHeaders,+ ) async {+ final origin = ApiService._originOf(serverUrl) ?? serverUrl;+ final cached = _serverVersions[origin];+ if (cached != null) return cached;+ try {+ final r = await http.get(+ Uri.parse('${_v1Of(serverUrl)}/app-info'),+ headers: {...customHeaders, 'Authorization': 'Bearer $accessToken'},+ ).timeout(const Duration(seconds: 10));+ if (r.statusCode == 200) {+ final v = (jsonDecode(r.body) as Map<String, dynamic>)['version'] as String?;+ if (v != null && v.isNotEmpty) {+ final label = 'BookOrbit ${v.startsWith('v') ? v.substring(1) : v}';+ _serverVersions[origin] = label;+ return label;+ }+ }+ } catch (_) {}+ return null;+ }++ @override+ Future<bool> revokeServerSession({bool allDevices = false}) async {+ final refresh = _refreshToken;+ if (refresh == null) return false;+ try {+ final r = await _post(+ Uri.parse('$_v1/auth/logout'),+ headers: _refreshHeaders(refresh),+ body: _refreshBody(refresh),+ ).timeout(const Duration(seconds: 10));+ return r.statusCode >= 200 && r.statusCode < 300;+ } catch (e) {+ debugPrint('[BookOrbit] logout error: $e');+ return false;+ }+ }++ @override+ Future<PasswordChangeResult> changeMyPassword({+ required String currentPassword,+ required String newPassword,+ }) async =>+ // BookOrbit signs every device out on a password change, so leave it+ // to the web app rather than strand this session.+ const PasswordChangeResult(PasswordChangeStatus.unsupported);++ @override+ Future<AuthSessionsResult> getAuthSessions({int page = 0, int itemsPerPage = 20}) async =>+ const AuthSessionsResult(AuthSessionsStatus.unsupported);++ Uri _boUri(String path, [Map<String, dynamic>? query]) {+ final q = <String, dynamic>{};+ query?.forEach((k, v) {+ if (v == null) return;+ q[k] = v is Iterable ? v.map((e) => '$e').toList() : '$v';+ });+ return Uri.parse('$_v1$path').replace(queryParameters: q.isEmpty ? null : q);+ }++ bool _isNative(Uri url) => url.path.startsWith('$_basePath/api/v1/');++ static const _timeout = Duration(seconds: 20);++ dynamic _decode(http.Response r) {+ if (r.statusCode < 200 || r.statusCode >= 300) {+ throw _BoHttpError(r.statusCode, r.body.length > 300 ? r.body.substring(0, 300) : r.body);+ }+ if (r.body.isEmpty) return null;+ return jsonDecode(r.body);+ }++ Future<dynamic> _boGet(String path, [Map<String, dynamic>? query, Duration timeout = _timeout]) async =>+ _decode(await super._authGet(_boUri(path, query), timeout: timeout));++ Future<dynamic> _boPost(String path, [Object? body, Duration timeout = _timeout]) async =>+ _decode(await super._authPost(+ _boUri(path),+ body: body == null ? null : jsonEncode(body),+ timeout: timeout,+ ));++ /// PUT, and DELETE with a body, which the shared helpers don't cover.+ Future<dynamic> _boSend(String method, String path, Object body) async {+ await _ensureFreshAccessToken();+ final payload = jsonEncode(body);+ Future<http.Response> send() async {+ final req = http.Request(method, _boUri(path))+ ..headers.addAll(_headers)+ ..body = payload;+ final client = _httpClient ?? http.Client();+ try {+ final streamed = await client.send(req).timeout(_timeout);+ return await http.Response.fromStream(streamed).timeout(_timeout);+ } finally {+ if (_httpClient == null) client.close();+ }+ }++ var r = await send();+ if (r.statusCode == 401) {+ final outcome = await _refreshAccessToken();+ if (outcome == _RefreshOutcome.refreshed) r = await send();+ if (outcome == _RefreshOutcome.rejected) onAuthExpired?.call();+ }+ return _decode(r);+ }++ Future<dynamic> _boPut(String path, Object body) => _boSend('PUT', path, body);++ Future<dynamic> _boPatch(String path, Object body) async => _decode(await super._authPatch(+ _boUri(path),+ body: jsonEncode(body),+ timeout: _timeout,+ ));++ Future<dynamic> _boDelete(String path, {Object? body}) async {+ if (body != null) return _boSend('DELETE', path, body);+ return _decode(await super._authDelete(_boUri(path), timeout: _timeout));+ }++ static Future<List<T>> _pool<T>(List<Future<T> Function()> jobs, {int width = 6}) async {+ final results = List<T?>.filled(jobs.length, null);+ var next = 0;+ Future<void> worker() async {+ while (true) {+ final i = next++;+ if (i >= jobs.length) return;+ results[i] = await jobs[i]();+ }+ }++ await Future.wait(List.generate(math.min(width, jobs.length), (_) => worker()));+ return results.cast<T>();+ }++ @override+ Future<http.Response> _authGet(Uri url,+ {Map<String, String>? headers,+ bool sendRefreshTokenHeader = false,+ Duration timeout = const Duration(seconds: 15)}) {+ if (_isNative(url)) return super._authGet(url, headers: headers, timeout: timeout);+ return _route('GET', url, null);+ }++ @override+ Future<http.Response> _authPost(Uri url,+ {Map<String, String>? headers, Object? body, Duration timeout = const Duration(seconds: 15)}) {+ if (_isNative(url)) return super._authPost(url, headers: headers, body: body, timeout: timeout);+ return _route('POST', url, body);+ }++ @override+ Future<http.Response> _authPatch(Uri url,+ {Map<String, String>? headers, Object? body, Duration timeout = const Duration(seconds: 15)}) {+ if (_isNative(url)) return super._authPatch(url, headers: headers, body: body, timeout: timeout);+ return _route('PATCH', url, body);+ }++ @override+ Future<http.Response> _authDelete(Uri url,+ {Map<String, String>? headers, Duration timeout = const Duration(seconds: 15)}) {+ if (_isNative(url)) return super._authDelete(url, headers: headers, timeout: timeout);+ return _route('DELETE', url, null);+ }++ static http.Response _json(Object? data, [int status = 200]) => http.Response.bytes(+ utf8.encode(jsonEncode(data)),+ status,+ headers: {'content-type': 'application/json; charset=utf-8'},+ );++ static http.Response _status(int status, [String message = '']) =>+ _json({'error': message}, status);++ Future<http.Response> _route(String method, Uri url, Object? body) async {+ var path = url.path;+ if (_basePath.isNotEmpty && path.startsWith(_basePath)) {+ path = path.substring(_basePath.length);+ }+ final seg = path.split('/').where((s) => s.isNotEmpty).map(Uri.decodeComponent).toList();+ final q = url.queryParameters;+ Map<String, dynamic> json = const {};+ if (body is String && body.isNotEmpty) {+ try {+ final decoded = jsonDecode(body);+ if (decoded is Map<String, dynamic>) json = decoded;+ } catch (_) {}+ }+ try {+ final result = await _dispatch(method, seg, q, json);+ if (result == null) {+ debugPrint('[BookOrbit] No BookOrbit route for $method $path');+ return _status(404, 'Not available on BookOrbit');+ }+ return result;+ } on _BoHttpError catch (e) {+ debugPrint('[BookOrbit] $method $path -> ${e.status} ${e.message}');+ return _status(e.status, e.message);+ } on http.ClientException {+ rethrow;+ } on TimeoutException {+ rethrow;+ } catch (e, st) {+ debugPrint('[BookOrbit] $method $path failed: $e\n$st');+ return _status(500, '$e');+ }+ }++ Future<http.Response?> _dispatch(+ String method,+ List<String> s,+ Map<String, String> q,+ Map<String, dynamic> body,+ ) async {+ if (s.isEmpty || s[0] != 'api') return null;+ final n = s.length;+ String at(int i) => i < n ? s[i] : '';++ switch (at(1)) {+ case 'authorize':+ if (method == 'POST') return _json(await _authorizePayload());+ case 'me':+ return _routeMe(method, s, q, body);+ case 'libraries':+ if (method != 'GET') return null;+ if (n == 2) return _json({'libraries': await _libraries()});+ final libId = at(2);+ if (n == 3) {+ final lib = (await _libraries()).firstWhere((l) => l['id'] == libId,+ orElse: () => const <String, dynamic>{});+ if (lib.isEmpty) return null;+ final out = Map<String, dynamic>.from(lib);+ if ((q['include'] ?? '').contains('filterdata')) {+ out['filterdata'] = await _filterData(libId);+ }+ return _json(out);+ }+ switch (at(3)) {+ case 'items':+ return _json(await _libraryItems(libId, q));+ case 'personalized':+ return _json(await _cached('personalized:$libId:${q['shelves'] ?? ''}:${q['limit'] ?? ''}',+ const Duration(seconds: 20), () => _personalized(libId, q)));+ case 'series':+ if (n == 4) return _json(await _librarySeries(libId, q));+ return _json(await _seriesMeta(at(4), libId));+ case 'authors':+ return _json(await _libraryAuthors(libId, q));+ case 'search':+ return _json(await _search(libId, q['q'] ?? '', int.tryParse(q['limit'] ?? '') ?? 25));+ case 'filterdata':+ return _json(await _filterData(libId));+ case 'narrators':+ final narrators = await _entityCounts('narrator', pages: 20);+ return _json({+ 'narrators': [for (final n in narrators) {'name': n.name, 'numBooks': n.books}],+ });+ case 'collections':+ return _json(await _libraryCollections(libId, q));+ case 'playlists':+ return _json({'results': const [], 'total': 0});+ case 'stats':+ return _json(await _libraryStats(libId));+ }+ return null;+ case 'series':+ if (method == 'GET' && n == 3) return _json(await _seriesMeta(at(2), null));+ return null;+ case 'authors':+ if (method == 'GET' && n == 3) {+ final author = await _authorDetail(at(2), q);+ return author == null ? _status(404, 'Author not found') : _json(author);+ }+ if (n < 3) return null;+ final authorId = await _resolveAuthorId(at(2));+ if (authorId == null) return _status(404, 'Author not found');+ if (n == 3 && method == 'PATCH') return _json(await _updateAuthor(authorId, body));+ if (n == 4 && at(3) == 'image' && method == 'POST') return _authorImageFromUrl(authorId, '${body['url'] ?? ''}');+ if (n == 4 && at(3) == 'image' && method == 'DELETE') {+ await _boDelete('/authors/$authorId/image');+ return _json({'success': true});+ }+ if (n == 4 && at(3) == 'match' && method == 'POST') return _json(await _matchAuthor(authorId));+ return null;+ case 'search':+ if (method != 'GET') return null;+ switch (at(2)) {+ case 'covers':+ return _json({'results': await _searchCovers(q)});+ case 'books':+ return _json(await _searchBooks(q));+ case 'chapters':+ return _json(await _searchChapters(q['asin'] ?? '', q['region'] ?? 'us'));+ }+ return null;+ case 'items':+ if (at(2) == 'batch' && at(3) == 'get' && method == 'POST') {+ final ids = (body['libraryItemIds'] as List<dynamic>? ?? const []).map((e) => '$e').toList();+ return _json({'libraryItems': await _itemsBatch(ids)});+ }+ if (at(2) == 'batch' && at(3) == 'delete' && method == 'POST') {+ final ids = (body['libraryItemIds'] as List<dynamic>? ?? const []).map((e) => '$e').toList();+ return _deleteBooks(ids, hard: q['hard'] == '1');+ }+ if (n == 3 && method == 'GET') {+ final include = q['include'] ?? '';+ return _json(await _item(at(2), withProgress: include.contains('progress')));+ }+ if (n == 3 && method == 'DELETE') return _deleteBooks([at(2)], hard: q['hard'] == '1');+ if (n == 4 && at(3) == 'media' && method == 'PATCH') return _json(await _updateMedia(at(2), body));+ if (n == 4 && at(3) == 'cover' && method == 'POST') return _coverFromUrl(at(2), '${body['url'] ?? ''}');+ if (n == 4 && at(3) == 'cover' && method == 'DELETE') {+ await _boDelete('/books/${at(2)}/cover?medium=${await _coverMedium(at(2))}');+ await _afterEdit(at(2));+ return _json({'success': true});+ }+ if (n == 4 && at(3) == 'match' && method == 'POST') return _json(await _quickMatch(at(2)));+ if (n == 4 && at(3) == 'chapters' && method == 'POST') {+ final chapters = BookOrbitMapper.chapters(body['chapters'] as List<dynamic>? ?? const []);+ await _boPatch('/books/${at(2)}/metadata', {+ 'audioMetadata': {'chapters': chapters},+ });+ await _afterEdit(at(2), chaptersChanged: true);+ return _json({'success': true, 'updated': true});+ }+ if (n >= 4 && at(3) == 'play' && method == 'POST') {+ if (n > 4) return null;+ return _json(await _startSession(at(2), body));+ }+ return null;+ case 'session':+ if (method != 'POST') return null;+ if (at(2) == 'local') return _json(await _localSession(body));+ if (at(2) == 'local-all') {+ final sessions = (body['sessions'] as List<dynamic>? ?? const [])+ .whereType<Map<String, dynamic>>()+ .toList();+ for (final session in sessions) {+ await _localSession(session);+ }+ return _json({'results': sessions.map((e) => {'id': e['id'], 'success': true}).toList()});+ }+ if (n == 4 && at(3) == 'sync') return _syncSession(at(2), body);+ if (n == 4 && at(3) == 'close') {+ await _closeSession(at(2), body);+ return _json(const <String, dynamic>{});+ }+ return null;+ case 'collections':+ return _routeCollections(method, s, body);+ }+ return null;+ }++ Future<http.Response?> _routeMe(+ String method,+ List<String> s,+ Map<String, String> q,+ Map<String, dynamic> body,+ ) async {+ final n = s.length;+ String at(int i) => i < n ? s[i] : '';+ if (n == 2 && method == 'GET') {+ final me = Map<String, dynamic>.from(BookOrbitMapper.user(+ await _boGet('/auth/me') as Map<String, dynamic>));+ return _json(me);+ }+ switch (at(2)) {+ case 'progress':+ if (n == 3 && method == 'GET') {+ return _json({+ 'mediaProgress': await _cached('progress', const Duration(seconds: 30), _allProgress),+ });+ }+ if (n == 4 && method == 'GET') {+ final p = await _itemProgress(at(3));+ return p == null ? _status(404, 'No progress') : _json(p);+ }+ if (n == 4 && method == 'PATCH') {+ await _patchProgress(at(3), body);+ return _json(const <String, dynamic>{});+ }+ if (n == 4 && method == 'DELETE') {+ await _deleteProgress(at(3));+ return _json(const <String, dynamic>{});+ }+ return null;+ case 'bookmarks':+ if (method != 'GET') return null;+ if (n == 4) return _json({'bookmarks': await _bookmarksFor(at(3))});+ return _json({'bookmarks': await _recentBookmarks()});+ case 'item':+ if (at(3) == 'listening-sessions' && n >= 5 && method == 'GET') {+ if (n > 5) return _json({'sessions': const [], 'total': 0, 'numPages': 1, 'page': 0});+ return _json(await _itemListeningSessions(at(4), q));+ }+ if (n >= 5 && at(4) == 'bookmark') {+ final itemId = at(3);+ if (method == 'POST') {+ final b = await _createBookmark(itemId, body);+ return _json(b);+ }+ if (method == 'PATCH') {+ final ok = await _updateBookmark(itemId, body);+ return ok ? _json(const <String, dynamic>{}) : _status(404, 'Bookmark not found');+ }+ if (method == 'DELETE' && n == 6) {+ final ok = await _deleteBookmark(itemId, double.tryParse(at(5)) ?? -1);+ return ok ? _json(const <String, dynamic>{}) : _status(404, 'Bookmark not found');+ }+ }+ return null;+ case 'listening-stats':+ if (method == 'GET') {+ return _json(await _cached('listening-stats', const Duration(minutes: 5), _listeningStats));+ }+ return null;+ case 'listening-sessions':+ if (method == 'GET') {+ return _json({+ 'sessions': const [],+ 'total': 0,+ 'numPages': 0,+ 'page': int.tryParse(q['page'] ?? '') ?? 0,+ 'itemsPerPage': int.tryParse(q['itemsPerPage'] ?? '') ?? 20,+ });+ }+ return null;+ case 'items-in-progress':+ if (method == 'GET') {+ final cards = await _shelfCards('continue-listening', 50);+ return _json({'libraryItems': cards.map((c) => _cardItem(c)).toList()});+ }+ return null;+ }+ return null;+ }++ Future<Map<String, dynamic>> _authorizePayload() async {+ final raw = await _boGet('/auth/me') as Map<String, dynamic>;+ final version = await _fetchVersion(_cleanBaseUrl, _accessToken, customHeaders);+ return {+ 'user': BookOrbitMapper.user(raw),+ 'userDefaultLibraryId': null,+ 'serverSettings': {'version': version ?? ''},+ 'ereaderDevices': const [],+ 'Source': 'bookorbit',+ };+ }++ Future<List<Map<String, dynamic>>> _libraries() async {+ final cached = _librariesCache;+ final at = _librariesAt;+ if (cached != null && at != null && DateTime.now().difference(at) < const Duration(minutes: 5)) {+ return cached;+ }+ final raw = await _boGet('/libraries') as List<dynamic>;+ final libs = raw+ .whereType<Map<String, dynamic>>()+ .where((l) => l['type'] != 'podcasts')+ .map(BookOrbitMapper.library)+ .toList();+ _librariesCache = libs;+ _librariesAt = DateTime.now();+ unawaited(loadCoverShape());+ return libs;+ }++ Future<Map<String, dynamic>?> _libraryStats(String libId) async {+ final s = await _boGet('/libraries/$libId/stats') as Map<String, dynamic>;+ final formats = (s['formatCounts'] as Map?)?.cast<String, dynamic>() ?? const {};+ final audio = formats.entries+ .where((e) => BookOrbitMapper.isAudioFormat(e.key))+ .fold<num>(0, (sum, e) => sum + ((e.value as num?) ?? 0));+ return {+ 'totalItems': s['totalBooks'] ?? 0,+ 'totalSize': s['totalSizeBytes'] ?? 0,+ 'totalDuration': 0,+ 'numAudioFiles': audio,+ 'numAudioTracks': audio,+ 'totalAuthors': 0,+ 'totalGenres': 0,+ };+ }++ Map<String, dynamic> _cardItem(Map<String, dynamic> card, {String? libraryId}) {+ final id = '${card['id']}';+ final cv = card['coverVersion'] as String?;+ if (cv != null) _coverVersions[_key(id)] = cv;+ if (libraryId != null) _bookLibrary[_key(id)] = libraryId;+ final manifest = _manifests[_key(id)];+ return BookOrbitMapper.item(+ card: card,+ manifest: manifest,+ libraryId: libraryId ?? _bookLibrary[_key(id)],+ );+ }++ Future<Map<String, dynamic>> _detail(String bookId, {bool fresh = false}) async {+ final k = _key(bookId);+ final at = _detailAt[k];+ if (!fresh && at != null && DateTime.now().difference(at) < _detailTtl) {+ return _details[k]!;+ }+ final d = await _boGet('/books/$bookId') as Map<String, dynamic>;+ _details[k] = d;+ _detailAt[k] = DateTime.now();+ final cv = d['coverVersion'] as String?;+ if (cv != null) _coverVersions[k] = cv;+ final lib = d['libraryId'];+ if (lib != null) _bookLibrary[k] = '$lib';+ return d;+ }++ static bool _detailHasAudio(Map<String, dynamic> detail) =>+ (detail['files'] as List<dynamic>? ?? const [])+ .whereType<Map<String, dynamic>>()+ .where((f) => f['role'] == 'primary' || f['role'] == 'content')+ .any((f) => BookOrbitMapper.isAudioFormat(f['format'] as String?));++ Future<Map<String, dynamic>?> _manifest(String bookId, {bool fresh = false}) async {+ final k = _key(bookId);+ final at = _manifestAt[k];+ if (!fresh && at != null && DateTime.now().difference(at) < _manifestTtl) {+ return _manifests[k];+ }+ try {+ final m = await _boGet('/audiobooks/$bookId/manifest') as Map<String, dynamic>;+ _manifests[k] = m;+ _manifestAt[k] = DateTime.now();+ for (final a in (m['assets'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>()) {+ _assetByFile[_key('${a['fileId']}')] = '${a['assetId']}';+ }+ return m;+ } on _BoHttpError catch (e) {+ if (e.status == 404) return null;+ rethrow;+ }+ }++ Future<Map<String, dynamic>> _item(String bookId, {bool withProgress = false}) async {+ final detail = await _detail(bookId, fresh: true);+ final manifest = _detailHasAudio(detail) ? await _manifest(bookId) : null;+ final item = BookOrbitMapper.item(detail: detail, manifest: manifest);+ if (withProgress) {+ final p = await _itemProgress(bookId, detail: detail, manifest: manifest);+ if (p != null) item['userMediaProgress'] = p;+ }+ return item;+ }++ Future<List<Map<String, dynamic>>> _itemsBatch(List<String> ids) async {+ final jobs = ids.map((id) => () async {+ try {+ final detail = await _detail(id);+ return BookOrbitMapper.item(detail: detail, manifest: _manifests[_key(id)]);+ } catch (_) {+ return null;+ }+ }).toList();+ final items = await _pool(jobs);+ return items.whereType<Map<String, dynamic>>().toList();+ }++ static const _audioFormatList = ['m4b', 'mp3', 'm4a', 'opus', 'ogg', 'flac'];+ static const _ebookFormatList = ['epub', 'kepub', 'pdf', 'mobi', 'azw3', 'azw', 'fb2', 'cbz', 'cbr', 'cb7'];++ Map<String, dynamic> _rule(String field, String op, [Object? value, Object? valueTo]) => {+ 'type': 'rule',+ 'field': field,+ 'operator': op,+ if (value != null) 'value': value,+ if (valueTo != null) 'valueTo': valueTo,+ };++ /// Turns an Audiobookshelf `group.base64value` filter into BookOrbit rules.+ /// Returns (rules, q, unsupported).+ Future<({List<Map<String, dynamic>> rules, String? q, bool unsupported, String? seriesId})>+ _translateFilter(String? filter) async {+ final rules = <Map<String, dynamic>>[];+ if (filter == null || filter.isEmpty) {+ return (rules: rules, q: null, unsupported: false, seriesId: null);+ }+ final dot = filter.indexOf('.');+ final group = dot < 0 ? filter : filter.substring(0, dot);+ var value = '';+ if (dot >= 0) {+ final raw = Uri.decodeComponent(filter.substring(dot + 1));+ try {+ value = utf8.decode(base64Decode(base64.normalize(raw)));+ } catch (_) {+ value = raw;+ }+ }+ String? q;+ switch (group) {+ case 'progress':+ switch (value) {+ case 'finished':+ rules.add(_rule('readStatus', 'includesAny', ['read', 'skimmed']));+ case 'in-progress':+ rules.add(_rule('readStatus', 'includesAny', ['reading', 'rereading', 'on_hold']));+ case 'not-started':+ rules.add(_rule('readStatus', 'includesAny', ['unread', 'want_to_read']));+ case 'not-finished':+ rules.add(_rule('readStatus', 'excludesAll', ['read', 'skimmed']));+ }+ case 'series':+ if (int.tryParse(value) != null) {+ return (rules: rules, q: null, unsupported: false, seriesId: value);+ }+ final name = value.startsWith('name:') ? value.substring(5) : value;+ rules.add(_rule('series', 'eq', name));+ case 'authors':+ final name = await _authorName(value);+ if (name == null) return (rules: rules, q: null, unsupported: true, seriesId: null);+ rules.add(_rule('author', 'includesAny', [name]));+ case 'narrators':+ q = value;+ case 'genres':+ rules.add(_rule('genre', 'includesAny', [value]));+ case 'tags':+ rules.add(_rule('tag', 'includesAny', [value]));+ case 'languages':+ rules.add(_rule('language', 'eq', value));+ case 'publishers':+ rules.add(_rule('publisher', 'eq', value));+ case 'publishedDecades':+ final decade = int.tryParse(value);+ if (decade != null) rules.add(_rule('publishedYear', 'between', decade, decade + 9));+ case 'ebooks':+ if (value == 'ebook' || value == 'supplementary') {+ rules.add(_rule('format', 'includesAny', _ebookFormatList));+ } else {+ rules.add(_rule('format', 'excludesAll', _ebookFormatList));+ }+ case 'tracks':+ if (value == 'none') {+ rules.add(_rule('format', 'excludesAll', _audioFormatList));+ } else {+ rules.add(_rule('format', 'includesAny', _audioFormatList));+ }+ case 'issues':+ rules.add(_rule('fileAvailability', 'isMissing'));+ case 'missing':+ final field = switch (value) {+ 'isbn' => 'isbn',+ 'description' => 'description',+ 'series' => 'series',+ 'authors' => 'author',+ 'publishedYear' => 'publishedYear',+ 'publisher' => 'publisher',+ 'genres' => 'genre',+ 'tags' => 'tag',+ 'language' => 'language',+ 'cover' => 'cover',+ _ => null,+ };+ if (field == null) return (rules: rules, q: null, unsupported: true, seriesId: null);+ rules.add(field == 'cover' ? _rule('cover', 'isMissing') : _rule(field, 'isEmpty'));+ default:+ return (rules: rules, q: null, unsupported: true, seriesId: null);+ }+ return (rules: rules, q: q, unsupported: false, seriesId: null);+ }++ List<Map<String, dynamic>> _translateSort(String? sort, bool desc) {+ final dir = desc ? 'desc' : 'asc';+ final field = switch (sort) {+ 'addedAt' || 'birthtimeMs' || 'mtimeMs' => 'addedAt',+ 'updatedAt' => 'updatedAt',+ 'media.metadata.title' || 'media.metadata.titleIgnorePrefix' => 'title',+ 'media.metadata.authorName' ||+ 'media.metadata.authorNameLF' ||+ 'media.metadata.author' =>+ 'author',+ 'media.metadata.publishedYear' => 'publishedYear',+ 'size' => 'fileSize',+ 'progress' => 'lastReadAt',+ 'progress.createdAt' => 'startedAt',+ 'progress.finishedAt' => 'finishedAt',+ 'sequence' || 'media.metadata.series.sequence' => 'seriesIndex',+ 'random' => 'random',+ _ => 'title',+ };+ return [+ {'field': field, 'dir': dir},+ if (field != 'title') {'field': 'title', 'dir': 'asc'},+ ];+ }++ Future<String?> _authorName(String authorId) async {+ if (authorId.startsWith(BookOrbitMapper.authorNamePrefix)) {+ return authorId.substring(BookOrbitMapper.authorNamePrefix.length);+ }+ if (int.tryParse(authorId) == null) return authorId;+ try {+ final a = await _boGet('/authors/$authorId') as Map<String, dynamic>;+ return a['name'] as String?;+ } catch (_) {+ return null;+ }+ }++ Future<Map<String, dynamic>> _libraryItems(String libId, Map<String, String> q) async {+ var page = int.tryParse(q['page'] ?? '') ?? 0;+ var limit = int.tryParse(q['limit'] ?? '') ?? 20;+ final desc = q['desc'] == '1';+ final sort = q['sort'];+ final collapse = q['collapseseries'] == '1';+ final filter = q['filter'];+ final t = await _translateFilter(filter);++ Map<String, dynamic> envelope(List<Map<String, dynamic>> results, int total) => {+ 'results': results,+ 'total': total,+ 'limit': limit,+ 'page': page,+ 'sortBy': sort,+ 'sortDesc': desc,+ 'filterBy': filter,+ 'mediaType': 'book',+ 'minified': q['minified'] != '0',+ 'collapseseries': collapse,+ 'include': '',+ };++ if (t.unsupported) {+ debugPrint('[BookOrbit] Filter $filter has no BookOrbit equivalent');+ return envelope(const [], 0);+ }+ // BookOrbit has no narrator rule, so a narrator is a text search narrowed+ // to exact names here. Paging happens after the narrowing.+ final narrator = filter != null && filter.startsWith('narrators.') ? t.q?.toLowerCase() : null;+ final wantPage = page;+ final wantLimit = limit;+ if (narrator != null) {+ page = 0;+ limit = 0;+ }+ if (t.seriesId != null) {+ final books = await _seriesBooks(t.seriesId!, libId, sort: sort, desc: desc);+ final start = limit <= 0 ? 0 : page * limit;+ final slice = limit <= 0+ ? books+ : books.skip(start).take(limit).toList();+ return envelope(slice, books.length);+ }++ final rules = t.rules;+ Map<String, dynamic> query(int p, int size) => {+ if (rules.isNotEmpty) 'filter': {'type': 'group', 'join': 'AND', 'rules': rules},+ 'sort': _translateSort(sort, desc),+ 'pagination': {'page': p, 'size': size},+ if (collapse) 'collapseSeries': true,+ if (t.q != null) 'q': t.q,+ };++ final cards = <Map<String, dynamic>>[];+ var total = 0;+ if (limit > 0 && limit <= 200) {+ final res = await _boPost('/libraries/$libId/books', query(page, limit)) as Map<String, dynamic>;+ cards.addAll((res['items'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>());+ total = (res['total'] as num?)?.toInt() ?? cards.length;+ } else {+ // limit 0 means everything; bigger pages are stitched from 200s.+ final start = limit <= 0 ? 0 : page * limit;+ final want = limit <= 0 ? 1 << 30 : limit;+ var serverPage = start ~/ 200;+ var skip = start % 200;+ for (var guard = 0; guard < 100 && cards.length < want; guard++) {+ final res = await _boPost('/libraries/$libId/books', query(serverPage, 200)) as Map<String, dynamic>;+ final items = (res['items'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>().toList();+ total = (res['total'] as num?)?.toInt() ?? total;+ cards.addAll(items.skip(skip).take(want - cards.length));+ skip = 0;+ serverPage++;+ if (items.length < 200 || serverPage * 200 >= total) break;+ }+ if (limit <= 0) limit = cards.length;+ }++ var results = cards.map((c) => _cardItem(c, libraryId: libId)).toList();+ if (narrator != null) {+ results = results.where((item) {+ final names = ((item['media'] as Map)['metadata'] as Map)['narrators'] as List;+ return names.any((n) => '$n'.toLowerCase() == narrator);+ }).toList();+ total = results.length;+ page = wantPage;+ limit = wantLimit;+ if (limit > 0) results = results.skip(page * limit).take(limit).toList();+ }+ return envelope(results, total);+ }++ Future<List<Map<String, dynamic>>> _seriesBooks(+ String seriesId,+ String? libId, {+ String? sort,+ bool desc = false,+ }) async {+ final bySort = switch (sort) {+ 'addedAt' => 'addedAt',+ 'media.metadata.title' => 'title',+ _ => 'seriesIndex',+ };+ final out = <Map<String, dynamic>>[];+ for (var page = 0; page < 20; page++) {+ final res = await _boGet('/series/$seriesId/books', {+ 'page': page,+ 'size': 100,+ 'sort': bySort,+ 'order': desc ? 'desc' : 'asc',+ if (libId != null) 'libraryId': libId,+ }) as Map<String, dynamic>;+ final items = (res['items'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>().toList();+ for (final c in items) {+ final item = _cardItem(c, libraryId: libId);+ // A series listing names this series' number in the single-map form+ // the series sheets read.+ final meta = (item['media'] as Map<String, dynamic>)['metadata'] as Map<String, dynamic>;+ meta['series'] = {+ 'id': seriesId,+ 'name': c['seriesName'],+ 'sequence': c['seriesIndex'],+ };+ out.add(item);+ }+ final total = (res['total'] as num?)?.toInt() ?? out.length;+ if (items.length < 100 || out.length >= total) break;+ }+ return out;+ }++ Future<List<Map<String, dynamic>>> _shelfCards(String type, int limit) async {+ final res = await _boGet('/dashboard/scrollers/$type', {'limit': limit.clamp(1, 50)}) as Map<String, dynamic>;+ return (res['books'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>().toList();+ }++ Future<bool> _hasOneLibrary() async => (await _libraries()).length <= 1;++ /// Dashboard shelves span every library. With more than one, keep the+ /// cards this library's in-progress books (one query) say belong here.+ Future<List<Map<String, dynamic>>> _inProgressHere(List<Map<String, dynamic>> cards, String libId) async {+ if (await _hasOneLibrary()) return cards;+ final here = await _libraryQueryCards(+ libId,+ rules: [_rule('readStatus', 'includesAny', ['reading', 'rereading', 'on_hold'])],+ sort: [{'field': 'lastReadAt', 'dir': 'desc'}],+ size: 200,+ );+ final ids = {for (final c in here) '${c['id']}'};+ for (final c in here) {+ _bookLibrary[_key('${c['id']}')] = libId;+ }+ final kept = cards.where((c) => ids.contains('${c['id']}')).toList();+ final keptIds = {for (final c in kept) '${c['id']}'};+ return [...kept, ...here.where((c) => !keptIds.contains('${c['id']}'))];+ }++ Future<List<Map<String, dynamic>>> _libraryQueryCards(+ String libId, {+ List<Map<String, dynamic>> rules = const [],+ required List<Map<String, dynamic>> sort,+ int size = 20,+ }) async {+ final res = await _boPost('/libraries/$libId/books', {+ if (rules.isNotEmpty) 'filter': {'type': 'group', 'join': 'AND', 'rules': rules},+ 'sort': sort,+ 'pagination': {'page': 0, 'size': size.clamp(1, 200)},+ }) as Map<String, dynamic>;+ return (res['items'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>().toList();+ }++ Future<List<Map<String, dynamic>>> _personalized(String libId, Map<String, String> q) async {+ final limit = (int.tryParse(q['limit'] ?? '') ?? 15).clamp(1, 50);+ final wanted = (q['shelves'] ?? '').split(',').where((s) => s.isNotEmpty).toSet();+ bool want(String id) => wanted.isEmpty || wanted.contains(id);++ Map<String, dynamic> shelf(String id, String label, List<Map<String, dynamic>> cards, {bool seriesEntity = false}) {+ final entities = cards.map((c) {+ final item = _cardItem(c, libraryId: libId);+ if (seriesEntity && c['seriesName'] != null) {+ ((item['media'] as Map<String, dynamic>)['metadata'] as Map<String, dynamic>)['series'] = {+ 'id': '${c['seriesId'] ?? 'name:${c['seriesName']}'}',+ 'name': c['seriesName'],+ 'sequence': c['seriesIndex'],+ };+ }+ return item;+ }).toList();+ return {+ 'id': id,+ 'label': label,+ 'labelStringKey': label,+ 'type': 'book',+ 'entities': entities,+ 'total': entities.length,+ };+ }++ final shelves = <Map<String, dynamic>>[];+ Future<void> add(String id, Future<Map<String, dynamic>> Function() build) async {+ if (!want(id)) return;+ try {+ final s = await build();+ if ((s['entities'] as List).isNotEmpty) shelves.add(s);+ } catch (e) {+ debugPrint('[BookOrbit] Shelf $id failed: $e');+ }+ }++ await add('continue-listening', () async {+ final listening = await _shelfCards('continue-listening', 50);+ final reading = await _shelfCards('continue-reading', 50);+ final seen = <String>{};+ final merged = [...listening, ...reading].where((c) => seen.add('${c['id']}')).toList();+ final cards = (await _inProgressHere(merged, libId)).take(limit).toList();+ return shelf('continue-listening', 'Continue Listening', cards);+ });+ await add('continue-series', () async {+ final cards = await _hasOneLibrary()+ ? await _shelfCards('up-next-in-series', limit)+ : await _libraryQueryCards(+ libId,+ rules: [_rule('seriesStatus', 'isUpNext')],+ sort: [{'field': 'series', 'dir': 'asc'}],+ size: limit,+ );+ return shelf('continue-series', 'Continue Series', cards.take(limit).toList(), seriesEntity: true);+ });+ await add('recently-added', () async {+ final cards = await _libraryQueryCards(libId, sort: [{'field': 'addedAt', 'dir': 'desc'}], size: limit);+ return shelf('recently-added', 'Recently Added', cards);+ });+ await add('listen-again', () async {+ final cards = await _libraryQueryCards(+ libId,+ rules: [_rule('readStatus', 'includesAny', ['read'])],+ sort: [{'field': 'finishedAt', 'dir': 'desc'}],+ size: limit,+ );+ return shelf('listen-again', 'Listen Again', cards);+ });+ await add('discover', () async {+ final cards = await _libraryQueryCards(+ libId,+ rules: [_rule('readStatus', 'includesAny', ['unread'])],+ sort: [{'field': 'random', 'dir': 'asc'}],+ size: limit,+ );+ return shelf('discover', 'Discover', cards);+ });+ return shelves;+ }++ Map<String, dynamic> _stubItem(String bookId, {String? title, String? seriesId, String? seriesName, Object? sequence}) => {+ 'id': bookId,+ 'mediaType': 'book',+ 'libraryId': _bookLibrary[_key(bookId)] ?? '',+ 'media': {+ 'coverPath': '/bookorbit/books/$bookId/cover',+ 'metadata': {+ 'title': title ?? '',+ 'authorName': '',+ if (seriesId != null) 'series': {'id': seriesId, 'name': seriesName, 'sequence': sequence?.toString()},+ },+ },+ };++ Map<String, dynamic> _seriesSummary(Map<String, dynamic> s, String? libId) {+ final id = '${s['id']}';+ final books = <Map<String, dynamic>>[];+ for (final v in (s['volumes'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>()) {+ final bookId = v['bookId'];+ if (bookId == null) continue;+ books.add(_stubItem('$bookId', title: v['title'] as String?, seriesId: id, seriesName: s['name'] as String?, sequence: v['index']));+ }+ if (books.isEmpty) {+ for (final bookId in (s['coverBookIds'] as List<dynamic>? ?? const [])) {+ books.add(_stubItem('$bookId', seriesId: id, seriesName: s['name'] as String?));+ }+ }+ return BookOrbitMapper.series(s, books: books)..['libraryId'] = libId ?? '';+ }++ Future<Map<String, dynamic>> _librarySeries(String libId, Map<String, String> q) async {+ final page = int.tryParse(q['page'] ?? '') ?? 0;+ final limit = (int.tryParse(q['limit'] ?? '') ?? 50).clamp(1, 1000);+ final desc = q['desc'] == '1';+ final sort = switch (q['sort']) {+ 'numBooks' || 'totalDuration' => 'bookCount',+ 'addedAt' || 'lastBookAdded' || 'lastBookUpdated' || 'updatedAt' => 'lastAddedAt',+ _ => 'name',+ };+ final results = <Map<String, dynamic>>[];+ var total = 0;+ final start = page * limit;+ var serverPage = start ~/ 100;+ var skip = start % 100;+ for (var guard = 0; guard < 50 && results.length < limit; guard++) {+ final res = await _boGet('/series', {+ 'page': serverPage,+ 'size': 100,+ 'sort': sort,+ 'order': desc ? 'desc' : 'asc',+ 'libraryId': libId,+ }) as Map<String, dynamic>;+ final items = (res['items'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>().toList();+ total = (res['total'] as num?)?.toInt() ?? total;+ results.addAll(items.skip(skip).take(limit - results.length).map((s) => _seriesSummary(s, libId)));+ skip = 0;+ serverPage++;+ if (items.length < 100 || serverPage * 100 >= total) break;+ }+ return {'results': results, 'total': total, 'limit': limit, 'page': page};+ }++ Future<Map<String, dynamic>?> _seriesMeta(String seriesId, String? libId) async {+ if (int.tryParse(seriesId) == null) return null;+ final res = await _boGet('/series/$seriesId/books', {+ 'page': 0,+ 'size': 1,+ if (libId != null) 'libraryId': libId,+ }) as Map<String, dynamic>;+ final info = res['seriesInfo'] as Map<String, dynamic>? ?? const {};+ return {+ 'id': seriesId,+ 'name': info['name'] ?? '',+ 'nameIgnorePrefix': info['name'] ?? '',+ 'numBooks': info['bookCount'] ?? res['total'] ?? 0,+ 'libraryId': libId ?? '',+ 'authors': info['authors'] ?? const [],+ };+ }++ Future<Map<String, dynamic>> _libraryAuthors(String libId, Map<String, String> q) async {+ final paged = q.containsKey('page');+ final page = int.tryParse(q['page'] ?? '') ?? 0;+ final limit = (int.tryParse(q['limit'] ?? '') ?? 100).clamp(1, 1000);+ final desc = q['desc'] == '1';+ final sort = switch (q['sort']) {+ 'lastFirst' => 'sortName',+ 'numBooks' => 'bookCount',+ 'addedAt' || 'updatedAt' => 'lastAddedAt',+ _ => 'name',+ };+ final authors = <Map<String, dynamic>>[];+ var total = 0;+ final start = paged ? page * limit : 0;+ final want = paged ? limit : 5000;+ var serverPage = start ~/ 100;+ var skip = start % 100;+ for (var guard = 0; guard < 60 && authors.length < want; guard++) {+ final res = await _boGet('/authors', {+ 'page': serverPage,+ 'size': 100,+ 'sort': sort,+ 'order': desc ? 'desc' : 'asc',+ 'libraryId': libId,+ }) as Map<String, dynamic>;+ final items = (res['items'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>().toList();+ total = (res['total'] as num?)?.toInt() ?? total;+ authors.addAll(items.skip(skip).take(want - authors.length).map(BookOrbitMapper.author));+ skip = 0;+ serverPage++;+ if (items.length < 100 || serverPage * 100 >= total) break;+ }+ if (!paged) return {'authors': authors};+ return {'results': authors, 'total': total, 'limit': limit, 'page': page};+ }++ Future<String?> _resolveAuthorId(String authorId) async {+ if (int.tryParse(authorId) != null) return authorId;+ final name = authorId.startsWith(BookOrbitMapper.authorNamePrefix)+ ? authorId.substring(BookOrbitMapper.authorNamePrefix.length)+ : authorId;+ final res = await _boGet('/authors', {'q': name, 'size': 25}) as Map<String, dynamic>;+ for (final a in (res['items'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>()) {+ if ('${a['name']}'.toLowerCase() == name.toLowerCase()) return '${a['id']}';+ }+ return null;+ }++ Future<Map<String, dynamic>?> _authorDetail(String authorId, Map<String, String> q) async {+ final id = await _resolveAuthorId(authorId);+ if (id == null) return null;+ final raw = await _boGet('/authors/$id') as Map<String, dynamic>;+ final author = BookOrbitMapper.author(raw);+ final include = q['include'] ?? '';+ if (include.contains('items') || include.contains('series')) {+ final libId = q['library'];+ final items = <Map<String, dynamic>>[];+ for (var page = 0; page < 20; page++) {+ final res = await _boGet('/authors/$id/books', {+ 'page': page,+ 'size': 100,+ 'sort': 'title',+ 'order': 'asc',+ if (libId != null) 'libraryId': libId,+ }) as Map<String, dynamic>;+ final cards = (res['items'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>().toList();+ items.addAll(cards.map((c) => _cardItem(c, libraryId: libId)));+ final total = (res['total'] as num?)?.toInt() ?? items.length;+ if (cards.length < 100 || items.length >= total) break;+ }+ author['libraryItems'] = items;+ final bySeries = <String, Map<String, dynamic>>{};+ for (final item in items) {+ final meta = (item['media'] as Map<String, dynamic>)['metadata'] as Map<String, dynamic>;+ for (final s in (meta['series'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>()) {+ final entry = bySeries.putIfAbsent('${s['id']}', () => {'id': s['id'], 'name': s['name'], 'items': <Map<String, dynamic>>[]});+ (entry['items'] as List<Map<String, dynamic>>).add(item);+ }+ }+ author['series'] = bySeries.values.toList();+ }+ return author;+ }++ Future<Map<String, dynamic>> _search(String libId, String text, int limit) async {+ final query = text.trim();+ final empty = {+ 'book': const [],+ 'podcast': const [],+ 'series': const [],+ 'authors': const [],+ 'narrators': const [],+ 'tags': const [],+ 'genres': const [],+ };+ if (query.isEmpty) return empty;+ final booksFuture = _boPost('/libraries/$libId/books', {+ 'q': query.length > 200 ? query.substring(0, 200) : query,+ 'sort': [{'field': 'relevance', 'dir': 'desc'}],+ 'pagination': {'page': 0, 'size': limit.clamp(1, 200)},+ });+ Future<dynamic>? globalFuture;+ if (query.length >= 2) {+ globalFuture = _boGet('/search', {+ 'q': query.length > 200 ? query.substring(0, 200) : query,+ 'limit': 10,+ 'libraryId': libId,+ }).catchError((_) => null);+ }+ final books = await booksFuture as Map<String, dynamic>;+ final global = await globalFuture as Map<String, dynamic>?;++ final bookHits = (books['items'] as List<dynamic>? ?? const [])+ .whereType<Map<String, dynamic>>()+ .map((c) => {'libraryItem': _cardItem(c, libraryId: libId), 'matchKey': 'title', 'matchText': c['title']})+ .toList();+ final series = ((global?['series'] as Map?)?['items'] as List<dynamic>? ?? const [])+ .whereType<Map<String, dynamic>>()+ .map((hit) {+ final summary = _seriesSummary(hit['item'] as Map<String, dynamic>, libId);+ return {'series': summary, 'books': summary['books']};+ }).toList();+ final authors = ((global?['authors'] as Map?)?['items'] as List<dynamic>? ?? const [])+ .whereType<Map<String, dynamic>>()+ .map((hit) => BookOrbitMapper.author(hit['item'] as Map<String, dynamic>))+ .toList();+ final narratorCounts = <String, int>{};+ final lower = query.toLowerCase();+ for (final hit in bookHits) {+ final meta = ((hit['libraryItem'] as Map)['media'] as Map)['metadata'] as Map;+ for (final name in (meta['narrators'] as List? ?? const [])) {+ if ('$name'.toLowerCase().contains(lower)) {+ narratorCounts['$name'] = (narratorCounts['$name'] ?? 0) + 1;+ }+ }+ }+ return {+ ...empty,+ 'book': bookHits,+ 'series': series,+ 'authors': authors,+ 'narrators': narratorCounts.entries.map((e) => {'name': e.key, 'numBooks': e.value}).toList(),+ };+ }++ /// Names and book counts of a genre, tag, narrator, publisher or language,+ /// most used first, [pages] of 100 at most. BookOrbit only lists them for+ /// accounts that can edit metadata; others get none.+ Future<List<({String name, int books})>> _entityCounts(String type, {int pages = 1}) async {+ final out = <({String name, int books})>[];+ try {+ for (var page = 1; page <= pages; page++) {+ final res = await _boGet('/entity-manager/$type/browse', {+ 'page': page,+ 'pageSize': 100,+ 'sortBy': 'bookCount',+ 'sortOrder': 'desc',+ }) as Map<String, dynamic>;+ final items = (res['items'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>().toList();+ for (final e in items) {+ final name = '${e['name'] ?? ''}';+ final books = (e['bookCount'] as num?)?.toInt() ?? 1;+ if (name.isNotEmpty && books > 0) out.add((name: name, books: books));+ }+ final total = (res['total'] as num?)?.toInt() ?? 0;+ if (items.length < 100 || page * 100 >= total) break;+ }+ } on _BoHttpError catch (e) {+ if (e.status != 403) debugPrint('[BookOrbit] No $type list: ${e.status}');+ }+ return out;+ }++ Future<List<String>> _entityNames(String type, {int pages = 1}) async =>+ (await _entityCounts(type, pages: pages)).map((e) => e.name).toList()+ ..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));++ /// The decades that have books in the library, newest last.+ Future<List<String>> _publishedDecades(String libId) async {+ Future<Map<String, dynamic>> books(List<Map<String, dynamic>> rules, String dir) async =>+ await _boPost('/libraries/$libId/books', {+ 'filter': {'type': 'group', 'join': 'AND', 'rules': rules},+ 'sort': [{'field': 'publishedYear', 'dir': dir}],+ 'pagination': {'page': 0, 'size': 1},+ }) as Map<String, dynamic>;+ int? year(Map<String, dynamic> res) {+ final items = res['items'] as List<dynamic>? ?? const [];+ return items.isEmpty ? null : ((items.first as Map)['publishedYear'] as num?)?.toInt();+ }++ try {+ final known = [_rule('publishedYear', 'isNotEmpty')];+ final ends = await Future.wait([books(known, 'asc'), books(known, 'desc')]);+ final first = year(ends[0]);+ final last = year(ends[1]);+ if (first == null || last == null) return const [];+ final decades = [for (var d = last - last % 10; d >= first - first % 10 && d > 0; d -= 10) d].take(30).toList();+ final counts = await Future.wait(decades.map((d) async =>+ ((await books([_rule('publishedYear', 'between', d, d + 9)], 'asc'))['total'] as num?)?.toInt() ?? 0));+ return [for (var i = decades.length - 1; i >= 0; i--) if (counts[i] > 0) '${decades[i]}'];+ } catch (e) {+ debugPrint('[BookOrbit] No decade list: $e');+ return const [];+ }+ }++ Future<Map<String, dynamic>> _filterData(String libId) =>+ _cached('filterdata:$libId', const Duration(minutes: 5), () => _loadFilterData(libId));++ Future<Map<String, dynamic>> _loadFilterData(String libId) async {+ final authors = (await _libraryAuthors(libId, const {}))['authors'] as List<dynamic>;+ final series = <Map<String, dynamic>>[];+ for (var page = 0; page < 30; page++) {+ final res = await _boGet('/series', {'page': page, 'size': 100, 'sort': 'name', 'order': 'asc', 'libraryId': libId}) as Map<String, dynamic>;+ final items = (res['items'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>().toList();+ series.addAll(items.map((s) => {'id': '${s['id']}', 'name': s['name'] ?? ''}));+ final total = (res['total'] as num?)?.toInt() ?? series.length;+ if (items.length < 100 || series.length >= total) break;+ }+ final lists = await Future.wait([+ _entityNames('genre'),+ _entityNames('tag'),+ _entityNames('narrator', pages: 20),+ _entityNames('language'),+ _entityNames('publisher', pages: 5),+ _publishedDecades(libId),+ ]);+ return {+ 'authors': authors.map((a) => {'id': (a as Map)['id'], 'name': a['name']}).toList(),+ 'series': series,+ 'genres': lists[0],+ 'tags': lists[1],+ 'narrators': lists[2],+ 'languages': lists[3],+ 'publishers': lists[4],+ 'publishedDecades': lists[5],+ };+ }++ Future<Map<String, dynamic>> _collection(Map<String, dynamic> c, {bool withBooks = true, int maxBooks = 2000}) async {+ final id = '${c['id']}';+ final books = <Map<String, dynamic>>[];+ if (withBooks) {+ for (var page = 0; page < 40 && books.length < maxBooks; page++) {+ final res = await _boGet('/collections/$id/books', {'page': page, 'size': 100}) as Map<String, dynamic>;+ final items = (res['items'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>().toList();+ books.addAll(items.map((card) => _cardItem(card)));+ final total = (res['total'] as num?)?.toInt() ?? books.length;+ if (items.length < 100 || books.length >= total) break;+ }+ }+ return {+ 'id': id,+ 'name': c['name'] ?? '',+ 'description': c['description'],+ 'libraryId': '',+ 'userId': '${c['userId'] ?? ''}',+ 'books': books,+ 'lastUpdate': BookOrbitMapper.ms(c['updatedAt']),+ 'createdAt': BookOrbitMapper.ms(c['createdAt']),+ 'bookOrbit': {'isOwner': c['isOwner'], 'isPublic': c['isPublic'], 'bookCount': c['bookCount']},+ };+ }++ Future<Map<String, dynamic>> _libraryCollections(String libId, Map<String, String> q) async {+ final page = int.tryParse(q['page'] ?? '') ?? 0;+ final limit = (int.tryParse(q['limit'] ?? '') ?? 25).clamp(1, 200);+ final all = (await _boGet('/collections') as List<dynamic>)+ .whereType<Map<String, dynamic>>()+ .where((c) => (c['mediaType'] ?? 'books') == 'books')+ .toList();+ final slice = all.skip(page * limit).take(limit).toList();+ final results = await _pool(slice.map((c) => () => _collection(c, maxBooks: 500)).toList(), width: 4);+ for (final r in results) {+ r['libraryId'] = libId;+ }+ return {'results': results, 'total': all.length, 'limit': limit, 'page': page};+ }++ Future<http.Response?> _routeCollections(String method, List<String> s, Map<String, dynamic> body) async {+ final n = s.length;+ String at(int i) => i < n ? s[i] : '';+ if (n == 2 && method == 'POST') {+ final created = await _boPost('/collections', {+ 'name': body['name'] ?? 'Collection',+ 'icon': 'pi pi-book',+ if ((body['description'] as String?)?.isNotEmpty == true) 'description': body['description'],+ }) as Map<String, dynamic>;+ final books = (body['books'] as List<dynamic>? ?? const []).map((e) => int.tryParse('$e')).whereType<int>().toList();+ if (books.isNotEmpty) await _boPost('/collections/${created['id']}/books', {'bookIds': books});+ return _json(await _collection(created)..['libraryId'] = body['libraryId'] ?? '');+ }+ final id = at(2);+ if (n == 3) {+ switch (method) {+ case 'GET':+ return _json(await _collection(await _boGet('/collections/$id') as Map<String, dynamic>));+ case 'DELETE':+ await _boDelete('/collections/$id');+ return _json(const <String, dynamic>{});+ case 'PATCH':+ final patch = <String, dynamic>{+ if (body['name'] != null) 'name': body['name'],+ if (body['description'] != null) 'description': body['description'],+ };+ if (patch.isNotEmpty) await _boPatch('/collections/$id', patch);+ final wanted = body['books'] as List<dynamic>?;+ if (wanted != null) {+ final current = await _collection(await _boGet('/collections/$id') as Map<String, dynamic>);+ final have = (current['books'] as List).map((b) => '${(b as Map)['id']}').toList();+ final want = wanted.map((e) => '$e').where((e) => int.tryParse(e) != null).toList();+ if (have.join(',') != want.join(',')) {+ // BookOrbit has no reorder call and keeps books in the order+ // they were added, so the new list is added back in sequence.+ if (have.isNotEmpty) {+ await _boDelete('/collections/$id/books', body: {'bookIds': have.map(int.parse).toList()});+ }+ if (want.isNotEmpty) {+ await _boPost('/collections/$id/books', {'bookIds': want.map(int.parse).toList()});+ }+ }+ }+ return _json(await _collection(await _boGet('/collections/$id') as Map<String, dynamic>));+ }+ }+ if (at(3) == 'book' || at(3) == 'books') {+ if (method == 'POST') {+ final bookId = int.tryParse('${body['id']}');+ if (bookId == null) return _status(400, 'Missing book id');+ await _boPost('/collections/$id/books', {'bookIds': [bookId]});+ } else if (method == 'DELETE' && n == 5) {+ final bookId = int.tryParse(at(4));+ if (bookId == null) return _status(400, 'Bad book id');+ await _boDelete('/collections/$id/books', body: {'bookIds': [bookId]});+ } else {+ return null;+ }+ return _json(await _collection(await _boGet('/collections/$id') as Map<String, dynamic>));+ }+ return null;+ }++ /// With [coverSlot] the URL shows that slot only (no fallback to the other+ /// one), which is what the cover editor wants.+ @override+ String getCoverUrl(String itemId, {int? width = 400, int? updatedAt, String? coverSlot}) {+ final kind = coverSlot == null && width != null && width <= 400 ? 'thumbnail' : 'cover';+ final cv = _coverVersions[_key(itemId)];+ final t = cv == null ? '' : '&t=${Uri.encodeQueryComponent(cv)}';+ final slot = coverSlot == null ? _listCoverSlot(itemId) : '$coverSlot&strict=true';+ return BookOrbitMediaProxy.instance.urlFor('/api/v1/books/$itemId/$kind?medium=$slot$t');+ }++ @override+ Future<int?> comicPageCount(String fileId) async {+ try {+ final r = await _boGet('/cbz/files/$fileId/pages') as Map<String, dynamic>;+ return (r['pageCount'] as num?)?.toInt();+ } catch (e) {+ debugPrint('[BookOrbit] comic page count for file $fileId: $e');+ return null;+ }+ }++ @override+ String? comicPageUrl(String fileId, int index) =>+ BookOrbitMediaProxy.instance.urlFor('/api/v1/cbz/files/$fileId/pages/$index');++ @override+ Future<List<String>> coverSlots(String itemId) async {+ try {+ final d = await _detail(itemId);+ return (d['coverMedia'] as List<dynamic>? ?? const [])+ .map((e) => '$e')+ .where((e) => e == 'audio' || e == 'ebook')+ .toList();+ } catch (e) {+ debugPrint('[BookOrbit] cover slots for $itemId: $e');+ return const [];+ }+ }++ @override+ Future<String?> defaultCoverSearchProvider() async {+ try {+ final p = await _boGet('/user-preferences/cover-search') as Map<String, dynamic>;+ return ((p['settings'] as Map?)?['defaultProvider'] ?? p['defaultProvider']) as String?;+ } catch (_) {+ return null;+ }+ }++ @override+ String getAuthorImageUrl(String authorId, {int width = 200, int? updatedAt}) {+ final id = int.tryParse(authorId) ?? 0;+ final kind = width <= 400 ? 'thumbnail' : 'image';+ final t = updatedAt == null ? '' : '?t=$updatedAt';+ return BookOrbitMediaProxy.instance.urlFor('/api/v1/authors/$id/$kind$t');+ }++ /// The cover slot an edit goes to: the audiobook's when there is audio,+ /// since that is the one the app shows.+ Future<String> _coverMedium(String bookId) async =>+ _detailHasAudio(await _detail(bookId)) ? 'audio' : 'ebook';++ /// Re-read a book after an edit and tell open views about it the way the+ /// Audiobookshelf socket would.+ Future<Map<String, dynamic>> _afterEdit(String bookId, {bool chaptersChanged = false}) async {+ final k = _key(bookId);+ if (chaptersChanged) {+ _manifests.remove(k);+ _manifestAt.remove(k);+ }+ _recent.removeWhere((key, _) => key.startsWith('personalized:'));+ final detail = await _detail(bookId, fresh: true);+ final manifest = _detailHasAudio(detail) ? await _manifest(bookId) : null;+ final item = BookOrbitMapper.item(detail: detail, manifest: manifest);+ SocketService().emitLocalItemUpdated(item);+ return item;+ }++ Future<Map<String, dynamic>> _updateMedia(String bookId, Map<String, dynamic> body) async {+ final detail = await _detail(bookId, fresh: true);+ final current = BookOrbitMapper.item(detail: detail)['media'] as Map<String, dynamic>;+ final changes = BookOrbitMapper.metadataPatch(+ metadata: (body['metadata'] as Map?)?.cast<String, dynamic>() ?? const {},+ tags: (body['tags'] as List<dynamic>?)?.map((e) => '$e').toList(),+ current: current,+ hasAudio: _detailHasAudio(detail),+ );+ if (changes.isEmpty) return {'updated': false, 'libraryItem': await _afterEdit(bookId)};+ await _boPatch('/books/$bookId/metadata', changes);+ return {'updated': true, 'libraryItem': await _afterEdit(bookId)};+ }++ /// Covers picked from a search come back through the proxy; BookOrbit+ /// wants the original address.+ String _upstreamImageUrl(String url) {+ final picked = _coverPicks[url];+ if (picked != null) return picked;+ if (!BookOrbitMediaProxy.instance.owns(url)) return url;+ final uri = Uri.parse(url);+ return uri.path.endsWith('/books/cover/proxy') ? (uri.queryParameters['url'] ?? url) : url;+ }++ Future<http.Response> _coverFromUrl(String bookId, String url, {String? slot}) async {+ if (url.isEmpty) return _status(400, 'No cover URL');+ await _boPost(+ '/books/$bookId/cover/from-url?medium=${slot ?? await _coverMedium(bookId)}',+ {'url': _upstreamImageUrl(url)},+ const Duration(seconds: 45),+ );+ await _afterEdit(bookId);+ return _json({'success': true});+ }++ @override+ Future<bool> updateItemCoverUrl(String itemId, String url, {String? coverSlot}) async {+ try {+ return (await _coverFromUrl(itemId, url, slot: coverSlot)).statusCode == 200;+ } catch (e) {+ debugPrint('[BookOrbit] updateItemCoverUrl error: $e');+ return false;+ }+ }++ @override+ Future<bool> removeItemCover(String itemId, {String? coverSlot}) async {+ try {+ await _boDelete('/books/$itemId/cover?medium=${coverSlot ?? await _coverMedium(itemId)}');+ await _afterEdit(itemId);+ return true;+ } catch (e) {+ debugPrint('[BookOrbit] removeItemCover error: $e');+ return false;+ }+ }++ @override+ Future<bool> uploadItemCover(String itemId, String filePath, {String? coverSlot}) async {+ try {+ final bytes = await (await http.MultipartFile.fromPath('file', filePath)).finalize().toBytes();+ await _boMultipart(+ '/books/$itemId/cover?medium=${coverSlot ?? await _coverMedium(itemId)}',+ bytes,+ filename: filePath.split(RegExp(r'[\\/]')).last,+ contentType: _imageType(filePath, null),+ );+ await _afterEdit(itemId);+ return true;+ } catch (e) {+ debugPrint('[BookOrbit] uploadItemCover error: $e');+ return false;+ }+ }++ static String _imageType(String name, String? header) {+ final h = header?.split(';').first.trim().toLowerCase();+ if (h != null && h.startsWith('image/')) return h;+ final ext = name.toLowerCase().split('?').first.split('.').last;+ return switch (ext) {+ 'png' => 'image/png',+ 'webp' => 'image/webp',+ 'gif' => 'image/gif',+ 'heic' => 'image/heic',+ 'avif' => 'image/avif',+ _ => 'image/jpeg',+ };+ }++ /// POST one image as multipart. The body is built here because the http+ /// package can't label a part's type without another dependency, and+ /// BookOrbit turns away anything not marked image/*.+ Future<dynamic> _boMultipart(String path, List<int> bytes,+ {required String filename, required String contentType}) async {+ await _ensureFreshAccessToken();+ final boundary = 'absorb${DateTime.now().microsecondsSinceEpoch}';+ final safeName = filename.replaceAll('"', '');+ final body = <int>[+ ...utf8.encode('--$boundary\r\n'+ 'Content-Disposition: form-data; name="file"; filename="$safeName"\r\n'+ 'Content-Type: $contentType\r\n\r\n'),+ ...bytes,+ ...utf8.encode('\r\n--$boundary--\r\n'),+ ];+ Future<http.Response> send() async {+ final req = http.Request('POST', _boUri(path))+ ..headers.addAll(_headers)+ ..headers['Content-Type'] = 'multipart/form-data; boundary=$boundary'+ ..bodyBytes = body;+ final client = _httpClient ?? http.Client();+ try {+ final streamed = await client.send(req).timeout(const Duration(seconds: 60));+ return await http.Response.fromStream(streamed).timeout(const Duration(seconds: 60));+ } finally {+ if (_httpClient == null) client.close();+ }+ }++ var r = await send();+ if (r.statusCode == 401) {+ final outcome = await _refreshAccessToken();+ if (outcome == _RefreshOutcome.refreshed) r = await send();+ if (outcome == _RefreshOutcome.rejected) onAuthExpired?.call();+ }+ return _decode(r);+ }++ /// BookOrbit's own one-tap match: it searches with what the book already+ /// has and fills fields by the server's metadata rules, so the title,+ /// author and provider the app sends have nothing to steer.+ Future<Map<String, dynamic>> _quickMatch(String bookId) async {+ String fingerprint(Map<String, dynamic> d) => jsonEncode([+ BookOrbitMapper.item(detail: d)['media'],+ d['coverVersion'],+ ]);+ final before = fingerprint(await _detail(bookId, fresh: true));+ await _boPost('/books/$bookId/refresh-metadata', null, const Duration(seconds: 120));+ final item = await _afterEdit(bookId, chaptersChanged: true);+ final after = fingerprint(_details[_key(bookId)]!);+ return {'updated': before != after, 'libraryItem': item};+ }++ Future<http.Response> _deleteBooks(List<String> ids, {required bool hard}) async {+ // BookOrbit has no way to drop a book and keep its files.+ if (!hard) return _status(400, 'BookOrbit always deletes the files');+ final bookIds = ids.map(int.tryParse).whereType<int>().toList();+ if (bookIds.isEmpty || bookIds.length != ids.length) return _status(404, 'Book not found');+ await _boDelete('/books', body: {'bookIds': bookIds});+ for (final id in ids) {+ final k = _key(id);+ _details.remove(k);+ _detailAt.remove(k);+ _manifests.remove(k);+ _manifestAt.remove(k);+ SocketService().emitLocalItemRemoved({'id': id});+ }+ _recent.removeWhere((key, _) => key.startsWith('personalized:'));+ return _json({'success': true});+ }++ /// Sends only what changed: a new name makes BookOrbit look the author up+ /// again in the background.+ Future<Map<String, dynamic>> _updateAuthor(String authorId, Map<String, dynamic> body) async {+ final current = await _boGet('/authors/$authorId') as Map<String, dynamic>;+ final changes = <String, dynamic>{};+ final name = '${body['name'] ?? ''}'.trim();+ if (name.isNotEmpty && name != current['name']) {+ changes['name'] = name.length > 500 ? name.substring(0, 500) : name;+ }+ if (body.containsKey('description')) {+ final d = '${body['description'] ?? ''}'.trim();+ final next = d.isEmpty ? null : (d.length > 10000 ? d.substring(0, 10000) : d);+ if (next != current['description']) changes['description'] = next;+ }+ final res = changes.isEmpty ? current : await _boPatch('/authors/$authorId', changes);+ return {'author': BookOrbitMapper.author(res as Map<String, dynamic>)};+ }++ /// BookOrbit only takes an uploaded author image, so fetch it here first.+ Future<http.Response> _authorImageFromUrl(String authorId, String url) async {+ final uri = Uri.tryParse(url.trim());+ if (uri == null || !(uri.scheme == 'http' || uri.scheme == 'https')) {+ return _status(400, 'Not an image URL');+ }+ final res = await http.get(uri).timeout(const Duration(seconds: 30));+ final type = res.headers['content-type'];+ if (res.statusCode != 200 || res.bodyBytes.isEmpty || (type != null && !type.startsWith('image/'))) {+ return _status(400, 'Could not download the image');+ }+ await _boMultipart(+ '/authors/$authorId/image',+ res.bodyBytes,+ filename: uri.pathSegments.isEmpty ? 'author.jpg' : uri.pathSegments.last,+ contentType: _imageType(uri.path, type),+ );+ return _json({'success': true});+ }++ /// Like Quick Match for books: the server looks the author up with its+ /// own provider settings.+ Future<Map<String, dynamic>> _matchAuthor(String authorId) async {+ final before = await _boGet('/authors/$authorId') as Map<String, dynamic>;+ final after = await _boPost('/authors/$authorId/enrichment/refresh', null, const Duration(seconds: 60))+ as Map<String, dynamic>;+ String key(Map<String, dynamic> a) => jsonEncode([a['name'], a['description'], a['imageUrl']]);+ return {'updated': key(before) != key(after), 'author': BookOrbitMapper.author(after)};+ }++ static const _coverProviders = {+ 'audiobookcovers': 'audiobookcovers',+ 'itunes': 'itunes',+ 'duckduckgo': 'duckduckgo',+ 'google': 'duckduckgo',+ 'all': 'all',+ };++ Future<List<String>> _searchCovers(Map<String, String> q) => _searchCoverUrls(+ title: q['title'] ?? '',+ author: q['author'],+ provider: q['provider'] ?? 'all',+ audiobook: q['isAudiobook'] != 'false',+ );++ @override+ Future<List<String>> searchCovers(String title,+ {String? author, String provider = 'google', String? coverSlot}) async {+ try {+ return await _searchCoverUrls(+ title: title,+ author: author,+ provider: provider,+ audiobook: coverSlot != 'ebook',+ );+ } catch (e) {+ debugPrint('[BookOrbit] cover search failed: $e');+ return const [];+ }+ }++ /// Display URL of a cover search result -> the full-size image to set.+ static final Map<String, String> _coverPicks = {};++ /// Cover search the way BookOrbit's web editor does it: [audiobook] says+ /// which slot it is for, which changes what each source looks for, and+ /// results show through BookOrbit's image proxy like on the web.+ Future<List<String>> _searchCoverUrls({+ required String title,+ String? author,+ required String provider,+ required bool audiobook,+ }) async {+ final source = _coverProviders[provider];+ final t = title.trim();+ if (source == null || t.isEmpty || (source == 'audiobookcovers' && !audiobook)) return const [];+ final a = (author ?? '').trim();+ final res = await _boGet('/books/cover/search', {+ 'title': t,+ if (a.isNotEmpty) 'author': a,+ 'isAudiobook': '$audiobook',+ 'provider': source,+ }, const Duration(seconds: 30));+ if (_coverPicks.length > 500) _coverPicks.clear();+ final urls = <String>[];+ for (final r in (res as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>()) {+ final full = '${r['url'] ?? ''}';+ final preview = r['previewUrl'];+ if (preview is String && preview.startsWith('/')) {+ final shown = BookOrbitMediaProxy.instance.urlFor(preview);+ if (full.startsWith('http')) _coverPicks[shown] = full;+ urls.add(shown);+ } else if (full.startsWith('http')) {+ urls.add(full);+ }+ }+ return urls;+ }++ /// Audiobookshelf finds a book's Audible match through its own server.+ /// BookOrbit only searches Audible when its admin turned that provider on,+ /// so ask Audible's catalog directly, as the rating lookup by ASIN does.+ @override+ Future<Map<String, dynamic>?> searchAudibleRating(String title, String? author) async {+ final wanted = _plainTitle(title);+ if (wanted.isEmpty) return null;+ final firstAuthor = (author ?? '').split(',').first.trim();+ try {+ final uri = Uri.parse('https://api.audible${ApiService._audibleTld}/1.0/catalog/products').replace(+ queryParameters: {+ 'title': title.trim(),+ if (firstAuthor.isNotEmpty) 'author': firstAuthor,+ 'num_results': '5',+ 'products_sort_by': 'Relevance',+ 'response_groups': 'product_desc,rating',+ },+ );+ final r = await http.get(uri).timeout(const Duration(seconds: 10));+ if (r.statusCode != 200) return null;+ final products = ((jsonDecode(r.body) as Map<String, dynamic>)['products'] as List<dynamic>? ?? const [])+ .whereType<Map<String, dynamic>>();+ for (final p in products) {+ final asin = p['asin'] as String?;+ final found = _plainTitle('${p['title'] ?? ''}');+ // Same book, not just a good keyword hit.+ if (asin == null || found.isEmpty || !(found.contains(wanted) || wanted.contains(found))) continue;+ final overall = (p['rating'] as Map?)?['overall_distribution'] as Map?;+ final score = (overall?['average_rating'] as num?)?.toDouble();+ if (score == null || !score.isFinite || score <= 0 || score > 5) continue;+ final count = (overall?['num_ratings'] as num?)?.toInt();+ return {'rating': score, 'count': count != null && count >= 0 ? count : null, 'asin': asin};+ }+ } catch (e) {+ debugPrint('[BookOrbit] Audible rating search failed: $e');+ }+ return null;+ }++ static String _plainTitle(String s) =>+ s.toLowerCase().replaceAll(RegExp(r'[^\p{L}\p{N}]+', unicode: true), ' ').trim();++ @override+ Future<List<Map<String, dynamic>>> getSimilarBooks(String itemId) async {+ try {+ final res = await _boGet('/books/$itemId/recommendations') as List<dynamic>;+ return res.whereType<Map<String, dynamic>>().map(BookOrbitMapper.similarBook).toList();+ } catch (e) {+ debugPrint('[BookOrbit] No similar books for $itemId: $e');+ return const [];+ }+ }++ @override+ Future<bool> setReadStatus(String itemId, String status) async {+ try {+ await _boPatch('/books/$itemId/status', {'status': status});+ _details.remove(_key(itemId));+ _detailAt.remove(_key(itemId));+ _recent.removeWhere((key, _) => key == 'progress' || key.startsWith('personalized:'));+ return true;+ } catch (e) {+ debugPrint('[BookOrbit] setReadStatus error: $e');+ return false;+ }+ }++ @override+ Future<bool> setPersonalNote(String itemId, String? note) async {+ final text = note?.trim();+ try {+ final d = await _boPatch('/books/$itemId/personal-note', {+ 'note': text == null || text.isEmpty ? null : (text.length > 10000 ? text.substring(0, 10000) : text),+ }) as Map<String, dynamic>;+ _details[_key(itemId)] = d;+ _detailAt[_key(itemId)] = DateTime.now();+ return true;+ } catch (e) {+ debugPrint('[BookOrbit] setPersonalNote error: $e');+ return false;+ }+ }++ @override+ Future<List<Map<String, String>>?> bookMatchProviders() async {+ try {+ final res = await _boGet('/metadata-fetch/providers') as List<dynamic>;+ return [+ for (final p in res.whereType<Map<String, dynamic>>())+ if (p['key'] is String) {'key': p['key'] as String, 'label': '${p['label'] ?? p['key']}'},+ ];+ } catch (e) {+ debugPrint('[BookOrbit] provider list failed: $e');+ return null;+ }+ }++ /// The app's provider names that BookOrbit spells differently. Anything+ /// else is passed through, since the list mostly comes from the server.+ static const _bookProviders = {'openlibrary': 'openLibrary'};++ /// Provider search, which BookOrbit streams back as server-sent events,+ /// one candidate per event.+ Future<List<Map<String, dynamic>>> _searchBooks(Map<String, String> q) async {+ final asked = (q['provider'] ?? '').trim();+ final provider = _bookProviders[asked] ?? asked;+ final title = (q['title'] ?? '').trim();+ final author = (q['author'] ?? '').trim();+ if (provider.isEmpty || (title.isEmpty && author.isEmpty)) return const [];+ final r = await super._authGet(+ _boUri('/metadata-fetch/stream', {+ if (title.isNotEmpty) 'title': title.length > 500 ? title.substring(0, 500) : title,+ if (author.isNotEmpty) 'author': author.length > 255 ? author.substring(0, 255) : author,+ 'providers': provider,+ }),+ timeout: const Duration(seconds: 60),+ );+ if (r.statusCode != 200) throw _BoHttpError(r.statusCode, r.body);+ final out = <Map<String, dynamic>>[];+ for (final block in utf8.decode(r.bodyBytes).split(RegExp(r'\r?\n\r?\n'))) {+ final lines = block.split(RegExp(r'\r?\n'));+ if (lines.any((l) => l.startsWith('event:'))) continue;+ final data = lines.where((l) => l.startsWith('data:')).map((l) => l.substring(5).trim()).join('\n');+ if (data.isEmpty) continue;+ try {+ final c = jsonDecode(data);+ if (c is Map<String, dynamic>) out.add(BookOrbitMapper.searchResult(c));+ } catch (_) {}+ }+ return out;+ }++ /// Chapter lookup by ASIN. BookOrbit only fetches chapters for an ASIN a+ /// book already has stored, so this asks Audnexus directly, the same+ /// source Audiobookshelf's lookup reads.+ Future<Map<String, dynamic>> _searchChapters(String asin, String region) async {+ const notFound = {'error': 'Chapters not found', 'stringKey': 'MessageChaptersNotFound'};+ final id = asin.trim();+ if (!RegExp(r'^[A-Za-z0-9]{10}$').hasMatch(id)) return notFound;+ final uri = Uri.https('api.audnex.us', '/books/$id/chapters', {'region': region.toLowerCase()});+ try {+ final r = await http.get(uri).timeout(const Duration(seconds: 20));+ if (r.statusCode != 200) return notFound;+ final data = jsonDecode(r.body);+ return data is Map<String, dynamic> && data['chapters'] is List ? data : notFound;+ } catch (e) {+ debugPrint('[BookOrbit] chapter lookup failed: $e');+ return notFound;+ }+ }++ /// Audiobookshelf-shaped content URLs (`/api/items/<book>/file/<file>`)+ /// become proxied BookOrbit asset streams.+ @override+ String buildTrackUrl(String contentUrl, {String? sessionId, int? trackIndex, int? playMethod}) {+ final uri = Uri.parse(contentUrl);+ if (BookOrbitMediaProxy.instance.owns(contentUrl)) return contentUrl;+ final seg = uri.pathSegments;+ final i = seg.indexOf('items');+ if (i >= 0 && i + 3 < seg.length && seg[i + 2] == 'file') {+ final bookId = seg[i + 1];+ final fileId = seg[i + 3];+ final asset = uri.queryParameters['asset'] ?? _assetByFile[_key(fileId)];+ if (asset != null) {+ return BookOrbitMediaProxy.instance.urlFor('/api/v1/audiobooks/$bookId/assets/$asset/content');+ }+ return BookOrbitMediaProxy.instance.urlFor('/api/v1/books/files/$fileId/download');+ }+ if (uri.path.contains('/api/v1/')) {+ final at = uri.path.indexOf('/api/v1/');+ return BookOrbitMediaProxy.instance.urlFor(uri.path.substring(at) + (uri.hasQuery ? '?${uri.query}' : ''));+ }+ return contentUrl;+ }++ @override+ String buildDownloadFileUrl(String itemId, String ino) {+ final ticket = _tickets[_key(itemId)];+ if (ticket != null &&+ ticket.fileIds.contains(ino) &&+ ticket.expiresAt.isAfter(DateTime.now().add(const Duration(hours: 1)))) {+ return '$_v1/watch-downloads/files/$ino';+ }+ return buildFileUrl(itemId, ino);+ }++ @override+ String buildFileUrl(String itemId, String ino) {+ final asset = _assetByFile[_key(ino)];+ if (asset != null) {+ return BookOrbitMediaProxy.instance.urlFor('/api/v1/audiobooks/$itemId/assets/$asset/content');+ }+ return BookOrbitMediaProxy.instance.urlFor('/api/v1/books/files/$ino/serve');+ }++ @override+ String buildEbookUrl(String itemId, String ino) =>+ BookOrbitMediaProxy.instance.urlFor('/api/v1/books/files/$ino/serve');++ @override+ Map<String, String> downloadHeadersFor(String url) {+ if (url.startsWith('$_v1/watch-downloads/files/')) {+ final fileId = Uri.parse(url).pathSegments.last;+ for (final t in _tickets.values) {+ if (t.fileIds.contains(fileId)) {+ return {...customHeaders, 'Authorization': 'Bearer ${t.token}'};+ }+ }+ }+ return mediaHeaders;+ }++ /// Background downloads outlive a fifteen-minute access token, so ask the+ /// server for a download ticket (good for twelve hours) covering the+ /// book's audio files. Without one the files go through the in-app proxy.+ @override+ Future<void> prepareDownload(String itemId) async {+ await ensureMediaReady();+ final manifest = await _manifest(itemId, fresh: true);+ final fileIds = (manifest?['assets'] as List<dynamic>? ?? const [])+ .whereType<Map<String, dynamic>>()+ .map((a) => a['fileId'])+ .whereType<int>()+ .toList();+ if (fileIds.isEmpty) return;+ try {+ final res = await _boPost('/watch-downloads', {+ 'bookId': int.parse(itemId),+ 'fileIds': fileIds.take(256).toList(),+ }) as Map<String, dynamic>;+ final token = res['token'] as String?;+ final expires = DateTime.tryParse(res['expiresAt'] as String? ?? '');+ if (token != null && expires != null) {+ _tickets[_key(itemId)] = _BoTicket(token, expires, fileIds.map((e) => '$e').toSet());+ }+ } catch (e) {+ debugPrint('[BookOrbit] No download ticket for $itemId ($e) - using the proxy');+ }+ }++ Future<Map<String, dynamic>?> _playbackState(String bookId) async {+ try {+ final state = await _boGet('/audiobooks/$bookId/playback-state');+ if (state is Map<String, dynamic>) {+ final rev = (state['revision'] as num?)?.toInt();+ if (rev != null) _revisions[_key(bookId)] = rev;+ return state;+ }+ _revisions[_key(bookId)] = 0;+ return null;+ } on _BoHttpError catch (e) {+ if (e.status == 404) return null;+ rethrow;+ }+ }++ ({String? cfi, double? percent, int? updated, int? fileId}) _ebookFrom(+ Map<String, dynamic> detail, List<dynamic> fileProgress) {+ final item = BookOrbitMapper.item(detail: detail);+ final ebook = (item['media'] as Map)['ebookFile'] as Map?;+ final fileId = int.tryParse('${ebook?['ino']}');+ if (fileId == null) return (cfi: null, percent: null, updated: null, fileId: null);+ for (final p in fileProgress.whereType<Map<String, dynamic>>()) {+ if (p['fileId'] == fileId) {+ final pct = (p['percentage'] as num?)?.toDouble();+ final cfi = p['cfi'] as String? ?? (p['pageNumber'] != null ? '${p['pageNumber']}' : null);+ if ((pct == null || pct == 0) && cfi == null) break;+ return (cfi: cfi, percent: pct, updated: BookOrbitMapper.ms(p['updatedAt']), fileId: fileId);+ }+ }+ return (cfi: null, percent: null, updated: null, fileId: fileId);+ }++ Future<Map<String, dynamic>?> _itemProgress(+ String bookId, {+ Map<String, dynamic>? detail,+ Map<String, dynamic>? manifest,+ }) async {+ detail ??= await _detail(bookId);+ final hasAudio = _detailHasAudio(detail);+ manifest ??= hasAudio ? await _manifest(bookId) : null;+ final state = manifest != null ? await _playbackState(bookId) : null;+ ({String? cfi, double? percent, int? updated, int? fileId}) ebook =+ (cfi: null, percent: null, updated: null, fileId: null);+ if ((BookOrbitMapper.item(detail: detail)['media'] as Map)['ebookFile'] != null) {+ try {+ final fp = await _boGet('/books/$bookId/progress') as List<dynamic>;+ ebook = _ebookFrom(detail, fp);+ } catch (_) {}+ }+ final readStatus = detail['readStatus'] as Map<String, dynamic>?;+ if (state == null && ebook.percent == null && readStatus == null) return null;+ final p = BookOrbitMapper.progress(+ bookId: bookId,+ manifest: manifest,+ state: state,+ readStatus: readStatus,+ ebookPercent: ebook.percent,+ ebookLocation: ebook.cfi,+ ebookUpdatedAt: ebook.updated,+ );+ if (!hasAudio && ebook.percent != null) p['progress'] = (ebook.percent! / 100).clamp(0.0, 1.0);+ return p;+ }++ Future<List<Map<String, dynamic>>> _allProgress() async {+ final byId = <String, Map<String, dynamic>>{};+ Future<void> collect(List<String> statuses, String sortField, int maxPages) async {+ for (var page = 0; page < maxPages; page++) {+ final res = await _boPost('/books/query', {+ 'filter': {+ 'type': 'group',+ 'join': 'AND',+ 'rules': [_rule('readStatus', 'includesAny', statuses)],+ },+ 'sort': [{'field': sortField, 'dir': 'desc'}],+ 'pagination': {'page': page, 'size': 200},+ }) as Map<String, dynamic>;+ final items = (res['items'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>().toList();+ for (final c in items) {+ _cardItem(c);+ byId['${c['id']}'] = BookOrbitMapper.cardProgress(c);+ }+ final total = (res['total'] as num?)?.toInt() ?? 0;+ if (items.length < 200 || (page + 1) * 200 >= total) break;+ }+ }++ await collect(['reading', 'rereading', 'on_hold'], 'startedAt', 5);+ await collect(['read', 'skimmed'], 'finishedAt', 2);+ // Real positions for what is being listened to right now, so another+ // device's place carries over.+ try {+ final listening = (await _shelfCards('continue-listening', 12)).map((c) => '${c['id']}').toList();+ final real = await _pool(listening.map((id) => () async {+ try {+ final manifest = await _manifest(id);+ if (manifest == null) return null;+ final state = await _playbackState(id);+ if (state == null) return null;+ final card = byId[id];+ return BookOrbitMapper.progress(+ bookId: id,+ manifest: manifest,+ state: state,+ readStatus: card == null ? null : {'status': card['isFinished'] == true ? 'read' : 'reading', 'updatedAt': null},+ );+ } catch (_) {+ return null;+ }+ }).toList());+ for (final p in real.whereType<Map<String, dynamic>>()) {+ byId['${p['libraryItemId']}'] = p;+ }+ } catch (e) {+ debugPrint('[BookOrbit] Continue-listening positions failed: $e');+ }+ return byId.values.toList();+ }++ /// Save a book-absolute position. Returns the HTTP status that best+ /// describes the outcome for Audiobookshelf callers.+ Future<int> _putPosition(String bookId, double absoluteSeconds, {DateTime? capturedAt}) async {+ var manifest = await _manifest(bookId);+ if (manifest == null) return 404;+ final when = (capturedAt ?? DateTime.now()).toUtc();+ final operationId = _uuid();+ for (var attempt = 0; attempt < 3; attempt++) {+ final pos = BookOrbitMapper.trackPosition(manifest!, absoluteSeconds);+ if (pos == null) return 404;+ var base = _revisions[_key(bookId)];+ if (base == null) {+ final state = await _playbackState(bookId);+ final serverAt = DateTime.tryParse(state?['capturedAt'] as String? ?? '');+ if (serverAt != null && serverAt.isAfter(when)) return 200;+ base = _revisions[_key(bookId)] ?? 0;+ }+ try {+ final saved = await _boPut('/audiobooks/$bookId/playback-state', {+ 'assetId': pos.assetId,+ 'positionMs': pos.positionMs,+ 'capturedAt': _iso(when),+ 'operationId': operationId,+ 'baseRevision': base,+ 'manifestRevision': manifest['revision'],+ }) as Map<String, dynamic>;+ final rev = (saved['revision'] as num?)?.toInt();+ if (rev != null) _revisions[_key(bookId)] = rev;+ return 200;+ } on _BoHttpError catch (e) {+ if (e.status == 409) {+ _revisions.remove(_key(bookId));+ final state = await _playbackState(bookId);+ final serverAt = DateTime.tryParse(state?['capturedAt'] as String? ?? '');+ if (serverAt != null && !serverAt.isBefore(when)) return 200;+ continue;+ }+ if (e.status == 412) {+ manifest = await _manifest(bookId, fresh: true);+ if (manifest == null) return 404;+ continue;+ }+ debugPrint('[BookOrbit] Position for $bookId not saved: ${e.status} ${e.message}');+ return e.status;+ }+ }+ return 409;+ }++ Future<void> _setStatus(String bookId, Map<String, dynamic> body) async {+ await _boPatch('/books/$bookId/status', body);+ _detailAt.remove(_key(bookId));+ }++ static String? _dateParam(Object? ms) {+ if (ms is! num || ms <= 0) return null;+ final d = DateTime.fromMillisecondsSinceEpoch(ms.toInt());+ final now = DateTime.now();+ return _iso(d.isAfter(now) ? now : d);+ }++ Future<void> _patchProgress(String bookId, Map<String, dynamic> body) async {+ if (bookId.length > 36) return;+ final isFinished = body['isFinished'];+ if (isFinished == true) {+ // List items carry no duration here, so the caller's end-of-book+ // position can be 0. The end comes from the track list instead.+ final manifest = await _manifest(bookId);+ if (manifest != null) {+ final status = await _putPosition(bookId, BookOrbitMapper.totalSeconds(manifest));+ if (status >= 500) throw _BoHttpError(status, 'Position not saved');+ }+ } else if (body['currentTime'] is num && isFinished == null) {+ final status = await _putPosition(bookId, (body['currentTime'] as num).toDouble());+ if (status >= 500) throw _BoHttpError(status, 'Position not saved');+ }+ if (body.containsKey('ebookLocation') || body.containsKey('ebookProgress')) {+ await _saveEbookProgress(bookId, body['ebookLocation'] as String?, (body['ebookProgress'] as num?)?.toDouble());+ }+ if (isFinished == true) {+ await _setStatus(bookId, {+ 'status': 'read',+ if (_dateParam(body['finishedAt']) != null) 'finishedAt': _dateParam(body['finishedAt']),+ });+ } else if (isFinished == false) {+ // Audiobookshelf clears the position when a book is un-finished.+ await _clearPosition(bookId);+ await _unfinish(bookId);+ } else if (body['finishedAt'] != null) {+ final d = _dateParam(body['finishedAt']);+ if (d != null) await _setStatus(bookId, {'finishedAt': d});+ }+ final started = _dateParam(body['startedAt'] ?? body['createdAt']);+ if (started != null && isFinished == null && body['currentTime'] == null) {+ await _setStatus(bookId, {'startedAt': started});+ }+ }++ Future<void> _saveEbookProgress(String bookId, String? location, double? progress) async {+ final detail = await _detail(bookId);+ final ebook = (BookOrbitMapper.item(detail: detail)['media'] as Map)['ebookFile'] as Map?;+ final fileId = ebook?['ino'];+ if (fileId == null) return;+ final pct = ((progress ?? 0) * 100).clamp(0.0, 100.0);+ final page = location == null ? null : int.tryParse(location);+ await _boPost('/books/files/$fileId/progress', {+ 'percentage': pct,+ if (location != null && page == null) 'cfi': location,+ if (page != null) 'pageNumber': page,+ });+ if (progress != null && progress >= 1.0) {+ await _setStatus(bookId, {'status': 'read'});+ }+ }++ Future<void> _clearPosition(String bookId) async {+ try {+ await _boDelete('/audiobooks/$bookId/playback-state');+ } on _BoHttpError catch (e) {+ if (e.status != 404) rethrow;+ }+ _revisions[_key(bookId)] = 0;+ }++ /// Take a finished book back to reading. Any status set from here is a+ /// manual one, which BookOrbit never updates on its own again, so nothing+ /// is written unless the book is actually marked finished.+ Future<void> _unfinish(String bookId) async {+ final status = ((await _detail(bookId, fresh: true))['readStatus'] as Map?)?['status'];+ if (status == 'read' || status == 'skimmed') {+ await _setStatus(bookId, {'status': 'reading'});+ }+ }++ Future<void> _deleteProgress(String progressId) async {+ final bookId = progressId.startsWith('bo-') ? progressId.substring(3) : progressId;+ await _clearPosition(bookId);+ await _unfinish(bookId);+ }++ @override+ Future<bool> updateEbookProgress(String itemId, {required String ebookLocation, required double ebookProgress}) async {+ try {+ await _saveEbookProgress(itemId, ebookLocation, ebookProgress);+ return true;+ } catch (e) {+ debugPrint('[BookOrbit] updateEbookProgress error: $e');+ return false;+ }+ }++ @override+ Future<bool> setCollectionPublic(String collectionId, bool isPublic) async {+ try {+ await _boPatch('/collections/$collectionId', {'isPublic': isPublic});+ return true;+ } catch (e) {+ debugPrint('[BookOrbit] setCollectionPublic error: $e');+ return false;+ }+ }++ @override+ Future<bool> updateLibraryItemsFinished(List<String> itemIds, {required bool isFinished}) async {+ if (itemIds.isEmpty) return false;+ try {+ await _pool(itemIds.map((id) => () => _patchProgress(id, {'isFinished': isFinished})).toList(), width: 4);+ return true;+ } catch (e) {+ debugPrint('[BookOrbit] updateLibraryItemsFinished error: $e');+ return false;+ }+ }++ @override+ Future<bool> resetProgress(String itemId, double duration, {String? progressId}) async {+ try {+ await _deleteProgress(itemId);+ return true;+ } catch (e) {+ debugPrint('[BookOrbit] resetProgress error: $e');+ return false;+ }+ }++ @override+ Future<bool> updateProgressStartDate(String itemId, int startedAt) async {+ try {+ final d = _dateParam(startedAt);+ if (d == null) return false;+ await _setStatus(itemId, {'startedAt': d});+ return true;+ } catch (e) {+ debugPrint('[BookOrbit] updateProgressStartDate error: $e');+ return false;+ }+ }++ @override+ Future<bool> updateProgressFinishedDate(String itemId, int finishedAt) async {+ try {+ final d = _dateParam(finishedAt);+ if (d == null) return false;+ await _setStatus(itemId, {'status': 'read', 'finishedAt': d});+ return true;+ } catch (e) {+ debugPrint('[BookOrbit] updateProgressFinishedDate error: $e');+ return false;+ }+ }++ Future<Map<String, dynamic>> _startSession(String bookId, Map<String, dynamic> body) async {+ final detail = await _detail(bookId, fresh: true);+ final manifest = await _manifest(bookId, fresh: true);+ if (manifest == null) throw _BoHttpError(404, 'Book has no audiobook assets');+ final state = await _playbackState(bookId);+ final item = BookOrbitMapper.item(detail: detail, manifest: manifest);+ final media = item['media'] as Map<String, dynamic>;+ final metadata = media['metadata'] as Map<String, dynamic>;+ final current = state == null ? 0.0 : BookOrbitMapper.absolutePosition(manifest, state);+ final now = DateTime.now();+ final sessionId = 'bo-$bookId-${now.millisecondsSinceEpoch}';+ final assets = (manifest['assets'] as List<dynamic>).whereType<Map<String, dynamic>>().toList();+ _sessions[sessionId] = _BoListenSession(bookId, _uuid(), now)+ ..fileId = assets.isEmpty ? null : (assets.first['fileId'] as num?)?.toInt()+ ..startPercent = BookOrbitMapper.totalSeconds(manifest) > 0+ ? (current / BookOrbitMapper.totalSeconds(manifest) * 100).clamp(0.0, 100.0)+ : null;+ return {+ 'id': sessionId,+ 'userId': '',+ 'libraryId': item['libraryId'],+ 'libraryItemId': bookId,+ 'episodeId': null,+ 'mediaType': 'book',+ 'mediaMetadata': metadata,+ 'chapters': media['chapters'],+ 'displayTitle': metadata['title'],+ 'displayAuthor': metadata['authorName'],+ 'coverPath': media['coverPath'],+ 'duration': media['duration'],+ 'playMethod': 0,+ 'mediaPlayer': 'exo-player',+ 'deviceInfo': _deviceInfo,+ 'date': '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}',+ 'timeListening': 0,+ 'startTime': current,+ 'currentTime': current,+ 'startedAt': now.millisecondsSinceEpoch,+ 'updatedAt': BookOrbitMapper.ms(state?['capturedAt']) ?? now.millisecondsSinceEpoch,+ 'audioTracks': media['tracks'],+ 'libraryItem': item,+ };+ }++ _BoListenSession? _sessionFor(String sessionId) {+ final existing = _sessions[sessionId];+ if (existing != null) return existing;+ final m = RegExp(r'^bo-(\d+)-(\d+)$').firstMatch(sessionId);+ if (m == null) return null;+ final started = DateTime.fromMillisecondsSinceEpoch(int.parse(m.group(2)!));+ return _sessions[sessionId] = _BoListenSession(m.group(1)!, _uuid(), started);+ }++ Future<void> _checkpoint(_BoListenSession s, {DateTime? endedAt}) async {+ final seconds = s.listenedSeconds.round();+ if (seconds < 10) return;+ var fileId = s.fileId;+ if (fileId == null) {+ final manifest = await _manifest(s.bookId);+ final assets = (manifest?['assets'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>();+ fileId = assets.isEmpty ? null : (assets.first['fileId'] as num?)?.toInt();+ s.fileId = fileId;+ }+ if (fileId == null) return;+ final end = endedAt ?? DateTime.now();+ final span = end.difference(s.startedAt).inSeconds;+ final source = _platformSource();+ try {+ await _boPost('/books/files/$fileId/sessions', {+ 'sessionId': s.sessionUuid,+ 'startedAt': _iso(s.startedAt),+ 'endedAt': _iso(end),+ 'durationSeconds': span < seconds ? math.max(span, 0) : seconds,+ if (s.startPercent != null && s.lastPercent != null)+ 'progressDelta': double.parse((s.lastPercent! - s.startPercent!).toStringAsFixed(4)),+ if (s.lastPercent != null) 'endProgress': s.lastPercent!.clamp(0.0, 100.0),+ 'sessionType': 'listen',+ if (source != null) 'source': source,+ });+ if (!s.deviceRemembered) {+ s.deviceRemembered = true;+ await _rememberSessionDevice(s.bookId, _iso(s.startedAt));+ }+ } catch (e) {+ debugPrint('[BookOrbit] Listening session checkpoint failed: $e');+ }+ }++ /// BookOrbit keeps a platform tag on each session but no device, so the+ /// sessions this phone recorded are remembered here to name them later.+ static const _sessionDevicesKey = 'bookorbit_session_devices';++ static String _thisDevice() {+ final name = [ApiService.deviceManufacturer, ApiService.deviceModel]+ .where((s) => s.isNotEmpty)+ .join(' ');+ return name.isEmpty ? 'Absorb' : name;+ }++ Future<void> _rememberSessionDevice(String bookId, String startedAtIso) async {+ try {+ final prefs = await SharedPreferences.getInstance();+ final raw = prefs.getString(_sessionDevicesKey);+ final map = raw == null ? <String, dynamic>{} : jsonDecode(raw) as Map<String, dynamic>;+ map['$bookId@$startedAtIso'] = _thisDevice();+ while (map.length > 500) {+ map.remove(map.keys.first);+ }+ await prefs.setString(_sessionDevicesKey, jsonEncode(map));+ } catch (_) {}+ }++ static String _sourceLabel(Object? source) => switch (source) {+ 'android' => 'Android',+ 'ios' => 'iOS',+ 'watchos' => 'Apple Watch',+ 'web' => 'BookOrbit web',+ 'koreader' => 'KOReader',+ 'kobo' => 'Kobo',+ 'manual' => 'Manual entry',+ _ => 'BookOrbit',+ };++ Future<http.Response> _syncSession(String sessionId, Map<String, dynamic> body) async {+ final s = _sessionFor(sessionId);+ if (s == null) return _status(404, 'Unknown session');+ final currentTime = (body['currentTime'] as num?)?.toDouble();+ final listened = (body['timeListened'] as num?)?.toDouble() ?? 0;+ if (listened > 0) s.listenedSeconds += listened;+ var status = 200;+ if (currentTime != null) {+ status = await _putPosition(s.bookId, currentTime);+ final manifest = _manifests[_key(s.bookId)];+ final total = manifest == null ? 0.0 : BookOrbitMapper.totalSeconds(manifest);+ if (total > 0) {+ s.lastPercent = (currentTime / total * 100).clamp(0.0, 100.0);+ s.startPercent ??= s.lastPercent;+ }+ }+ await _checkpoint(s);+ return status == 200 ? _json(const <String, dynamic>{}) : _status(status, 'Sync failed');+ }++ Future<void> _closeSession(String sessionId, Map<String, dynamic> body) async {+ final s = _sessions.remove(sessionId);+ if (s == null) return;+ final currentTime = (body['currentTime'] as num?)?.toDouble();+ if (currentTime != null) await _putPosition(s.bookId, currentTime);+ await _checkpoint(s);+ }++ /// An offline listen from the app's own session log: the position (only if+ /// nothing newer reached the server since) and the listening time.+ Future<Map<String, dynamic>> _localSession(Map<String, dynamic> session) async {+ final bookId = '${session['libraryItemId'] ?? ''}';+ if (bookId.isEmpty || session['episodeId'] != null) return const {};+ final updated = (session['updatedAt'] as num?)?.toInt();+ final when = updated == null ? DateTime.now() : DateTime.fromMillisecondsSinceEpoch(updated);+ final currentTime = (session['currentTime'] as num?)?.toDouble();+ if (currentTime != null) await _putPosition(bookId, currentTime, capturedAt: when);+ final started = (session['startedAt'] as num?)?.toInt();+ final listened = (session['timeListening'] as num?)?.toDouble() ?? 0;+ if (listened >= 10) {+ final rawId = '${session['id'] ?? _uuid()}';+ final s = _BoListenSession(+ bookId,+ rawId.length > 64 ? rawId.substring(0, 64) : rawId,+ started == null ? when.subtract(Duration(seconds: listened.round())) : DateTime.fromMillisecondsSinceEpoch(started),+ )..listenedSeconds = listened;+ final manifest = _manifests[_key(bookId)] ?? await _manifest(bookId);+ final total = manifest == null ? 0.0 : BookOrbitMapper.totalSeconds(manifest);+ final startTime = (session['startTime'] as num?)?.toDouble();+ if (total > 0 && currentTime != null) s.lastPercent = (currentTime / total * 100).clamp(0.0, 100.0);+ if (total > 0 && startTime != null) s.startPercent = (startTime / total * 100).clamp(0.0, 100.0);+ await _checkpoint(s, endedAt: when);+ }+ return {'id': session['id']};+ }++ @override+ Future<Map<String, dynamic>?> startEpisodePlaybackSession(String itemId, String episodeId,+ {bool forceTranscode = false}) async =>+ null;++ Future<List<Map<String, dynamic>>> _rawBookmarks(String bookId) async {+ try {+ final list = await _boGet('/audiobooks/$bookId/bookmarks') as List<dynamic>;+ return list.whereType<Map<String, dynamic>>().toList();+ } on _BoHttpError catch (e) {+ if (e.status == 404 || e.status == 400) return const [];+ rethrow;+ }+ }++ Future<List<Map<String, dynamic>>> _bookmarksFor(String bookId) async =>+ (await _rawBookmarks(bookId)).map(BookOrbitMapper.bookmark).toList();++ Future<List<Map<String, dynamic>>> _recentBookmarks() async {+ final ids = <String>{};+ try {+ ids.addAll((await _shelfCards('continue-listening', 50)).map((c) => '${c['id']}'));+ } catch (_) {}+ final lists = await _pool(ids.map((id) => () async {+ try {+ return await _bookmarksFor(id);+ } catch (_) {+ return <Map<String, dynamic>>[];+ }+ }).toList());+ return lists.expand((l) => l).toList();+ }++ Future<Map<String, dynamic>> _createBookmark(String bookId, Map<String, dynamic> body) async {+ final time = (body['time'] as num?)?.toDouble() ?? 0;+ final title = '${body['title'] ?? ''}'.trim();+ final created = await _boPost('/audiobooks/$bookId/bookmarks', {+ 'clientId': _uuid(),+ 'positionMs': (time * 1000).round(),+ 'title': title.isEmpty ? 'Bookmark' : (title.length > 500 ? title.substring(0, 500) : title),+ }) as Map<String, dynamic>;+ return BookOrbitMapper.bookmark(created);+ }++ Future<Map<String, dynamic>?> _findBookmark(String bookId, double time) async {+ Map<String, dynamic>? best;+ var bestGap = 1.0;+ for (final b in await _rawBookmarks(bookId)) {+ final gap = (((b['positionMs'] as num?) ?? 0) / 1000.0 - time).abs();+ if (gap < bestGap) {+ best = b;+ bestGap = gap;+ }+ }+ return best;+ }++ Future<bool> _updateBookmark(String bookId, Map<String, dynamic> body) async {+ final b = await _findBookmark(bookId, (body['time'] as num?)?.toDouble() ?? -1);+ if (b == null) return false;+ final title = '${body['title'] ?? ''}'.trim();+ if (title.isEmpty) return true;+ await _boPatch('/audiobooks/$bookId/bookmarks/${b['id']}', {'title': title});+ return true;+ }++ Future<bool> _deleteBookmark(String bookId, double time) async {+ final b = await _findBookmark(bookId, time);+ if (b == null) return false;+ await _boDelete('/audiobooks/$bookId/bookmarks/${b['id']}');+ return true;+ }++ Future<Map<String, dynamic>> _listeningStats() async {+ final overview = await _boGet('/user-statistics/activity-overview', null, const Duration(seconds: 45)) as Map<String, dynamic>;+ final days = <String, num>{};+ void addDays(Object? list) {+ for (final d in (list as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>()) {+ final day = d['day'] as String?;+ final secs = (d['listeningSeconds'] as num?) ?? 0;+ if (day != null && secs > 0) days[day] = secs;+ }+ }++ addDays((overview['calendar'] as Map?)?['days']);+ addDays((overview['dailyActivity'] as Map?)?['days']);+ const names = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];+ final dayOfWeek = <String, num>{};+ days.forEach((day, secs) {+ final d = DateTime.tryParse(day);+ if (d == null) return;+ final name = names[d.weekday % 7];+ dayOfWeek[name] = (dayOfWeek[name] ?? 0) + secs;+ });+ final today = ((overview['snapshot'] as Map?)?['today'] as Map?)?['listeningSeconds'] as num? ?? 0;+ final items = <String, dynamic>{};+ try {+ final genres = await _boGet('/user-statistics/activity-details/genre-time', null, const Duration(seconds: 45)) as Map<String, dynamic>;+ for (final g in (genres['genres'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>()) {+ for (final a in (g['authors'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>()) {+ for (final b in (a['books'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>()) {+ final id = '${b['bookId']}';+ final prev = (items[id] as Map?)?['timeListening'] as num? ?? 0;+ items[id] = {+ 'id': id,+ 'timeListening': prev + ((b['totalSeconds'] as num?) ?? 0),+ 'mediaMetadata': {'title': b['title'], 'author': a['author']},+ };+ }+ }+ }+ } catch (_) {}+ return {+ 'totalTime': days.values.fold<num>(0, (sum, v) => sum + v),+ 'items': items,+ 'days': days,+ 'dayOfWeek': dayOfWeek,+ 'today': today,+ 'recentSessions': const [],+ };+ }++ Future<Map<String, dynamic>> _itemListeningSessions(String bookId, Map<String, String> q) async {+ final perPage = (int.tryParse(q['itemsPerPage'] ?? '') ?? 100).clamp(1, 100);+ final page = int.tryParse(q['page'] ?? '') ?? 0;+ final res = await _boGet('/books/$bookId/sessions', {+ 'page': page + 1,+ 'pageSize': perPage,+ 'sortBy': 'startedAt',+ 'sortDir': 'desc',+ }) as Map<String, dynamic>;+ final total = (res['total'] as num?)?.toInt() ?? 0;+ Map<String, dynamic>? manifest;+ try {+ manifest = await _manifest(bookId);+ } catch (_) {}+ final bookSeconds = manifest == null ? 0.0 : BookOrbitMapper.totalSeconds(manifest);+ // Session rows carry the book's own title and author, as Audiobookshelf's do.+ final book = manifest?['book'] as Map?;+ var title = book?['title'] as String?;+ var author = (book?['authors'] as List<dynamic>?)?.map((a) => '$a').join(', ');+ if (title == null) {+ try {+ final d = await _detail(bookId);+ title = d['title'] as String?;+ author = (d['authors'] as List<dynamic>? ?? const [])+ .map((a) => a is Map ? '${a['name'] ?? ''}' : '$a')+ .where((a) => a.isNotEmpty)+ .join(', ');+ } catch (_) {}+ }+ var mine = <String, dynamic>{};+ try {+ final raw = (await SharedPreferences.getInstance()).getString(_sessionDevicesKey);+ if (raw != null) mine = jsonDecode(raw) as Map<String, dynamic>;+ } catch (_) {}+ final sessions = (res['items'] as List<dynamic>? ?? const [])+ .whereType<Map<String, dynamic>>()+ // Reading the ebook of the same book is not listening.+ .where((s) => s['format'] == null || BookOrbitMapper.isAudioFormat(s['format'] as String?))+ .map((s) {+ final started = DateTime.tryParse(s['startedAt'] as String? ?? '')?.toLocal();+ final endPct = (s['endProgress'] as num?)?.toDouble();+ final deltaPct = (s['progressDelta'] as num?)?.toDouble();+ final endAt = endPct != null && bookSeconds > 0 ? endPct / 100 * bookSeconds : null;+ final startAt = endAt != null && deltaPct != null+ ? ((endPct! - deltaPct) / 100 * bookSeconds).clamp(0.0, bookSeconds)+ : endAt;+ final ownDevice = mine['$bookId@${s['startedAt']}'] as String?;+ return {+ 'id': 'bo-session-${s['id']}',+ 'libraryItemId': bookId,+ 'episodeId': null,+ 'mediaType': 'book',+ 'displayTitle': title,+ 'displayAuthor': author,+ 'mediaMetadata': {'title': title, 'authorName': author},+ if (bookSeconds > 0) 'duration': bookSeconds,+ 'timeListening': s['durationSeconds'] ?? 0,+ if (startAt != null) 'startTime': startAt,+ if (endAt != null) 'currentTime': endAt,+ 'startedAt': BookOrbitMapper.ms(s['startedAt']),+ 'updatedAt': BookOrbitMapper.ms(s['endedAt']),+ 'date': started == null+ ? null+ : '${started.year}-${started.month.toString().padLeft(2, '0')}-${started.day.toString().padLeft(2, '0')}',+ 'deviceInfo': ownDevice != null+ ? {'clientName': 'Absorb', 'deviceName': ownDevice}+ : {'clientName': _sourceLabel(s['source'])},+ 'mediaPlayer': s['source'] ?? 'web',+ };+ }).toList();+ return {+ 'sessions': sessions,+ 'total': total,+ 'numPages': total == 0 ? 1 : (total / perPage).ceil(),+ 'page': page,+ 'itemsPerPage': perPage,+ };+ }+}diff --git a/lib/services/bookorbit_mapper.dart b/lib/services/bookorbit_mapper.dartnew file mode 100644index 00000000..ff6e1774--- /dev/null+++ b/lib/services/bookorbit_mapper.dart@@ -0,0 +1,916 @@+/// Turns BookOrbit API payloads into the Audiobookshelf JSON shapes the rest+/// of the app reads. Pure functions only, so the shapes can be unit tested+/// without a server.+class BookOrbitMapper {+ BookOrbitMapper._();++ static const audioFormats = {'m4b', 'mp3', 'm4a', 'opus', 'ogg', 'flac'};+ static const ebookFormats = {+ 'epub',+ 'kepub',+ 'pdf',+ 'mobi',+ 'azw3',+ 'azw',+ 'fb2',+ 'djvu',+ 'cbz',+ 'cbr',+ 'cb7',+ };++ /// Formats the app's reader can open, best first.+ static const _readerPreference = ['epub', 'kepub', 'pdf', 'cbz', 'cbr', 'cb7', 'mobi', 'azw3', 'azw', 'fb2'];++ static const _mimeTypes = {+ 'm4b': 'audio/mp4',+ 'm4a': 'audio/mp4',+ 'mp3': 'audio/mpeg',+ 'opus': 'audio/ogg',+ 'ogg': 'audio/ogg',+ 'flac': 'audio/flac',+ };++ /// Prefix for author ids the app made up from a name. Book cards only+ /// carry author names, so a tap on one resolves the real id later.+ static const authorNamePrefix = 'name:';++ static bool isAudioFormat(String? format) =>+ format != null && audioFormats.contains(format.toLowerCase());++ static bool _isContent(Map<String, dynamic> file) {+ final role = file['role'] as String?;+ return role == 'primary' || role == 'content';+ }++ static String? _format(Map<String, dynamic> file) =>+ (file['format'] as String?)?.toLowerCase();++ static int? ms(Object? iso) {+ if (iso is num) return iso.toInt();+ if (iso is! String || iso.isEmpty) return null;+ return DateTime.tryParse(iso)?.millisecondsSinceEpoch;+ }++ static String _str(Object? v) => v == null ? '' : '$v';++ static List<Map<String, dynamic>> _maps(Object? list) =>+ (list as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>().toList();++ static List<String> _strings(Object? list) =>+ (list as List<dynamic>? ?? const []).map((e) => '$e').where((e) => e.isNotEmpty).toList();++ static String _lastFirst(String name) {+ final parts = name.trim().split(RegExp(r'\s+'));+ if (parts.length < 2) return name;+ final last = parts.removeLast();+ return '$last, ${parts.join(' ')}';+ }++ static Map<String, dynamic> library(Map<String, dynamic> lib) {+ final type = lib['type'] as String? ?? 'books';+ return {+ 'id': _str(lib['id']),+ 'name': lib['name'] ?? '',+ 'displayOrder': lib['displayOrder'] ?? 0,+ 'icon': 'database',+ 'mediaType': type == 'podcasts' ? 'podcast' : 'book',+ 'provider': 'audible',+ 'folders': const [],+ 'settings': {+ 'coverAspectRatio': lib['coverAspectRatio'] == '1/1' ? 1 : 0,+ },+ 'createdAt': ms(lib['createdAt']),+ 'lastUpdate': ms(lib['updatedAt']),+ 'bookCount': lib['bookCount'],+ };+ }++ static Map<String, dynamic> user(Map<String, dynamic> u) {+ final perms = _strings(u['permissions']);+ final superuser = u['isSuperuser'] == true || perms.contains('*');+ bool has(String p) => superuser || perms.contains(p);+ return {+ 'id': _str(u['id']),+ 'username': u['username'] ?? '',+ 'email': u['email'],+ // Admin screens talk to Audiobookshelf-only endpoints, so everyone is+ // a plain user here until those screens learn BookOrbit.+ 'type': 'user',+ 'isActive': u['active'] != false,+ 'isLocked': false,+ 'permissions': {+ 'download': has('library_download'),+ 'update': has('library_edit_metadata'),+ 'delete': has('library_delete_books'),+ 'upload': false,+ 'accessAllLibraries': true,+ 'accessAllTags': true,+ 'accessExplicitContent': true,+ },+ 'librariesAccessible': const [],+ 'itemTagsSelected': const [],+ 'mediaProgress': const [],+ 'bookmarks': const [],+ 'seriesHideFromContinueListening': const [],+ 'bookOrbit': {+ 'name': u['name'],+ 'isSuperuser': superuser,+ 'permissions': perms,+ 'timezone': (u['settings'] as Map?)?['timezone'],+ },+ };+ }++ static String trackContentUrl(String bookId, Object? fileId, String? assetId) {+ final asset = assetId == null ? '' : '?asset=$assetId';+ return '/api/items/$bookId/file/$fileId$asset';+ }++ /// Library item in the expanded Audiobookshelf shape. [detail] is a+ /// BookOrbit BookDetail, [card] a BookCard; either may be missing. With a+ /// [manifest] the tracks, chapters and duration come from it.+ static Map<String, dynamic> item({+ Map<String, dynamic>? card,+ Map<String, dynamic>? detail,+ Map<String, dynamic>? manifest,+ String? libraryId,+ }) {+ final src = detail ?? card ?? const <String, dynamic>{};+ final id = _str(src['id']);+ final files = _maps(src['files']);+ final contentFiles = files.where(_isContent).toList();++ final authorRefs = <Map<String, dynamic>>[];+ if (detail != null) {+ for (final a in _maps(detail['authors'])) {+ authorRefs.add({'id': _str(a['id']), 'name': a['name'] ?? ''});+ }+ } else {+ for (final name in _strings(src['authors'])) {+ authorRefs.add({'id': '$authorNamePrefix$name', 'name': name});+ }+ }+ final authorNames = authorRefs.map((a) => a['name'] as String).toList();++ final narratorNames = detail != null+ ? _maps((detail['audioMetadata'] as Map?)?['narrators'])+ .map((n) => '${n['name'] ?? ''}')+ .where((n) => n.isNotEmpty)+ .toList()+ : _strings(src['narrators']);++ final seriesList = <Map<String, dynamic>>[];+ final memberships = _maps(src['seriesMemberships']);+ if (memberships.isNotEmpty) {+ memberships.sort((a, b) =>+ ((a['displayOrder'] as num?) ?? 0).compareTo((b['displayOrder'] as num?) ?? 0));+ for (final m in memberships) {+ seriesList.add({+ 'id': _str(m['seriesId']),+ 'name': m['seriesName'] ?? '',+ 'sequence': m['seriesIndex'],+ });+ }+ } else if (src['seriesName'] != null) {+ seriesList.add({+ 'id': _str(src['seriesId'] ?? 'name:${src['seriesName']}'),+ 'name': src['seriesName'],+ 'sequence': src['seriesIndex'],+ });+ }+ final seriesName = seriesList+ .map((s) => s['sequence'] != null ? '${s['name']} #${s['sequence']}' : '${s['name']}')+ .join(', ');++ final title = (src['title'] as String?) ?? '';+ final providerIds = (detail?['providerIds'] as Map?) ?? const {};+ final audioMeta = detail?['audioMetadata'] as Map<String, dynamic>?;++ final metadata = <String, dynamic>{+ 'title': title,+ 'titleIgnorePrefix': title,+ 'subtitle': src['subtitle'],+ 'authors': authorRefs,+ 'narrators': narratorNames,+ 'series': seriesList,+ 'genres': _strings(src['genres']),+ 'publishedYear': src['publishedYear'] == null ? null : '${src['publishedYear']}',+ 'publishedDate': src['publishedDate'],+ 'publisher': src['publisher'],+ 'description': detail?['description'],+ 'isbn': detail?['isbn13'] ?? detail?['isbn10'] ?? src['isbn13'],+ 'asin': providerIds['audible'] ?? providerIds['audnexus'],+ 'language': src['language'],+ 'explicit': false,+ 'abridged': audioMeta?['abridged'] == true,+ 'authorName': authorNames.join(', '),+ 'authorNameLF': authorNames.map(_lastFirst).join(', '),+ 'narratorName': narratorNames.join(', '),+ 'seriesName': seriesName,+ };++ // Tracks: the manifest is the playback order; without one, fall back to+ // the file list (good enough to tell audio from ebook on a card).+ final audioFiles = <Map<String, dynamic>>[];+ final tracks = <Map<String, dynamic>>[];+ final assets = _maps(manifest?['assets']);+ final fileById = {for (final f in files) _str(f['id']): f};+ double offset = 0;+ if (assets.isNotEmpty) {+ for (var i = 0; i < assets.length; i++) {+ final a = assets[i];+ final fileId = _str(a['fileId']);+ final f = fileById[fileId] ?? const <String, dynamic>{};+ final fmt = ((a['format'] as String?) ?? _format(f) ?? 'mp3').toLowerCase();+ final dur = ((a['durationMs'] as num?) ?? 0) / 1000.0;+ final filename = (f['filename'] as String?) ?? 'track_${i + 1}.$fmt';+ final fileMeta = {+ 'filename': filename,+ 'ext': '.$fmt',+ 'path': f['absolutePath'] ?? filename,+ 'relPath': filename,+ 'size': a['sizeBytes'] ?? f['sizeBytes'] ?? 0,+ };+ audioFiles.add({+ 'index': i + 1,+ 'ino': fileId,+ 'metadata': fileMeta,+ 'duration': dur,+ 'mimeType': _mimeTypes[fmt] ?? 'audio/mpeg',+ 'format': fmt,+ 'assetId': a['assetId'],+ });+ tracks.add({+ 'index': i + 1,+ 'startOffset': offset,+ 'duration': dur,+ 'title': filename,+ 'contentUrl': trackContentUrl(id, fileId, a['assetId'] as String?),+ 'mimeType': _mimeTypes[fmt] ?? 'audio/mpeg',+ 'metadata': fileMeta,+ });+ offset += dur;+ }+ } else {+ var i = 0;+ for (final f in contentFiles.where((f) => isAudioFormat(_format(f)))) {+ i++;+ final fmt = _format(f)!;+ final dur = ((f['durationSeconds'] as num?) ?? 0).toDouble();+ final filename = (f['filename'] as String?) ?? 'track_$i.$fmt';+ audioFiles.add({+ 'index': i,+ 'ino': _str(f['id']),+ 'metadata': {+ 'filename': filename,+ 'ext': '.$fmt',+ 'path': f['absolutePath'] ?? filename,+ 'relPath': filename,+ 'size': f['sizeBytes'] ?? 0,+ },+ 'duration': dur,+ 'mimeType': _mimeTypes[fmt] ?? 'audio/mpeg',+ 'format': fmt,+ });+ offset += dur;+ }+ }++ final chapters = <Map<String, dynamic>>[];+ final manifestChapters = _maps(manifest?['chapters']);+ if (manifestChapters.isNotEmpty) {+ for (var i = 0; i < manifestChapters.length; i++) {+ final c = manifestChapters[i];+ chapters.add({+ 'id': i,+ 'start': ((c['startMs'] as num?) ?? 0) / 1000.0,+ 'end': ((c['endMs'] as num?) ?? 0) / 1000.0,+ 'title': c['title'] ?? 'Chapter ${i + 1}',+ 'bookOrbitId': c['id'],+ });+ }+ } else {+ final raw = _maps(audioMeta?['chapters']);+ final total = _bookDurationSeconds(manifest, audioMeta, offset);+ for (var i = 0; i < raw.length; i++) {+ final start = ((raw[i]['startMs'] as num?) ?? 0) / 1000.0;+ final end = i + 1 < raw.length+ ? ((raw[i + 1]['startMs'] as num?) ?? 0) / 1000.0+ : total;+ chapters.add({'id': i, 'start': start, 'end': end, 'title': raw[i]['title'] ?? 'Chapter ${i + 1}'});+ }+ }++ final ebook = _primaryEbook(contentFiles);+ final ebookFormat = ebook == null ? null : _format(ebook);+ final duration = _bookDurationSeconds(manifest, audioMeta, offset);+ final size = files.fold<num>(0, (sum, f) => sum + ((f['sizeBytes'] as num?) ?? 0));+ final hasCover = detail != null+ ? detail['coverSource'] != null+ : src['hasCover'] == true;++ final media = <String, dynamic>{+ 'id': id,+ 'libraryItemId': id,+ 'metadata': metadata,+ 'coverPath': hasCover ? '/bookorbit/books/$id/cover' : null,+ 'tags': _strings(src['tags']),+ 'audioFiles': audioFiles,+ 'chapters': chapters,+ 'duration': duration,+ 'size': size,+ 'tracks': tracks,+ 'ebookFile': ebook == null+ ? null+ : {+ 'ino': _str(ebook['id']),+ 'ebookFormat': ebookFormat,+ 'metadata': {+ 'filename': ebook['filename'] ?? 'book.$ebookFormat',+ 'ext': '.$ebookFormat',+ 'size': ebook['sizeBytes'] ?? 0,+ },+ },+ 'ebookFormat': ebookFormat,+ 'numTracks': audioFiles.length,+ 'numAudioFiles': audioFiles.length,+ 'numChapters': chapters.length,+ };++ final item = <String, dynamic>{+ 'id': id,+ 'ino': id,+ 'libraryId': _str(detail?['libraryId'] ?? libraryId),+ 'folderId': '',+ 'path': detail?['folderPath'] ?? '',+ 'relPath': '',+ 'isFile': false,+ 'mediaType': 'book',+ 'addedAt': ms(src['addedAt']),+ 'updatedAt': ms(src['updatedAt']) ?? ms(src['addedAt']),+ 'isMissing': src['status'] == 'missing',+ 'isInvalid': false,+ 'size': size,+ 'numFiles': files.length,+ 'media': media,+ 'libraryFiles': const [],+ 'bookOrbit': {+ 'coverVersion': src['coverVersion'],+ 'audioCover': _hasAudio(files),+ 'readStatus': src['readStatus'],+ 'readingProgress': src['readingProgress'],+ if (detail != null) ...{+ 'personalNote': detail['personalNote'],+ 'communityRatings': detail['communityRatings'] ?? const [],+ 'providerIds': detail['providerIds'] ?? const {},+ },+ },+ };++ final collapsed = card?['collapsedSeries'] as Map<String, dynamic>?;+ if (collapsed != null && seriesList.isNotEmpty) {+ final seriesId = card?['seriesId'] != null ? _str(card!['seriesId']) : seriesList.first['id'];+ final seriesTitle = card?['seriesName'] ?? seriesList.first['name'];+ item['collapsedSeries'] = {+ 'id': seriesId,+ 'name': seriesTitle,+ 'nameIgnorePrefix': seriesTitle,+ 'numBooks': collapsed['bookCount'] ?? 0,+ 'libraryItemIds': (collapsed['coverBookIds'] as List<dynamic>? ?? const [])+ .map((e) => '$e')+ .toList(),+ 'seriesSequenceList': '',+ };+ }+ return item;+ }++ static bool _hasAudio(List<Map<String, dynamic>> files) =>+ files.where(_isContent).any((f) => isAudioFormat(_format(f)));++ static Map<String, dynamic>? _primaryEbook(List<Map<String, dynamic>> contentFiles) {+ final ebooks = contentFiles.where((f) {+ final fmt = _format(f);+ return fmt != null && ebookFormats.contains(fmt);+ }).toList();+ if (ebooks.isEmpty) return null;+ bool narrated(Map<String, dynamic> f) => (f['mediaOverlay'] as Map?)?['available'] == true;+ for (final fmt in _readerPreference) {+ Map<String, dynamic>? fallback;+ for (final f in ebooks) {+ if (_format(f) != fmt) continue;+ if (!narrated(f)) return f;+ fallback ??= f;+ }+ if (fallback != null) return fallback;+ }+ return ebooks.first;+ }++ static double _bookDurationSeconds(+ Map<String, dynamic>? manifest,+ Map<String, dynamic>? audioMeta,+ double trackSum,+ ) {+ final total = manifest?['totalDurationMs'] as num?;+ if (total != null && total > 0) return total / 1000.0;+ if (trackSum > 0) return trackSum;+ final meta = audioMeta?['durationSeconds'] as num?;+ return meta?.toDouble() ?? 0;+ }++ /// Book-absolute seconds for a track-local playback state.+ static double absolutePosition(Map<String, dynamic> manifest, Map<String, dynamic> state) {+ final assetId = state['assetId'];+ final local = ((state['positionMs'] as num?) ?? 0) / 1000.0;+ double elapsed = 0;+ for (final a in _maps(manifest['assets'])) {+ if (a['assetId'] == assetId) return elapsed + local;+ elapsed += ((a['durationMs'] as num?) ?? 0) / 1000.0;+ }+ return local;+ }++ /// The asset and track-local milliseconds for a book-absolute position.+ static ({String assetId, int positionMs})? trackPosition(+ Map<String, dynamic> manifest,+ double absoluteSeconds,+ ) {+ final assets = _maps(manifest['assets']);+ if (assets.isEmpty) return null;+ var remainingMs = (absoluteSeconds * 1000).round();+ if (remainingMs < 0) remainingMs = 0;+ for (var i = 0; i < assets.length; i++) {+ final a = assets[i];+ final dur = (a['durationMs'] as num?)?.toInt();+ final last = i == assets.length - 1;+ if (dur == null || last || remainingMs < dur) {+ final pos = dur != null && remainingMs > dur ? dur : remainingMs;+ return (assetId: a['assetId'] as String, positionMs: pos);+ }+ remainingMs -= dur;+ }+ return null;+ }++ static double totalSeconds(Map<String, dynamic> manifest) =>+ ((manifest['totalDurationMs'] as num?) ?? 0) / 1000.0;++ static bool _finishedStatus(Map<String, dynamic>? readStatus) {+ final s = readStatus?['status'];+ return s == 'read' || s == 'skimmed';+ }++ /// Audiobookshelf media progress for a book. [state] is the audiobook+ /// playback state (may be null), [readStatus] the book's UserBookStatus.+ static Map<String, dynamic> progress({+ required String bookId,+ Map<String, dynamic>? manifest,+ Map<String, dynamic>? state,+ Map<String, dynamic>? readStatus,+ double? ebookPercent,+ String? ebookLocation,+ int? ebookUpdatedAt,+ }) {+ final duration = manifest != null ? totalSeconds(manifest) : 0.0;+ final current = manifest != null && state != null ? absolutePosition(manifest, state) : 0.0;+ final pct = ((state?['percentage'] as num?) ?? 0).toDouble();+ final finished = _finishedStatus(readStatus) || state?['completed'] == true;+ final stateUpdated = ms(state?['capturedAt']) ?? 0;+ final statusUpdated = ms(readStatus?['updatedAt']) ?? 0;+ final lastUpdate = [stateUpdated, statusUpdated, ebookUpdatedAt ?? 0].reduce((a, b) => a > b ? a : b);+ return {+ 'id': 'bo-$bookId',+ 'libraryItemId': bookId,+ 'episodeId': null,+ 'mediaItemId': bookId,+ 'mediaItemType': 'book',+ 'duration': duration,+ 'progress': finished ? 1.0 : (pct / 100.0).clamp(0.0, 1.0),+ 'currentTime': current,+ 'isFinished': finished,+ 'hideFromContinueListening': false,+ 'ebookLocation': ebookLocation,+ 'ebookProgress': ebookPercent == null ? null : (ebookPercent / 100.0).clamp(0.0, 1.0),+ 'lastUpdate': lastUpdate,+ 'startedAt': ms(readStatus?['startedAt']) ?? stateUpdated,+ 'finishedAt': finished ? ms(readStatus?['finishedAt']) : null,+ 'bookOrbitRevision': state?['revision'],+ };+ }++ /// Progress built from a book card alone, for list-level sync. It carries+ /// the percent and finished flag but no position, so callers must not+ /// treat its currentTime as a place to resume from.+ static Map<String, dynamic> cardProgress(Map<String, dynamic> card) {+ final id = _str(card['id']);+ final readStatus = card['readStatus'] as Map<String, dynamic>?;+ final finished = _finishedStatus(readStatus);+ final pct = ((card['readingProgress'] as num?) ?? 0).toDouble();+ return {+ 'id': 'bo-$id',+ 'libraryItemId': id,+ 'episodeId': null,+ 'mediaItemId': id,+ 'mediaItemType': 'book',+ 'duration': 0,+ 'progress': finished ? 1.0 : (pct / 100.0).clamp(0.0, 1.0),+ 'currentTime': 0,+ 'isFinished': finished,+ 'hideFromContinueListening': false,+ 'lastUpdate': ms(readStatus?['updatedAt']) ?? 0,+ 'startedAt': ms(readStatus?['startedAt']),+ 'finishedAt': finished ? ms(readStatus?['finishedAt']) : null,+ 'positionUnknown': true,+ };+ }++ static Map<String, dynamic> bookmark(Map<String, dynamic> b) => {+ 'libraryItemId': _str(b['bookId']),+ 'title': b['title'] ?? '',+ 'time': ((b['positionMs'] as num?) ?? 0) / 1000.0,+ 'createdAt': ms(b['createdAt']) ?? 0,+ 'bookOrbitId': b['id'],+ 'note': b['note'],+ };++ static Map<String, dynamic> series(Map<String, dynamic> s, {List<Map<String, dynamic>> books = const []}) {+ final coverIds = (s['coverBookIds'] as List<dynamic>? ?? const []).map((e) => '$e').toList();+ return {+ 'id': _str(s['id']),+ 'name': s['name'] ?? '',+ 'nameIgnorePrefix': s['name'] ?? '',+ 'type': 'series',+ 'numBooks': s['bookCount'] ?? books.length,+ 'addedAt': ms(s['lastAddedAt']),+ 'updatedAt': ms(s['lastAddedAt']),+ 'books': books,+ 'coverBookIds': coverIds,+ 'authors': _strings(s['authors']),+ };+ }++ static Map<String, dynamic> author(Map<String, dynamic> a) => {+ 'id': _str(a['id']),+ 'name': a['name'] ?? '',+ 'description': a['description'],+ 'imagePath': a['imageUrl'],+ 'numBooks': a['bookCount'] ?? 0,+ 'addedAt': ms(a['lastAddedAt']),+ // The image URL carries the file's time, so a new image busts caches.+ 'updatedAt': int.tryParse(Uri.tryParse('${a['imageUrl'] ?? ''}')?.queryParameters['t'] ?? '') ??+ ms(a['lastAddedAt']),+ 'bookOrbit': {+ 'imageUrl': a['imageUrl'],+ 'coverBookId': a['coverBookId'],+ 'sortName': a['sortName'],+ },+ };++ /// Metadata providers in the order, colors and wording of BookOrbit's web+ /// book page.+ static const _providerOrder = [+ 'google',+ 'goodreads',+ 'amazon',+ 'hardcover',+ 'openLibrary',+ 'itunes',+ 'audible',+ 'librofm',+ 'kobo',+ 'comicvine',+ 'ranobedb',+ 'lubimyczytac',+ 'aladin',+ ];++ static const providerColors = {+ 'google': 0xFF34A853,+ 'goodreads': 0xFF00D8D1,+ 'amazon': 0xFFFF9900,+ 'hardcover': 0xFF7772FF,+ 'openLibrary': 0xFF49A4FF,+ 'itunes': 0xFFFF4F5D,+ 'audible': 0xFFFF8A00,+ 'librofm': 0xFF62B9B6,+ 'comicvine': 0xFFFFDB0F,+ 'ranobedb': 0xFFA78CFF,+ 'kobo': 0xFFE23434,+ 'lubimyczytac': 0xFFF47373,+ 'aladin': 0xFF3E7FFF,+ };++ static const _providerLabels = {+ 'google': 'Google Books',+ 'goodreads': 'Goodreads',+ 'amazon': 'Amazon',+ 'hardcover': 'Hardcover',+ 'openLibrary': 'Open Library',+ 'itunes': 'Apple Books',+ 'audible': 'Audible',+ 'librofm': 'Libro.fm',+ 'kobo': 'Kobo',+ 'comicvine': 'ComicVine',+ 'ranobedb': 'RanobeDB',+ 'lubimyczytac': 'LubimyCzytac',+ 'aladin': 'Aladin',+ };++ /// Icon file names under the server's `/assets/provider-icons/`.+ static const _providerIcons = {+ 'google': 'google.svg',+ 'goodreads': 'goodreads.svg',+ 'amazon': 'amazon.svg',+ 'hardcover': 'hardcover.svg',+ 'openLibrary': 'openlibrary.svg',+ 'itunes': 'apple-books.svg',+ 'audible': 'audible.svg',+ 'librofm': 'librofm.svg',+ 'kobo': 'kobo.svg',+ 'ranobedb': 'ranobedb.svg',+ 'lubimyczytac': 'lubimyczytac.svg',+ 'aladin': 'aladin.svg',+ };++ static const _providerMarks = {+ 'google': 'G',+ 'goodreads': 'GR',+ 'amazon': 'A',+ 'hardcover': 'H',+ 'openLibrary': 'OL',+ 'itunes': 'AB',+ 'audible': 'Au',+ 'librofm': 'Lf',+ 'kobo': 'K',+ 'comicvine': 'CV',+ 'ranobedb': 'RN',+ 'lubimyczytac': 'LC',+ 'aladin': 'Al',+ };++ /// The book's page on a provider's site, as the web app links it.+ static String? providerUrl(String key, String id) {+ final e = Uri.encodeComponent(id);+ return switch (key) {+ 'google' => 'https://books.google.com/books?id=$e',+ 'goodreads' => 'https://www.goodreads.com/book/show/$e',+ 'amazon' => 'https://www.amazon.com/dp/$e',+ 'hardcover' => 'https://hardcover.app/books/$e',+ 'openLibrary' =>+ 'https://openlibrary.org/works/${Uri.encodeComponent(id.startsWith('/works/') ? id.substring(7) : id)}',+ 'itunes' => 'https://books.apple.com/book/id$e',+ 'audible' => 'https://www.audible.com/pd/$e',+ 'librofm' => 'https://libro.fm/audiobooks/$e',+ 'kobo' => 'https://www.kobo.com/us/en/ebook/$e',+ 'comicvine' => 'https://comicvine.gamespot.com/issue/4000-$e/',+ 'ranobedb' => 'https://ranobedb.org/book/$e',+ 'lubimyczytac' =>+ 'https://lubimyczytac.pl/ksiazka/${(id.contains('/') ? id : '$id/-').split('/').map(Uri.encodeComponent).join('/')}',+ 'aladin' => 'https://www.aladin.co.kr/shop/wproduct.aspx?ItemId=$e',+ _ => null,+ };+ }++ /// A badge for [key] with no link or rating yet.+ static Map<String, dynamic> providerBadge(String key) => {+ 'key': key,+ 'label': _providerLabels[key] ?? key,+ 'url': null,+ 'icon': _providerIcons[key],+ 'mark': _providerMarks[key] ?? (key.length > 2 ? key.substring(0, 2) : key).toUpperCase(),+ 'color': providerColors[key] ?? 0xFF7A7A7A,+ };++ /// One badge per provider the book links to or has a rating from, in the+ /// web app's order: {key, label, url, icon, mark, color, rating?, count?}.+ static List<Map<String, dynamic>> providerBadges(Map? providerIds, List? ratings) {+ final ids = <String, String>{+ for (final e in (providerIds ?? const {}).entries)+ if (e.value is String && (e.value as String).trim().isNotEmpty) '${e.key}': (e.value as String).trim(),+ };+ final rated = <String, Map>{};+ for (final r in (ratings ?? const []).whereType<Map>()) {+ final value = r['rating'];+ if (value is! num || !value.isFinite || value <= 0) continue;+ final key = r['provider'] == 'audnexus' ? 'audible' : '${r['provider']}';+ rated.putIfAbsent(key, () => r);+ }+ final keys = [+ ..._providerOrder.where((k) => ids.containsKey(k) || rated.containsKey(k)),+ ...rated.keys.where((k) => !_providerOrder.contains(k)),+ ];+ return [+ for (final k in keys)+ {+ ...providerBadge(k),+ 'url': ids[k] == null ? null : providerUrl(k, ids[k]!),+ if (rated[k] != null) ...{+ 'rating': (rated[k]!['rating'] as num).toDouble(),+ 'count': (rated[k]!['ratingCount'] as num?)?.toInt(),+ },+ },+ ];+ }++ /// A BookOrbit "more like this" pick, trimmed to what a cover row shows.+ static Map<String, dynamic> similarBook(Map<String, dynamic> r) {+ final status = (r['readStatus'] as Map?)?['status'];+ return {+ 'id': _str(r['id']),+ 'title': r['title'] ?? '',+ 'authorName': _strings(r['authors']).join(', '),+ 'hasCover': r['hasCover'] == true,+ 'isAudiobook': r['isAudiobook'] == true,+ 'finished': status == 'read' || status == 'skimmed',+ };+ }++ static String? _text(Object? v) {+ final s = v?.toString().trim() ?? '';+ return s.isEmpty ? null : s;+ }++ static List<String> _names(Object? list) => (list as List<dynamic>? ?? const [])+ .map((e) => e is Map ? _text(e['name'] ?? e['series']) : _text(e))+ .whereType<String>()+ .toList();++ static bool _sameList(List<Object?> a, List<Object?> b) {+ if (a.length != b.length) return false;+ for (var i = 0; i < a.length; i++) {+ if (a[i] != b[i]) return false;+ }+ return true;+ }++ static final _seriesIndexPattern = RegExp(r'^\d+(?:\.\d+)?$');++ /// BookOrbit only takes plain numbers ("2", "2.5") as a series index.+ static String? seriesIndex(Object? raw) {+ final s = _text(raw);+ if (s == null) return null;+ if (_seriesIndexPattern.hasMatch(s)) return s;+ final m = RegExp(r'\d+(?:\.\d+)?').firstMatch(s);+ return m?.group(0);+ }++ /// The BookOrbit metadata PATCH for an Audiobookshelf media update, holding+ /// only the fields that differ from [current] (the item as the app shows+ /// it). Untouched fields stay out so a locked field the user did not change+ /// can't make BookOrbit refuse the whole save.+ static Map<String, dynamic> metadataPatch({+ required Map<String, dynamic> metadata,+ List<String>? tags,+ required Map<String, dynamic> current,+ required bool hasAudio,+ }) {+ final cur = (current['metadata'] as Map?)?.cast<String, dynamic>() ?? const <String, dynamic>{};+ final out = <String, dynamic>{};+ final audio = <String, dynamic>{};++ void text(String key, String boKey, int? max) {+ if (!metadata.containsKey(key)) return;+ final next = _text(metadata[key]);+ if (next == _text(cur[key])) return;+ out[boKey] = next != null && max != null && next.length > max ? next.substring(0, max) : next;+ }++ text('title', 'title', 1000);+ text('subtitle', 'subtitle', 1000);+ text('description', 'description', null);+ text('publisher', 'publisher', 500);+ text('language', 'language', 100);++ if (metadata.containsKey('publishedYear')) {+ final next = _text(metadata['publishedYear']);+ if (next != _text(cur['publishedYear'])) {+ if (next == null) {+ out['publishedYear'] = null;+ } else if (RegExp(r'^\d{4}-\d{2}-\d{2}$').hasMatch(next)) {+ out['publishedDate'] = next;+ } else {+ final year = int.tryParse(RegExp(r'\d{4}').firstMatch(next)?.group(0) ?? '');+ if (year != null && year >= 1000 && year <= 2200) out['publishedYear'] = year;+ }+ }+ }++ if (metadata.containsKey('asin')) {+ final next = _text(metadata['asin']);+ if (next != _text(cur['asin']) && (next == null || next.length <= 20)) out['audibleId'] = next;+ }++ if (metadata.containsKey('isbn')) {+ final next = _text(metadata['isbn']);+ if (next != _text(cur['isbn'])) {+ final plain = next?.replaceAll(RegExp(r'[\s-]'), '');+ if (plain == null) {+ out['isbn13'] = null;+ out['isbn10'] = null;+ } else if (plain.length == 10) {+ // The app shows the 13-digit one first, so drop it or the edit+ // would look like it never saved.+ out['isbn10'] = plain;+ out['isbn13'] = null;+ } else if (plain.length <= 13) {+ out['isbn13'] = plain;+ }+ }+ }++ if (metadata.containsKey('authors')) {+ final next = _names(metadata['authors']);+ if (!_sameList(next, _names(cur['authors']))) out['authors'] = next;+ }++ if (metadata.containsKey('genres')) {+ final next = _names(metadata['genres']);+ if (!_sameList(next, _names(cur['genres']))) out['genres'] = next;+ }++ if (tags != null) {+ final next = tags.map(_text).whereType<String>().toList();+ if (!_sameList(next, _names(current['tags']))) out['tags'] = next;+ }++ if (metadata.containsKey('series')) {+ final next = <({String name, String? index})>[];+ for (final s in (metadata['series'] as List<dynamic>? ?? const []).whereType<Map>()) {+ final name = _text(s['name'] ?? s['series']);+ if (name == null) continue;+ next.add((name: name.length > 500 ? name.substring(0, 500) : name, index: seriesIndex(s['sequence'])));+ }+ final now = [+ for (final s in (cur['series'] as List<dynamic>? ?? const []).whereType<Map>())+ (name: _text(s['name']) ?? '', index: seriesIndex(s['sequence'])),+ ];+ if (!_sameList(next, now)) {+ out['seriesMemberships'] = next.isEmpty+ ? null+ : [for (final s in next) {'seriesName': s.name, 'seriesIndex': s.index}];+ }+ }++ if (hasAudio) {+ if (metadata.containsKey('narrators')) {+ final next = _names(metadata['narrators']);+ if (!_sameList(next, _names(cur['narrators']))) audio['narrators'] = next;+ }+ if (metadata.containsKey('abridged')) {+ final next = metadata['abridged'] == true;+ if (next != (cur['abridged'] == true)) audio['abridged'] = next;+ }+ }+ if (audio.isNotEmpty) out['audioMetadata'] = audio;+ return out;+ }++ /// Audiobookshelf chapters ({start, end, title} in seconds) as BookOrbit's+ /// audio chapters. Null clears them.+ static List<Map<String, dynamic>>? chapters(List<dynamic> abs) {+ final rows = abs.whereType<Map>().toList()+ ..sort((a, b) => ((a['start'] as num?) ?? 0).compareTo((b['start'] as num?) ?? 0));+ if (rows.isEmpty) return null;+ return [+ for (var i = 0; i < rows.length; i++)+ {+ 'title': _text(rows[i]['title']) ?? 'Chapter ${i + 1}',+ 'startMs': (((rows[i]['start'] as num?) ?? 0) * 1000).round(),+ if (rows[i]['end'] is num && (rows[i]['end'] as num) > ((rows[i]['start'] as num?) ?? 0))+ 'durationMs': ((((rows[i]['end'] as num) - ((rows[i]['start'] as num?) ?? 0))) * 1000).round(),+ },+ ];+ }++ /// A BookOrbit metadata candidate in the shape Audiobookshelf's book+ /// search returns.+ static Map<String, dynamic> searchResult(Map<String, dynamic> c) {+ final memberships = _maps(c['seriesMemberships']);+ final year = c['publishedYear'] ??+ RegExp(r'^\d{4}').firstMatch('${c['publishedDate'] ?? ''}')?.group(0);+ final authors = _strings(c['authors']);+ final narrators = _strings(c['narrators']);+ return {+ 'title': c['displayTitle'] ?? c['title'],+ 'subtitle': c['subtitle'],+ 'author': authors.isEmpty ? null : authors.join(', '),+ 'narrator': narrators.isEmpty ? null : narrators.join(', '),+ 'description': c['description'],+ 'publisher': c['publisher'],+ 'publishedYear': year?.toString(),+ 'asin': c['audibleId'] ?? (c['provider'] == 'audible' ? c['providerId'] : null),+ 'isbn': c['isbn13'] ?? c['isbn10'],+ 'language': c['language'],+ 'genres': _strings(c['genres']),+ 'series': memberships.isNotEmpty+ ? [for (final m in memberships) {'name': m['seriesName'], 'sequence': m['seriesIndex']}]+ : c['seriesName'],+ 'sequence': c['seriesIndex'],+ 'cover': c['coverUrl'],+ 'duration': c['durationSeconds'],+ 'provider': c['provider'],+ };+ }+}diff --git a/lib/services/bookorbit_media_proxy.dart b/lib/services/bookorbit_media_proxy.dartnew file mode 100644index 00000000..b4666c2b--- /dev/null+++ b/lib/services/bookorbit_media_proxy.dart@@ -0,0 +1,273 @@+import 'dart:async';+import 'dart:io';+import 'dart:math';++import 'package:flutter/foundation.dart';+import 'package:shared_preferences/shared_preferences.dart';++/// Where the proxy gets the server address and a working access token.+abstract class BookOrbitTokenSource {+ String get upstreamBaseUrl;+ Map<String, String> get upstreamCustomHeaders;++ /// A token that is valid right now, refreshing first when it is about to+ /// expire. Null when there is no session.+ Future<String?> currentAccessToken();++ /// The server turned the last token away. Refresh and hand back the new one,+ /// or null when the session is gone.+ Future<String?> tokenAfterRejection();+}++/// Loopback HTTP proxy for BookOrbit media.+///+/// BookOrbit only takes a Bearer header (no token in the query string) and+/// its access tokens last fifteen minutes. Covers, audio and ebook files are+/// fetched by players, image caches and native code that can't refresh a+/// header, so they get a 127.0.0.1 URL instead and this adds a fresh token to+/// every request on the way through.+///+/// The port and the path secret are kept across launches so cover URLs stay+/// the same and image caches keep hitting. The secret keeps other apps on the+/// device from borrowing the session through the port.+class BookOrbitMediaProxy {+ BookOrbitMediaProxy._();+ static final BookOrbitMediaProxy instance = BookOrbitMediaProxy._();++ static const _portKey = 'bookorbit_proxy_port';+ static const _secretKey = 'bookorbit_proxy_secret';++ HttpServer? _server;+ Future<void>? _starting;+ int _port = 0;+ String _secret = '';+ BookOrbitTokenSource? _source;+ HttpClient? _client;++ bool get isReady => _port > 0 && _secret.isNotEmpty;++ /// The newest BookOrbit client wins: it carries the current server address+ /// (local or remote) and the newest tokens.+ void attach(BookOrbitTokenSource source) => _source = source;++ String get _prefix => 'http://127.0.0.1:$_port/$_secret';++ /// Proxy URL for a server path like `/api/v1/books/5/thumbnail?t=x`.+ String urlFor(String serverPathAndQuery) {+ final path = serverPathAndQuery.startsWith('/')+ ? serverPathAndQuery+ : '/$serverPathAndQuery';+ return '$_prefix$path';+ }++ bool owns(String url) => isReady && url.startsWith(_prefix);++ /// The server URL a proxy URL stands for, for callers that can send their+ /// own headers (downloads that outlive the app).+ String? upstreamUrlFor(String proxyUrl) {+ final source = _source;+ if (source == null || !owns(proxyUrl)) return null;+ return '${source.upstreamBaseUrl}${proxyUrl.substring(_prefix.length)}';+ }++ /// Load the saved port and secret and start listening. Safe to call again;+ /// it rebinds when the platform took the socket away while suspended.+ Future<void> ensureRunning() {+ return _starting ??= _ensure().whenComplete(() => _starting = null);+ }++ Future<void> _ensure() async {+ final server = _server;+ if (server != null) {+ if (await _portAnswers(_port, _secret)) return;+ debugPrint('[BookOrbitProxy] Not answering on $_port, rebinding');+ _server = null;+ try {+ await server.close(force: true);+ } catch (_) {}+ }+ await _start();+ }++ Future<void> _start() async {+ final prefs = await SharedPreferences.getInstance();+ var secret = prefs.getString(_secretKey);+ if (secret == null || secret.length < 16) {+ final rng = Random.secure();+ secret = List.generate(24, (_) => rng.nextInt(256))+ .map((b) => b.toRadixString(16).padLeft(2, '0'))+ .join();+ await prefs.setString(_secretKey, secret);+ }+ _secret = secret;++ final savedPort = prefs.getInt(_portKey) ?? 0;+ HttpServer? server;+ if (savedPort > 0) {+ try {+ server = await HttpServer.bind(InternetAddress.loopbackIPv4, savedPort);+ } on SocketException catch (e) {+ // Another isolate of this app may already be serving it, in which+ // case the saved URLs still work and there is nothing to do.+ if (await _portAnswers(savedPort, secret)) {+ _port = savedPort;+ debugPrint('[BookOrbitProxy] Port $savedPort already served');+ return;+ }+ debugPrint('[BookOrbitProxy] Port $savedPort busy ($e), picking another');+ }+ }+ server ??= await HttpServer.bind(InternetAddress.loopbackIPv4, 0);+ if (server.port != savedPort) await prefs.setInt(_portKey, server.port);+ _port = server.port;+ _server = server;+ server.listen(+ _handle,+ onError: (Object e) => debugPrint('[BookOrbitProxy] Server error: $e'),+ onDone: () {+ if (identical(_server, server)) _server = null;+ debugPrint('[BookOrbitProxy] Server closed');+ },+ );+ debugPrint('[BookOrbitProxy] Listening on 127.0.0.1:$_port');+ }++ Future<bool> _portAnswers(int port, String secret) async {+ final client = HttpClient()..connectionTimeout = const Duration(seconds: 1);+ try {+ final req = await client.get('127.0.0.1', port, '/$secret/__ping');+ final res = await req.close().timeout(const Duration(seconds: 1));+ await res.drain<void>();+ return res.statusCode == 204;+ } catch (_) {+ return false;+ } finally {+ client.close(force: true);+ }+ }++ Future<void> stop() async {+ final server = _server;+ _server = null;+ await server?.close(force: true);+ }++ HttpClient get _http {+ return _client ??= HttpClient()+ ..autoUncompress = false+ ..connectionTimeout = const Duration(seconds: 15)+ ..idleTimeout = const Duration(seconds: 30);+ }++ static const _forwardRequestHeaders = [+ HttpHeaders.rangeHeader,+ HttpHeaders.ifRangeHeader,+ HttpHeaders.ifNoneMatchHeader,+ HttpHeaders.ifModifiedSinceHeader,+ HttpHeaders.acceptHeader,+ ];++ static const _forwardResponseHeaders = [+ HttpHeaders.contentTypeHeader,+ HttpHeaders.contentLengthHeader,+ HttpHeaders.contentRangeHeader,+ HttpHeaders.acceptRangesHeader,+ HttpHeaders.etagHeader,+ HttpHeaders.lastModifiedHeader,+ HttpHeaders.cacheControlHeader,+ 'content-disposition',+ ];++ Future<void> _handle(HttpRequest req) async {+ final res = req.response;+ final path = req.uri.path;+ if (!path.startsWith('/$_secret/')) {+ res.statusCode = HttpStatus.notFound;+ await res.close();+ return;+ }+ final serverPath = path.substring(_secret.length + 1);+ if (serverPath == '/__ping') {+ res.statusCode = HttpStatus.noContent;+ await res.close();+ return;+ }+ if (req.method != 'GET' && req.method != 'HEAD') {+ res.statusCode = HttpStatus.methodNotAllowed;+ await res.close();+ return;+ }+ final source = _source;+ if (source == null) {+ res.statusCode = HttpStatus.serviceUnavailable;+ await res.close();+ return;+ }++ final query = req.uri.hasQuery ? '?${req.uri.query}' : '';+ final upstream = Uri.parse('${source.upstreamBaseUrl}$serverPath$query');++ HttpClientRequest? upstreamReq;+ try {+ var token = await source.currentAccessToken();+ upstreamReq = await _open(req, upstream, source, token);+ var upstreamRes = await upstreamReq.close();+ if (upstreamRes.statusCode == HttpStatus.unauthorized) {+ await upstreamRes.drain<void>().catchError((_) {});+ token = await source.tokenAfterRejection();+ if (token != null) {+ upstreamReq = await _open(req, upstream, source, token);+ upstreamRes = await upstreamReq.close();+ }+ }++ res.statusCode = upstreamRes.statusCode;+ for (final name in _forwardResponseHeaders) {+ final value = upstreamRes.headers.value(name);+ if (value != null) res.headers.set(name, value);+ }+ if (upstreamRes.statusCode >= 400) {+ debugPrint('[BookOrbitProxy] ${upstreamRes.statusCode} for $serverPath');+ }+ if (req.method == 'HEAD') {+ await upstreamRes.drain<void>().catchError((_) {});+ await res.close();+ return;+ }+ try {+ await res.addStream(upstreamRes);+ await res.close();+ } catch (_) {+ // The player hung up (seek, skip, stop). Drop the upstream body too.+ upstreamReq.abort();+ }+ } catch (e) {+ debugPrint('[BookOrbitProxy] Upstream failed for $serverPath: $e');+ upstreamReq?.abort();+ try {+ res.statusCode = HttpStatus.badGateway;+ await res.close();+ } catch (_) {}+ }+ }++ Future<HttpClientRequest> _open(+ HttpRequest incoming,+ Uri upstream,+ BookOrbitTokenSource source,+ String? token,+ ) async {+ final out = await _http.openUrl(incoming.method, upstream);+ out.followRedirects = true;+ source.upstreamCustomHeaders.forEach(out.headers.set);+ if (token != null && token.isNotEmpty) {+ out.headers.set(HttpHeaders.authorizationHeader, 'Bearer $token');+ }+ out.headers.set(HttpHeaders.acceptEncodingHeader, 'identity');+ for (final name in _forwardRequestHeaders) {+ final value = incoming.headers.value(name);+ if (value != null) out.headers.set(name, value);+ }+ return out;+ }+}diff --git a/lib/services/bookorbit_media_proxy_stub.dart b/lib/services/bookorbit_media_proxy_stub.dartnew file mode 100644index 00000000..5438b15f--- /dev/null+++ b/lib/services/bookorbit_media_proxy_stub.dart@@ -0,0 +1,31 @@+/// Web stand-in for the BookOrbit media proxy, which needs dart:io. URLs+/// pass straight to the server, so media on web only loads where the+/// browser already holds a BookOrbit session.+abstract class BookOrbitTokenSource {+ String get upstreamBaseUrl;+ Map<String, String> get upstreamCustomHeaders;+ Future<String?> currentAccessToken();+ Future<String?> tokenAfterRejection();+}++class BookOrbitMediaProxy {+ BookOrbitMediaProxy._();+ static final BookOrbitMediaProxy instance = BookOrbitMediaProxy._();++ BookOrbitTokenSource? _source;++ bool get isReady => _source != null;++ void attach(BookOrbitTokenSource source) => _source = source;++ String urlFor(String serverPathAndQuery) =>+ '${_source?.upstreamBaseUrl ?? ''}$serverPathAndQuery';++ bool owns(String url) => false;++ String? upstreamUrlFor(String proxyUrl) => proxyUrl;++ Future<void> ensureRunning() async {}++ Future<void> stop() async {}+}diff --git a/lib/services/carplay_service.dart b/lib/services/carplay_service.dartindex 1d863874..dfd72896 100644--- a/lib/services/carplay_service.dart+++ b/lib/services/carplay_service.dart@@ -7,6 +7,7 @@ import 'android_auto_service.dart';import 'api_service.dart';import 'audio_player_service.dart';import 'carplay_image_url.dart';+import 'server_backend.dart';/// Manages Apple CarPlay browse tree and playback integration./// Mirrors the Android Auto layout: 3 tabs (Continue, Library, Downloads)@@ -428,6 +429,7 @@ class CarPlayService {complete();},),+ if (!ServerBackend.active.isBookOrbit)CPListItem(text: 'Playlists',accessoryType: CPListItemAccessoryTypes.disclosureIndicator,diff --git a/lib/services/download_service.dart b/lib/services/download_service.dartindex beb4d653..5dea5173 100644--- a/lib/services/download_service.dart+++ b/lib/services/download_service.dart@@ -1753,6 +1753,7 @@ class DownloadService extends ChangeNotifier {}}+ await api.prepareDownload(apiItemId);final files = _resolveDurableFiles(api, apiItemId, audioTracks);// Pull the companion ebook into the offline cache too, so a downloaded@@ -1875,7 +1876,7 @@ class DownloadService extends ChangeNotifier {task = DownloadTask(taskId: _taskId(itemId, i),url: files[i].url,- headers: api.mediaHeaders,+ headers: api.downloadHeadersFor(files[i].url),filename: files[i].filename,baseDirectory: BaseDirectory.root,directory: bookDir.path,@@ -1890,7 +1891,7 @@ class DownloadService extends ChangeNotifier {task = DownloadTask(taskId: _taskId(itemId, i),url: files[i].url,- headers: api.mediaHeaders,+ headers: api.downloadHeadersFor(files[i].url),filename: files[i].filename,baseDirectory: BaseDirectory.applicationDocuments,directory: relDir!,@@ -2028,7 +2029,7 @@ class DownloadService extends ChangeNotifier {ino.contains('#')) {throw Exception('Missing direct file URL for track ${i + 1}');}- out.add((url: api.buildFileUrl(apiItemId, ino), filename: _trackFileName(track, i)));+ out.add((url: api.buildDownloadFileUrl(apiItemId, ino), filename: _trackFileName(track, i)));}return out;}diff --git a/lib/services/ebook_cache.dart b/lib/services/ebook_cache.dartindex e4bf4078..e0747ad8 100644--- a/lib/services/ebook_cache.dart+++ b/lib/services/ebook_cache.dart@@ -19,11 +19,14 @@ String ebookExtFromFile(Map<String, dynamic> ebookFile) {}/// Formats the in-app readers can open. EPUB uses the full reader, PDF the-/// dedicated viewer, and foliate-js covers MOBI/AZW3/CBZ. CBR is RAR-based-/// and foliate-js can't read it, so it's recognized but stays download-only.-const foliateEbookFormats = {'mobi', 'azw3', 'cbz'};-const readableEbookFormats = {'epub', 'pdf', ...foliateEbookFormats};-const allEbookFormats = {...readableEbookFormats, 'cbr'};+/// dedicated viewer, foliate-js covers MOBI/AZW3, and comics get the comic+/// reader. A CBZ opens on the phone; CBR (RAR) and CB7 (7-Zip) need a server+/// that hands out the pages (BookOrbit), so on their own they stay+/// download-only.+const foliateEbookFormats = {'mobi', 'azw3'};+const comicEbookFormats = {'cbz', 'cbr', 'cb7'};+const readableEbookFormats = {'epub', 'pdf', 'cbz', ...foliateEbookFormats};+const allEbookFormats = {...readableEbookFormats, 'cbr', 'cb7'};/// The ebook to use for a library item: the server's primary (media.ebookFile)/// when set, otherwise the best supplementary ebook from libraryFiles - epub@@ -221,7 +224,9 @@ Future<File> fetchEbookToCache(// manual redirect hops below) plus `?token=` in the URL, because some// reverse proxies strip the header - the same reason audio file downloads// use the token form (see ApiService.buildFileUrl).- final url = '$cleanBase/api/items/$itemId/file/$ino?token=${api.token}';+ final url = api.isBookOrbit+ ? api.buildEbookUrl(itemId, ino)+ : '$cleanBase/api/items/$itemId/file/$ino?token=${api.token}';debugPrint('[EbookCache] downloading item=$itemId path=/api/items/$itemId/file/$ino');final startedAt = DateTime.now();diff --git a/lib/services/episode_notification_service.dart b/lib/services/episode_notification_service.dartindex ed29e485..ce87d9c1 100644--- a/lib/services/episode_notification_service.dart+++ b/lib/services/episode_notification_service.dart@@ -12,6 +12,7 @@ import '../providers/library_provider.dart';import '../screens/upcoming_releases_screen.dart';import '../widgets/episode_list_sheet.dart';import 'api_service.dart';+import 'server_backend.dart';import 'download_service.dart';import 'player_settings.dart';import 'scoped_prefs.dart';@@ -388,12 +389,14 @@ Future<ApiService?> _buildApiService() async {final localEnabled = await PlayerSettings.getLocalServerEnabled();final localUrl = await PlayerSettings.getLocalServerUrl();if (localEnabled && localUrl.isNotEmpty) {- final localReachable = await ApiService.pingServer(localUrl, customHeaders: headers)+ final localReachable = await ApiService.pingServer(localUrl,+ customHeaders: headers, backend: ServerBackend.loadActive(prefs)).timeout(const Duration(seconds: 3), onTimeout: () => false);if (localReachable) baseUrl = localUrl;}- return ApiService(+ return ApiService.forSession(+ backend: ServerBackend.loadActive(prefs),baseUrl: baseUrl,token: token,refreshToken: refreshToken,@@ -408,5 +411,5 @@ Future<ApiService?> _buildApiService() async {serverUrl: remoteUrl,username: username,),- );+ ).withMediaReady();}diff --git a/lib/services/home_widget_service.dart b/lib/services/home_widget_service.dartindex f6699a60..251e5728 100644--- a/lib/services/home_widget_service.dart+++ b/lib/services/home_widget_service.dart@@ -11,6 +11,8 @@ import 'package:shared_preferences/shared_preferences.dart';import 'audio_player_service.dart';import 'api_service.dart';+import 'bookorbit_media_proxy.dart';+import 'server_backend.dart';import 'download_service.dart';import 'progress_sync_service.dart';import 'scoped_prefs.dart';@@ -366,7 +368,8 @@ class HomeWidgetService {} catch (_) {}}- final api = ApiService(+ final api = ApiService.forSession(+ backend: ServerBackend.loadActive(prefs),baseUrl: serverUrl,token: token,refreshToken: refreshToken,@@ -382,6 +385,7 @@ class HomeWidgetService {username: username,),);+ await api.ensureMediaReady();try {final fullItem = await api.getLibraryItem(itemId);@@ -576,7 +580,8 @@ class HomeWidgetService {);} catch (_) {}}- return ApiService(+ return ApiService.forSession(+ backend: ServerBackend.loadActive(prefs),baseUrl: serverUrl,token: token,refreshToken: refreshToken,@@ -903,8 +908,11 @@ class HomeWidgetService {// via the widget without their server progress falling behind.final api = player.currentApi;if (api != null) {+ // The native core only knows the Audiobookshelf progress endpoint. With+ // no token it skips the push, and the app syncs on its next start.await HomeWidget.saveWidgetData<String>('np_server_url', api.baseUrl);- await HomeWidget.saveWidgetData<String>('np_api_token', api.token);+ await HomeWidget.saveWidgetData<String>(+ 'np_api_token', api.isBookOrbit ? '' : api.token);}// EQ-enabled flag in the app group so a cold widget-launch (engine never@@ -1127,11 +1135,13 @@ class HomeWidgetService {final localReachable = await ApiService.pingServer(localUrl,customHeaders: headers,+ backend: ServerBackend.loadActive(prefs),).timeout(const Duration(seconds: 3), onTimeout: () => false);if (localReachable) baseUrl = localUrl;}- return ApiService(+ return ApiService.forSession(+ backend: ServerBackend.loadActive(prefs),baseUrl: baseUrl,token: token,refreshToken: refreshToken,@@ -1146,7 +1156,7 @@ class HomeWidgetService {serverUrl: remoteUrl,username: username,),- );+ ).withMediaReady();}Map<String, dynamic> _extractDailyMap(Map<String, dynamic>? stats) {@@ -1268,10 +1278,14 @@ class HomeWidgetService {// Ask for a bigger one just for the widget file. The Kotlin side caps// what it actually hands to RemoteViews, so this only improves the// source it has to work from.- final widgetCoverUrl = coverUrl.replaceAllMapped(+ var widgetCoverUrl = coverUrl.replaceAllMapped(RegExp(r'([?&])width=\d+'),(m) => '${m[1]}width=$_widgetCoverWidth',);+ if (BookOrbitMediaProxy.instance.owns(widgetCoverUrl)) {+ await BookOrbitMediaProxy.instance.ensureRunning();+ widgetCoverUrl = widgetCoverUrl.replaceFirst('/thumbnail?', '/cover?');+ }final response = await http.get(Uri.parse(widgetCoverUrl)).timeout(const Duration(seconds: 10));diff --git a/lib/services/oidc_service.dart b/lib/services/oidc_service.dartindex 42132380..e56f36a0 100644--- a/lib/services/oidc_service.dart+++ b/lib/services/oidc_service.dart@@ -6,6 +6,7 @@ import 'package:flutter/services.dart' show PlatformException;import 'package:http/http.dart' as http;import 'package:flutter_web_auth_2/flutter_web_auth_2.dart';import 'dart:io' show HttpClient, HttpHeaders;+import 'api_service.dart';/// Manages the OIDC/OAuth2 PKCE flow for audiobookshelf SSO login.class OidcService {@@ -18,6 +19,7 @@ class OidcService {String? _codeChallenge;String? _state;String? _serverUrl;+ String? _nonce;/// The raw cookie strings from the /auth/openid response.List<String> _rawCookies = [];@@ -145,16 +147,131 @@ class OidcService {}debugPrint('[OIDC] Opening Custom Tab for: $providerUrl');+ return _openBrowser(providerUrl, 'audiobookshelf');+ }++ /// BookOrbit only takes this return address from an app (unless its admin+ /// renamed it), the same one BookOrbit's own apps use.+ static const bookOrbitRedirectUri = 'bookorbit://oauth2-callback';++ /// The identity provider's sign-in page for a BookOrbit login, with PKCE.+ /// BookOrbit leaves this step to the app and only checks the result.+ static Uri bookOrbitAuthorizeUrl({+ required String authorizationEndpoint,+ required BookOrbitOidcProvider provider,+ required String state,+ required String nonce,+ required String codeChallenge,+ }) {+ final endpoint = Uri.parse(authorizationEndpoint);+ return endpoint.replace(queryParameters: {+ ...endpoint.queryParameters,+ 'response_type': 'code',+ 'client_id': provider.clientId,+ 'scope': provider.scopes,+ 'redirect_uri': bookOrbitRedirectUri,+ 'state': state,+ 'nonce': nonce,+ 'code_challenge': codeChallenge,+ 'code_challenge_method': 'S256',+ });+ }++ /// Start a BookOrbit single sign-on through [provider]. Returns the+ /// callback like [startLogin].+ Future<Uri?> startBookOrbitLogin(+ String serverUrl,+ BookOrbitOidcProvider provider, {+ Map<String, String> customHeaders = const {},+ }) async {+ _serverUrl = serverUrl.endsWith('/') ? serverUrl.substring(0, serverUrl.length - 1) : serverUrl;+ _generatePkce();+ _nonce = _generateRandom(16);+ _rawCookies = [];+ _customHeaders = customHeaders;+ _lastError = null;+ _lastWasUserCancel = false;+ final String url;+ try {+ final start = await BookOrbitApiService.oidcState(_serverUrl!, provider.slug, customHeaders: customHeaders);+ _state = start.state;+ url = bookOrbitAuthorizeUrl(+ authorizationEndpoint: start.authorizationEndpoint,+ provider: provider,+ state: start.state,+ nonce: _nonce!,+ codeChallenge: _codeChallenge!,+ ).toString();+ } catch (e) {+ debugPrint('[OIDC] BookOrbit start failed: $e');+ _lastError = 'Could not start sign-in with ${provider.displayName}: $e';+ _cleanup();+ return null;+ }+ debugPrint('[OIDC] Opening BookOrbit sign-in with ${provider.slug}');+ return _openBrowser(url, 'bookorbit');+ }++ /// Finish a BookOrbit sign-on from its callback. Returns an+ /// Audiobookshelf-shaped login response, or null with [lastError] set.+ Future<Map<String, dynamic>?> handleBookOrbitCallback(Uri uri) async {+ _lastError = null;+ _lastWasUserCancel = false;+ final providerError = uri.queryParameters['error'];+ final code = uri.queryParameters['code'];+ final state = uri.queryParameters['state'];+ if (providerError != null) {+ final detail = uri.queryParameters['error_description'];+ _lastError = 'The sign-in provider answered "$providerError"${detail != null ? ': $detail' : ''}. '+ 'Check that $bookOrbitRedirectUri is an allowed redirect URI for this client.';+ _cleanup();+ return null;+ }+ if (code == null || code.isEmpty) {+ _lastError = 'OIDC provider returned no authorization code. '+ 'Check the provider logs for an "invalid redirect_uri" or '+ '"invalid client" error.';+ _cleanup();+ return null;+ }+ if (state != _state) {+ _lastError = 'OIDC state mismatch - possible session expiry or '+ 'cross-tab interference. Try again.';+ _cleanup();+ return null;+ }+ if (_serverUrl == null || _codeVerifier == null || _nonce == null) {+ _lastError = 'OIDC flow state was lost between popup and callback.';+ _cleanup();+ return null;+ }+ final (result, status, message) = await BookOrbitApiService.signInWithOidc(+ serverUrl: _serverUrl!,+ code: code,+ codeVerifier: _codeVerifier!,+ redirectUri: bookOrbitRedirectUri,+ nonce: _nonce!,+ state: state!,+ customHeaders: _customHeaders,+ );+ _cleanup();+ if (result == null) {+ _lastError = status == 0+ ? 'BookOrbit sign-in request failed: $message'+ : 'BookOrbit returned HTTP $status${message != null && message.isNotEmpty ? ': $message' : ''}';+ }+ return result;+ }- // Open the OIDC provider in an in-app browser tab. On Android this is a- // Chrome Custom Tab; on iOS, ASWebAuthenticationSession. Both intercept- // the audiobookshelf:// callback and return it to us. Unlike an external- // browser, neither can be hijacked by PWAs or other apps registered for- // the provider's domain.+ /// Open [url] in an in-app browser tab. On Android this is a Chrome Custom+ /// Tab; on iOS, ASWebAuthenticationSession. Both intercept the [scheme]+ /// callback and return it to us. Unlike an external browser, neither can be+ /// hijacked by PWAs or other apps registered for the provider's domain.+ Future<Uri?> _openBrowser(String url, String scheme) async {try {final resultUrl = await FlutterWebAuth2.authenticate(- url: providerUrl,- callbackUrlScheme: 'audiobookshelf',+ url: url,+ callbackUrlScheme: scheme,);debugPrint('[OIDC] Custom Tab returned: $resultUrl');return Uri.parse(resultUrl);@@ -278,6 +395,7 @@ class OidcService {_codeVerifier = null;_codeChallenge = null;_state = null;+ _nonce = null;_rawCookies = [];_customHeaders = const {};}@@ -316,6 +434,42 @@ class OidcService {hasLocalAuth: authMethods.contains('local'),);}++ /// The single sign-on providers a BookOrbit server offers.+ static Future<OidcConfig?> checkBookOrbitOidc(String serverUrl, {Map<String, String> customHeaders = const {}}) async {+ final options = await BookOrbitApiService.loginOptions(serverUrl, customHeaders: customHeaders);+ if (options == null) return null;+ final providers = [+ for (final p in options.oidcProviders)+ BookOrbitOidcProvider(+ slug: p['slug'] as String,+ displayName: '${p['displayName'] ?? p['slug']}',+ clientId: p['clientId'] as String,+ scopes: (p['scopes'] as String?)?.trim().isNotEmpty == true ? p['scopes'] as String : 'openid profile email',+ ),+ ];+ return OidcConfig(+ enabled: providers.isNotEmpty,+ buttonText: '',+ hasLocalAuth: options.passwordLogin,+ bookOrbitProviders: providers,+ );+ }+}++/// A BookOrbit single sign-on provider, from its public login options.+class BookOrbitOidcProvider {+ final String slug;+ final String displayName;+ final String clientId;+ final String scopes;++ const BookOrbitOidcProvider({+ required this.slug,+ required this.displayName,+ required this.clientId,+ required this.scopes,+ });}/// Configuration about what auth methods a server supports.@@ -323,10 +477,12 @@ class OidcConfig {final bool enabled;final String buttonText;final bool hasLocalAuth;+ final List<BookOrbitOidcProvider> bookOrbitProviders;const OidcConfig({required this.enabled,required this.buttonText,required this.hasLocalAuth,+ this.bookOrbitProviders = const [],});}diff --git a/lib/services/server_backend.dart b/lib/services/server_backend.dartnew file mode 100644index 00000000..de06b14f--- /dev/null+++ b/lib/services/server_backend.dart@@ -0,0 +1,48 @@+import 'package:shared_preferences/shared_preferences.dart';++/// Which kind of server an account talks to. Everything above ApiService+/// speaks Audiobookshelf shapes; a BookOrbit account gets an ApiService that+/// translates on the way in and out.+enum ServerBackend {+ audiobookshelf('abs'),+ bookorbit('bookorbit');++ const ServerBackend(this.key);++ /// Stored in prefs and saved accounts.+ final String key;++ static const prefsKey = 'server_backend';++ /// The backend of the signed-in session in this isolate. ApiService falls+ /// back to it when a caller doesn't say, so code that builds an ApiService+ /// from the stored session gets the right flavor without knowing about it.+ static ServerBackend active = ServerBackend.audiobookshelf;++ static ServerBackend fromKey(String? key) {+ for (final b in values) {+ if (b.key == key) return b;+ }+ return ServerBackend.audiobookshelf;+ }++ /// Read the stored session's backend and make it [active]. Background+ /// isolates (widgets, workers) call this before building an ApiService.+ static ServerBackend loadActive(SharedPreferences prefs) {+ active = fromKey(prefs.getString(prefsKey));+ return active;+ }++ static Future<void> saveActive(ServerBackend backend) async {+ active = backend;+ final prefs = await SharedPreferences.getInstance();+ await prefs.setString(prefsKey, backend.key);+ }++ bool get isBookOrbit => this == ServerBackend.bookorbit;++ String get displayName => switch (this) {+ ServerBackend.audiobookshelf => 'Audiobookshelf',+ ServerBackend.bookorbit => 'BookOrbit',+ };+}diff --git a/lib/services/socket_service.dart b/lib/services/socket_service.dartindex e166c829..9377a214 100644--- a/lib/services/socket_service.dart+++ b/lib/services/socket_service.dart@@ -2,6 +2,7 @@ import 'package:flutter/foundation.dart';import 'package:socket_io_client/socket_io_client.dart' as io;import 'player_settings.dart';+import 'server_backend.dart';class SocketService {static const authorChangeEvents = <String>[@@ -276,6 +277,21 @@ class SocketService {}}+ /// An item change made by this app on a server with no socket (BookOrbit),+ /// sent to the same listeners the socket's item_updated reaches.+ void emitLocalItemUpdated(Map<String, dynamic> item) {+ onItemUpdated?.call(item);+ _emitItemUpdated(item);+ _emitItemsChanged();+ }++ /// The item_removed counterpart of [emitLocalItemUpdated].+ void emitLocalItemRemoved(Map<String, dynamic> item) {+ onItemRemoved?.call(item);+ _emitItemRemoved(item);+ _emitItemsChanged();+ }+// Removal fan-out with payload ({id, ...}), alongside the single-slot// onItemRemoved owned by the library provider.final List<void Function(Map<String, dynamic>)> _itemRemovedListeners = [];@@ -331,6 +347,10 @@ class SocketService {void connect(String serverUrl, String token, {Map<String, String> customHeaders = const {}}) {if (_socket != null) disconnect();+ // BookOrbit has its own socket namespaces and no progress events, so+ // its accounts run on the refresh timers instead.+ if (ServerBackend.active.isBookOrbit) return;+_token = token;_serverUrl = serverUrl;_customHeaders = customHeaders;@@ -546,6 +566,7 @@ class SocketService {/// Reconnect after a soft disconnect, reusing saved credentials.void softReconnect() {if (_socket != null) return; // already connected+ if (ServerBackend.active.isBookOrbit) return;if (PlayerSettings.einkMode) return;final url = _serverUrl;final token = _token;diff --git a/lib/services/user_account_service.dart b/lib/services/user_account_service.dartindex 4b181b66..9afaff3e 100644--- a/lib/services/user_account_service.dart+++ b/lib/services/user_account_service.dart@@ -4,6 +4,7 @@ import 'package:shared_preferences/shared_preferences.dart';import '../utils/server_url.dart';import 'api_service.dart';import 'auth_tokens.dart';+import 'server_backend.dart';/// Represents a saved user account (server + credentials).class SavedAccount {@@ -14,6 +15,7 @@ class SavedAccount {final String? userId;final bool isLegacyToken;final Map<String, String> customHeaders;+ final ServerBackend backend;SavedAccount({required this.serverUrl,@@ -23,6 +25,7 @@ class SavedAccount {this.userId,this.isLegacyToken = false,Map<String, String> customHeaders = const {},+ this.backend = ServerBackend.audiobookshelf,}) : customHeaders = Map.unmodifiable(customHeaders);/// Unique key for scoping per-user SharedPreferences data.@@ -43,6 +46,7 @@ class SavedAccount {'userId': userId,'isLegacyToken': isLegacyToken,'customHeaders': customHeaders,+ 'backend': backend.key,};factory SavedAccount.fromJson(@@ -59,6 +63,7 @@ class SavedAccount {customHeaders: json.containsKey('customHeaders')? Map<String, String>.from(json['customHeaders'] as Map? ?? const {}): legacyCustomHeaders,+ backend: ServerBackend.fromKey(json['backend'] as String?),);@override@@ -213,6 +218,7 @@ class UserAccountService {userId: old.userId,isLegacyToken: old.isLegacyToken,customHeaders: old.customHeaders,+ backend: old.backend,);await _persist();}@@ -328,6 +334,7 @@ class UserAccountService {userId: old.userId,isLegacyToken: old.isLegacyToken,customHeaders: old.customHeaders,+ backend: old.backend,);await _persist();}@@ -371,6 +378,7 @@ class UserAccountService {userId: old.userId,isLegacyToken: old.isLegacyToken,customHeaders: customHeaders,+ backend: old.backend,);final oldScope = old.scopeKey;diff --git a/lib/widgets/book_detail_sheet.dart b/lib/widgets/book_detail_sheet.dartindex 800be5d1..2d734500 100644--- a/lib/widgets/book_detail_sheet.dart+++ b/lib/widgets/book_detail_sheet.dart@@ -1,3 +1,4 @@+import 'package:flutter_svg/flutter_svg.dart';import 'dart:async';import 'dart:convert';import 'dart:io';@@ -8,6 +9,7 @@ import 'package:flutter/material.dart';import 'package:flutter/services.dart';import 'package:provider/provider.dart';import 'overlay_toast.dart';+import '../services/bookorbit_mapper.dart';import 'absorb_placement.dart';import 'package:cached_network_image/cached_network_image.dart';import 'package:palette_generator/palette_generator.dart';@@ -189,6 +191,10 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {Map<String, dynamic>? _item;Map<String, dynamic>? _rating;String? _asin;+ // BookOrbit only: its "more like this" picks for the book.+ List<Map<String, dynamic>> _similar = const [];+ bool _similarLoaded = false;+ bool _savingStatus = false;bool _isLoading = true;bool _bookmarksExpanded = false;BookmarkPreviewPlayer? _preview;@@ -469,6 +475,10 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {setState(() { _item = finalItem; _isLoading = false; });_deriveCoverScheme();+ if (api.isBookOrbit && !_similarLoaded) {+ _similarLoaded = true;+ unawaited(_loadSimilar(api));+ }// Fetch Audible ratingfinal media = finalItem['media'] as Map<String, dynamic>? ?? {};@@ -719,6 +729,9 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {final isFinished = progressData?['isFinished'] == true;final currentTime = (progressData?['currentTime'] as num?)?.toDouble() ?? 0;final ebookFile = resolveEbookFile(_item) ?? _cachedEbookFallback;+ final bookOrbitOnline = auth.isBookOrbit && !lib.isOffline;+ final readStatus = _displayReadStatus(isFinished);+ final providerBadges = auth.isBookOrbit ? _providerBadges() : const <Map<String, dynamic>>[];final isEbookOnly = PlayerSettings.isEbookOnly(_item!);// Preview only makes sense before the book has been started. The 60s@@ -829,7 +842,9 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {],// ─── AUDIBLE RATING (space always reserved) ─────────const SizedBox(height: 8),- if (_rating != null && (_rating!['rating'] as num).toDouble() > 0)+ if (providerBadges.isNotEmpty)+ _providerBadgeRow(cs, lib, providerBadges)+ else if (_rating != null && (_rating!['rating'] as num).toDouble() > 0)Center(child: GestureDetector(onTap: _asin != null ? () => _showAudibleReviews(context) : null,@@ -1182,6 +1197,12 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {],const SizedBox(height: 16),Wrap(spacing: 8, runSpacing: 8, children: [+ if (bookOrbitOnline)+ _chip(+ _readStatusIcon(readStatus),+ _readStatusLabel(l, readStatus),+ onTap: _savingStatus ? null : () => _pickReadStatus(auth, lib, readStatus),+ ),if (year.isNotEmpty) _chip(Icons.calendar_today_rounded, year),_chip(Icons.schedule_rounded, formatHm(duration)),if (chapters.isNotEmpty) _chip(Icons.list_rounded, l.chaptersChip(chapters.length)),@@ -1234,6 +1255,10 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {style: tt.bodySmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.7), height: 1.5),linkColor: accent,)],+ if (bookOrbitOnline) ...[+ const SizedBox(height: 16),+ _personalNoteBlock(cs, tt, auth),+ ],if (chapters.isNotEmpty) ...[const SizedBox(height: 16),Text(l.chaptersCount(chapters.length), style: tt.titleSmall?.copyWith(color: cs.onSurfaceVariant, fontWeight: FontWeight.w600)),const SizedBox(height: 4),@@ -1314,10 +1339,318 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {])),]));})]],+ if (_similar.isNotEmpty && !lib.isOffline) ...[+ const SizedBox(height: 16),+ Text(l.moreLikeThis, style: tt.titleSmall?.copyWith(color: cs.onSurfaceVariant, fontWeight: FontWeight.w600)),+ const SizedBox(height: 8),+ SizedBox(+ height: (_squareCovers ? 100.0 : 135.0) + 40,+ child: ListView.separated(+ scrollDirection: Axis.horizontal,+ itemCount: _similar.length,+ separatorBuilder: (_, __) => const SizedBox(width: 10),+ itemBuilder: (_, i) => _similarTile(cs, tt, lib, auth, _similar[i]),+ ),+ ),+ ],const SizedBox(height: 20),]);}+ Future<void> _loadSimilar(ApiService api) async {+ final list = await api.getSimilarBooks(widget.itemId);+ if (mounted && list.isNotEmpty) setState(() => _similar = list.take(20).toList());+ }++ Widget _similarTile(ColorScheme cs, TextTheme tt, LibraryProvider lib, AuthProvider auth, Map<String, dynamic> book) {+ final id = book['id'] as String;+ final width = _squareCovers ? 100.0 : 90.0;+ final height = _squareCovers ? 100.0 : 135.0;+ final url = book['hasCover'] == true ? auth.apiService?.getCoverUrl(id) : null;+ final blank = Container(+ color: cs.surfaceContainerHighest,+ child: Icon(Icons.menu_book_rounded, color: cs.onSurfaceVariant),+ );+ return SizedBox(+ width: width,+ child: GestureDetector(+ onTap: () => showBookDetailSheet(context, id),+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [+ ClipRRect(+ borderRadius: BorderRadius.circular(8),+ child: SizedBox(+ width: width,+ height: height,+ child: url == null+ ? blank+ : CachedNetworkImage(+ imageUrl: url,+ httpHeaders: lib.mediaHeaders,+ fit: BoxFit.cover,+ placeholder: (_, __) => Container(color: cs.surfaceContainerHighest),+ errorWidget: (_, __, ___) => blank,+ ),+ ),+ ),+ const SizedBox(height: 6),+ Text(+ book['title'] as String? ?? '',+ maxLines: 2,+ overflow: TextOverflow.ellipsis,+ style: tt.labelSmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.8), height: 1.2),+ ),+ ]),+ ),+ );+ }++ /// BookOrbit's status for the book, squared with the finish button, which+ /// changes the server without reloading the book here.+ String _displayReadStatus(bool isFinished) {+ final s = ((_item?['bookOrbit'] as Map?)?['readStatus'] as Map?)?['status'] as String? ?? 'unread';+ final done = s == 'read' || s == 'skimmed';+ if (isFinished && !done) return 'read';+ if (!isFinished && done) return 'reading';+ return s;+ }++ static String _readStatusLabel(AppLocalizations l, String s) => switch (s) {+ 'want_to_read' => l.readStatusWantToRead,+ 'reading' => l.readStatusReading,+ 'on_hold' => l.readStatusOnHold,+ 'rereading' => l.readStatusRereading,+ 'read' => l.readStatusRead,+ 'skimmed' => l.readStatusSkimmed,+ 'abandoned' => l.readStatusAbandoned,+ _ => l.readStatusUnread,+ };++ static IconData _readStatusIcon(String s) => switch (s) {+ 'want_to_read' => Icons.bookmark_add_outlined,+ 'reading' || 'rereading' => Icons.auto_stories_outlined,+ 'on_hold' => Icons.pause_circle_outline_rounded,+ 'read' || 'skimmed' => Icons.check_circle_outline_rounded,+ 'abandoned' => Icons.do_not_disturb_on_outlined,+ _ => Icons.radio_button_unchecked_rounded,+ };++ // Unread and Read stay with the finish button: a hand-set Unread would+ // keep BookOrbit from ever moving the book back to Reading.+ static const _pickableReadStatuses = ['want_to_read', 'reading', 'rereading', 'on_hold', 'skimmed', 'abandoned'];++ Future<void> _pickReadStatus(AuthProvider auth, LibraryProvider lib, String current) async {+ final l = AppLocalizations.of(context)!;+ final picked = await showModalBottomSheet<String>(+ context: context,+ showDragHandle: true,+ builder: (ctx) {+ final cs = Theme.of(ctx).colorScheme;+ final tt = Theme.of(ctx).textTheme;+ return SafeArea(+ child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [+ Padding(+ padding: const EdgeInsets.fromLTRB(24, 0, 24, 4),+ child: Text(l.readStatusTitle, style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600)),+ ),+ Padding(+ padding: const EdgeInsets.fromLTRB(24, 0, 24, 8),+ child: Text(l.readStatusHint, style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),+ ),+ for (final s in _pickableReadStatuses)+ ListTile(+ leading: Icon(_readStatusIcon(s)),+ title: Text(_readStatusLabel(l, s)),+ trailing: s == current ? Icon(Icons.check_rounded, color: cs.primary) : null,+ onTap: () => Navigator.pop(ctx, s),+ ),+ ]),+ );+ },+ );+ final api = auth.apiService;+ if (picked == null || picked == current || api == null || !mounted) return;+ setState(() => _savingStatus = true);+ final ok = await api.setReadStatus(widget.itemId, picked);+ if (!mounted) return;+ setState(() {+ _savingStatus = false;+ if (ok) {+ final bo = Map<String, dynamic>.from((_item?['bookOrbit'] as Map?) ?? const {});+ bo['readStatus'] = {...?(bo['readStatus'] as Map?)?.cast<String, dynamic>(), 'status': picked};+ _item = {..._item!, 'bookOrbit': bo};+ }+ });+ if (ok) {+ unawaited(lib.refresh());+ } else {+ showOverlayToast(context, l.failedToUpdateCheckConnection, icon: Icons.error_outline_rounded);+ }+ }++ Widget _personalNoteBlock(ColorScheme cs, TextTheme tt, AuthProvider auth) {+ final l = AppLocalizations.of(context)!;+ final note = ((_item?['bookOrbit'] as Map?)?['personalNote'] as String?)?.trim() ?? '';+ if (note.isEmpty) {+ return Align(+ alignment: Alignment.centerLeft,+ child: TextButton.icon(+ onPressed: () => _editPersonalNote(auth, note),+ icon: const Icon(Icons.edit_note_rounded, size: 18),+ label: Text(l.personalNoteAdd),+ ),+ );+ }+ return InkWell(+ onTap: () => _editPersonalNote(auth, note),+ borderRadius: BorderRadius.circular(10),+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [+ Row(children: [+ Text(l.personalNoteTitle, style: tt.titleSmall?.copyWith(color: cs.onSurfaceVariant, fontWeight: FontWeight.w600)),+ const Spacer(),+ Icon(Icons.edit_rounded, size: 16, color: cs.onSurface.withValues(alpha: 0.4)),+ ]),+ const SizedBox(height: 6),+ Text(note, style: tt.bodySmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.7), height: 1.5)),+ ]),+ );+ }++ Future<void> _editPersonalNote(AuthProvider auth, String current) async {+ final l = AppLocalizations.of(context)!;+ final result = await showDialog<String>(+ context: context,+ builder: (_) => _PersonalNoteDialog(initial: current),+ );+ final api = auth.apiService;+ if (result == null || result.trim() == current || api == null || !mounted) return;+ final ok = await api.setPersonalNote(widget.itemId, result);+ if (!mounted) return;+ if (!ok) {+ showOverlayToast(context, l.failedToUpdateCheckConnection, icon: Icons.error_outline_rounded);+ return;+ }+ setState(() {+ final bo = Map<String, dynamic>.from((_item?['bookOrbit'] as Map?) ?? const {});+ bo['personalNote'] = result.trim().isEmpty ? null : result.trim();+ _item = {..._item!, 'bookOrbit': bo};+ });+ }++ /// BookOrbit's provider links and ratings the way its web book page shows+ /// them, with the live Audible rating folded into the Audible badge.+ List<Map<String, dynamic>> _providerBadges() {+ final bo = _item?['bookOrbit'] as Map?;+ if (bo == null) return const [];+ final badges = BookOrbitMapper.providerBadges(bo['providerIds'] as Map?, bo['communityRatings'] as List?);+ final live = _rating != null && (_rating!['rating'] as num).toDouble() > 0 ? _rating! : null;+ if (live == null) return badges;+ final i = badges.indexWhere((b) => b['key'] == 'audible');+ final audible = i >= 0 ? badges[i] : BookOrbitMapper.providerBadge('audible');+ if (audible['rating'] == null) {+ audible['rating'] = (live['rating'] as num).toDouble();+ audible['count'] = (live['count'] as num?)?.toInt();+ }+ if (i < 0) badges.add(audible);+ return badges;+ }++ Widget _providerBadgeRow(ColorScheme cs, LibraryProvider lib, List<Map<String, dynamic>> badges) {+ final base = context.read<AuthProvider>().apiService?.baseUrl.replaceAll(RegExp(r'/+$'), '');+ return Center(+ child: SingleChildScrollView(+ scrollDirection: Axis.horizontal,+ child: Row(mainAxisSize: MainAxisSize.min, children: [+ for (var i = 0; i < badges.length; i++) ...[+ if (i > 0) const SizedBox(width: 6),+ _providerBadgeChip(cs, lib, base, badges[i]),+ ],+ ]),+ ),+ );+ }++ Widget _providerBadgeChip(ColorScheme cs, LibraryProvider lib, String? base, Map<String, dynamic> b) {+ final l = AppLocalizations.of(context)!;+ final color = Color(b['color'] as int);+ final rating = (b['rating'] as num?)?.toDouble();+ final count = (b['count'] as num?)?.toInt() ?? 0;+ final label = b['label'] as String;+ final url = b['url'] as String?;+ final VoidCallback? onTap = b['key'] == 'audible' && _asin != null+ ? () => _showAudibleReviews(context)+ : url == null+ ? null+ : () => _openProviderPage(url);+ final mark = Text(b['mark'] as String,+ style: TextStyle(fontSize: 8, fontWeight: FontWeight.w700, color: cs.onSurface));+ final icon = b['icon'] as String?;+ return Tooltip(+ message: rating == null+ ? label+ : '$label ${rating.toStringAsFixed(1)}${count > 0 ? ' (${_formatRatingCount(count, l.localeName)})' : ''}',+ child: Material(+ color: color.withValues(alpha: 0.10),+ shape: RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(6),+ side: BorderSide(color: color.withValues(alpha: 0.45)),+ ),+ clipBehavior: Clip.antiAlias,+ child: InkWell(+ onTap: onTap,+ child: SizedBox(+ height: 24,+ child: Row(mainAxisSize: MainAxisSize.min, children: [+ SizedBox(+ width: 24,+ child: Center(+ child: icon == null || base == null+ ? mark+ : SvgPicture.network(+ '$base/assets/provider-icons/$icon',+ width: 14,+ height: 14,+ headers: lib.mediaHeaders,+ placeholderBuilder: (_) => mark,+ errorBuilder: (_, __, ___) => mark,+ ),+ ),+ ),+ if (rating != null)+ Container(+ padding: const EdgeInsets.symmetric(horizontal: 6),+ alignment: Alignment.center,+ decoration: BoxDecoration(+ color: cs.surface.withValues(alpha: 0.5),+ border: Border(left: BorderSide(color: color.withValues(alpha: 0.3))),+ ),+ child: Text(+ rating == rating.roundToDouble() ? rating.toStringAsFixed(0) : rating.toStringAsFixed(1),+ style: TextStyle(+ fontSize: 11,+ fontWeight: FontWeight.w600,+ color: cs.onSurface,+ fontFeatures: const [FontFeature.tabularFigures()],+ ),+ ),+ ),+ ]),+ ),+ ),+ ),+ );+ }++ Future<void> _openProviderPage(String url) async {+ final uri = Uri.parse(url);+ try {+ if (!await launchUrl(uri, mode: LaunchMode.externalNonBrowserApplication)) {+ await launchUrl(uri, mode: LaunchMode.externalApplication);+ }+ } catch (_) {+ await launchUrl(uri, mode: LaunchMode.externalApplication);+ }+ }+// ─── QUICK ACTIONS (long-press) ─────────────────────────────// Compact long-press layout: cover + title, an Absorb/Download grid, then// the same actions as the detail sheet's "more" menu rendered as pills.@@ -1444,7 +1777,9 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {item: _item, addedToast: Wording.of(context).addedToAbsorbing);}});- if (!lib.isOffline) {+ // BookOrbit has no playlists; its collections are personal, so+ // everyone gets Add to Collection there instead.+ if (!lib.isOffline && !auth.isBookOrbit) {add(Icons.playlist_add_rounded, l.addToPlaylist, () => PlaylistPickerSheet.show(context, widget.itemId));}if (!includeOpenDetails && !lib.isOffline) {@@ -1459,7 +1794,7 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {),);}- if (!lib.isOffline && !lib.isPodcastLibrary && auth.isAdmin) {+ if (!lib.isOffline && !lib.isPodcastLibrary && (auth.isAdmin || auth.isBookOrbit)) {add(Icons.collections_bookmark_rounded, l.addToCollection, () => CollectionPickerSheet.show(context, widget.itemId));}if (ebookFile != null && canReadEbook(ebookFile)) {@@ -2278,7 +2613,9 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {if (!cachedFile.existsSync()) {final cleanBase = api.baseUrl.endsWith('/') ? api.baseUrl.substring(0, api.baseUrl.length - 1) : api.baseUrl;- final url = '$cleanBase/api/items/${widget.itemId}/file/$ino';+ final url = api.isBookOrbit+ ? api.buildEbookUrl(widget.itemId, ino)+ : '$cleanBase/api/items/${widget.itemId}/file/$ino';// Use streamed download with proper headers (including custom// reverse-proxy headers) and manual redirect following so auth@@ -3064,3 +3401,44 @@ class _FullCoverViewerState extends State<_FullCoverViewer> {);}}++/// Edits a BookOrbit private note. Owns its controller so the text field+/// outlives the dialog's closing animation.+class _PersonalNoteDialog extends StatefulWidget {+ final String initial;+ const _PersonalNoteDialog({required this.initial});++ @override+ State<_PersonalNoteDialog> createState() => _PersonalNoteDialogState();+}++class _PersonalNoteDialogState extends State<_PersonalNoteDialog> {+ late final TextEditingController _ctrl = TextEditingController(text: widget.initial);++ @override+ void dispose() {+ _ctrl.dispose();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) {+ final l = AppLocalizations.of(context)!;+ return AlertDialog(+ title: Text(l.personalNoteTitle),+ content: TextField(+ controller: _ctrl,+ autofocus: true,+ minLines: 3,+ maxLines: 8,+ maxLength: 10000,+ textCapitalization: TextCapitalization.sentences,+ decoration: InputDecoration(hintText: l.personalNoteHint),+ ),+ actions: [+ TextButton(onPressed: () => Navigator.pop(context), child: Text(l.cancel)),+ FilledButton(onPressed: () => Navigator.pop(context, _ctrl.text), child: Text(l.save)),+ ],+ );+ }+}diff --git a/lib/widgets/chromecast_button.dart b/lib/widgets/chromecast_button.dartindex 6b091817..d8ec207a 100644--- a/lib/widgets/chromecast_button.dart+++ b/lib/widgets/chromecast_button.dart@@ -3,6 +3,8 @@ import 'package:flutter_chrome_cast/flutter_chrome_cast.dart';import '../l10n/app_localizations.dart';import '../services/chromecast_service.dart';import '../services/api_service.dart';+import '../services/server_backend.dart';+import 'overlay_toast.dart';/// Shows a device picker. If castAfter params are provided, automatically/// casts the book after connecting to the selected device.@@ -17,6 +19,13 @@ void showCastDevicePicker(List<dynamic>? chapters,String? episodeId,}) {+ // A Cast receiver fetches media itself and can't send the Bearer header+ // BookOrbit needs.+ if (ServerBackend.active.isBookOrbit) {+ showOverlayToast(context, AppLocalizations.of(context)!.castNotAvailableBookOrbit,+ icon: Icons.cast_rounded);+ return;+ }final cast = ChromecastService();showModalBottomSheet(context: context,diff --git a/lib/widgets/collection_detail_sheet.dart b/lib/widgets/collection_detail_sheet.dartindex 04d8c250..2e6b53d8 100644--- a/lib/widgets/collection_detail_sheet.dart+++ b/lib/widgets/collection_detail_sheet.dart@@ -50,6 +50,18 @@ class CollectionDetailSheet extends StatefulWidget {class _CollectionDetailSheetState extends State<CollectionDetailSheet> {bool _editing = false;+ bool _savingPublic = false;++ Future<void> _setPublic(LibraryProvider lib, bool isPublic) async {+ setState(() => _savingPublic = true);+ final ok = await lib.setCollectionPublic(widget.collectionId, isPublic);+ if (!mounted) return;+ setState(() => _savingPublic = false);+ if (!ok) {+ showOverlayToast(context, AppLocalizations.of(context)!.failedToUpdateCheckConnection,+ icon: Icons.error_outline_rounded);+ }+ }bool _gridView = false;List<Map<String, dynamic>>? _editItems;final Set<String> _selectedItemIds = {};@@ -204,11 +216,6 @@ class _CollectionDetailSheetState extends State<CollectionDetailSheet> {final l = AppLocalizations.of(context)!;final lib = context.watch<LibraryProvider>();final auth = context.read<AuthProvider>();- // Both gated at isAdmin in the UI; server returns 403 when admin lacks- // the `delete` permission flag and we show a friendly toast then.- final canEditCollection = auth.isAdmin;- final canDeleteCollection = auth.isAdmin;-final collection = lib.collections.cast<Map<String, dynamic>>().where((c) => c['id'] == widget.collectionId,).firstOrNull;@@ -217,6 +224,14 @@ class _CollectionDetailSheetState extends State<CollectionDetailSheet> {return Center(child: Text(l.collectionNotFound));}+ // Both gated at isAdmin in the UI; server returns 403 when admin lacks+ // the `delete` permission flag and we show a friendly toast then. A+ // BookOrbit collection belongs to whoever made it.+ final ownsBookOrbitCollection = auth.isBookOrbit &&+ (collection['bookOrbit'] as Map?)?['isOwner'] == true;+ final canEditCollection = auth.isAdmin || ownsBookOrbitCollection;+ final canDeleteCollection = auth.isAdmin || ownsBookOrbitCollection;+final name = collection['name'] as String? ?? l.collectionDetailDefaultName;final description = collection['description'] as String? ?? '';final books = (collection['books'] as List<dynamic>?) ?? [];@@ -290,6 +305,15 @@ class _CollectionDetailSheetState extends State<CollectionDetailSheet> {const SizedBox(height: 12),Divider(height: 1, color: cs.outlineVariant.withValues(alpha: 0.3),indent: 20, endIndent: 20),+ if (_editing && ownsBookOrbitCollection)+ SwitchListTile(+ dense: true,+ contentPadding: const EdgeInsets.symmetric(horizontal: 20),+ title: Text(l.collectionPublicTitle),+ subtitle: Text(l.collectionPublicSubtitle),+ value: (collection['bookOrbit'] as Map?)?['isPublic'] == true,+ onChanged: _savingPublic ? null : (v) => _setPublic(lib, v),+ ),if (!_editing)_buildPlayButton(cs, lib, books, name, l),// Contentdiff --git a/lib/widgets/collection_picker_sheet.dart b/lib/widgets/collection_picker_sheet.dartindex 15285931..0b8a4159 100644--- a/lib/widgets/collection_picker_sheet.dart+++ b/lib/widgets/collection_picker_sheet.dart@@ -1,6 +1,7 @@import 'package:flutter/material.dart';import 'package:provider/provider.dart';import '../l10n/app_localizations.dart';+import '../providers/auth_provider.dart';import '../providers/library_provider.dart';import 'overlay_toast.dart';@@ -75,7 +76,12 @@ class _CollectionPickerSheetState extends State<CollectionPickerSheet> {Widget build(BuildContext context) {final cs = Theme.of(context).colorScheme;final lib = context.watch<LibraryProvider>();- final collections = lib.collections;+ // A BookOrbit collection only takes books from its owner.+ final collections = context.read<AuthProvider>().isBookOrbit+ ? lib.collections+ .where((c) => ((c as Map)['bookOrbit'] as Map?)?['isOwner'] == true)+ .toList()+ : lib.collections;final l = AppLocalizations.of(context)!;return SafeArea(diff --git a/lib/widgets/comic_reader_view.dart b/lib/widgets/comic_reader_view.dartnew file mode 100644index 00000000..40edf012--- /dev/null+++ b/lib/widgets/comic_reader_view.dart@@ -0,0 +1,588 @@+import 'dart:io';++import 'package:archive/archive_io.dart';+import 'package:cached_network_image/cached_network_image.dart';+import 'package:flutter/foundation.dart';+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:path_provider/path_provider.dart';+import 'package:provider/provider.dart';++import '../l10n/app_localizations.dart';+import '../providers/auth_provider.dart';+import '../providers/library_provider.dart';+import '../services/api_service.dart';+import '../services/ebook_cache.dart';+import '../services/progress_sync_service.dart';+import '../services/scoped_prefs.dart';+import '../services/volume_key_service.dart';+import 'ebook_router.dart' show ebookExt;++const _imageExts = {'jpg', 'jpeg', 'png', 'webp', 'gif', 'bmp'};++/// Natural order for page file names, so "page2" comes before "page10".+int comicPageNameCompare(String a, String b) {+ final re = RegExp(r'\d+|\D+');+ final pa = re.allMatches(a.toLowerCase()).map((m) => m.group(0)!).toList();+ final pb = re.allMatches(b.toLowerCase()).map((m) => m.group(0)!).toList();+ for (var i = 0; i < pa.length && i < pb.length; i++) {+ final x = pa[i], y = pb[i];+ final xd = int.tryParse(x), yd = int.tryParse(y);+ final c = xd != null && yd != null ? xd.compareTo(yd) : x.compareTo(y);+ if (c != 0) return c;+ }+ return pa.length.compareTo(pb.length);+}++bool _isPageEntry(String name) {+ final parts = name.replaceAll('\\', '/').split('/');+ if (parts.any((p) => p.startsWith('.') || p == '__MACOSX')) return false;+ final dot = name.lastIndexOf('.');+ return dot > 0 && _imageExts.contains(name.substring(dot + 1).toLowerCase());+}++/// Unpacks a CBZ's page images into [dest] as 00000.jpg, 00001.png, ... in+/// reading order. Runs in a background isolate. Returns the page paths.+List<String> extractComicPages(List<String> args) {+ final src = args[0], dest = args[1];+ final input = InputFileStream(src);+ try {+ final archive = ZipDecoder().decodeStream(input);+ final entries = archive.files.where((f) => f.isFile && _isPageEntry(f.name)).toList()+ ..sort((a, b) => comicPageNameCompare(a.name, b.name));+ Directory(dest).createSync(recursive: true);+ final paths = <String>[];+ for (var i = 0; i < entries.length; i++) {+ final name = entries[i].name;+ final ext = name.substring(name.lastIndexOf('.') + 1).toLowerCase();+ final path = '$dest${Platform.pathSeparator}${i.toString().padLeft(5, '0')}.$ext';+ final out = OutputFileStream(path);+ entries[i].writeContent(out);+ out.closeSync();+ paths.add(path);+ }+ File('$dest${Platform.pathSeparator}.done').writeAsStringSync('${paths.length}');+ return paths;+ } finally {+ input.closeSync();+ }+}++/// Where a comic's pages come from: images unpacked on the phone, or pages+/// the server hands out one at a time (BookOrbit, which also opens CBR and+/// CB7 archives the phone can't).+abstract class _ComicPages {+ int get count;+ ImageProvider image(int index);+}++class _FilePages implements _ComicPages {+ final List<String> paths;+ _FilePages(this.paths);+ @override+ int get count => paths.length;+ @override+ ImageProvider image(int index) => FileImage(File(paths[index]));+}++class _ServerPages implements _ComicPages {+ final ApiService api;+ final String fileId;+ @override+ final int count;+ _ServerPages(this.api, this.fileId, this.count);+ @override+ ImageProvider image(int index) =>+ CachedNetworkImageProvider(api.comicPageUrl(fileId, index)!, headers: api.mediaHeaders);+}++/// Full-screen comic reader: one page at a time, pinch or double-tap to zoom+/// and drag to pan, swipe or tap the edges to turn pages, left to right or+/// right to left (manga) per book. The page number is stored as the+/// ebookLocation, like the PDF reader, which is also what BookOrbit's own+/// comic reader saves.+class ComicReaderView extends StatefulWidget {+ final String itemId;+ final String title;+ final Map<String, dynamic> ebookFile;++ const ComicReaderView({+ super.key,+ required this.itemId,+ required this.title,+ required this.ebookFile,+ });++ @override+ State<ComicReaderView> createState() => _ComicReaderViewState();+}++class _ComicReaderViewState extends State<ComicReaderView> with WidgetsBindingObserver {+ ApiService? _api;+ LibraryProvider? _lib;+ _ComicPages? _pages;+ PageController? _controller;+ String? _error;+ bool _loading = true;++ int _page = 1;+ bool _rtl = false;+ bool _zoomed = false;+ bool _showControls = true;+ double? _scrubPage;++ DateTime _lastSync = DateTime.fromMillisecondsSinceEpoch(0);+ int _lastSyncedPage = -1;+ int? _pendingPage;++ String get _directionKey => 'comic_rtl_${widget.itemId}';++ @override+ void initState() {+ super.initState();+ WidgetsBinding.instance.addObserver(this);+ _setFullscreen(true);+ _api = context.read<AuthProvider>().apiService;+ _lib = context.read<LibraryProvider>();+ _lib?.setReaderQuiet(true);+ ScopedPrefs.getBool(_directionKey).then((v) {+ if (mounted && v != null) setState(() => _rtl = v);+ });+ _open();+ _volumeNav.attach();+ }++ @override+ void didChangeAppLifecycleState(AppLifecycleState state) {+ if (state == AppLifecycleState.paused) _flushProgress();+ }++ late final EreaderVolumeNav _volumeNav = EreaderVolumeNav(+ onPrev: () => _turn(-1),+ onNext: () => _turn(1),+ );++ @override+ void dispose() {+ _lib?.setReaderQuiet(false);+ WidgetsBinding.instance.removeObserver(this);+ _volumeNav.detach();+ _setFullscreen(false);+ _flushProgress();+ _controller?.dispose();+ super.dispose();+ }++ void _setFullscreen(bool fullscreen) {+ if (fullscreen) {+ SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);+ } else {+ SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: SystemUiOverlay.values);+ }+ }++ /// The saved page: the location when it is a page number, otherwise the+ /// progress fraction (a CBZ last read in the old reader saved neither).+ int _savedPage(int count) {+ final data = _lib?.getProgressData(widget.itemId);+ final loc = int.tryParse((data?['ebookLocation'] as String?)?.trim() ?? '');+ if (loc != null && loc >= 1) return loc.clamp(1, count);+ final frac = (data?['ebookProgress'] as num?)?.toDouble() ?? 0;+ if (frac > 0 && frac < 1) return (frac * count).round().clamp(1, count);+ return 1;+ }++ Future<void> _open() async {+ final l = AppLocalizations.of(context)!;+ final ext = ebookExt(widget.ebookFile);+ final api = _api;+ final offline = _lib?.isOffline ?? true;+ try {+ _ComicPages? pages;+ if (ext == 'cbz' && await isEbookCached(widget.itemId, widget.ebookFile)) {+ pages = await _unpack(await ebookCacheFileFor(widget.itemId, widget.ebookFile));+ }+ final fileId = widget.ebookFile['ino'] as String?;+ if (pages == null && api != null && fileId != null && !offline) {+ final count = await api.comicPageCount(fileId);+ if (count != null && count > 0) pages = _ServerPages(api, fileId, count);+ }+ if (pages == null && ext == 'cbz' && api != null && !offline) {+ pages = await _unpack(await fetchEbookToCache(api, widget.itemId, widget.ebookFile, widget.title));+ }+ if (!mounted) return;+ if (pages == null) {+ setState(() {+ _error = ext == 'cbz' ? l.noEbookFileFound : l.comicNeedsConnection;+ _loading = false;+ });+ return;+ }+ if (pages.count == 0) {+ setState(() {+ _error = l.comicNoPages;+ _loading = false;+ });+ return;+ }+ final start = _savedPage(pages.count);+ setState(() {+ _pages = pages;+ _page = start;+ _controller = PageController(initialPage: start - 1);+ _loading = false;+ });+ _precacheAround(start - 1);+ } catch (e) {+ debugPrint('[Comic] open failed: $e');+ if (mounted) setState(() { _error = '$e'; _loading = false; });+ }+ }++ /// Unpacks a CBZ into a scratch folder once per file version, keeping the+ /// three most recent comics so the cache doesn't grow without end.+ Future<_ComicPages> _unpack(File archive) async {+ final root = Directory('${(await getTemporaryDirectory()).path}/comic_pages');+ final dest = Directory('${root.path}/${widget.itemId}_${await archive.length()}');+ final done = File('${dest.path}/.done');+ List<String> paths;+ if (done.existsSync()) {+ paths = dest+ .listSync()+ .whereType<File>()+ .map((f) => f.path)+ .where((p) => !p.endsWith('.done'))+ .toList()+ ..sort();+ } else {+ if (dest.existsSync()) dest.deleteSync(recursive: true);+ paths = await compute(extractComicPages, [archive.path, dest.path]);+ }+ try {+ done.setLastModifiedSync(DateTime.now());+ DateTime opened(Directory d) {+ final marker = File('${d.path}/.done');+ return marker.existsSync() ? marker.lastModifiedSync() : d.statSync().modified;+ }+ final others = root.listSync().whereType<Directory>().where((d) => d.path != dest.path).toList()+ ..sort((a, b) => opened(b).compareTo(opened(a)));+ for (final old in others.skip(2)) {+ old.deleteSync(recursive: true);+ }+ } catch (_) {}+ return _FilePages(paths);+ }++ void _precacheAround(int index) {+ final pages = _pages;+ if (pages == null || !mounted) return;+ for (final i in [index + 1, index + 2, index - 1]) {+ if (i >= 0 && i < pages.count) {+ precacheImage(pages.image(i), context).catchError((_) {});+ }+ }+ }++ void _onPageChanged(int index) {+ setState(() {+ _page = index + 1;+ _zoomed = false;+ });+ _precacheAround(index);+ _pendingPage = _page;+ if (DateTime.now().difference(_lastSync).inSeconds >= 10) _flushProgress();+ }++ void _flushProgress() {+ final page = _pendingPage;+ final api = _api;+ final count = _pages?.count ?? 0;+ if (page == null || api == null || count <= 0 || page == _lastSyncedPage) return;+ final frac = (page / count).clamp(0.0, 1.0);+ ProgressSyncService().pushEbookProgress(api, widget.itemId, location: '$page', progress: frac);+ _lib?.applyLocalEbookProgress(widget.itemId, location: '$page', progress: frac);+ _lastSync = DateTime.now();+ _lastSyncedPage = page;+ _pendingPage = null;+ }++ /// [delta] in reading order: +1 is the next page whichever way it reads.+ void _turn(int delta) {+ final c = _controller;+ final pages = _pages;+ if (c == null || pages == null) return;+ final target = (_page - 1 + delta).clamp(0, pages.count - 1);+ if (target == _page - 1) return;+ c.animateToPage(target, duration: const Duration(milliseconds: 220), curve: Curves.easeOut);+ }++ /// Edges turn the page (mirrored when reading right to left), the middle+ /// shows or hides the controls.+ void _onPageTap(TapUpDetails d) {+ final width = MediaQuery.of(context).size.width;+ final x = d.globalPosition.dx;+ if (x < width * 0.3) {+ _turn(_rtl ? 1 : -1);+ } else if (x > width * 0.7) {+ _turn(_rtl ? -1 : 1);+ } else {+ setState(() => _showControls = !_showControls);+ }+ }++ void _setDirection(bool rtl) {+ setState(() => _rtl = rtl);+ ScopedPrefs.setBool(_directionKey, rtl);+ }++ void _showSettings() {+ final l = AppLocalizations.of(context)!;+ showModalBottomSheet(+ context: context,+ showDragHandle: true,+ builder: (ctx) => SafeArea(+ child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [+ Padding(+ padding: const EdgeInsets.fromLTRB(24, 0, 24, 8),+ child: Text(l.comicReadingDirection,+ style: Theme.of(ctx).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.w600)),+ ),+ for (final rtl in [false, true])+ ListTile(+ leading: Icon(rtl ? Icons.format_textdirection_r_to_l_rounded : Icons.format_textdirection_l_to_r_rounded),+ title: Text(rtl ? l.comicRightToLeft : l.comicLeftToRight),+ trailing: rtl == _rtl ? Icon(Icons.check_rounded, color: Theme.of(ctx).colorScheme.primary) : null,+ onTap: () {+ Navigator.pop(ctx);+ _setDirection(rtl);+ },+ ),+ ]),+ ),+ );+ }++ @override+ Widget build(BuildContext context) {+ final l = AppLocalizations.of(context)!;+ final tt = Theme.of(context).textTheme;+ final pages = _pages;+ final controller = _controller;++ Widget body;+ if (_loading) {+ body = const Center(child: CircularProgressIndicator(color: Colors.white70));+ } else if (_error != null || pages == null || controller == null) {+ body = Center(+ child: Padding(+ padding: const EdgeInsets.all(24),+ child: Text(_error ?? l.noEbookFileFound,+ textAlign: TextAlign.center, style: const TextStyle(color: Colors.white70)),+ ),+ );+ } else {+ final shownPage = (_scrubPage?.round() ?? _page).clamp(1, pages.count);+ body = Stack(children: [+ Positioned.fill(+ child: PageView.builder(+ controller: controller,+ reverse: _rtl,+ physics: _zoomed ? const NeverScrollableScrollPhysics() : const PageScrollPhysics(),+ onPageChanged: _onPageChanged,+ itemCount: pages.count,+ itemBuilder: (_, i) => _ComicPage(+ key: ValueKey('comic-page-$i'),+ image: pages.image(i),+ active: i == _page - 1,+ onTap: _onPageTap,+ onZoomChanged: (z) {+ if (i == _page - 1 && z != _zoomed) setState(() => _zoomed = z);+ },+ ),+ ),+ ),+ Positioned(+ top: 0,+ left: 0,+ right: 0,+ child: _bar(+ top: true,+ child: Row(children: [+ IconButton(+ icon: const Icon(Icons.arrow_back_rounded, color: Colors.white),+ onPressed: () => Navigator.pop(context),+ ),+ Expanded(+ child: Text(widget.title,+ maxLines: 1, overflow: TextOverflow.ellipsis, style: tt.titleSmall?.copyWith(color: Colors.white)),+ ),+ IconButton(+ tooltip: l.comicReadingDirection,+ icon: Icon(+ _rtl ? Icons.format_textdirection_r_to_l_rounded : Icons.format_textdirection_l_to_r_rounded,+ color: Colors.white,+ ),+ onPressed: _showSettings,+ ),+ ]),+ ),+ ),+ Positioned(+ left: 0,+ right: 0,+ bottom: 0,+ child: _bar(+ top: false,+ child: Row(children: [+ Text('$shownPage / ${pages.count}', style: tt.bodySmall?.copyWith(color: Colors.white70)),+ Expanded(+ child: pages.count > 1+ ? Directionality(+ textDirection: _rtl ? TextDirection.rtl : TextDirection.ltr,+ child: Slider(+ min: 1,+ max: pages.count.toDouble(),+ divisions: pages.count - 1,+ value: (_scrubPage ?? _page.toDouble()).clamp(1, pages.count.toDouble()),+ onChanged: (v) => setState(() => _scrubPage = v),+ onChangeEnd: (v) {+ setState(() => _scrubPage = null);+ controller.jumpToPage(v.round() - 1);+ },+ ),+ )+ : const SizedBox.shrink(),+ ),+ ]),+ ),+ ),+ ]);+ }+ return Scaffold(backgroundColor: Colors.black, body: body);+ }++ Widget _bar({required bool top, required Widget child}) => AnimatedOpacity(+ opacity: _showControls ? 1 : 0,+ duration: const Duration(milliseconds: 200),+ child: IgnorePointer(+ ignoring: !_showControls,+ child: Container(+ decoration: BoxDecoration(+ gradient: LinearGradient(+ begin: top ? Alignment.topCenter : Alignment.bottomCenter,+ end: top ? Alignment.bottomCenter : Alignment.topCenter,+ colors: [Colors.black.withValues(alpha: 0.85), Colors.black.withValues(alpha: 0)],+ ),+ ),+ child: SafeArea(+ top: top,+ bottom: !top,+ child: Padding(+ padding: EdgeInsets.symmetric(horizontal: top ? 4 : 16, vertical: top ? 4 : 8),+ child: child,+ ),+ ),+ ),+ ),+ );+}++/// One page: fit to the screen, pinch or double-tap to zoom, drag to pan+/// while zoomed. Zoom resets when the page is swiped away.+class _ComicPage extends StatefulWidget {+ final ImageProvider image;+ final bool active;+ final GestureTapUpCallback onTap;+ final ValueChanged<bool> onZoomChanged;++ const _ComicPage({+ super.key,+ required this.image,+ required this.active,+ required this.onTap,+ required this.onZoomChanged,+ });++ @override+ State<_ComicPage> createState() => _ComicPageState();+}++class _ComicPageState extends State<_ComicPage> with SingleTickerProviderStateMixin {+ static const _doubleTapScale = 2.5;+ final _transform = TransformationController();+ late final AnimationController _anim = AnimationController(+ vsync: this,+ duration: const Duration(milliseconds: 220),+ )..addListener(() {+ final a = _animation;+ if (a != null) _transform.value = a.value;+ });+ Animation<Matrix4>? _animation;+ Offset? _doubleTapAt;++ bool get _isZoomed => _transform.value.getMaxScaleOnAxis() > 1.01;++ @override+ void didUpdateWidget(covariant _ComicPage oldWidget) {+ super.didUpdateWidget(oldWidget);+ if (oldWidget.active && !widget.active && _isZoomed) {+ _anim.stop();+ _transform.value = Matrix4.identity();+ }+ }++ @override+ void dispose() {+ _anim.dispose();+ _transform.dispose();+ super.dispose();+ }++ void _animateTo(Matrix4 target) {+ _animation = Matrix4Tween(begin: _transform.value, end: target)+ .animate(CurvedAnimation(parent: _anim, curve: Curves.easeOut));+ _anim.forward(from: 0);+ }++ void _onDoubleTap() {+ if (_isZoomed) {+ _animateTo(Matrix4.identity());+ widget.onZoomChanged(false);+ return;+ }+ final size = context.size ?? Size.zero;+ final at = _doubleTapAt ?? Offset(size.width / 2, size.height / 2);+ _animateTo(Matrix4.identity()+ ..translate(-at.dx * (_doubleTapScale - 1), -at.dy * (_doubleTapScale - 1))+ ..scale(_doubleTapScale));+ widget.onZoomChanged(true);+ }++ @override+ Widget build(BuildContext context) {+ return GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTapUp: widget.onTap,+ onDoubleTapDown: (d) => _doubleTapAt = d.localPosition,+ onDoubleTap: _onDoubleTap,+ child: InteractiveViewer(+ transformationController: _transform,+ minScale: 1,+ maxScale: 5,+ onInteractionEnd: (_) => widget.onZoomChanged(_isZoomed),+ child: SizedBox.expand(+ child: Image(+ image: widget.image,+ fit: BoxFit.contain,+ filterQuality: FilterQuality.medium,+ loadingBuilder: (_, child, progress) => progress == null+ ? child+ : const Center(child: CircularProgressIndicator(color: Colors.white54, strokeWidth: 2)),+ errorBuilder: (_, __, ___) =>+ const Center(child: Icon(Icons.broken_image_outlined, color: Colors.white38, size: 48)),+ ),+ ),+ ),+ );+ }+}diff --git a/lib/widgets/delete_confirm_dialog.dart b/lib/widgets/delete_confirm_dialog.dartindex a9b9fb5b..f63442b1 100644--- a/lib/widgets/delete_confirm_dialog.dart+++ b/lib/widgets/delete_confirm_dialog.dart@@ -1,6 +1,7 @@import 'package:flutter/material.dart';import '../l10n/app_localizations.dart';import '../services/player_settings.dart';+import '../services/server_backend.dart';/// What the user picked in [showDeleteConfirmDialog]. [hardDelete] true means/// the server wipes the files on disk too (`?hard=1`), false means it only@@ -22,7 +23,10 @@ Future<DeleteChoice?> showDeleteConfirmDialog(required String message,String? confirmLabel,}) async {- final initial = await PlayerSettings.getDeleteFromFileSystem();+ // BookOrbit always removes the files with the book, so there is no choice+ // to offer, only the warning.+ final filesAlwaysGo = ServerBackend.active.isBookOrbit;+ final initial = filesAlwaysGo || await PlayerSettings.getDeleteFromFileSystem();if (!context.mounted) return null;final l = AppLocalizations.of(context)!;final choice = await showDialog<DeleteChoice>(@@ -41,7 +45,7 @@ Future<DeleteChoice?> showDeleteConfirmDialog(children: [Text(message),const SizedBox(height: 8),- InkWell(+ if (!filesAlwaysGo) InkWell(onTap: () => setLocal(() => hard = !hard),borderRadius: BorderRadius.circular(10),child: Row(children: [@@ -81,7 +85,7 @@ Future<DeleteChoice?> showDeleteConfirmDialog();},);- if (choice != null) {+ if (choice != null && !filesAlwaysGo) {await PlayerSettings.setDeleteFromFileSystem(choice.hardDelete);}return choice;diff --git a/lib/widgets/ebook_router.dart b/lib/widgets/ebook_router.dartindex 6c2fe7fc..36eef047 100644--- a/lib/widgets/ebook_router.dart+++ b/lib/widgets/ebook_router.dart@@ -1,6 +1,8 @@import 'package:flutter/material.dart';import '../l10n/app_localizations.dart';import '../services/ebook_cache.dart';+import '../services/server_backend.dart';+import 'comic_reader_view.dart';import 'ebook_reader_view.dart';import 'pdf_reader_view.dart';import 'foliate_reader_view.dart';@@ -15,8 +17,13 @@ String ebookExt(Map<String, dynamic>? ebookFile) {return ext.startsWith('.') ? ext.substring(1) : ext;}-bool canReadEbook(Map<String, dynamic>? ebookFile) =>- ebookFile != null && readableEbookFormats.contains(ebookExt(ebookFile));+bool canReadEbook(Map<String, dynamic>? ebookFile) {+ if (ebookFile == null) return false;+ final ext = ebookExt(ebookFile);+ // BookOrbit unpacks CBR and CB7 on the server and sends the pages.+ if (comicEbookFormats.contains(ext) && ServerBackend.active.isBookOrbit) return true;+ return readableEbookFormats.contains(ext);+}/// Routes an ebook to the right reader for its format, or toasts when the/// format isn't supported in-app. [openAtCfi] jumps an EPUB straight to a@@ -41,6 +48,8 @@ Future<void> openEbookReader(itemId: itemId, title: title, ebookFile: ebookFile, openAtCfi: openAtCfi,findText: findText, findChapterHint: findChapterHint,findPositionSeconds: findPositionSeconds, startReadAlong: startReadAlong);+ } else if (comicEbookFormats.contains(ext)) {+ viewer = ComicReaderView(itemId: itemId, title: title, ebookFile: ebookFile);} else if (ext == 'pdf') {viewer = PdfReaderView(itemId: itemId, title: title, ebookFile: ebookFile);} else if (foliateEbookFormats.contains(ext)) {diff --git a/lib/widgets/edit_author_sheet.dart b/lib/widgets/edit_author_sheet.dartindex 6e2cfdf1..0c67cdf9 100644--- a/lib/widgets/edit_author_sheet.dart+++ b/lib/widgets/edit_author_sheet.dart@@ -315,6 +315,7 @@ class _EditAuthorContentState extends State<_EditAuthorContent>// ─── Quick Match Tab ────────────────────────────────────────Widget _buildQuickMatchTab(ColorScheme cs, TextTheme tt, AppLocalizations l) {+ final bookOrbit = context.read<AuthProvider>().isBookOrbit;return ListView(controller: widget.scrollController,padding: EdgeInsets.fromLTRB(20, 16, 20, 32 + MediaQuery.of(context).viewInsets.bottom + MediaQuery.of(context).viewPadding.bottom),@@ -324,7 +325,7 @@ class _EditAuthorContentState extends State<_EditAuthorContent>_searchField(_searchCtrl, l.authorName, Icons.person_rounded, cs, tt),const SizedBox(height: 10),Row(children: [- Expanded(+ if (bookOrbit) const Spacer() else Expanded(child: Container(height: 44,padding: const EdgeInsets.symmetric(horizontal: 12),@@ -465,6 +466,7 @@ class _EditAuthorContentState extends State<_EditAuthorContent>// ─── Custom Tab ─────────────────────────────────────────────Widget _buildCustomTab(ColorScheme cs, TextTheme tt, AppLocalizations l) {+ final bookOrbit = context.read<AuthProvider>().isBookOrbit;return Column(children: [Padding(padding: const EdgeInsets.fromLTRB(20, 8, 8, 0),@@ -486,7 +488,7 @@ class _EditAuthorContentState extends State<_EditAuthorContent>padding: EdgeInsets.fromLTRB(20, 0, 20, 32 + MediaQuery.of(context).viewInsets.bottom + MediaQuery.of(context).viewPadding.bottom),children: [_field(l.authorName, _nameCtrl, tt),- _field(l.asinLabel, _asinCtrl, tt),+ if (!bookOrbit) _field(l.asinLabel, _asinCtrl, tt),_field(l.descriptionLabel, _descCtrl, tt, maxLines: 6),const SizedBox(height: 12),Text(l.authorImage, style: tt.titleSmall?.copyWith(fontWeight: FontWeight.w600)),diff --git a/lib/widgets/edit_metadata_sheet.dart b/lib/widgets/edit_metadata_sheet.dartindex 0654402d..45a0d56a 100644--- a/lib/widgets/edit_metadata_sheet.dart+++ b/lib/widgets/edit_metadata_sheet.dart@@ -87,6 +87,17 @@ class _MetadataEditViewState extends State<MetadataEditView>bool _quickMatching = false;String _provider = 'audible';static const _providerKeys = ['audible', 'itunes', 'openlibrary'];+ // The server's own provider list, when it offers one (BookOrbit).+ List<Map<String, String>>? _serverProviders;++ Future<void> _loadServerProviders() async {+ final list = await context.read<AuthProvider>().apiService?.bookMatchProviders();+ if (!mounted || list == null || list.isEmpty) return;+ setState(() {+ _serverProviders = list;+ if (!list.any((p) => p['key'] == _provider)) _provider = list.first['key']!;+ });+ }String _providerLabel(AppLocalizations l, String key) {switch (key) {@@ -102,6 +113,32 @@ class _MetadataEditViewState extends State<MetadataEditView>List<String> _coverResults = [];bool _coverSearching = false;String _coverProvider = 'best';+ // BookOrbit keeps a square audiobook cover and a portrait book cover.+ List<String> _coverSlots = const [];+ String? _coverSlot;++ Future<void> _loadCoverSlots() async {+ final api = context.read<AuthProvider>().apiService;+ if (api == null || !api.isBookOrbit) return;+ final slots = await api.coverSlots(widget.itemId);+ final provider = await api.defaultCoverSearchProvider();+ if (!mounted) return;+ setState(() {+ _coverSlots = slots;+ _coverSlot = slots.contains('audio')+ ? 'audio'+ : slots.isNotEmpty+ ? slots.first+ : (widget.isEbookOnly ? 'ebook' : 'audio');+ _coverProvider = provider ?? 'duckduckgo';+ });+ }++ List<String> get _bookOrbitCoverProviders =>+ ['duckduckgo', 'itunes', if (_coverSlot != 'ebook') 'audiobookcovers', 'all'];++ String get _bookOrbitCoverProvider =>+ _bookOrbitCoverProviders.contains(_coverProvider) ? _coverProvider : 'duckduckgo';bool _saving = false;bool _explicit = false;bool _abridged = false;@@ -146,6 +183,8 @@ class _MetadataEditViewState extends State<MetadataEditView>unawaited(_restoreRunningTask());});_loadFilterSuggestions();+ _loadServerProviders();+ _loadCoverSlots();final m = widget.metadata;_titleCtrl = TextEditingController(text: m['title'] as String? ?? '');_subtitleCtrl = TextEditingController(text: m['subtitle'] as String? ?? '');@@ -430,7 +469,7 @@ class _MetadataEditViewState extends State<MetadataEditView>? _safeString(book['cover']): _safeString(book['image']);if (coverUrl.isNotEmpty) {- await api.updateItemCoverUrl(widget.itemId, coverUrl);+ await api.updateItemCoverUrl(widget.itemId, coverUrl, coverSlot: _coverSlot);}}@@ -616,9 +655,9 @@ class _MetadataEditViewState extends State<MetadataEditView>bool ok = await api.updateItemMedia(widget.itemId, update, tags: tags);if (ok && _coverFilePath != null) {- ok = await api.uploadItemCover(widget.itemId, _coverFilePath!);+ ok = await api.uploadItemCover(widget.itemId, _coverFilePath!, coverSlot: _coverSlot);} else if (ok && _coverUrlCtrl.text.trim().isNotEmpty) {- ok = await api.updateItemCoverUrl(widget.itemId, _coverUrlCtrl.text.trim());+ ok = await api.updateItemCoverUrl(widget.itemId, _coverUrlCtrl.text.trim(), coverSlot: _coverSlot);}if (!mounted) return;@@ -677,7 +716,7 @@ class _MetadataEditViewState extends State<MetadataEditView>final api = context.read<AuthProvider>().apiService;if (api == null) return;setState(() => _saving = true);- final ok = await api.removeItemCover(widget.itemId);+ final ok = await api.removeItemCover(widget.itemId, coverSlot: _coverSlot);if (!mounted) return;setState(() {_saving = false;@@ -1194,7 +1233,12 @@ class _MetadataEditViewState extends State<MetadataEditView>dropdownColor: cs.surfaceContainerHigh,style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant),icon: Icon(Icons.expand_more_rounded, size: 18, color: cs.onSurfaceVariant),- items: _providerKeys.map((k) => DropdownMenuItem(value: k, child: Text(_providerLabel(l, k)))).toList(),+ items: _serverProviders != null+ ? [+ for (final p in _serverProviders!)+ DropdownMenuItem(value: p['key'], child: Text(p['label'] ?? p['key']!)),+ ]+ : _providerKeys.map((k) => DropdownMenuItem(value: k, child: Text(_providerLabel(l, k)))).toList(),onChanged: (v) { if (v != null) setState(() => _provider = v); },),),@@ -1362,12 +1406,13 @@ class _MetadataEditViewState extends State<MetadataEditView>Widget _buildCustomTab(ColorScheme cs, TextTheme tt, AppLocalizations l) {final filePaths = fullLibraryFilePaths(widget.libraryFiles);+ final bookOrbit = context.read<AuthProvider>().isBookOrbit;return Column(children: [// Save button barPadding(padding: const EdgeInsets.fromLTRB(20, 8, 8, 0),child: Row(children: [- if (widget.isAdmin)+ if (widget.isAdmin || bookOrbit)OutlinedButton.icon(key: MetadataEditView.quickMatchButtonKey,onPressed: _saving || _quickMatching ? null : _runServerQuickMatch,@@ -1456,7 +1501,7 @@ class _MetadataEditViewState extends State<MetadataEditView>Expanded(child: _field(l.isbnLabel, _isbnCtrl, tt)),]),Row(children: [- Expanded(+ if (!bookOrbit) Expanded(child: InkWell(onTap: () => setState(() => _explicit = !_explicit),borderRadius: BorderRadius.circular(10),@@ -1469,7 +1514,7 @@ class _MetadataEditViewState extends State<MetadataEditView>]),),),- const SizedBox(width: 12),+ if (!bookOrbit) const SizedBox(width: 12),Expanded(child: InkWell(onTap: () => setState(() => _abridged = !_abridged),@@ -1507,8 +1552,12 @@ class _MetadataEditViewState extends State<MetadataEditView>// ─── Cover Tab ──────────────────────────────────────────────Widget _buildCoverTab(ColorScheme cs, TextTheme tt, AppLocalizations l) {+ final api = context.read<AuthProvider>().apiService;+ final bookOrbit = api?.isBookOrbit == true;final base = _safeBaseCoverUrl();- final coverUrl = base.isEmpty ? '' : '$base?v=$_coverVersion';+ final coverUrl = bookOrbit+ ? api!.getCoverUrl(widget.itemId, width: null, coverSlot: _coverSlot)+ : base.isEmpty ? '' : '$base?v=$_coverVersion';return Column(children: [Padding(padding: const EdgeInsets.fromLTRB(20, 8, 8, 0),@@ -1530,6 +1579,32 @@ class _MetadataEditViewState extends State<MetadataEditView>controller: _coverScroll,padding: const EdgeInsets.fromLTRB(20, 0, 20, 32),children: [+ if (_coverSlots.length > 1) ...[+ Center(+ child: SegmentedButton<String>(+ segments: [+ ButtonSegment(+ value: 'audio',+ icon: const Icon(Icons.crop_square_rounded),+ label: Text(l.coverSlotAudiobook),+ ),+ ButtonSegment(+ value: 'ebook',+ icon: const Icon(Icons.crop_portrait_rounded),+ label: Text(l.coverSlotBook),+ ),+ ],+ selected: {_coverSlot ?? 'audio'},+ onSelectionChanged: _saving+ ? null+ : (s) => setState(() {+ _coverSlot = s.first;+ _coverResults = [];+ }),+ ),+ ),+ const SizedBox(height: 12),+ ],Center(child: ClipRRect(borderRadius: BorderRadius.circular(12),@@ -1631,18 +1706,31 @@ class _MetadataEditViewState extends State<MetadataEditView>const SizedBox(height: 8),Row(children: [DropdownButton<String>(- value: _coverProvider,+ value: bookOrbit ? _bookOrbitCoverProvider : _coverProvider,onChanged: (v) => setState(() => _coverProvider = v ?? 'best'),- items: const [- DropdownMenuItem(value: 'best', child: Text('Best')),- DropdownMenuItem(value: 'all', child: Text('All')),- DropdownMenuItem(value: 'google', child: Text('Google')),- DropdownMenuItem(value: 'fantlab', child: Text('FantLab')),- DropdownMenuItem(value: 'audible', child: Text('Audible')),- DropdownMenuItem(value: 'itunes', child: Text('iTunes')),- DropdownMenuItem(value: 'openlibrary', child: Text('OpenLibrary')),- DropdownMenuItem(value: 'audiobookcovers', child: Text('AudiobookCovers.com')),- ],+ items: bookOrbit+ ? [+ for (final p in _bookOrbitCoverProviders)+ DropdownMenuItem(+ value: p,+ child: Text(switch (p) {+ 'duckduckgo' => 'DuckDuckGo',+ 'itunes' => 'iTunes',+ 'audiobookcovers' => 'AudiobookCovers.com',+ _ => 'All',+ }),+ ),+ ]+ : const [+ DropdownMenuItem(value: 'best', child: Text('Best')),+ DropdownMenuItem(value: 'all', child: Text('All')),+ DropdownMenuItem(value: 'google', child: Text('Google')),+ DropdownMenuItem(value: 'fantlab', child: Text('FantLab')),+ DropdownMenuItem(value: 'audible', child: Text('Audible')),+ DropdownMenuItem(value: 'itunes', child: Text('iTunes')),+ DropdownMenuItem(value: 'openlibrary', child: Text('OpenLibrary')),+ DropdownMenuItem(value: 'audiobookcovers', child: Text('AudiobookCovers.com')),+ ],),const Spacer(),FilledButton.tonalIcon(@@ -1661,7 +1749,7 @@ class _MetadataEditViewState extends State<MetadataEditView>crossAxisCount: 3,mainAxisSpacing: 8,crossAxisSpacing: 8,- childAspectRatio: 1.0,+ childAspectRatio: _coverSlot == 'ebook' ? 2 / 3 : 1.0,children: [for (final url in _coverResults)GestureDetector(@@ -1714,11 +1802,13 @@ class _MetadataEditViewState extends State<MetadataEditView>return;}final author = _coverSearchAuthorCtrl.text.trim();- final providers = switch (_coverProvider) {- 'best' => _bestCoverProviders,- 'all' => _allCoverProviders,- _ => [_coverProvider],- };+ final providers = api.isBookOrbit+ ? [_bookOrbitCoverProvider]+ : switch (_coverProvider) {+ 'best' => _bestCoverProviders,+ 'all' => _allCoverProviders,+ _ => [_coverProvider],+ };// Query one provider at a time and append results as they arrive, so a// slow provider can't time out the whole search and covers stream in.setState(() {@@ -1728,7 +1818,7 @@ class _MetadataEditViewState extends State<MetadataEditView>final seen = <String>{};for (final p in providers) {if (!mounted) return;- final results = await api.searchCovers(title, author: author, provider: p);+ final results = await api.searchCovers(title, author: author, provider: p, coverSlot: _coverSlot);if (!mounted) return;final fresh = results.where(seen.add).toList();if (fresh.isNotEmpty) setState(() => _coverResults = [..._coverResults, ...fresh]);@@ -1746,7 +1836,7 @@ class _MetadataEditViewState extends State<MetadataEditView>final api = context.read<AuthProvider>().apiService;if (api == null) return;setState(() => _saving = true);- final ok = await api.updateItemCoverUrl(widget.itemId, url);+ final ok = await api.updateItemCoverUrl(widget.itemId, url, coverSlot: _coverSlot);if (!mounted) return;if (ok) context.read<LibraryProvider>().refresh();setState(() {diff --git a/lib/widgets/library_search_results.dart b/lib/widgets/library_search_results.dartindex 95c0046e..7b4fccfd 100644--- a/lib/widgets/library_search_results.dart+++ b/lib/widgets/library_search_results.dart@@ -3,6 +3,7 @@ import 'package:cached_network_image/cached_network_image.dart';import 'package:provider/provider.dart';import '../l10n/app_localizations.dart';import 'cover_badges.dart';+import '../providers/auth_provider.dart';import '../providers/library_provider.dart';import '../services/audio_player_service.dart';import '../services/download_service.dart';@@ -45,7 +46,10 @@ class BookResultTile extends StatelessWidget {final isFinished = itemId != null && lib.getProgressData(itemId)?['isFinished'] == true;String? coverUrl;- if (itemId != null && serverUrl != null && token != null) {+ final bookOrbitApi = context.read<AuthProvider>().apiService;+ if (itemId != null && bookOrbitApi != null && bookOrbitApi.isBookOrbit) {+ coverUrl = lib.getCoverUrl(itemId, width: 200);+ } else if (itemId != null && serverUrl != null && token != null) {final cleanUrl = serverUrl!.endsWith('/')? serverUrl!.substring(0, serverUrl!.length - 1): serverUrl!;@@ -396,7 +400,10 @@ class AuthorResultTile extends StatelessWidget {final numBooks = author['numBooks'] as int?;String? imageUrl;- if (authorId.isNotEmpty && serverUrl != null && token != null) {+ final api = context.read<AuthProvider>().apiService;+ if (api != null && api.isBookOrbit) {+ if (author['imagePath'] != null) imageUrl = api.getAuthorImageUrl(authorId);+ } else if (authorId.isNotEmpty && serverUrl != null && token != null) {final cleanUrl = serverUrl!.endsWith('/')? serverUrl!.substring(0, serverUrl!.length - 1): serverUrl!;diff --git a/lib/widgets/library_sort_filter_sheet.dart b/lib/widgets/library_sort_filter_sheet.dartindex 7d79bf73..652c3f32 100644--- a/lib/widgets/library_sort_filter_sheet.dart+++ b/lib/widgets/library_sort_filter_sheet.dart@@ -402,7 +402,7 @@ class _SortFilterSheetState extends State<SortFilterSheet> with SingleTickerProv(LibrarySort.dateStarted, l.dateStarted, Icons.play_arrow_rounded),(LibrarySort.dateFinished, l.dateFinished, Icons.done_all_rounded),(LibrarySort.random, l.random, Icons.shuffle_rounded),- ];+ ]..removeWhere((o) => librarySortForServer(o.$1) != o.$1);if (widget.currentFilter == LibraryFilter.series &&widget.filterValue != null &&widget.filterValue != 'no-series') {@@ -452,6 +452,7 @@ class _SortFilterSheetState extends State<SortFilterSheet> with SingleTickerProv(LibraryFilter.explicit, l.explicitContent, Icons.explicit_rounded),);}+ filters.removeWhere((f) => !libraryFilterSupportedOnServer(f.$1));return ListView(padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),children: [@@ -554,7 +555,9 @@ class _SortFilterSheetState extends State<SortFilterSheet> with SingleTickerProvPadding(padding: const EdgeInsets.only(left: 16),child: Column(- children: MissingMetadataField.values.map((field) {+ children: MissingMetadataField.values+ .where(missingMetadataSupportedOnServer)+ .map((field) {final selected =widget.currentFilter == LibraryFilter.missingMetadata &&widget.missingMetadataFilter == field;diff --git a/pubspec.lock b/pubspec.lockindex b4b523dd..ef439145 100644--- a/pubspec.lock+++ b/pubspec.lock@@ -527,6 +527,14 @@ packages:url: "https://pub.dev"source: hostedversion: "3.4.2"+ flutter_svg:+ dependency: "direct main"+ description:+ name: flutter_svg+ sha256: "35882981abcbfb8c15b286f0cd690ff25bac12d95eff3e25ee207f37d4c42e7f"+ url: "https://pub.dev"+ source: hosted+ version: "2.3.0"flutter_test:dependency: "direct dev"description: flutter@@ -904,6 +912,14 @@ packages:url: "https://pub.dev"source: hostedversion: "1.9.1"+ path_parsing:+ dependency: transitive+ description:+ name: path_parsing+ sha256: "883402936929eac138ee0a45da5b0f2c80f89913e6dc3bf77eb65b84b409c6ca"+ url: "https://pub.dev"+ source: hosted+ version: "1.1.0"path_provider:dependency: "direct main"description:@@ -1541,6 +1557,30 @@ packages:url: "https://pub.dev"source: hostedversion: "4.5.2"+ vector_graphics:+ dependency: transitive+ description:+ name: vector_graphics+ sha256: "9d0e3b9cb16542ad660daee871e726a10d13a93b7b5391677c3160e8f5e83935"+ url: "https://pub.dev"+ source: hosted+ version: "1.2.3"+ vector_graphics_codec:+ dependency: transitive+ description:+ name: vector_graphics_codec+ sha256: "99fd9fbd34d9f9a32efd7b6a6aae14125d8237b10403b422a6a6dfeac2806146"+ url: "https://pub.dev"+ source: hosted+ version: "1.1.13"+ vector_graphics_compiler:+ dependency: transitive+ description:+ name: vector_graphics_compiler+ sha256: "4dca4feb77dc3ec7f6e27e49c53241eb8217f55e4f9b12599a27f8903bca5682"+ url: "https://pub.dev"+ source: hosted+ version: "1.3.0"vector_math:dependency: transitivedescription:diff --git a/pubspec.yaml b/pubspec.yamlindex e0a7d2fd..0fd696c7 100644--- a/pubspec.yaml+++ b/pubspec.yaml@@ -125,6 +125,7 @@ dependencies:# foliate-js host for MOBI/AZW3/FB2/CBZ (already transitive via the epub# viewer; pinned direct so the bridge API is a declared dependency)flutter_inappwebview: ^6.0.0+ flutter_svg: ^2.3.0dev_dependencies:flutter_test: