Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Add ReadMeABook API integration

Barnabasf6e041637c26
diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb
index 232a88e1..c68ed837 100644
--- a/lib/l10n/app_en.arb
+++ b/lib/l10n/app_en.arb
@@ -586,6 +586,69 @@
"adminRmabUrlHelpUser": "Get a login URL from your server admin. They generate one in RMAB > Admin > Users.",
"adminRmabSettingsInfo": "ReadMeABook is a self-hosted service for requesting and downloading audiobooks. It must be installed and set up by your server admin.",
+ "rmabConfigTitle": "Connect ReadMeABook",
+ "rmabConfigExplainerAdmin": "ReadMeABook is a self-hosted service for requesting audiobooks. Generate an API token in RMAB under Profile, API Tokens, then paste the server URL and token below. Absorb doesn't host or download any content, it just sends requests to your server.",
+ "rmabConfigExplainerUser": "ReadMeABook is a self-hosted service for requesting audiobooks. Ask your server admin for the RMAB URL and an API token. Absorb doesn't host or download any content, it just sends requests to your server.",
+ "rmabConfigLearnMore": "Learn more about ReadMeABook",
+ "rmabConfigBaseUrlLabel": "RMAB server URL",
+ "rmabConfigBaseUrlHint": "https://rmab.example.com",
+ "rmabConfigTokenLabel": "API token",
+ "rmabConfigTokenHint": "rmab_...",
+ "rmabConfigConnect": "Connect",
+ "rmabConfigDisconnect": "Disconnect",
+ "rmabConfigOpenWebView": "Open in browser view",
+ "rmabConfigConnectedAs": "Connected as {name}",
+ "@rmabConfigConnectedAs": { "placeholders": { "name": { "type": "String" } } },
+ "rmabConfigErrorInvalidUrl": "Enter a valid http(s) URL",
+ "rmabConfigErrorMissingToken": "Enter your API token",
+ "rmabConfigErrorUnauthorized": "Token rejected by server",
+ "rmabConfigErrorForbidden": "This token isn't allowed for that action",
+ "rmabConfigErrorNetwork": "Couldn't reach RMAB. Check the URL.",
+ "rmabConfigErrorGeneric": "Couldn't connect",
+ "rmabConfigSavedSnackbar": "ReadMeABook connected",
+ "rmabConfigDisconnectedSnackbar": "ReadMeABook disconnected",
+
+ "rmabRequestCta": "Request via ReadMeABook",
+ "rmabSearchHeader": "Request via ReadMeABook",
+ "rmabSearchHint": "Search by title or author",
+ "rmabSearchEmpty": "No matches on your ReadMeABook server",
+ "rmabSearchError": "Couldn't search ReadMeABook",
+ "rmabSearchPrompt": "Type a title or author to search",
+ "rmabSearchFooterPrompt": "Looking for something else?",
+ "rmabSearchFooterCta": "Search ReadMeABook for \"{query}\"",
+ "@rmabSearchFooterCta": { "placeholders": { "query": { "type": "String" } } },
+ "rmabBookDetailExplainer": "This request will be sent through your ReadMeABook server. The admin will review and process it. You can track it under My Requests on the ReadMeABook tile.",
+ "rmabBookAlreadyAvailable": "Already in your library",
+ "rmabBookAlreadyRequested": "Already requested",
+ "rmabRequestSubmitting": "Submitting…",
+ "rmabRequestSent": "Request sent",
+ "rmabRequestErrorAlreadyAvailable": "Already in your library",
+ "rmabRequestErrorBeingProcessed": "Already being processed",
+ "rmabRequestErrorDuplicate": "You've already requested this",
+ "rmabRequestErrorValidation": "Couldn't send the request",
+ "rmabRequestErrorUserNotFound": "Token user no longer exists. Reconnect ReadMeABook.",
+ "rmabRequestErrorIgnored": "This book is on your ignore list",
+ "rmabRequestErrorGeneric": "Couldn't send the request",
+ "rmabRequestErrorTokenRejected": "Token rejected by server. Reconnect ReadMeABook.",
+ "rmabMyRequestsTab": "My Requests",
+ "rmabSetupTab": "Setup",
+ "rmabMyRequestsEmpty": "You haven't requested any books yet",
+ "rmabMyRequestsError": "Couldn't load requests",
+ "rmabMyRequestsRefresh": "Refresh",
+ "rmabRequestDetailTitle": "Request details",
+ "rmabRequestDetailStatus": "Status",
+ "rmabRequestDetailRequestedOn": "Requested on",
+ "rmabRequestDetailCompletedOn": "Completed on",
+ "rmabRequestDetailProgress": "Progress",
+ "rmabStatusActive": "In progress",
+ "rmabStatusWaiting": "Waiting",
+ "rmabStatusAvailable": "Available",
+ "rmabStatusDownloaded": "Downloaded",
+ "rmabStatusFailed": "Failed",
+ "rmabStatusCancelled": "Cancelled",
+ "rmabStatusDenied": "Denied",
+ "rmabStatusUnknown": "Unknown",
+
"narratedBy": "Narrated by {narrator}",
"@narratedBy": { "placeholders": { "narrator": { "type": "String" } } },
"onAudible": "on Audible",
diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart
index 9aeb4578..da9e6691 100644
--- a/lib/l10n/app_localizations.dart
+++ b/lib/l10n/app_localizations.dart
@@ -3166,6 +3166,360 @@ abstract class AppLocalizations {
/// **'ReadMeABook is a self-hosted service for requesting and downloading audiobooks. It must be installed and set up by your server admin.'**
String get adminRmabSettingsInfo;
+ /// No description provided for @rmabConfigTitle.
+ ///
+ /// In en, this message translates to:
+ /// **'Connect ReadMeABook'**
+ String get rmabConfigTitle;
+
+ /// No description provided for @rmabConfigExplainerAdmin.
+ ///
+ /// In en, this message translates to:
+ /// **'ReadMeABook is a self-hosted service for requesting audiobooks. Generate an API token in RMAB under Profile, API Tokens, then paste the server URL and token below. Absorb doesn\'t host or download any content, it just sends requests to your server.'**
+ String get rmabConfigExplainerAdmin;
+
+ /// No description provided for @rmabConfigExplainerUser.
+ ///
+ /// In en, this message translates to:
+ /// **'ReadMeABook is a self-hosted service for requesting audiobooks. Ask your server admin for the RMAB URL and an API token. Absorb doesn\'t host or download any content, it just sends requests to your server.'**
+ String get rmabConfigExplainerUser;
+
+ /// No description provided for @rmabConfigLearnMore.
+ ///
+ /// In en, this message translates to:
+ /// **'Learn more about ReadMeABook'**
+ String get rmabConfigLearnMore;
+
+ /// No description provided for @rmabConfigBaseUrlLabel.
+ ///
+ /// In en, this message translates to:
+ /// **'RMAB server URL'**
+ String get rmabConfigBaseUrlLabel;
+
+ /// No description provided for @rmabConfigBaseUrlHint.
+ ///
+ /// In en, this message translates to:
+ /// **'https://rmab.example.com'**
+ String get rmabConfigBaseUrlHint;
+
+ /// No description provided for @rmabConfigTokenLabel.
+ ///
+ /// In en, this message translates to:
+ /// **'API token'**
+ String get rmabConfigTokenLabel;
+
+ /// No description provided for @rmabConfigTokenHint.
+ ///
+ /// In en, this message translates to:
+ /// **'rmab_...'**
+ String get rmabConfigTokenHint;
+
+ /// No description provided for @rmabConfigConnect.
+ ///
+ /// In en, this message translates to:
+ /// **'Connect'**
+ String get rmabConfigConnect;
+
+ /// No description provided for @rmabConfigDisconnect.
+ ///
+ /// In en, this message translates to:
+ /// **'Disconnect'**
+ String get rmabConfigDisconnect;
+
+ /// No description provided for @rmabConfigOpenWebView.
+ ///
+ /// In en, this message translates to:
+ /// **'Open in browser view'**
+ String get rmabConfigOpenWebView;
+
+ /// No description provided for @rmabConfigConnectedAs.
+ ///
+ /// In en, this message translates to:
+ /// **'Connected as {name}'**
+ String rmabConfigConnectedAs(String name);
+
+ /// No description provided for @rmabConfigErrorInvalidUrl.
+ ///
+ /// In en, this message translates to:
+ /// **'Enter a valid http(s) URL'**
+ String get rmabConfigErrorInvalidUrl;
+
+ /// No description provided for @rmabConfigErrorMissingToken.
+ ///
+ /// In en, this message translates to:
+ /// **'Enter your API token'**
+ String get rmabConfigErrorMissingToken;
+
+ /// No description provided for @rmabConfigErrorUnauthorized.
+ ///
+ /// In en, this message translates to:
+ /// **'Token rejected by server'**
+ String get rmabConfigErrorUnauthorized;
+
+ /// No description provided for @rmabConfigErrorForbidden.
+ ///
+ /// In en, this message translates to:
+ /// **'This token isn\'t allowed for that action'**
+ String get rmabConfigErrorForbidden;
+
+ /// No description provided for @rmabConfigErrorNetwork.
+ ///
+ /// In en, this message translates to:
+ /// **'Couldn\'t reach RMAB. Check the URL.'**
+ String get rmabConfigErrorNetwork;
+
+ /// No description provided for @rmabConfigErrorGeneric.
+ ///
+ /// In en, this message translates to:
+ /// **'Couldn\'t connect'**
+ String get rmabConfigErrorGeneric;
+
+ /// No description provided for @rmabConfigSavedSnackbar.
+ ///
+ /// In en, this message translates to:
+ /// **'ReadMeABook connected'**
+ String get rmabConfigSavedSnackbar;
+
+ /// No description provided for @rmabConfigDisconnectedSnackbar.
+ ///
+ /// In en, this message translates to:
+ /// **'ReadMeABook disconnected'**
+ String get rmabConfigDisconnectedSnackbar;
+
+ /// No description provided for @rmabRequestCta.
+ ///
+ /// In en, this message translates to:
+ /// **'Request via ReadMeABook'**
+ String get rmabRequestCta;
+
+ /// No description provided for @rmabSearchHeader.
+ ///
+ /// In en, this message translates to:
+ /// **'Request via ReadMeABook'**
+ String get rmabSearchHeader;
+
+ /// No description provided for @rmabSearchHint.
+ ///
+ /// In en, this message translates to:
+ /// **'Search by title or author'**
+ String get rmabSearchHint;
+
+ /// No description provided for @rmabSearchEmpty.
+ ///
+ /// In en, this message translates to:
+ /// **'No matches on your ReadMeABook server'**
+ String get rmabSearchEmpty;
+
+ /// No description provided for @rmabSearchError.
+ ///
+ /// In en, this message translates to:
+ /// **'Couldn\'t search ReadMeABook'**
+ String get rmabSearchError;
+
+ /// No description provided for @rmabSearchPrompt.
+ ///
+ /// In en, this message translates to:
+ /// **'Type a title or author to search'**
+ String get rmabSearchPrompt;
+
+ /// No description provided for @rmabSearchFooterPrompt.
+ ///
+ /// In en, this message translates to:
+ /// **'Looking for something else?'**
+ String get rmabSearchFooterPrompt;
+
+ /// No description provided for @rmabSearchFooterCta.
+ ///
+ /// In en, this message translates to:
+ /// **'Search ReadMeABook for \"{query}\"'**
+ String rmabSearchFooterCta(String query);
+
+ /// No description provided for @rmabBookDetailExplainer.
+ ///
+ /// In en, this message translates to:
+ /// **'This request will be sent through your ReadMeABook server. The admin will review and process it. You can track it under My Requests on the ReadMeABook tile.'**
+ String get rmabBookDetailExplainer;
+
+ /// No description provided for @rmabBookAlreadyAvailable.
+ ///
+ /// In en, this message translates to:
+ /// **'Already in your library'**
+ String get rmabBookAlreadyAvailable;
+
+ /// No description provided for @rmabBookAlreadyRequested.
+ ///
+ /// In en, this message translates to:
+ /// **'Already requested'**
+ String get rmabBookAlreadyRequested;
+
+ /// No description provided for @rmabRequestSubmitting.
+ ///
+ /// In en, this message translates to:
+ /// **'Submitting…'**
+ String get rmabRequestSubmitting;
+
+ /// No description provided for @rmabRequestSent.
+ ///
+ /// In en, this message translates to:
+ /// **'Request sent'**
+ String get rmabRequestSent;
+
+ /// No description provided for @rmabRequestErrorAlreadyAvailable.
+ ///
+ /// In en, this message translates to:
+ /// **'Already in your library'**
+ String get rmabRequestErrorAlreadyAvailable;
+
+ /// No description provided for @rmabRequestErrorBeingProcessed.
+ ///
+ /// In en, this message translates to:
+ /// **'Already being processed'**
+ String get rmabRequestErrorBeingProcessed;
+
+ /// No description provided for @rmabRequestErrorDuplicate.
+ ///
+ /// In en, this message translates to:
+ /// **'You\'ve already requested this'**
+ String get rmabRequestErrorDuplicate;
+
+ /// No description provided for @rmabRequestErrorValidation.
+ ///
+ /// In en, this message translates to:
+ /// **'Couldn\'t send the request'**
+ String get rmabRequestErrorValidation;
+
+ /// No description provided for @rmabRequestErrorUserNotFound.
+ ///
+ /// In en, this message translates to:
+ /// **'Token user no longer exists. Reconnect ReadMeABook.'**
+ String get rmabRequestErrorUserNotFound;
+
+ /// No description provided for @rmabRequestErrorIgnored.
+ ///
+ /// In en, this message translates to:
+ /// **'This book is on your ignore list'**
+ String get rmabRequestErrorIgnored;
+
+ /// No description provided for @rmabRequestErrorGeneric.
+ ///
+ /// In en, this message translates to:
+ /// **'Couldn\'t send the request'**
+ String get rmabRequestErrorGeneric;
+
+ /// No description provided for @rmabRequestErrorTokenRejected.
+ ///
+ /// In en, this message translates to:
+ /// **'Token rejected by server. Reconnect ReadMeABook.'**
+ String get rmabRequestErrorTokenRejected;
+
+ /// No description provided for @rmabMyRequestsTab.
+ ///
+ /// In en, this message translates to:
+ /// **'My Requests'**
+ String get rmabMyRequestsTab;
+
+ /// No description provided for @rmabSetupTab.
+ ///
+ /// In en, this message translates to:
+ /// **'Setup'**
+ String get rmabSetupTab;
+
+ /// No description provided for @rmabMyRequestsEmpty.
+ ///
+ /// In en, this message translates to:
+ /// **'You haven\'t requested any books yet'**
+ String get rmabMyRequestsEmpty;
+
+ /// No description provided for @rmabMyRequestsError.
+ ///
+ /// In en, this message translates to:
+ /// **'Couldn\'t load requests'**
+ String get rmabMyRequestsError;
+
+ /// No description provided for @rmabMyRequestsRefresh.
+ ///
+ /// In en, this message translates to:
+ /// **'Refresh'**
+ String get rmabMyRequestsRefresh;
+
+ /// No description provided for @rmabRequestDetailTitle.
+ ///
+ /// In en, this message translates to:
+ /// **'Request details'**
+ String get rmabRequestDetailTitle;
+
+ /// No description provided for @rmabRequestDetailStatus.
+ ///
+ /// In en, this message translates to:
+ /// **'Status'**
+ String get rmabRequestDetailStatus;
+
+ /// No description provided for @rmabRequestDetailRequestedOn.
+ ///
+ /// In en, this message translates to:
+ /// **'Requested on'**
+ String get rmabRequestDetailRequestedOn;
+
+ /// No description provided for @rmabRequestDetailCompletedOn.
+ ///
+ /// In en, this message translates to:
+ /// **'Completed on'**
+ String get rmabRequestDetailCompletedOn;
+
+ /// No description provided for @rmabRequestDetailProgress.
+ ///
+ /// In en, this message translates to:
+ /// **'Progress'**
+ String get rmabRequestDetailProgress;
+
+ /// No description provided for @rmabStatusActive.
+ ///
+ /// In en, this message translates to:
+ /// **'In progress'**
+ String get rmabStatusActive;
+
+ /// No description provided for @rmabStatusWaiting.
+ ///
+ /// In en, this message translates to:
+ /// **'Waiting'**
+ String get rmabStatusWaiting;
+
+ /// No description provided for @rmabStatusAvailable.
+ ///
+ /// In en, this message translates to:
+ /// **'Available'**
+ String get rmabStatusAvailable;
+
+ /// No description provided for @rmabStatusDownloaded.
+ ///
+ /// In en, this message translates to:
+ /// **'Downloaded'**
+ String get rmabStatusDownloaded;
+
+ /// No description provided for @rmabStatusFailed.
+ ///
+ /// In en, this message translates to:
+ /// **'Failed'**
+ String get rmabStatusFailed;
+
+ /// No description provided for @rmabStatusCancelled.
+ ///
+ /// In en, this message translates to:
+ /// **'Cancelled'**
+ String get rmabStatusCancelled;
+
+ /// No description provided for @rmabStatusDenied.
+ ///
+ /// In en, this message translates to:
+ /// **'Denied'**
+ String get rmabStatusDenied;
+
+ /// No description provided for @rmabStatusUnknown.
+ ///
+ /// In en, this message translates to:
+ /// **'Unknown'**
+ String get rmabStatusUnknown;
+
/// No description provided for @narratedBy.
///
/// In en, this message translates to:
diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart
index cf7e727d..fd8e7801 100644
--- a/lib/l10n/app_localizations_de.dart
+++ b/lib/l10n/app_localizations_de.dart
@@ -1732,6 +1732,193 @@ class AppLocalizationsDe extends AppLocalizations {
String get adminRmabSettingsInfo =>
'ReadMeABook ist ein selbst gehosteter Dienst zum Anfordern und Herunterladen von Hörbüchern. Es muss von deinem Server-Admin installiert und eingerichtet werden.';
+ @override
+ String get rmabConfigTitle => 'Connect ReadMeABook';
+
+ @override
+ String get rmabConfigExplainerAdmin =>
+ 'ReadMeABook is a self-hosted service for requesting audiobooks. Generate an API token in RMAB under Profile, API Tokens, then paste the server URL and token below. Absorb doesn\'t host or download any content, it just sends requests to your server.';
+
+ @override
+ String get rmabConfigExplainerUser =>
+ 'ReadMeABook is a self-hosted service for requesting audiobooks. Ask your server admin for the RMAB URL and an API token. Absorb doesn\'t host or download any content, it just sends requests to your server.';
+
+ @override
+ String get rmabConfigLearnMore => 'Learn more about ReadMeABook';
+
+ @override
+ String get rmabConfigBaseUrlLabel => 'RMAB server URL';
+
+ @override
+ String get rmabConfigBaseUrlHint => 'https://rmab.example.com';
+
+ @override
+ String get rmabConfigTokenLabel => 'API token';
+
+ @override
+ String get rmabConfigTokenHint => 'rmab_...';
+
+ @override
+ String get rmabConfigConnect => 'Connect';
+
+ @override
+ String get rmabConfigDisconnect => 'Disconnect';
+
+ @override
+ String get rmabConfigOpenWebView => 'Open in browser view';
+
+ @override
+ String rmabConfigConnectedAs(String name) {
+ return 'Connected as $name';
+ }
+
+ @override
+ String get rmabConfigErrorInvalidUrl => 'Enter a valid http(s) URL';
+
+ @override
+ String get rmabConfigErrorMissingToken => 'Enter your API token';
+
+ @override
+ String get rmabConfigErrorUnauthorized => 'Token rejected by server';
+
+ @override
+ String get rmabConfigErrorForbidden =>
+ 'This token isn\'t allowed for that action';
+
+ @override
+ String get rmabConfigErrorNetwork => 'Couldn\'t reach RMAB. Check the URL.';
+
+ @override
+ String get rmabConfigErrorGeneric => 'Couldn\'t connect';
+
+ @override
+ String get rmabConfigSavedSnackbar => 'ReadMeABook connected';
+
+ @override
+ String get rmabConfigDisconnectedSnackbar => 'ReadMeABook disconnected';
+
+ @override
+ String get rmabRequestCta => 'Request via ReadMeABook';
+
+ @override
+ String get rmabSearchHeader => 'Request via ReadMeABook';
+
+ @override
+ String get rmabSearchHint => 'Search by title or author';
+
+ @override
+ String get rmabSearchEmpty => 'No matches on your ReadMeABook server';
+
+ @override
+ String get rmabSearchError => 'Couldn\'t search ReadMeABook';
+
+ @override
+ String get rmabSearchPrompt => 'Type a title or author to search';
+
+ @override
+ String get rmabSearchFooterPrompt => 'Looking for something else?';
+
+ @override
+ String rmabSearchFooterCta(String query) {
+ return 'Search ReadMeABook for \"$query\"';
+ }
+
+ @override
+ String get rmabBookDetailExplainer =>
+ 'This request will be sent through your ReadMeABook server. The admin will review and process it. You can track it under My Requests on the ReadMeABook tile.';
+
+ @override
+ String get rmabBookAlreadyAvailable => 'Already in your library';
+
+ @override
+ String get rmabBookAlreadyRequested => 'Already requested';
+
+ @override
+ String get rmabRequestSubmitting => 'Submitting…';
+
+ @override
+ String get rmabRequestSent => 'Request sent';
+
+ @override
+ String get rmabRequestErrorAlreadyAvailable => 'Already in your library';
+
+ @override
+ String get rmabRequestErrorBeingProcessed => 'Already being processed';
+
+ @override
+ String get rmabRequestErrorDuplicate => 'You\'ve already requested this';
+
+ @override
+ String get rmabRequestErrorValidation => 'Couldn\'t send the request';
+
+ @override
+ String get rmabRequestErrorUserNotFound =>
+ 'Token user no longer exists. Reconnect ReadMeABook.';
+
+ @override
+ String get rmabRequestErrorIgnored => 'This book is on your ignore list';
+
+ @override
+ String get rmabRequestErrorGeneric => 'Couldn\'t send the request';
+
+ @override
+ String get rmabRequestErrorTokenRejected =>
+ 'Token rejected by server. Reconnect ReadMeABook.';
+
+ @override
+ String get rmabMyRequestsTab => 'My Requests';
+
+ @override
+ String get rmabSetupTab => 'Setup';
+
+ @override
+ String get rmabMyRequestsEmpty => 'You haven\'t requested any books yet';
+
+ @override
+ String get rmabMyRequestsError => 'Couldn\'t load requests';
+
+ @override
+ String get rmabMyRequestsRefresh => 'Refresh';
+
+ @override
+ String get rmabRequestDetailTitle => 'Request details';
+
+ @override
+ String get rmabRequestDetailStatus => 'Status';
+
+ @override
+ String get rmabRequestDetailRequestedOn => 'Requested on';
+
+ @override
+ String get rmabRequestDetailCompletedOn => 'Completed on';
+
+ @override
+ String get rmabRequestDetailProgress => 'Progress';
+
+ @override
+ String get rmabStatusActive => 'In progress';
+
+ @override
+ String get rmabStatusWaiting => 'Waiting';
+
+ @override
+ String get rmabStatusAvailable => 'Available';
+
+ @override
+ String get rmabStatusDownloaded => 'Downloaded';
+
+ @override
+ String get rmabStatusFailed => 'Failed';
+
+ @override
+ String get rmabStatusCancelled => 'Cancelled';
+
+ @override
+ String get rmabStatusDenied => 'Denied';
+
+ @override
+ String get rmabStatusUnknown => 'Unknown';
+
@override
String narratedBy(String narrator) {
return 'Gesprochen von $narrator';
diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart
index 1911e215..b0626fae 100644
--- a/lib/l10n/app_localizations_en.dart
+++ b/lib/l10n/app_localizations_en.dart
@@ -1713,6 +1713,193 @@ class AppLocalizationsEn extends AppLocalizations {
String get adminRmabSettingsInfo =>
'ReadMeABook is a self-hosted service for requesting and downloading audiobooks. It must be installed and set up by your server admin.';
+ @override
+ String get rmabConfigTitle => 'Connect ReadMeABook';
+
+ @override
+ String get rmabConfigExplainerAdmin =>
+ 'ReadMeABook is a self-hosted service for requesting audiobooks. Generate an API token in RMAB under Profile, API Tokens, then paste the server URL and token below. Absorb doesn\'t host or download any content, it just sends requests to your server.';
+
+ @override
+ String get rmabConfigExplainerUser =>
+ 'ReadMeABook is a self-hosted service for requesting audiobooks. Ask your server admin for the RMAB URL and an API token. Absorb doesn\'t host or download any content, it just sends requests to your server.';
+
+ @override
+ String get rmabConfigLearnMore => 'Learn more about ReadMeABook';
+
+ @override
+ String get rmabConfigBaseUrlLabel => 'RMAB server URL';
+
+ @override
+ String get rmabConfigBaseUrlHint => 'https://rmab.example.com';
+
+ @override
+ String get rmabConfigTokenLabel => 'API token';
+
+ @override
+ String get rmabConfigTokenHint => 'rmab_...';
+
+ @override
+ String get rmabConfigConnect => 'Connect';
+
+ @override
+ String get rmabConfigDisconnect => 'Disconnect';
+
+ @override
+ String get rmabConfigOpenWebView => 'Open in browser view';
+
+ @override
+ String rmabConfigConnectedAs(String name) {
+ return 'Connected as $name';
+ }
+
+ @override
+ String get rmabConfigErrorInvalidUrl => 'Enter a valid http(s) URL';
+
+ @override
+ String get rmabConfigErrorMissingToken => 'Enter your API token';
+
+ @override
+ String get rmabConfigErrorUnauthorized => 'Token rejected by server';
+
+ @override
+ String get rmabConfigErrorForbidden =>
+ 'This token isn\'t allowed for that action';
+
+ @override
+ String get rmabConfigErrorNetwork => 'Couldn\'t reach RMAB. Check the URL.';
+
+ @override
+ String get rmabConfigErrorGeneric => 'Couldn\'t connect';
+
+ @override
+ String get rmabConfigSavedSnackbar => 'ReadMeABook connected';
+
+ @override
+ String get rmabConfigDisconnectedSnackbar => 'ReadMeABook disconnected';
+
+ @override
+ String get rmabRequestCta => 'Request via ReadMeABook';
+
+ @override
+ String get rmabSearchHeader => 'Request via ReadMeABook';
+
+ @override
+ String get rmabSearchHint => 'Search by title or author';
+
+ @override
+ String get rmabSearchEmpty => 'No matches on your ReadMeABook server';
+
+ @override
+ String get rmabSearchError => 'Couldn\'t search ReadMeABook';
+
+ @override
+ String get rmabSearchPrompt => 'Type a title or author to search';
+
+ @override
+ String get rmabSearchFooterPrompt => 'Looking for something else?';
+
+ @override
+ String rmabSearchFooterCta(String query) {
+ return 'Search ReadMeABook for \"$query\"';
+ }
+
+ @override
+ String get rmabBookDetailExplainer =>
+ 'This request will be sent through your ReadMeABook server. The admin will review and process it. You can track it under My Requests on the ReadMeABook tile.';
+
+ @override
+ String get rmabBookAlreadyAvailable => 'Already in your library';
+
+ @override
+ String get rmabBookAlreadyRequested => 'Already requested';
+
+ @override
+ String get rmabRequestSubmitting => 'Submitting…';
+
+ @override
+ String get rmabRequestSent => 'Request sent';
+
+ @override
+ String get rmabRequestErrorAlreadyAvailable => 'Already in your library';
+
+ @override
+ String get rmabRequestErrorBeingProcessed => 'Already being processed';
+
+ @override
+ String get rmabRequestErrorDuplicate => 'You\'ve already requested this';
+
+ @override
+ String get rmabRequestErrorValidation => 'Couldn\'t send the request';
+
+ @override
+ String get rmabRequestErrorUserNotFound =>
+ 'Token user no longer exists. Reconnect ReadMeABook.';
+
+ @override
+ String get rmabRequestErrorIgnored => 'This book is on your ignore list';
+
+ @override
+ String get rmabRequestErrorGeneric => 'Couldn\'t send the request';
+
+ @override
+ String get rmabRequestErrorTokenRejected =>
+ 'Token rejected by server. Reconnect ReadMeABook.';
+
+ @override
+ String get rmabMyRequestsTab => 'My Requests';
+
+ @override
+ String get rmabSetupTab => 'Setup';
+
+ @override
+ String get rmabMyRequestsEmpty => 'You haven\'t requested any books yet';
+
+ @override
+ String get rmabMyRequestsError => 'Couldn\'t load requests';
+
+ @override
+ String get rmabMyRequestsRefresh => 'Refresh';
+
+ @override
+ String get rmabRequestDetailTitle => 'Request details';
+
+ @override
+ String get rmabRequestDetailStatus => 'Status';
+
+ @override
+ String get rmabRequestDetailRequestedOn => 'Requested on';
+
+ @override
+ String get rmabRequestDetailCompletedOn => 'Completed on';
+
+ @override
+ String get rmabRequestDetailProgress => 'Progress';
+
+ @override
+ String get rmabStatusActive => 'In progress';
+
+ @override
+ String get rmabStatusWaiting => 'Waiting';
+
+ @override
+ String get rmabStatusAvailable => 'Available';
+
+ @override
+ String get rmabStatusDownloaded => 'Downloaded';
+
+ @override
+ String get rmabStatusFailed => 'Failed';
+
+ @override
+ String get rmabStatusCancelled => 'Cancelled';
+
+ @override
+ String get rmabStatusDenied => 'Denied';
+
+ @override
+ String get rmabStatusUnknown => 'Unknown';
+
@override
String narratedBy(String narrator) {
return 'Narrated by $narrator';
diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart
index b3dd44f8..64336a91 100644
--- a/lib/l10n/app_localizations_zh.dart
+++ b/lib/l10n/app_localizations_zh.dart
@@ -1650,6 +1650,193 @@ class AppLocalizationsZh extends AppLocalizations {
String get adminRmabSettingsInfo =>
'ReadMeABook 是一个用于请求和下载有声书的自托管服务,需要由您的服务器管理员安装和设置。';
+ @override
+ String get rmabConfigTitle => 'Connect ReadMeABook';
+
+ @override
+ String get rmabConfigExplainerAdmin =>
+ 'ReadMeABook is a self-hosted service for requesting audiobooks. Generate an API token in RMAB under Profile, API Tokens, then paste the server URL and token below. Absorb doesn\'t host or download any content, it just sends requests to your server.';
+
+ @override
+ String get rmabConfigExplainerUser =>
+ 'ReadMeABook is a self-hosted service for requesting audiobooks. Ask your server admin for the RMAB URL and an API token. Absorb doesn\'t host or download any content, it just sends requests to your server.';
+
+ @override
+ String get rmabConfigLearnMore => 'Learn more about ReadMeABook';
+
+ @override
+ String get rmabConfigBaseUrlLabel => 'RMAB server URL';
+
+ @override
+ String get rmabConfigBaseUrlHint => 'https://rmab.example.com';
+
+ @override
+ String get rmabConfigTokenLabel => 'API token';
+
+ @override
+ String get rmabConfigTokenHint => 'rmab_...';
+
+ @override
+ String get rmabConfigConnect => 'Connect';
+
+ @override
+ String get rmabConfigDisconnect => 'Disconnect';
+
+ @override
+ String get rmabConfigOpenWebView => 'Open in browser view';
+
+ @override
+ String rmabConfigConnectedAs(String name) {
+ return 'Connected as $name';
+ }
+
+ @override
+ String get rmabConfigErrorInvalidUrl => 'Enter a valid http(s) URL';
+
+ @override
+ String get rmabConfigErrorMissingToken => 'Enter your API token';
+
+ @override
+ String get rmabConfigErrorUnauthorized => 'Token rejected by server';
+
+ @override
+ String get rmabConfigErrorForbidden =>
+ 'This token isn\'t allowed for that action';
+
+ @override
+ String get rmabConfigErrorNetwork => 'Couldn\'t reach RMAB. Check the URL.';
+
+ @override
+ String get rmabConfigErrorGeneric => 'Couldn\'t connect';
+
+ @override
+ String get rmabConfigSavedSnackbar => 'ReadMeABook connected';
+
+ @override
+ String get rmabConfigDisconnectedSnackbar => 'ReadMeABook disconnected';
+
+ @override
+ String get rmabRequestCta => 'Request via ReadMeABook';
+
+ @override
+ String get rmabSearchHeader => 'Request via ReadMeABook';
+
+ @override
+ String get rmabSearchHint => 'Search by title or author';
+
+ @override
+ String get rmabSearchEmpty => 'No matches on your ReadMeABook server';
+
+ @override
+ String get rmabSearchError => 'Couldn\'t search ReadMeABook';
+
+ @override
+ String get rmabSearchPrompt => 'Type a title or author to search';
+
+ @override
+ String get rmabSearchFooterPrompt => 'Looking for something else?';
+
+ @override
+ String rmabSearchFooterCta(String query) {
+ return 'Search ReadMeABook for \"$query\"';
+ }
+
+ @override
+ String get rmabBookDetailExplainer =>
+ 'This request will be sent through your ReadMeABook server. The admin will review and process it. You can track it under My Requests on the ReadMeABook tile.';
+
+ @override
+ String get rmabBookAlreadyAvailable => 'Already in your library';
+
+ @override
+ String get rmabBookAlreadyRequested => 'Already requested';
+
+ @override
+ String get rmabRequestSubmitting => 'Submitting…';
+
+ @override
+ String get rmabRequestSent => 'Request sent';
+
+ @override
+ String get rmabRequestErrorAlreadyAvailable => 'Already in your library';
+
+ @override
+ String get rmabRequestErrorBeingProcessed => 'Already being processed';
+
+ @override
+ String get rmabRequestErrorDuplicate => 'You\'ve already requested this';
+
+ @override
+ String get rmabRequestErrorValidation => 'Couldn\'t send the request';
+
+ @override
+ String get rmabRequestErrorUserNotFound =>
+ 'Token user no longer exists. Reconnect ReadMeABook.';
+
+ @override
+ String get rmabRequestErrorIgnored => 'This book is on your ignore list';
+
+ @override
+ String get rmabRequestErrorGeneric => 'Couldn\'t send the request';
+
+ @override
+ String get rmabRequestErrorTokenRejected =>
+ 'Token rejected by server. Reconnect ReadMeABook.';
+
+ @override
+ String get rmabMyRequestsTab => 'My Requests';
+
+ @override
+ String get rmabSetupTab => 'Setup';
+
+ @override
+ String get rmabMyRequestsEmpty => 'You haven\'t requested any books yet';
+
+ @override
+ String get rmabMyRequestsError => 'Couldn\'t load requests';
+
+ @override
+ String get rmabMyRequestsRefresh => 'Refresh';
+
+ @override
+ String get rmabRequestDetailTitle => 'Request details';
+
+ @override
+ String get rmabRequestDetailStatus => 'Status';
+
+ @override
+ String get rmabRequestDetailRequestedOn => 'Requested on';
+
+ @override
+ String get rmabRequestDetailCompletedOn => 'Completed on';
+
+ @override
+ String get rmabRequestDetailProgress => 'Progress';
+
+ @override
+ String get rmabStatusActive => 'In progress';
+
+ @override
+ String get rmabStatusWaiting => 'Waiting';
+
+ @override
+ String get rmabStatusAvailable => 'Available';
+
+ @override
+ String get rmabStatusDownloaded => 'Downloaded';
+
+ @override
+ String get rmabStatusFailed => 'Failed';
+
+ @override
+ String get rmabStatusCancelled => 'Cancelled';
+
+ @override
+ String get rmabStatusDenied => 'Denied';
+
+ @override
+ String get rmabStatusUnknown => 'Unknown';
+
@override
String narratedBy(String narrator) {
return '朗读者: $narrator';
diff --git a/lib/screens/admin_screen.dart b/lib/screens/admin_screen.dart
index 492af5ff..4badc246 100644
--- a/lib/screens/admin_screen.dart
+++ b/lib/screens/admin_screen.dart
@@ -3,12 +3,10 @@ import 'package:provider/provider.dart';
import '../providers/auth_provider.dart';
import '../services/scoped_prefs.dart';
import '../widgets/absorb_page_header.dart';
+import '../widgets/rmab_config_sheet.dart';
import '../l10n/app_localizations.dart';
import 'admin_users_screen.dart';
import 'admin_podcasts_screen.dart';
-import 'admin_rmab_screen.dart';
-
-const _kRmabUrlKey = 'rmab_url';
class AdminScreen extends StatefulWidget {
const AdminScreen({super.key});
@@ -24,7 +22,8 @@ class _AdminScreenState extends State<AdminScreen> {
List<dynamic> _sessions = [];
final Map<String, Map<String, dynamic>> _libraryStats = {};
String? _serverVersion;
- String? _rmabUrl;
+ String? _rmabBaseUrl;
+ String? _rmabApiToken;
final Set<String> _scanningLibraries = {};
final Set<String> _matchingLibraries = {};
@@ -56,11 +55,13 @@ class _AdminScreenState extends State<AdminScreen> {
if (stats != null) _libraryStats[id] = stats;
}
}
- _rmabUrl = await ScopedPrefs.getString(_kRmabUrlKey);
+ _rmabBaseUrl = await ScopedPrefs.getString(kRmabBaseUrlKey);
+ _rmabApiToken = await ScopedPrefs.getString(kRmabApiTokenKey);
if (mounted) setState(() => _loading = false);
}
- bool get _hasRmab => (_rmabUrl ?? '').isNotEmpty;
+ bool get _hasRmab =>
+ (_rmabBaseUrl ?? '').isNotEmpty && (_rmabApiToken ?? '').isNotEmpty;
bool get _hasPodcastLibrary => _libraries.any((l) => l['mediaType'] == 'podcast');
@@ -217,8 +218,7 @@ class _AdminScreenState extends State<AdminScreen> {
Widget _rmabTile(ColorScheme cs, TextTheme tt) {
final l = AppLocalizations.of(context)!;
return GestureDetector(
- onTap: () => Navigator.push(context, MaterialPageRoute(
- builder: (_) => AdminRmabScreen(url: _rmabUrl!))),
+ onTap: _openRmabSheet,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
decoration: _cardDeco(cs),
@@ -230,20 +230,9 @@ class _AdminScreenState extends State<AdminScreen> {
const SizedBox(width: 14),
Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Text(l.adminRmab, style: tt.titleSmall?.copyWith(fontWeight: FontWeight.w600, color: cs.onSurface)),
- Text(l.adminRmabSubtitle, style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant.withValues(alpha: 0.6))),
+ Text(l.adminRmabConnected, style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant.withValues(alpha: 0.6))),
])),
- PopupMenuButton<String>(
- icon: Icon(Icons.more_vert_rounded, color: cs.onSurface.withValues(alpha: 0.4), size: 20),
- tooltip: '',
- onSelected: (v) {
- if (v == 'edit') _showRmabUrlDialog();
- if (v == 'remove') _clearRmab();
- },
- itemBuilder: (_) => [
- PopupMenuItem(value: 'edit', child: Text(l.edit)),
- PopupMenuItem(value: 'remove', child: Text(l.remove)),
- ],
- ),
+ Icon(Icons.chevron_right_rounded, color: cs.onSurface.withValues(alpha: 0.15)),
]),
),
);
@@ -254,7 +243,7 @@ class _AdminScreenState extends State<AdminScreen> {
return Align(
alignment: Alignment.centerLeft,
child: TextButton.icon(
- onPressed: _showRmabUrlDialog,
+ onPressed: _openRmabSheet,
style: TextButton.styleFrom(
foregroundColor: cs.onSurfaceVariant.withValues(alpha: 0.6),
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 0),
@@ -267,62 +256,18 @@ class _AdminScreenState extends State<AdminScreen> {
);
}
- Future<void> _showRmabUrlDialog() async {
+ Future<void> _openRmabSheet() async {
final l = AppLocalizations.of(context)!;
- final controller = TextEditingController(text: _rmabUrl ?? '');
- String? err;
-
- final saved = await showDialog<String?>(
- context: context,
- builder: (ctx) => StatefulBuilder(builder: (ctx, setLocal) => AlertDialog(
- title: Text(l.adminRmabUrlTitle),
- content: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [
- Text(l.adminRmabUrlHelp, style: Theme.of(ctx).textTheme.bodySmall),
- const SizedBox(height: 12),
- TextField(
- controller: controller,
- autofocus: true,
- keyboardType: TextInputType.url,
- autocorrect: false,
- decoration: InputDecoration(
- hintText: l.adminRmabUrlHint,
- errorText: err,
- border: const OutlineInputBorder(),
- ),
- ),
- ]),
- actions: [
- TextButton(onPressed: () => Navigator.pop(ctx, null), child: Text(l.cancel)),
- TextButton(
- onPressed: () {
- final v = controller.text.trim();
- if (v.isEmpty) { setLocal(() => err = l.adminRmabInvalidUrl); return; }
- final u = Uri.tryParse(v);
- if (u == null || !(u.scheme == 'http' || u.scheme == 'https') || u.host.isEmpty) {
- setLocal(() => err = l.adminRmabInvalidUrl);
- return;
- }
- Navigator.pop(ctx, v);
- },
- child: Text(l.save),
- ),
- ],
- )),
- );
-
- if (saved == null) return;
- await ScopedPrefs.setString(_kRmabUrlKey, saved);
- if (!mounted) return;
- setState(() => _rmabUrl = saved);
- _msg(l.adminRmabSaved);
- }
-
- Future<void> _clearRmab() async {
- final l = AppLocalizations.of(context)!;
- await ScopedPrefs.remove(_kRmabUrlKey);
- if (!mounted) return;
- setState(() => _rmabUrl = null);
- _msg(l.adminRmabRemoved);
+ final result =
+ await showRmabConfigSheet(context, isAdminContext: true);
+ if (!mounted || result == null) return;
+ if (result.changed || result.disconnected) {
+ await _loadAll();
+ if (!mounted) return;
+ _msg(result.disconnected
+ ? l.rmabConfigDisconnectedSnackbar
+ : l.rmabConfigSavedSnackbar);
+ }
}
// ─── Library Card ───────────────────────────────────────────
diff --git a/lib/screens/library_screen.dart b/lib/screens/library_screen.dart
index b0f48810..998ac434 100644
--- a/lib/screens/library_screen.dart
+++ b/lib/screens/library_screen.dart
@@ -24,7 +24,10 @@ import 'app_shell.dart';
import 'upcoming_releases_screen.dart';
import '../widgets/audible_series_sheet.dart' show showAudibleRegionPicker;
import '../widgets/offline_status_icon.dart';
+import '../widgets/rmab_config_sheet.dart' show kRmabBaseUrlKey, kRmabApiTokenKey;
+import '../widgets/rmab_search_results_sheet.dart';
import '../widgets/scroll_reveal.dart';
+import '../services/scoped_prefs.dart';
import '../l10n/app_localizations.dart';
/// Responsive grid column count based on available width.
@@ -65,6 +68,7 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
// ── Search state ──
final _searchController = TextEditingController();
final _focusNode = FocusNode();
+ bool _rmabConfigured = false;
/// GlobalKey on the SearchBar so its Element (and the TextField + focus
/// inside) survives the tree swap when `_isInSearchMode` flips. Without
/// this, typing the first character unmounts the tabbed tree, the
@@ -204,6 +208,19 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) AppShell.notifyScreenReady(1);
});
+ _loadRmabConfigured();
+ }
+
+ Future<void> _loadRmabConfigured() async {
+ final base = await ScopedPrefs.getString(kRmabBaseUrlKey);
+ final token = await ScopedPrefs.getString(kRmabApiTokenKey);
+ if (!mounted) return;
+ final next =
+ (base ?? '').isNotEmpty && (token ?? '').isNotEmpty;
+ debugPrint('[RMAB] library: _rmabConfigured=$next');
+ if (next != _rmabConfigured) {
+ setState(() => _rmabConfigured = next);
+ }
}
void _initTabController() {
@@ -2147,6 +2164,8 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
);
}
if (_searchBookResults.isEmpty && _searchSeriesResults.isEmpty && _searchAuthorResults.isEmpty && _searchNarratorResults.isEmpty && _searchEpisodeResults.isEmpty && _searchTagResults.isEmpty && _searchGenreResults.isEmpty) {
+ final libProv = context.read<LibraryProvider>();
+ final showRmabCta = _rmabConfigured && !libProv.isPodcastLibrary;
return CustomScrollView(
physics: const AlwaysScrollableScrollPhysics(),
slivers: [
@@ -2161,6 +2180,22 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
const SizedBox(height: 12),
Text(l.libraryNoResults,
style: tt.bodyLarge?.copyWith(color: cs.onSurfaceVariant)),
+ if (showRmabCta) ...[
+ const SizedBox(height: 20),
+ OutlinedButton.icon(
+ icon: const Icon(Icons.menu_book_rounded, size: 18),
+ label: Text(l.rmabRequestCta),
+ onPressed: () {
+ final q = _searchController.text.trim();
+ debugPrint(
+ '[RMAB] library CTA tapped (query="$q")');
+ showRmabSearchResultsSheet(
+ context,
+ initialQuery: q,
+ );
+ },
+ ),
+ ],
],
),
),
@@ -2324,6 +2359,55 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
onTap: () => _applyTagFilter(name),
)),
],
+ // ─── RMAB FOOTER (when results exist + RMAB configured) ───
+ if (_rmabConfigured && !isPodcast) ...[
+ Padding(
+ padding: const EdgeInsets.only(top: 28),
+ child: Divider(color: cs.outlineVariant.withValues(alpha: 0.4)),
+ ),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(4, 12, 4, 4),
+ child: Text(
+ l.rmabSearchFooterPrompt,
+ style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant),
+ ),
+ ),
+ Material(
+ color: Colors.transparent,
+ child: InkWell(
+ borderRadius: BorderRadius.circular(10),
+ onTap: () {
+ final q = _searchController.text.trim();
+ debugPrint(
+ '[RMAB] library footer CTA tapped (query="$q")');
+ showRmabSearchResultsSheet(
+ context,
+ initialQuery: q,
+ );
+ },
+ child: Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 4, vertical: 12),
+ child: Row(children: [
+ Icon(Icons.menu_book_rounded,
+ size: 20, color: cs.primary),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Text(
+ l.rmabSearchFooterCta(
+ _searchController.text.trim()),
+ style: tt.bodyMedium?.copyWith(
+ color: cs.primary,
+ fontWeight: FontWeight.w600),
+ ),
+ ),
+ Icon(Icons.arrow_forward_rounded,
+ size: 18, color: cs.primary),
+ ]),
+ ),
+ ),
+ ),
+ ],
];
return CustomScrollView(
diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart
index 6698826e..cac859fe 100644
--- a/lib/screens/settings_screen.dart
+++ b/lib/screens/settings_screen.dart
@@ -21,7 +21,6 @@ import '../screens/login_screen.dart';
import '../screens/app_shell.dart';
import '../services/update_checker_service.dart';
import '../screens/admin_screen.dart';
-import '../screens/admin_rmab_screen.dart';
import '../screens/downloads_screen.dart';
import '../screens/bookmarks_screen.dart';
import '../main.dart' show applyThemeMode, applyTrustAllCerts, localeNotifier, oledNotifier, snappyTransitionsNotifier;
@@ -33,6 +32,7 @@ import '../widgets/overlay_toast.dart';
import '../widgets/tips_sheet.dart';
import '../widgets/feature_hint.dart';
import '../widgets/welcome_sheet.dart';
+import '../widgets/rmab_config_sheet.dart';
import '../l10n/app_localizations.dart';
class SettingsScreen extends StatefulWidget {
@@ -97,7 +97,8 @@ class _SettingsScreenState extends State<SettingsScreen> {
late final TextEditingController _localServerController;
bool _trustAllCerts = false;
bool _includePreReleases = false;
- String? _rmabUrl;
+ String? _rmabBaseUrl;
+ String? _rmabApiToken;
bool _loaded = false;
String _downloadLocationLabel = 'App Internal Storage (Default)';
bool _canPickDownloadLocation = false;
@@ -257,9 +258,11 @@ class _SettingsScreenState extends State<SettingsScreen> {
final shakeSens = results[45] as String;
final language = results[46] as String;
final classicWording = results[47] as bool;
- final rmabUrl = await ScopedPrefs.getString('rmab_url');
+ final rmabBaseUrl = await ScopedPrefs.getString(kRmabBaseUrlKey);
+ final rmabApiToken = await ScopedPrefs.getString(kRmabApiTokenKey);
if (mounted) setState(() {
- _rmabUrl = rmabUrl;
+ _rmabBaseUrl = rmabBaseUrl;
+ _rmabApiToken = rmabApiToken;
_rewindSettings = s;
_defaultSpeed = speed;
_wifiOnlyDownloads = wifiOnly;
@@ -2130,34 +2133,14 @@ class _SettingsScreenState extends State<SettingsScreen> {
const Divider(height: 1, indent: 16, endIndent: 16),
ListTile(
leading: Icon(Icons.menu_book_rounded, color: cs.primary),
- title: Row(children: [
- Flexible(child: Text(l.adminRmab)),
- _infoIcon(l.adminRmab, l.adminRmabSettingsInfo),
- ]),
+ title: Text(l.adminRmab),
subtitle: Text(
- (_rmabUrl ?? '').isNotEmpty ? l.adminRmabConnected : l.adminRmabAskAdmin,
+ ((_rmabBaseUrl ?? '').isNotEmpty && (_rmabApiToken ?? '').isNotEmpty)
+ ? l.adminRmabConnected
+ : l.adminRmabAskAdmin,
style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
- trailing: (_rmabUrl ?? '').isNotEmpty
- ? PopupMenuButton<String>(
- icon: Icon(Icons.more_vert_rounded, color: cs.onSurfaceVariant),
- onSelected: (v) {
- if (v == 'edit') _showRmabSettingsDialog();
- if (v == 'remove') _clearRmabSettings();
- },
- itemBuilder: (_) => [
- PopupMenuItem(value: 'edit', child: Text(l.edit)),
- PopupMenuItem(value: 'remove', child: Text(l.remove)),
- ],
- )
- : Icon(Icons.chevron_right_rounded, color: cs.onSurfaceVariant.withValues(alpha: 0.5)),
- onTap: () {
- if ((_rmabUrl ?? '').isNotEmpty) {
- Navigator.push(context, MaterialPageRoute(
- builder: (_) => AdminRmabScreen(url: _rmabUrl!)));
- } else {
- _showRmabSettingsDialog();
- }
- },
+ trailing: Icon(Icons.chevron_right_rounded, color: cs.onSurfaceVariant.withValues(alpha: 0.5)),
+ onTap: _openRmabSheetFromSettings,
),
],
),
@@ -2947,70 +2930,28 @@ class _SettingsScreenState extends State<SettingsScreen> {
}
}
- Future<void> _showRmabSettingsDialog() async {
- final l = AppLocalizations.of(context)!;
- final controller = TextEditingController(text: _rmabUrl ?? '');
- String? err;
-
- final saved = await showDialog<String?>(
- context: context,
- builder: (ctx) => StatefulBuilder(builder: (ctx, setLocal) => AlertDialog(
- title: Text(l.adminRmabUrlTitle),
- content: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [
- Text(l.adminRmabUrlHelpUser, style: Theme.of(ctx).textTheme.bodySmall),
- const SizedBox(height: 12),
- TextField(
- controller: controller,
- autofocus: true,
- keyboardType: TextInputType.url,
- autocorrect: false,
- decoration: InputDecoration(
- hintText: l.adminRmabUrlHint,
- errorText: err,
- border: const OutlineInputBorder(),
- ),
- ),
- ]),
- actions: [
- TextButton(onPressed: () => Navigator.pop(ctx, null), child: Text(l.cancel)),
- TextButton(
- onPressed: () {
- final v = controller.text.trim();
- if (v.isEmpty) { setLocal(() => err = l.adminRmabInvalidUrl); return; }
- final u = Uri.tryParse(v);
- if (u == null || !(u.scheme == 'http' || u.scheme == 'https') || u.host.isEmpty) {
- setLocal(() => err = l.adminRmabInvalidUrl);
- return;
- }
- Navigator.pop(ctx, v);
- },
- child: Text(l.save),
- ),
- ],
- )),
- );
-
- if (saved == null) return;
- await ScopedPrefs.setString('rmab_url', saved);
- if (!mounted) return;
- setState(() => _rmabUrl = saved);
- ScaffoldMessenger.of(context).showSnackBar(SnackBar(
- content: Text(l.adminRmabSaved),
- behavior: SnackBarBehavior.floating,
- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
- ));
- }
-
- Future<void> _clearRmabSettings() async {
+ Future<void> _openRmabSheetFromSettings() async {
final l = AppLocalizations.of(context)!;
- await ScopedPrefs.remove('rmab_url');
- if (!mounted) return;
- setState(() => _rmabUrl = null);
- ScaffoldMessenger.of(context).showSnackBar(SnackBar(
- content: Text(l.adminRmabRemoved),
- behavior: SnackBarBehavior.floating,
- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
- ));
+ final isAdmin = context.read<AuthProvider>().isAdmin;
+ final result =
+ await showRmabConfigSheet(context, isAdminContext: isAdmin);
+ if (!mounted || result == null) return;
+ if (result.changed || result.disconnected) {
+ final base = await ScopedPrefs.getString(kRmabBaseUrlKey);
+ final token = await ScopedPrefs.getString(kRmabApiTokenKey);
+ if (!mounted) return;
+ setState(() {
+ _rmabBaseUrl = base;
+ _rmabApiToken = token;
+ });
+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(
+ content: Text(result.disconnected
+ ? l.rmabConfigDisconnectedSnackbar
+ : l.rmabConfigSavedSnackbar),
+ behavior: SnackBarBehavior.floating,
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
+ ));
+ }
}
void _confirmLogout(BuildContext context) {
diff --git a/lib/screens/upcoming_releases_screen.dart b/lib/screens/upcoming_releases_screen.dart
index 11e537b7..bef1da08 100644
--- a/lib/screens/upcoming_releases_screen.dart
+++ b/lib/screens/upcoming_releases_screen.dart
@@ -5,10 +5,15 @@ import '../providers/auth_provider.dart';
import '../providers/library_provider.dart';
import '../services/api_service.dart';
import '../services/audio_player_service.dart';
+import '../services/rmab_service.dart';
+import '../services/scoped_prefs.dart';
import '../services/upcoming_releases_service.dart';
import '../widgets/absorb_page_header.dart';
import '../widgets/audible_series_sheet.dart';
import '../widgets/overlay_toast.dart';
+import '../widgets/rmab_book_detail_sheet.dart';
+import '../widgets/rmab_config_sheet.dart'
+ show kRmabBaseUrlKey, kRmabApiTokenKey;
import '../l10n/app_localizations.dart';
class UpcomingReleasesScreen extends StatefulWidget {
@@ -22,12 +27,26 @@ class _UpcomingReleasesScreenState extends State<UpcomingReleasesScreen> {
final _service = UpcomingReleasesService();
String _region = 'us';
bool _sortByDate = false;
+ bool _rmabConfigured = false;
@override
void initState() {
super.initState();
_service.addListener(_onServiceChanged);
_initAndStart();
+ _loadRmabConfigured();
+ }
+
+ Future<void> _loadRmabConfigured() async {
+ final base = await ScopedPrefs.getString(kRmabBaseUrlKey);
+ final token = await ScopedPrefs.getString(kRmabApiTokenKey);
+ if (!mounted) return;
+ final next =
+ (base ?? '').isNotEmpty && (token ?? '').isNotEmpty;
+ debugPrint('[RMAB] upcoming: _rmabConfigured=$next');
+ if (next != _rmabConfigured) {
+ setState(() => _rmabConfigured = next);
+ }
}
Future<void> _initAndStart() async {
@@ -142,15 +161,21 @@ class _UpcomingReleasesScreenState extends State<UpcomingReleasesScreen> {
return l.statsScreenDurationShortM(m);
}
- void _showBookMenu(Map<String, dynamic> book, String seriesName) {
+ void _showBookMenu(Map<String, dynamic> book, String seriesName,
+ {bool isUpcoming = false}) {
final l = AppLocalizations.of(context)!;
+ final cs = Theme.of(context).colorScheme;
+ final isOwned = book['_owned'] == true;
+ // Show the RMAB request entry only for books that have been released but
+ // aren't in the library yet, and only when the user has RMAB configured.
+ final showRequest = _rmabConfigured && !isOwned && !isUpcoming;
showAudibleBookMenu(context,
book: book,
seriesName: seriesName,
region: _region,
extraActions: [
ListTile(
- leading: Icon(Icons.refresh_rounded, color: Theme.of(context).colorScheme.primary, size: 22),
+ leading: Icon(Icons.refresh_rounded, color: cs.primary, size: 22),
title: Text(l.upcomingReleasesRescanReleaseDate, style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w500)),
dense: true, visualDensity: VisualDensity.compact,
onTap: () {
@@ -158,6 +183,26 @@ class _UpcomingReleasesScreenState extends State<UpcomingReleasesScreen> {
_rescanBook(book['asin'] as String? ?? '');
},
),
+ if (showRequest)
+ ListTile(
+ leading: Icon(Icons.menu_book_rounded, color: cs.primary, size: 22),
+ title: Text(l.rmabRequestCta,
+ style: const TextStyle(
+ fontSize: 14, fontWeight: FontWeight.w500)),
+ dense: true,
+ visualDensity: VisualDensity.compact,
+ onTap: () {
+ Navigator.pop(context);
+ final asin = book['asin'] as String? ?? '';
+ final title = book['title'] as String? ?? '';
+ debugPrint(
+ '[RMAB] upcoming Request tapped (asin=$asin title="$title")');
+ showRmabBookDetailSheet(
+ context,
+ book: RmabSearchResult.fromUpcomingBookMap(book),
+ );
+ },
+ ),
],
);
}
@@ -436,7 +481,7 @@ class _UpcomingReleasesScreenState extends State<UpcomingReleasesScreen> {
return Padding(
padding: const EdgeInsets.only(bottom: 8),
child: GestureDetector(
- onTap: () => _showBookMenu(book, seriesName),
+ onTap: () => _showBookMenu(book, seriesName, isUpcoming: isUpcoming),
child: Card(
elevation: 0,
color: isUpcoming
@@ -610,7 +655,7 @@ class _UpcomingReleasesScreenState extends State<UpcomingReleasesScreen> {
return Padding(
padding: const EdgeInsets.only(bottom: 8),
child: GestureDetector(
- onTap: () => _showBookMenu(book, seriesName),
+ onTap: () => _showBookMenu(book, seriesName, isUpcoming: isUpcoming),
child: Card(
elevation: 0,
color: isUpcoming
diff --git a/lib/services/rmab_service.dart b/lib/services/rmab_service.dart
new file mode 100644
index 00000000..80ad8510
--- /dev/null
+++ b/lib/services/rmab_service.dart
@@ -0,0 +1,787 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+import 'package:flutter/foundation.dart';
+import 'package:http/http.dart' as http;
+
+/// HTTP client for the ReadMeABook (RMAB) native API.
+///
+/// Covers the user-scoped allowlisted endpoints: me, search, listRequests,
+/// getRequest, createRequest. Admin-only endpoints (metrics / active downloads
+/// / recent requests) will land in a follow-up.
+///
+/// See: documentation/backend/services/api-tokens.md in the RMAB repo.
+class RmabService {
+ RmabService({required String baseUrl, required this.apiToken})
+ : baseUrl = _trimTrailingSlash(baseUrl);
+
+ /// Bare RMAB server URL with no trailing slash (e.g. https://rmab.example.com).
+ final String baseUrl;
+
+ /// `rmab_…` bearer token issued by the RMAB server.
+ final String apiToken;
+
+ static String _trimTrailingSlash(String s) =>
+ s.endsWith('/') ? s.substring(0, s.length - 1) : s;
+
+ Map<String, String> get _headers => {
+ 'Authorization': 'Bearer $apiToken',
+ 'Content-Type': 'application/json',
+ 'Accept': 'application/json',
+ };
+
+ // ─── /api/auth/me ───────────────────────────────────────────────
+
+ /// GET /api/auth/me — verifies the token and returns the connected user.
+ Future<RmabMe> me() async {
+ final uri = Uri.parse('$baseUrl/api/auth/me');
+ final res = await _get(uri, label: 'me');
+ final result = _decode(res, (json) {
+ final user = json['user'];
+ if (user is! Map<String, dynamic>) {
+ throw const FormatException('Response missing "user" object');
+ }
+ return RmabMe.fromJson(user);
+ }, label: 'me');
+ debugPrint(
+ '[RMAB] me() ok username=${result.username} role=${result.role}');
+ return result;
+ }
+
+ // ─── /api/audiobooks/search ─────────────────────────────────────
+
+ /// GET /api/audiobooks/search?q=…&page=… — search Audible via RMAB.
+ ///
+ /// Results are per-user enriched (isRequested, requestStatus, isAvailable,
+ /// isIgnored, hasReportedIssue) when called with a valid `rmab_` token.
+ Future<RmabSearchResponse> search(String query, {int page = 1}) async {
+ debugPrint('[RMAB] search(query="$query", page=$page)');
+ final uri = Uri.parse('$baseUrl/api/audiobooks/search').replace(
+ queryParameters: {'q': query, 'page': '$page'},
+ );
+ final res = await _get(uri, label: 'search');
+ final out = _decode(res, (json) {
+ final list = (json['results'] as List<dynamic>? ?? [])
+ .whereType<Map<String, dynamic>>()
+ .map(RmabSearchResult.fromJson)
+ .toList();
+ return RmabSearchResponse(
+ query: (json['query'] as String?) ?? query,
+ results: list,
+ page: _asInt(json['page']) ?? page,
+ hasMore: (json['hasMore'] as bool?) ?? false,
+ );
+ }, label: 'search');
+ final requestedCount = out.results.where((r) => r.isRequested).length;
+ final availableCount = out.results.where((r) => r.isAvailable).length;
+ debugPrint('[RMAB] search() -> ${out.results.length} results '
+ '(${out.hasMore ? 'hasMore' : 'last page'}, '
+ 'requested=$requestedCount available=$availableCount)');
+ return out;
+ }
+
+ // ─── /api/requests ──────────────────────────────────────────────
+
+ /// GET /api/requests — paginated list of the user's requests.
+ Future<RmabRequestsPage> listRequests({
+ RmabStatusGroup? statusGroup,
+ String? cursor,
+ int take = 20,
+ bool myOnly = true,
+ String type = 'audiobook',
+ }) async {
+ debugPrint(
+ '[RMAB] listRequests(statusGroup=${statusGroup?.name ?? 'all'}, '
+ 'cursor=${cursor ?? '-'}, take=$take, myOnly=$myOnly, type=$type)');
+ final qp = <String, String>{
+ 'take': '$take',
+ if (statusGroup != null) 'status': statusGroup.name,
+ if (cursor != null) 'cursor': cursor,
+ if (myOnly) 'myOnly': 'true',
+ 'type': type,
+ };
+ final uri =
+ Uri.parse('$baseUrl/api/requests').replace(queryParameters: qp);
+ final res = await _get(uri, label: 'listRequests');
+ final out = _decode(res, (json) {
+ final requests = (json['requests'] as List<dynamic>? ?? [])
+ .whereType<Map<String, dynamic>>()
+ .map(RmabRequest.fromJson)
+ .toList();
+ final countsJson = (json['counts'] as Map<String, dynamic>?) ?? const {};
+ return RmabRequestsPage(
+ requests: requests,
+ nextCursor: json['nextCursor'] as String?,
+ counts: RmabRequestCounts(
+ all: _asInt(countsJson['all']) ?? requests.length,
+ active: _asInt(countsJson['active']) ?? 0,
+ waiting: _asInt(countsJson['waiting']) ?? 0,
+ completed: _asInt(countsJson['completed']) ?? 0,
+ failed: _asInt(countsJson['failed']) ?? 0,
+ cancelled: _asInt(countsJson['cancelled']) ?? 0,
+ ),
+ );
+ }, label: 'listRequests');
+ debugPrint('[RMAB] listRequests() -> ${out.requests.length} '
+ '(counts: all=${out.counts.all} active=${out.counts.active} '
+ 'waiting=${out.counts.waiting} completed=${out.counts.completed} '
+ 'failed=${out.counts.failed} cancelled=${out.counts.cancelled})');
+ return out;
+ }
+
+ /// GET /api/requests/:id — full detail for a single request.
+ Future<RmabRequest> getRequest(String id) async {
+ debugPrint('[RMAB] getRequest(id=$id)');
+ final uri = Uri.parse('$baseUrl/api/requests/$id');
+ final res = await _get(uri, label: 'getRequest');
+ final out = _decode(res, (json) {
+ final req = json['request'];
+ if (req is! Map<String, dynamic>) {
+ throw const FormatException('Response missing "request"');
+ }
+ return RmabRequest.fromJson(req);
+ }, label: 'getRequest');
+ debugPrint('[RMAB] getRequest() -> status=${out.status} '
+ 'progress=${out.progress}%');
+ return out;
+ }
+
+ /// POST /api/requests — create a request. Returns a typed success or named
+ /// error. Throws [RmabException] only for transport / auth / 5xx failures.
+ Future<RmabCreateResult> createRequest(RmabRequestInput input) async {
+ debugPrint('[RMAB] createRequest(asin=${input.asin} '
+ 'title="${input.title}" author="${input.author}")');
+ final uri = Uri.parse('$baseUrl/api/requests');
+ final http.Response res;
+ try {
+ res = await http
+ .post(
+ uri,
+ headers: _headers,
+ body: jsonEncode({'audiobook': input.toJson()}),
+ )
+ .timeout(const Duration(seconds: 15));
+ debugPrint('[RMAB] createRequest <- ${res.statusCode} '
+ '(${res.body.length} bytes, '
+ 'content-type: ${res.headers['content-type']})');
+ } on TimeoutException {
+ throw RmabException(RmabErrorKind.network, 'Request timed out');
+ } on SocketException catch (e) {
+ throw RmabException(RmabErrorKind.network, e.message);
+ } on http.ClientException catch (e) {
+ throw RmabException(RmabErrorKind.network, e.message);
+ } catch (e) {
+ throw RmabException(RmabErrorKind.network, e.toString());
+ }
+
+ if (res.statusCode == 401) {
+ throw RmabException(RmabErrorKind.unauthorized,
+ _safeServerMessage(res) ?? 'Unauthorized');
+ }
+ if (res.statusCode == 403) {
+ throw RmabException(RmabErrorKind.forbidden,
+ _safeServerMessage(res) ?? 'Forbidden');
+ }
+
+ if (res.statusCode == 201) {
+ try {
+ final body = jsonDecode(res.body) as Map<String, dynamic>;
+ final reqJson = body['request'];
+ if (reqJson is! Map<String, dynamic>) {
+ throw const FormatException('Response missing "request"');
+ }
+ final created = RmabRequest.fromJson(reqJson);
+ debugPrint('[RMAB] createRequest ok '
+ 'requestId=${created.id} status=${created.status}');
+ return RmabCreateSuccess(created);
+ } catch (e) {
+ debugPrint('[RMAB] createRequest parse error: $e');
+ throw RmabException(
+ RmabErrorKind.parse, 'Unexpected response from server');
+ }
+ }
+
+ // Named errors — server returns 4xx / 5xx with { error, message }
+ try {
+ final body = jsonDecode(res.body) as Map<String, dynamic>;
+ final errorName = (body['error'] as String?) ?? '';
+ final message = (body['message'] as String?) ?? '';
+ final kind = _mapCreateError(errorName);
+ debugPrint(
+ '[RMAB] createRequest named error: $errorName -> ${kind.name} '
+ '("$message")');
+ return RmabCreateNamedError(kind, message);
+ } catch (_) {
+ throw RmabException(RmabErrorKind.server,
+ 'Server returned HTTP ${res.statusCode}');
+ }
+ }
+
+ RmabCreateErrorKind _mapCreateError(String name) {
+ switch (name) {
+ case 'AlreadyAvailable':
+ return RmabCreateErrorKind.alreadyAvailable;
+ case 'BeingProcessed':
+ return RmabCreateErrorKind.beingProcessed;
+ case 'DuplicateRequest':
+ return RmabCreateErrorKind.duplicateRequest;
+ case 'Ignored':
+ return RmabCreateErrorKind.ignored;
+ case 'UserNotFound':
+ return RmabCreateErrorKind.userNotFound;
+ case 'ValidationError':
+ return RmabCreateErrorKind.validationError;
+ default:
+ return RmabCreateErrorKind.requestError;
+ }
+ }
+
+ // ─── Shared helpers ─────────────────────────────────────────────
+
+ Future<http.Response> _get(Uri uri, {required String label}) async {
+ debugPrint('[RMAB] $label GET $uri');
+ final http.Response res;
+ try {
+ res = await http
+ .get(uri, headers: _headers)
+ .timeout(const Duration(seconds: 15));
+ debugPrint('[RMAB] $label <- ${res.statusCode} '
+ '(${res.body.length} bytes, '
+ 'content-type: ${res.headers['content-type']})');
+ } on TimeoutException {
+ debugPrint('[RMAB] $label network: timeout');
+ throw RmabException(RmabErrorKind.network, 'Request timed out');
+ } on SocketException catch (e) {
+ debugPrint('[RMAB] $label network: socket ${e.message}');
+ throw RmabException(RmabErrorKind.network, e.message);
+ } on http.ClientException catch (e) {
+ debugPrint('[RMAB] $label network: client ${e.message}');
+ throw RmabException(RmabErrorKind.network, e.message);
+ } catch (e) {
+ debugPrint('[RMAB] $label network: $e');
+ throw RmabException(RmabErrorKind.network, e.toString());
+ }
+
+ if (res.statusCode == 401) {
+ throw RmabException(RmabErrorKind.unauthorized,
+ _safeServerMessage(res) ?? 'Unauthorized');
+ }
+ if (res.statusCode == 403) {
+ throw RmabException(RmabErrorKind.forbidden,
+ _safeServerMessage(res) ?? 'Forbidden');
+ }
+ if (res.statusCode < 200 || res.statusCode >= 300) {
+ throw RmabException(
+ RmabErrorKind.server,
+ _safeServerMessage(res) ??
+ 'Server returned HTTP ${res.statusCode}');
+ }
+ return res;
+ }
+
+ /// Wrap a JSON decode in [RmabException]-aware error handling so callers
+ /// don't have to repeat the try/catch.
+ T _decode<T>(http.Response res, T Function(Map<String, dynamic>) builder,
+ {required String label}) {
+ try {
+ final body = jsonDecode(res.body) as Map<String, dynamic>;
+ return builder(body);
+ } catch (e) {
+ debugPrint('[RMAB] $label() parse error: $e');
+ throw RmabException(
+ RmabErrorKind.parse, 'Unexpected response from server');
+ }
+ }
+
+ String? _safeServerMessage(http.Response res) {
+ try {
+ final body = jsonDecode(res.body);
+ if (body is Map<String, dynamic>) {
+ final msg = body['message'] ?? body['error'];
+ if (msg is String && msg.isNotEmpty) return msg;
+ }
+ } catch (_) {}
+ return null;
+ }
+}
+
+// ─── Error model ──────────────────────────────────────────────────
+
+enum RmabErrorKind {
+ /// Connection refused, DNS failure, timeout, TLS error, etc.
+ network,
+
+ /// HTTP 401 — token rejected.
+ unauthorized,
+
+ /// HTTP 403 — token valid but not allowed (e.g. user-scoped token hitting
+ /// an admin endpoint).
+ forbidden,
+
+ /// HTTP 4xx / 5xx that isn't 401/403.
+ server,
+
+ /// Response was 2xx but the body didn't match the expected shape.
+ parse,
+}
+
+class RmabException implements Exception {
+ RmabException(this.kind, this.message);
+
+ final RmabErrorKind kind;
+ final String message;
+
+ @override
+ String toString() => 'RmabException($kind): $message';
+}
+
+// ─── /api/auth/me models ──────────────────────────────────────────
+
+class RmabMe {
+ RmabMe({
+ required this.id,
+ required this.username,
+ required this.role,
+ required this.isLocalAdmin,
+ });
+
+ final String id;
+ final String username;
+ final String role; // 'user' | 'admin'
+ final bool isLocalAdmin;
+
+ bool get isAdmin => role == 'admin';
+
+ factory RmabMe.fromJson(Map<String, dynamic> json) => RmabMe(
+ id: (json['id'] ?? '') as String,
+ username: (json['username'] ?? '') as String,
+ role: (json['role'] ?? 'user') as String,
+ isLocalAdmin: (json['isLocalAdmin'] ?? false) as bool,
+ );
+}
+
+// ─── /api/audiobooks/search models ────────────────────────────────
+
+class RmabSearchResponse {
+ RmabSearchResponse({
+ required this.query,
+ required this.results,
+ required this.page,
+ required this.hasMore,
+ });
+
+ final String query;
+ final List<RmabSearchResult> results;
+ final int page;
+ final bool hasMore;
+}
+
+class RmabSearchResult {
+ RmabSearchResult({
+ required this.asin,
+ required this.title,
+ required this.author,
+ this.narrator,
+ this.description,
+ this.coverArtUrl,
+ this.durationMinutes,
+ this.releaseDate,
+ this.rating,
+ this.series,
+ this.seriesPart,
+ this.language,
+ this.publisherName,
+ this.isAvailable = false,
+ this.isRequested = false,
+ this.requestStatus,
+ this.requestId,
+ this.isIgnored = false,
+ this.hasReportedIssue = false,
+ });
+
+ final String asin;
+ final String title;
+ final String author;
+ final String? narrator;
+ final String? description;
+ final String? coverArtUrl;
+ final int? durationMinutes;
+ final String? releaseDate;
+ final double? rating;
+ final String? series;
+ final String? seriesPart;
+ final String? language;
+ final String? publisherName;
+
+ /// Per-user enrichment (set by RMAB when called with a valid token).
+ final bool isAvailable;
+ final bool isRequested;
+ final String? requestStatus;
+ final String? requestId;
+ final bool isIgnored;
+ final bool hasReportedIssue;
+
+ /// Year extracted from [releaseDate] (best-effort parse, null on failure).
+ int? get releaseYear {
+ final raw = releaseDate;
+ if (raw == null || raw.isEmpty) return null;
+ final dt = DateTime.tryParse(raw);
+ return dt?.year;
+ }
+
+ factory RmabSearchResult.fromJson(Map<String, dynamic> json) =>
+ RmabSearchResult(
+ asin: (json['asin'] ?? '') as String,
+ title: (json['title'] ?? '') as String,
+ author: (json['author'] ?? '') as String,
+ narrator: json['narrator'] as String?,
+ description: json['description'] as String?,
+ coverArtUrl: json['coverArtUrl'] as String?,
+ durationMinutes: _asInt(json['durationMinutes']),
+ releaseDate: json['releaseDate'] as String?,
+ rating: _asDouble(json['rating']),
+ series: json['series'] as String?,
+ seriesPart: json['seriesPart'] as String?,
+ language: json['language'] as String?,
+ publisherName: json['publisherName'] as String?,
+ isAvailable: (json['isAvailable'] as bool?) ?? false,
+ isRequested: (json['isRequested'] as bool?) ?? false,
+ requestStatus: json['requestStatus'] as String?,
+ requestId: json['requestId'] as String?,
+ isIgnored: (json['isIgnored'] as bool?) ?? false,
+ hasReportedIssue: (json['hasReportedIssue'] as bool?) ?? false,
+ );
+
+ /// Bridge a book map from the Absorb upcoming-releases service into a
+ /// [RmabSearchResult] we can hand to the detail sheet. The upcoming-side
+ /// map uses different field names (authors/narrators as lists, coverUrl,
+ /// publisherSummary) so do the translation here in one place.
+ factory RmabSearchResult.fromUpcomingBookMap(Map<String, dynamic> m) {
+ String joinList(dynamic v) {
+ if (v is List) {
+ return v
+ .map((e) {
+ if (e is String) return e;
+ if (e is Map && e['name'] is String) return e['name'] as String;
+ return '';
+ })
+ .where((s) => s.isNotEmpty)
+ .join(', ');
+ }
+ if (v is String) return v;
+ return '';
+ }
+
+ return RmabSearchResult(
+ asin: (m['asin'] ?? '') as String,
+ title: (m['title'] ?? '') as String,
+ author: joinList(m['authors'] ?? m['author']),
+ narrator: () {
+ final s = joinList(m['narrators'] ?? m['narrator']);
+ return s.isEmpty ? null : s;
+ }(),
+ description: (m['publisherSummary'] ?? m['description']) as String?,
+ coverArtUrl: (m['coverUrl'] ?? m['coverArtUrl']) as String?,
+ durationMinutes: _asInt(m['runtimeMinutes'] ?? m['durationMinutes']),
+ releaseDate: m['releaseDate'] as String?,
+ rating: _asDouble(m['rating']),
+ series: m['series'] as String?,
+ seriesPart: (m['sequence'] ?? m['seriesPart']) as String?,
+ );
+ }
+}
+
+// ─── /api/requests models ─────────────────────────────────────────
+
+class RmabRequest {
+ RmabRequest({
+ required this.id,
+ required this.status,
+ required this.progress,
+ required this.createdAt,
+ required this.updatedAt,
+ required this.audiobook,
+ this.completedAt,
+ this.errorMessage,
+ this.type = 'audiobook',
+ this.downloadAvailable = false,
+ });
+
+ final String id;
+ final String status;
+ final int progress;
+ final DateTime createdAt;
+ final DateTime updatedAt;
+ final DateTime? completedAt;
+ final String? errorMessage;
+ final String type;
+ final bool downloadAvailable;
+ final RmabAudiobookSummary audiobook;
+
+ RmabStatusGroup? get statusGroup => status.rmabGroup;
+
+ factory RmabRequest.fromJson(Map<String, dynamic> json) {
+ final book = json['audiobook'] as Map<String, dynamic>?;
+ return RmabRequest(
+ id: (json['id'] ?? '') as String,
+ status: (json['status'] ?? '') as String,
+ progress: _asInt(json['progress']) ?? 0,
+ createdAt: _asDate(json['createdAt']) ?? DateTime.now(),
+ updatedAt: _asDate(json['updatedAt']) ?? DateTime.now(),
+ completedAt: _asDate(json['completedAt']),
+ errorMessage: json['errorMessage'] as String?,
+ type: (json['type'] ?? 'audiobook') as String,
+ downloadAvailable: (json['downloadAvailable'] as bool?) ?? false,
+ audiobook: book != null
+ ? RmabAudiobookSummary.fromJson(book)
+ : RmabAudiobookSummary.empty(),
+ );
+ }
+}
+
+class RmabAudiobookSummary {
+ RmabAudiobookSummary({
+ required this.id,
+ required this.title,
+ required this.author,
+ this.audibleAsin,
+ this.narrator,
+ this.coverArtUrl,
+ this.series,
+ this.seriesPart,
+ this.year,
+ });
+
+ final String id;
+ final String title;
+ final String author;
+ final String? audibleAsin;
+ final String? narrator;
+ final String? coverArtUrl;
+ final String? series;
+ final String? seriesPart;
+ final int? year;
+
+ factory RmabAudiobookSummary.empty() =>
+ RmabAudiobookSummary(id: '', title: '', author: '');
+
+ factory RmabAudiobookSummary.fromJson(Map<String, dynamic> json) =>
+ RmabAudiobookSummary(
+ id: (json['id'] ?? '') as String,
+ title: (json['title'] ?? '') as String,
+ author: (json['author'] ?? '') as String,
+ audibleAsin: json['audibleAsin'] as String?,
+ narrator: json['narrator'] as String?,
+ coverArtUrl: json['coverArtUrl'] as String?,
+ series: json['series'] as String?,
+ seriesPart: json['seriesPart'] as String?,
+ year: _asInt(json['year']),
+ );
+}
+
+class RmabRequestsPage {
+ RmabRequestsPage({
+ required this.requests,
+ required this.counts,
+ this.nextCursor,
+ });
+
+ final List<RmabRequest> requests;
+ final String? nextCursor;
+ final RmabRequestCounts counts;
+}
+
+class RmabRequestCounts {
+ const RmabRequestCounts({
+ required this.all,
+ required this.active,
+ required this.waiting,
+ required this.completed,
+ required this.failed,
+ required this.cancelled,
+ });
+
+ final int all;
+ final int active;
+ final int waiting;
+ final int completed;
+ final int failed;
+ final int cancelled;
+}
+
+// ─── createRequest models ─────────────────────────────────────────
+
+class RmabRequestInput {
+ RmabRequestInput({
+ required this.asin,
+ required this.title,
+ required this.author,
+ this.narrator,
+ this.description,
+ this.coverArtUrl,
+ this.durationMinutes,
+ this.releaseDate,
+ this.rating,
+ });
+
+ final String asin;
+ final String title;
+ final String author;
+ final String? narrator;
+ final String? description;
+ final String? coverArtUrl;
+ final int? durationMinutes;
+ final String? releaseDate;
+ final double? rating;
+
+ Map<String, dynamic> toJson() => {
+ 'asin': asin,
+ 'title': title,
+ 'author': author,
+ if (narrator != null) 'narrator': narrator,
+ if (description != null) 'description': description,
+ if (coverArtUrl != null) 'coverArtUrl': coverArtUrl,
+ if (durationMinutes != null) 'durationMinutes': durationMinutes,
+ if (releaseDate != null) 'releaseDate': releaseDate,
+ if (rating != null) 'rating': rating,
+ };
+
+ factory RmabRequestInput.fromSearchResult(RmabSearchResult r) =>
+ RmabRequestInput(
+ asin: r.asin,
+ title: r.title,
+ author: r.author,
+ narrator: r.narrator,
+ description: r.description,
+ coverArtUrl: r.coverArtUrl,
+ durationMinutes: r.durationMinutes,
+ releaseDate: r.releaseDate,
+ rating: r.rating,
+ );
+}
+
+sealed class RmabCreateResult {
+ const RmabCreateResult();
+}
+
+class RmabCreateSuccess extends RmabCreateResult {
+ const RmabCreateSuccess(this.request);
+ final RmabRequest request;
+}
+
+class RmabCreateNamedError extends RmabCreateResult {
+ const RmabCreateNamedError(this.kind, this.message);
+ final RmabCreateErrorKind kind;
+ final String message;
+}
+
+enum RmabCreateErrorKind {
+ alreadyAvailable,
+ beingProcessed,
+ duplicateRequest,
+ /// `bypassIgnore: true` is hardcoded for token requests so this shouldn't
+ /// fire, but model it for completeness.
+ ignored,
+ userNotFound,
+ validationError,
+ requestError,
+}
+
+// ─── Local in-memory request cache ────────────────────────────────
+
+/// In-memory bridge between "I just submitted a request" and "the server's
+/// next enrichment will reflect it."
+///
+/// Without this, dismissing and reopening the detail sheet for a freshly
+/// requested book would reset the UI to the unrequested state (because the
+/// `RmabSearchResult` we were handed by the parent still has
+/// `isRequested: false` from the last search).
+///
+/// All RMAB widgets consult this on render. The cache only adds requested
+/// state — it never claims a book ISN'T requested. So a stale "Already
+/// requested" badge is the worst case (better UX than showing a Request
+/// button that would just 409 with `DuplicateRequest`).
+///
+/// In-memory only. Cleared on app restart and on disconnect.
+class RmabLocalRequestCache {
+ RmabLocalRequestCache._();
+
+ static final Map<String, String> _statusByAsin = {};
+
+ /// The locally-cached status for [asin], or null if we haven't recorded
+ /// a fresh request for it during this app session.
+ static String? statusFor(String asin) => _statusByAsin[asin];
+
+ /// Record a freshly-created request. [status] should be the server's
+ /// returned status string (e.g. `pending`, `searching`).
+ static void markRequested(String asin, String status) {
+ if (asin.isEmpty) return;
+ _statusByAsin[asin] = status;
+ }
+
+ /// Clear every cached entry. Called on disconnect.
+ static void clear() {
+ _statusByAsin.clear();
+ }
+}
+
+// ─── Status taxonomy ──────────────────────────────────────────────
+
+/// The five status buckets the server groups by in `STATUS_GROUPS`
+/// (src/app/api/requests/route.ts).
+enum RmabStatusGroup { active, waiting, completed, failed, cancelled }
+
+extension RmabStatusGroupOf on String {
+ /// Map a raw status string to its visual group. Returns null for `warn`
+ /// or any unknown status (callers should treat null as "unknown" rather
+ /// than miscategorising).
+ RmabStatusGroup? get rmabGroup {
+ switch (this) {
+ case 'pending':
+ case 'searching':
+ case 'downloading':
+ case 'processing':
+ return RmabStatusGroup.active;
+ case 'awaiting_search':
+ case 'awaiting_import':
+ case 'awaiting_approval':
+ case 'awaiting_release':
+ return RmabStatusGroup.waiting;
+ case 'available':
+ case 'downloaded':
+ return RmabStatusGroup.completed;
+ case 'failed':
+ return RmabStatusGroup.failed;
+ case 'cancelled':
+ case 'denied':
+ return RmabStatusGroup.cancelled;
+ default:
+ return null;
+ }
+ }
+}
+
+// ─── tiny coercion helpers ────────────────────────────────────────
+
+int? _asInt(dynamic v) {
+ if (v == null) return null;
+ if (v is int) return v;
+ if (v is num) return v.toInt();
+ if (v is String) return int.tryParse(v);
+ return null;
+}
+
+double? _asDouble(dynamic v) {
+ if (v == null) return null;
+ if (v is double) return v;
+ if (v is num) return v.toDouble();
+ if (v is String) return double.tryParse(v);
+ return null;
+}
+
+DateTime? _asDate(dynamic v) {
+ if (v == null) return null;
+ if (v is DateTime) return v;
+ if (v is String && v.isNotEmpty) return DateTime.tryParse(v);
+ return null;
+}
diff --git a/lib/widgets/audible_series_sheet.dart b/lib/widgets/audible_series_sheet.dart
index a0d79502..a0c5a221 100644
--- a/lib/widgets/audible_series_sheet.dart
+++ b/lib/widgets/audible_series_sheet.dart
@@ -5,7 +5,11 @@ import 'package:url_launcher/url_launcher.dart';
import '../l10n/app_localizations.dart';
import '../services/api_service.dart';
import '../services/player_settings.dart';
+import '../services/rmab_service.dart';
+import '../services/scoped_prefs.dart';
import 'overlay_toast.dart';
+import 'rmab_book_detail_sheet.dart';
+import 'rmab_config_sheet.dart' show kRmabBaseUrlKey, kRmabApiTokenKey;
import 'stackable_sheet.dart';
/// Show a bottom sheet with Audible series discovery results.
@@ -55,12 +59,26 @@ class _AudibleSeriesSheetState extends State<AudibleSeriesSheet> {
String? _error;
int _filter = 0; // 0 = missing, 1 = upcoming, 2 = all
late String _region;
+ bool _rmabConfigured = false;
@override
void initState() {
super.initState();
_region = ApiService.debugRegion;
_loadRegionAndFetch();
+ _loadRmabConfigured();
+ }
+
+ Future<void> _loadRmabConfigured() async {
+ final base = await ScopedPrefs.getString(kRmabBaseUrlKey);
+ final token = await ScopedPrefs.getString(kRmabApiTokenKey);
+ if (!mounted) return;
+ final next =
+ (base ?? '').isNotEmpty && (token ?? '').isNotEmpty;
+ debugPrint('[RMAB] audible-series: _rmabConfigured=$next');
+ if (next != _rmabConfigured) {
+ setState(() => _rmabConfigured = next);
+ }
}
Future<void> _loadRegionAndFetch() async {
@@ -137,6 +155,47 @@ class _AudibleSeriesSheetState extends State<AudibleSeriesSheet> {
return date.isAfter(now);
}
+ void _openBookMenu(
+ Map<String, dynamic> book, {
+ required bool owned,
+ required bool upcoming,
+ }) {
+ final l = AppLocalizations.of(context)!;
+ final cs = Theme.of(context).colorScheme;
+ // Surface the RMAB Request action only for missing-but-released books,
+ // and only when the user has RMAB configured.
+ final showRequest = _rmabConfigured && !owned && !upcoming;
+ showAudibleBookMenu(
+ context,
+ book: book,
+ seriesName: widget.seriesName,
+ region: _region,
+ extraActions: [
+ if (showRequest)
+ ListTile(
+ leading: Icon(Icons.menu_book_rounded,
+ color: cs.primary, size: 22),
+ title: Text(l.rmabRequestCta,
+ style: const TextStyle(
+ fontSize: 14, fontWeight: FontWeight.w500)),
+ dense: true,
+ visualDensity: VisualDensity.compact,
+ onTap: () {
+ Navigator.pop(context);
+ final asin = book['asin'] as String? ?? '';
+ final title = book['title'] as String? ?? '';
+ debugPrint(
+ '[RMAB] audible-series Request tapped (asin=$asin title="$title")');
+ showRmabBookDetailSheet(
+ context,
+ book: RmabSearchResult.fromUpcomingBookMap(book),
+ );
+ },
+ ),
+ ],
+ );
+ }
+
String _formatRuntime(dynamic minutes) {
final mins = (minutes is num) ? minutes.toInt() : 0;
if (mins <= 0) return '';
@@ -304,8 +363,7 @@ class _AudibleSeriesSheetState extends State<AudibleSeriesSheet> {
return Padding(
padding: const EdgeInsets.only(bottom: 8),
child: GestureDetector(
- onTap: () => showAudibleBookMenu(context,
- book: book, seriesName: widget.seriesName, region: _region),
+ onTap: () => _openBookMenu(book, owned: owned, upcoming: upcoming),
child: Card(
elevation: 0,
color: upcoming
diff --git a/lib/widgets/rmab_book_detail_sheet.dart b/lib/widgets/rmab_book_detail_sheet.dart
new file mode 100644
index 00000000..72e5766e
--- /dev/null
+++ b/lib/widgets/rmab_book_detail_sheet.dart
@@ -0,0 +1,494 @@
+import 'package:cached_network_image/cached_network_image.dart';
+import 'package:flutter/material.dart';
+
+import '../l10n/app_localizations.dart';
+import '../services/rmab_service.dart';
+import '../services/scoped_prefs.dart';
+import 'html_description.dart';
+import 'rmab_config_sheet.dart' show kRmabBaseUrlKey, kRmabApiTokenKey;
+import 'rmab_request_status_chip.dart';
+import 'stackable_sheet.dart';
+
+/// Show the RMAB book detail sheet for [book]. The sheet renders without any
+/// extra network roundtrip — the search response already carries every field
+/// we need.
+Future<void> showRmabBookDetailSheet(
+ BuildContext context, {
+ required RmabSearchResult book,
+}) {
+ debugPrint('[RMAB] detail sheet opened (asin=${book.asin} '
+ 'title="${book.title}" isAvailable=${book.isAvailable} '
+ 'isRequested=${book.isRequested} status=${book.requestStatus ?? '-'})');
+ return showStackableSheet<void>(
+ context: context,
+ initialChildSize: 0.85,
+ maxChildSize: 0.95,
+ showHandle: true,
+ backgroundColor: Theme.of(context).colorScheme.surface,
+ useSafeArea: true,
+ builder: (ctx, sc) =>
+ _RmabBookDetailContent(book: book, scrollController: sc),
+ );
+}
+
+class _RmabBookDetailContent extends StatefulWidget {
+ const _RmabBookDetailContent({
+ required this.book,
+ required this.scrollController,
+ });
+
+ final RmabSearchResult book;
+ final ScrollController scrollController;
+
+ @override
+ State<_RmabBookDetailContent> createState() =>
+ _RmabBookDetailContentState();
+}
+
+class _RmabBookDetailContentState extends State<_RmabBookDetailContent> {
+ bool _submitting = false;
+
+ /// Local mirror of the book's request state. Seeded from (a) the search
+ /// result we were handed, OR (b) the session-local cache for cases where
+ /// the user just requested this book moments ago via a different open of
+ /// this sheet. The cache means dismiss + reopen no longer "forgets" the
+ /// request.
+ late bool _isRequested = widget.book.isRequested ||
+ RmabLocalRequestCache.statusFor(widget.book.asin) != null;
+ late String? _localRequestStatus = widget.book.requestStatus ??
+ RmabLocalRequestCache.statusFor(widget.book.asin);
+
+ Future<void> _submitRequest() async {
+ final l = AppLocalizations.of(context)!;
+ debugPrint('[RMAB] detail Request tapped (asin=${widget.book.asin})');
+ final base = await ScopedPrefs.getString(kRmabBaseUrlKey);
+ final token = await ScopedPrefs.getString(kRmabApiTokenKey);
+ if (!mounted) return;
+ if (base == null || base.isEmpty || token == null || token.isEmpty) {
+ debugPrint('[RMAB] detail Request: missing creds, prompting reconnect');
+ _toast(l.rmabRequestErrorTokenRejected);
+ return;
+ }
+
+ setState(() => _submitting = true);
+
+ try {
+ final result = await RmabService(baseUrl: base, apiToken: token)
+ .createRequest(RmabRequestInput.fromSearchResult(widget.book));
+
+ if (!mounted) return;
+
+ if (result is RmabCreateSuccess) {
+ RmabLocalRequestCache.markRequested(
+ widget.book.asin, result.request.status);
+ setState(() {
+ _submitting = false;
+ _isRequested = true;
+ _localRequestStatus = result.request.status;
+ });
+ _toast(l.rmabRequestSent);
+ return;
+ }
+
+ if (result is RmabCreateNamedError) {
+ setState(() => _submitting = false);
+ _toast(_messageForCreateError(result.kind, l));
+ // For already-available / duplicate / processed, flip the UI to
+ // reflect the server's view of the world — and remember it for
+ // subsequent re-opens of this sheet.
+ if (result.kind == RmabCreateErrorKind.duplicateRequest ||
+ result.kind == RmabCreateErrorKind.beingProcessed) {
+ final inferredStatus =
+ result.kind == RmabCreateErrorKind.beingProcessed
+ ? 'processing'
+ : 'pending';
+ RmabLocalRequestCache.markRequested(
+ widget.book.asin, inferredStatus);
+ setState(() {
+ _isRequested = true;
+ _localRequestStatus ??= inferredStatus;
+ });
+ }
+ }
+ } on RmabException catch (e) {
+ if (!mounted) return;
+ debugPrint('[RMAB] detail submit exception: ${e.kind} ${e.message}');
+ setState(() => _submitting = false);
+ _toast(_messageForException(e, l));
+ } catch (e) {
+ if (!mounted) return;
+ debugPrint('[RMAB] detail submit unexpected: $e');
+ setState(() => _submitting = false);
+ _toast('${l.rmabRequestErrorGeneric}: $e');
+ }
+ }
+
+ String _messageForCreateError(
+ RmabCreateErrorKind kind, AppLocalizations l) {
+ switch (kind) {
+ case RmabCreateErrorKind.alreadyAvailable:
+ return l.rmabRequestErrorAlreadyAvailable;
+ case RmabCreateErrorKind.beingProcessed:
+ return l.rmabRequestErrorBeingProcessed;
+ case RmabCreateErrorKind.duplicateRequest:
+ return l.rmabRequestErrorDuplicate;
+ case RmabCreateErrorKind.ignored:
+ return l.rmabRequestErrorIgnored;
+ case RmabCreateErrorKind.userNotFound:
+ return l.rmabRequestErrorUserNotFound;
+ case RmabCreateErrorKind.validationError:
+ return l.rmabRequestErrorValidation;
+ case RmabCreateErrorKind.requestError:
+ return l.rmabRequestErrorGeneric;
+ }
+ }
+
+ String _messageForException(RmabException e, AppLocalizations l) {
+ switch (e.kind) {
+ case RmabErrorKind.unauthorized:
+ return l.rmabRequestErrorTokenRejected;
+ case RmabErrorKind.network:
+ return l.rmabConfigErrorNetwork;
+ default:
+ return '${l.rmabRequestErrorGeneric}: ${e.message}';
+ }
+ }
+
+ void _toast(String msg) {
+ ScaffoldMessenger.of(context)
+ ..clearSnackBars()
+ ..showSnackBar(SnackBar(
+ content: Text(msg),
+ behavior: SnackBarBehavior.floating,
+ shape:
+ RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
+ ));
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ final l = AppLocalizations.of(context)!;
+ final book = widget.book;
+
+ final hasDescription =
+ book.description != null && book.description!.trim().isNotEmpty;
+
+ return ClipRRect(
+ borderRadius:
+ const BorderRadius.vertical(top: Radius.circular(24)),
+ child: Container(
+ color: cs.surface,
+ child: ListView(
+ controller: widget.scrollController,
+ padding: const EdgeInsets.fromLTRB(20, 8, 20, 32),
+ children: [
+ // ── Cover + headline ────────────────────────
+ Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ _Cover(url: book.coverArtUrl),
+ const SizedBox(width: 16),
+ Expanded(child: _Headline(book: book)),
+ ],
+ ),
+ const SizedBox(height: 16),
+
+ // ── Meta row (year + duration + rating) ────
+ _MetaRow(book: book),
+
+ // ── Status banner if relevant ──────────────
+ if (book.isAvailable) ...[
+ const SizedBox(height: 14),
+ _Banner(
+ icon: Icons.check_circle_rounded,
+ color: Colors.green.shade600,
+ text: l.rmabBookAlreadyAvailable,
+ ),
+ ] else if (_isRequested) ...[
+ const SizedBox(height: 14),
+ _RequestedBanner(rawStatus: _localRequestStatus ?? 'pending'),
+ ],
+
+ // ── Explainer ──────────────────────────────
+ const SizedBox(height: 16),
+ Container(
+ padding: const EdgeInsets.all(14),
+ decoration: BoxDecoration(
+ color: cs.surfaceContainerHighest.withValues(alpha: 0.5),
+ borderRadius: BorderRadius.circular(12),
+ ),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Icon(Icons.info_outline_rounded,
+ size: 18, color: cs.onSurfaceVariant),
+ const SizedBox(width: 10),
+ Expanded(
+ child: Text(
+ l.rmabBookDetailExplainer,
+ style: tt.bodySmall
+ ?.copyWith(color: cs.onSurfaceVariant, height: 1.4),
+ ),
+ ),
+ ],
+ ),
+ ),
+
+ // ── Description ────────────────────────────
+ if (hasDescription) ...[
+ const SizedBox(height: 18),
+ HtmlDescription(html: book.description!, maxLines: 8),
+ ],
+
+ // ── Request CTA ────────────────────────────
+ const SizedBox(height: 24),
+ _RequestButton(
+ disabled: book.isAvailable || _isRequested,
+ submitting: _submitting,
+ onPressed: _submitRequest,
+ ),
+ const SizedBox(height: 8),
+ ],
+ ),
+ ),
+ );
+ }
+}
+
+// ─── Sub-widgets ───────────────────────────────────────────────────
+
+class _Cover extends StatelessWidget {
+ const _Cover({required this.url});
+ final String? url;
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ return ClipRRect(
+ borderRadius: BorderRadius.circular(10),
+ child: SizedBox(
+ width: 110,
+ height: 110,
+ child: url == null || url!.isEmpty
+ ? Container(
+ color: cs.surfaceContainerHighest,
+ child: Icon(Icons.menu_book_rounded,
+ color: cs.onSurfaceVariant, size: 36),
+ )
+ : CachedNetworkImage(
+ imageUrl: url!,
+ fit: BoxFit.cover,
+ placeholder: (_, __) => Container(color: cs.surfaceContainerHighest),
+ errorWidget: (_, __, ___) => Container(
+ color: cs.surfaceContainerHighest,
+ child: Icon(Icons.broken_image_rounded,
+ color: cs.onSurfaceVariant, size: 36),
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+class _Headline extends StatelessWidget {
+ const _Headline({required this.book});
+ final RmabSearchResult book;
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ final l = AppLocalizations.of(context)!;
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ book.title,
+ style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600),
+ ),
+ if (book.author.isNotEmpty) ...[
+ const SizedBox(height: 4),
+ Text(book.author,
+ style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)),
+ ],
+ if (book.narrator != null && book.narrator!.isNotEmpty) ...[
+ const SizedBox(height: 2),
+ Text(l.narratedBy(book.narrator!),
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ ],
+ if (book.series != null && book.series!.isNotEmpty) ...[
+ const SizedBox(height: 6),
+ Text(
+ book.seriesPart != null && book.seriesPart!.isNotEmpty
+ ? '${book.series}, ${book.seriesPart}'
+ : book.series!,
+ style: tt.bodySmall?.copyWith(
+ color: cs.primary, fontWeight: FontWeight.w600),
+ ),
+ ],
+ ],
+ );
+ }
+}
+
+class _MetaRow extends StatelessWidget {
+ const _MetaRow({required this.book});
+ final RmabSearchResult book;
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ final items = <Widget>[];
+
+ final year = book.releaseYear;
+ if (year != null) {
+ items.add(_chip(cs, tt, Icons.event_rounded, '$year'));
+ }
+ if (book.durationMinutes != null && book.durationMinutes! > 0) {
+ final h = book.durationMinutes! ~/ 60;
+ final m = book.durationMinutes! % 60;
+ final text = h > 0 ? '${h}h ${m.toString().padLeft(2, '0')}m' : '${m}m';
+ items.add(_chip(cs, tt, Icons.schedule_rounded, text));
+ }
+ if (book.rating != null && book.rating! > 0) {
+ items.add(_chip(
+ cs, tt, Icons.star_rounded, book.rating!.toStringAsFixed(1)));
+ }
+
+ if (items.isEmpty) return const SizedBox.shrink();
+
+ return Wrap(
+ spacing: 8,
+ runSpacing: 8,
+ children: items,
+ );
+ }
+
+ Widget _chip(
+ ColorScheme cs, TextTheme tt, IconData icon, String label) {
+ return Container(
+ padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
+ decoration: BoxDecoration(
+ color: cs.surfaceContainerHighest.withValues(alpha: 0.6),
+ borderRadius: BorderRadius.circular(8),
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(icon, size: 14, color: cs.onSurfaceVariant),
+ const SizedBox(width: 6),
+ Text(label, style: tt.labelMedium?.copyWith(color: cs.onSurface)),
+ ],
+ ),
+ );
+ }
+}
+
+class _Banner extends StatelessWidget {
+ const _Banner(
+ {required this.icon, required this.color, required this.text});
+ final IconData icon;
+ final Color color;
+ final String text;
+
+ @override
+ Widget build(BuildContext context) {
+ final tt = Theme.of(context).textTheme;
+ return Container(
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
+ decoration: BoxDecoration(
+ color: color.withValues(alpha: 0.14),
+ borderRadius: BorderRadius.circular(10),
+ ),
+ child: Row(
+ children: [
+ Icon(icon, size: 18, color: color),
+ const SizedBox(width: 10),
+ Expanded(
+ child: Text(
+ text,
+ style: tt.bodyMedium
+ ?.copyWith(color: color, fontWeight: FontWeight.w600),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
+
+class _RequestedBanner extends StatelessWidget {
+ const _RequestedBanner({required this.rawStatus});
+ final String rawStatus;
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ final l = AppLocalizations.of(context)!;
+ return Container(
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
+ decoration: BoxDecoration(
+ color: cs.surfaceContainerHighest.withValues(alpha: 0.5),
+ borderRadius: BorderRadius.circular(10),
+ ),
+ child: Row(
+ children: [
+ Icon(Icons.send_rounded, size: 18, color: cs.onSurfaceVariant),
+ const SizedBox(width: 10),
+ Expanded(
+ child: Text(
+ l.rmabBookAlreadyRequested,
+ style: tt.bodyMedium?.copyWith(
+ color: cs.onSurface, fontWeight: FontWeight.w600),
+ ),
+ ),
+ RmabRequestStatusChip(rawStatus: rawStatus),
+ ],
+ ),
+ );
+ }
+}
+
+class _RequestButton extends StatelessWidget {
+ const _RequestButton({
+ required this.disabled,
+ required this.submitting,
+ required this.onPressed,
+ });
+ final bool disabled;
+ final bool submitting;
+ final VoidCallback onPressed;
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final l = AppLocalizations.of(context)!;
+ return SizedBox(
+ width: double.infinity,
+ child: FilledButton.icon(
+ onPressed: (disabled || submitting) ? null : onPressed,
+ icon: submitting
+ ? SizedBox(
+ width: 18,
+ height: 18,
+ child: CircularProgressIndicator(
+ strokeWidth: 2,
+ color: cs.onPrimary,
+ ),
+ )
+ : const Icon(Icons.menu_book_rounded, size: 18),
+ label: Text(
+ submitting ? l.rmabRequestSubmitting : l.rmabRequestCta),
+ style: FilledButton.styleFrom(
+ padding: const EdgeInsets.symmetric(vertical: 14),
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(12)),
+ ),
+ ),
+ );
+ }
+}
diff --git a/lib/widgets/rmab_config_sheet.dart b/lib/widgets/rmab_config_sheet.dart
new file mode 100644
index 00000000..be7eeda1
--- /dev/null
+++ b/lib/widgets/rmab_config_sheet.dart
@@ -0,0 +1,1057 @@
+import 'package:cached_network_image/cached_network_image.dart';
+import 'package:flutter/gestures.dart';
+import 'package:flutter/material.dart';
+import 'package:url_launcher/url_launcher.dart';
+
+import '../l10n/app_localizations.dart';
+import '../screens/admin_rmab_screen.dart';
+import '../services/rmab_service.dart';
+import '../services/scoped_prefs.dart';
+import 'rmab_request_status_chip.dart';
+import 'stackable_sheet.dart';
+
+/// ScopedPrefs keys used by the RMAB integration.
+const String kRmabBaseUrlKey = 'rmab_base_url';
+const String kRmabApiTokenKey = 'rmab_api_token';
+
+/// Legacy single-URL key. Still read so existing WebView-only users keep
+/// working, and so the "Open in browser view" action prefers their
+/// embedded-token URL when present.
+const String kRmabLegacyUrlKey = 'rmab_url';
+
+const String _kRmabGithubUrl = 'https://github.com/kikootwo/ReadMeABook';
+
+/// Result returned by [showRmabConfigSheet] so the caller knows whether to
+/// reload its RMAB state.
+class RmabConfigResult {
+ const RmabConfigResult({this.changed = false, this.disconnected = false});
+
+ final bool changed;
+ final bool disconnected;
+}
+
+/// Show the shared RMAB config bottom sheet. Used by both the admin screen
+/// tile and the settings screen tile.
+///
+/// [isAdminContext] controls the explainer copy: admin context tells the user
+/// to generate a token in RMAB themselves; user context tells them to ask
+/// their server admin.
+Future<RmabConfigResult?> showRmabConfigSheet(
+ BuildContext context, {
+ required bool isAdminContext,
+}) {
+ return showStackableSheet<RmabConfigResult>(
+ context: context,
+ initialChildSize: 0.78,
+ maxChildSize: 0.95,
+ showHandle: true,
+ backgroundColor: Theme.of(context).colorScheme.surface,
+ useSafeArea: true,
+ builder: (ctx, scrollController) => _RmabConfigSheet(
+ isAdminContext: isAdminContext,
+ scrollController: scrollController,
+ ),
+ );
+}
+
+class _RmabConfigSheet extends StatefulWidget {
+ const _RmabConfigSheet({
+ required this.isAdminContext,
+ required this.scrollController,
+ });
+
+ final bool isAdminContext;
+ final ScrollController scrollController;
+
+ @override
+ State<_RmabConfigSheet> createState() => _RmabConfigSheetState();
+}
+
+class _RmabConfigSheetState extends State<_RmabConfigSheet> {
+ final _urlController = TextEditingController();
+ final _tokenController = TextEditingController();
+ final _urlFocus = FocusNode();
+ final _tokenFocus = FocusNode();
+
+ bool _loadingPrefs = true;
+ bool _connecting = false;
+ bool _obscureToken = true;
+ bool _wasConfigured = false;
+ String? _legacyUrl;
+ String? _errorText;
+ String? _connectedAsName;
+
+ /// Bumped when the user successfully (re)connects or disconnects, so the
+ /// My Requests tab knows to refetch.
+ int _credsVersion = 0;
+
+ @override
+ void initState() {
+ super.initState();
+ _loadPrefs();
+ }
+
+ Future<void> _loadPrefs() async {
+ final base = await ScopedPrefs.getString(kRmabBaseUrlKey);
+ final token = await ScopedPrefs.getString(kRmabApiTokenKey);
+ final legacy = await ScopedPrefs.getString(kRmabLegacyUrlKey);
+
+ // Migration: if the new base URL isn't set but a legacy URL is, try to
+ // extract just the origin so the user only needs to paste a token.
+ String prefilledBase = base ?? '';
+ if (prefilledBase.isEmpty && legacy != null && legacy.isNotEmpty) {
+ final parsed = Uri.tryParse(legacy);
+ if (parsed != null && parsed.hasScheme && parsed.host.isNotEmpty) {
+ prefilledBase =
+ '${parsed.scheme}://${parsed.host}${parsed.hasPort ? ':${parsed.port}' : ''}';
+ }
+ }
+
+ if (!mounted) return;
+ setState(() {
+ _urlController.text = prefilledBase;
+ _tokenController.text = token ?? '';
+ _legacyUrl = legacy;
+ _wasConfigured =
+ (base ?? '').isNotEmpty && (token ?? '').isNotEmpty;
+ _loadingPrefs = false;
+ });
+ }
+
+ @override
+ void dispose() {
+ _urlController.dispose();
+ _tokenController.dispose();
+ _urlFocus.dispose();
+ _tokenFocus.dispose();
+ super.dispose();
+ }
+
+ Uri? _parseBaseUrl(String raw) {
+ final v = raw.trim();
+ if (v.isEmpty) return null;
+ final u = Uri.tryParse(v);
+ if (u == null || u.host.isEmpty) return null;
+ if (u.scheme != 'http' && u.scheme != 'https') return null;
+ return u;
+ }
+
+ Future<void> _connect() async {
+ final l = AppLocalizations.of(context)!;
+
+ final baseUri = _parseBaseUrl(_urlController.text);
+ if (baseUri == null) {
+ debugPrint('[RMAB] connect: invalid URL');
+ setState(() => _errorText = l.rmabConfigErrorInvalidUrl);
+ return;
+ }
+ final token = _tokenController.text.trim();
+ if (token.isEmpty) {
+ debugPrint('[RMAB] connect: token field empty');
+ setState(() => _errorText = l.rmabConfigErrorMissingToken);
+ return;
+ }
+ debugPrint(
+ '[RMAB] connect starting (origin=${baseUri.origin} tokenLen=${token.length})');
+
+ setState(() {
+ _connecting = true;
+ _errorText = null;
+ _connectedAsName = null;
+ });
+
+ // Uri.origin gives scheme://host[:port] with no path/query/fragment markers.
+ // Don't use Uri.replace(path:'', query:'', fragment:'') here — it preserves
+ // empty `?` and `#` in toString(), which then turns appended `/api/...`
+ // into a URL fragment that never reaches the server.
+ final cleanBase = baseUri.origin;
+
+ try {
+ final me =
+ await RmabService(baseUrl: cleanBase, apiToken: token).me();
+
+ await ScopedPrefs.setString(kRmabBaseUrlKey, cleanBase);
+ await ScopedPrefs.setString(kRmabApiTokenKey, token);
+ // If no legacy URL exists, plant the bare base URL so "Open in browser
+ // view" has something to load (the user will see RMAB's login page).
+ // Don't overwrite an existing legacy URL — power users may rely on the
+ // embedded `?token=` for one-tap SSO into the web UI.
+ final existingLegacy = await ScopedPrefs.getString(kRmabLegacyUrlKey);
+ if (existingLegacy == null || existingLegacy.isEmpty) {
+ await ScopedPrefs.setString(kRmabLegacyUrlKey, cleanBase);
+ }
+
+ if (!mounted) return;
+ debugPrint('[RMAB] connect ok (username=${me.username} role=${me.role})');
+ setState(() {
+ _connecting = false;
+ _connectedAsName = me.username;
+ _wasConfigured = true;
+ _credsVersion++;
+ });
+ } on RmabException catch (e) {
+ if (!mounted) return;
+ debugPrint('[RMAB] connect failed: ${e.kind} ${e.message}');
+ setState(() {
+ _connecting = false;
+ _errorText = _errorTextFor(e, l);
+ });
+ } catch (e) {
+ if (!mounted) return;
+ debugPrint('[RMAB] connect unexpected error: $e');
+ setState(() {
+ _connecting = false;
+ _errorText = '${l.rmabConfigErrorGeneric}: $e';
+ });
+ }
+ }
+
+ String _errorTextFor(RmabException e, AppLocalizations l) {
+ switch (e.kind) {
+ case RmabErrorKind.unauthorized:
+ return l.rmabConfigErrorUnauthorized;
+ case RmabErrorKind.forbidden:
+ return l.rmabConfigErrorForbidden;
+ case RmabErrorKind.network:
+ return l.rmabConfigErrorNetwork;
+ case RmabErrorKind.parse:
+ return l.rmabConfigErrorGeneric;
+ case RmabErrorKind.server:
+ return '${l.rmabConfigErrorGeneric}: ${e.message}';
+ }
+ }
+
+ void _toggleObscureToken() {
+ setState(() => _obscureToken = !_obscureToken);
+ }
+
+ Future<void> _disconnect() async {
+ debugPrint('[RMAB] disconnect: clearing all rmab_* keys + local cache');
+ await ScopedPrefs.remove(kRmabBaseUrlKey);
+ await ScopedPrefs.remove(kRmabApiTokenKey);
+ await ScopedPrefs.remove(kRmabLegacyUrlKey);
+ RmabLocalRequestCache.clear();
+ if (!mounted) return;
+ Navigator.of(context).pop(const RmabConfigResult(disconnected: true));
+ }
+
+ void _openWebView() {
+ final l = AppLocalizations.of(context)!;
+ final baseUri = _parseBaseUrl(_urlController.text);
+ final fallbackBase = baseUri?.origin;
+ final usingLegacy = _legacyUrl != null && _legacyUrl!.isNotEmpty;
+ final target = usingLegacy ? _legacyUrl! : (fallbackBase ?? '');
+ debugPrint(
+ '[RMAB] openWebView (usingLegacy=$usingLegacy target=$target)');
+ if (target.isEmpty) {
+ setState(() => _errorText = l.rmabConfigErrorInvalidUrl);
+ return;
+ }
+ Navigator.of(context).push(MaterialPageRoute(
+ builder: (_) => AdminRmabScreen(url: target),
+ ));
+ }
+
+ Future<void> _openGithub() async {
+ await launchUrl(
+ Uri.parse(_kRmabGithubUrl),
+ mode: LaunchMode.externalApplication,
+ );
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ if (_loadingPrefs) {
+ return const SizedBox(
+ height: 220,
+ child: Center(child: CircularProgressIndicator()),
+ );
+ }
+ if (_wasConfigured) {
+ // Tabbed layout: My Requests (default) | Setup
+ return _ConfiguredView(
+ state: this,
+ credsVersion: _credsVersion,
+ scrollController: widget.scrollController,
+ );
+ }
+ // First-time connect form (no tabs)
+ return _UnconfiguredView(
+ state: this,
+ scrollController: widget.scrollController,
+ );
+ }
+}
+
+// ─── Unconfigured view (Phase 1 layout, no tabs) ──────────────────
+
+class _UnconfiguredView extends StatelessWidget {
+ const _UnconfiguredView({
+ required this.state,
+ required this.scrollController,
+ });
+ final _RmabConfigSheetState state;
+ final ScrollController scrollController;
+
+ @override
+ Widget build(BuildContext context) {
+ final mediaQuery = MediaQuery.of(context);
+ return Padding(
+ padding: EdgeInsets.only(bottom: mediaQuery.viewInsets.bottom),
+ child: SingleChildScrollView(
+ controller: scrollController,
+ padding: const EdgeInsets.fromLTRB(20, 4, 20, 24),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ _SheetHeader(state: state),
+ const SizedBox(height: 12),
+ _ExplainerBlock(state: state),
+ const SizedBox(height: 20),
+ _SetupForm(state: state),
+ ],
+ ),
+ ),
+ );
+ }
+}
+
+// ─── Configured view (tabbed) ─────────────────────────────────────
+
+class _ConfiguredView extends StatelessWidget {
+ const _ConfiguredView({
+ required this.state,
+ required this.credsVersion,
+ required this.scrollController,
+ });
+ final _RmabConfigSheetState state;
+ final int credsVersion;
+ final ScrollController scrollController;
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final l = AppLocalizations.of(context)!;
+
+ // No fixed SizedBox height here — the parent DraggableScrollableSheet
+ // (via showStackableSheet) supplies the bounded space. The My Requests
+ // tab's ListView uses [scrollController] so drag-down-when-at-top
+ // bubbles up to the sheet for dismissal.
+ return DefaultTabController(
+ length: 2,
+ child: Column(
+ children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(20, 4, 20, 0),
+ child: _SheetHeader(state: state),
+ ),
+ const SizedBox(height: 4),
+ TabBar(
+ labelColor: cs.primary,
+ unselectedLabelColor: cs.onSurfaceVariant,
+ indicatorColor: cs.primary,
+ tabs: [
+ Tab(text: l.rmabMyRequestsTab),
+ Tab(text: l.rmabSetupTab),
+ ],
+ ),
+ Expanded(
+ child: TabBarView(
+ children: [
+ _MyRequestsTab(
+ key: ValueKey('myrequests-$credsVersion'),
+ state: state,
+ scrollController: scrollController,
+ ),
+ _SetupTab(state: state),
+ ],
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
+
+// ─── Reusable bits ───────────────────────────────────────────────
+
+class _SheetHeader extends StatelessWidget {
+ const _SheetHeader({required this.state});
+ final _RmabConfigSheetState state;
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ final l = AppLocalizations.of(context)!;
+ return Row(children: [
+ Icon(Icons.menu_book_rounded, color: cs.primary, size: 22),
+ const SizedBox(width: 10),
+ Expanded(
+ child: Text(
+ l.rmabConfigTitle,
+ style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600),
+ ),
+ ),
+ ]);
+ }
+}
+
+class _ExplainerBlock extends StatelessWidget {
+ const _ExplainerBlock({required this.state});
+ final _RmabConfigSheetState state;
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ final l = AppLocalizations.of(context)!;
+ final explainer = state.widget.isAdminContext
+ ? l.rmabConfigExplainerAdmin
+ : l.rmabConfigExplainerUser;
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ explainer,
+ style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant),
+ ),
+ const SizedBox(height: 6),
+ Text.rich(
+ TextSpan(
+ text: l.rmabConfigLearnMore,
+ style: tt.bodySmall?.copyWith(
+ color: cs.primary,
+ decoration: TextDecoration.underline,
+ decorationColor: cs.primary.withValues(alpha: 0.6),
+ ),
+ recognizer: TapGestureRecognizer()..onTap = state._openGithub,
+ ),
+ ),
+ ],
+ );
+ }
+}
+
+class _SetupForm extends StatelessWidget {
+ const _SetupForm({required this.state});
+ final _RmabConfigSheetState state;
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ final l = AppLocalizations.of(context)!;
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ TextField(
+ controller: state._urlController,
+ focusNode: state._urlFocus,
+ enabled: !state._connecting,
+ autocorrect: false,
+ keyboardType: TextInputType.url,
+ textInputAction: TextInputAction.next,
+ decoration: InputDecoration(
+ labelText: l.rmabConfigBaseUrlLabel,
+ hintText: l.rmabConfigBaseUrlHint,
+ border: const OutlineInputBorder(),
+ ),
+ onSubmitted: (_) => state._tokenFocus.requestFocus(),
+ ),
+ const SizedBox(height: 12),
+ TextField(
+ controller: state._tokenController,
+ focusNode: state._tokenFocus,
+ enabled: !state._connecting,
+ autocorrect: false,
+ obscureText: state._obscureToken,
+ keyboardType: TextInputType.visiblePassword,
+ decoration: InputDecoration(
+ labelText: l.rmabConfigTokenLabel,
+ hintText: l.rmabConfigTokenHint,
+ border: const OutlineInputBorder(),
+ suffixIcon: IconButton(
+ icon: Icon(state._obscureToken
+ ? Icons.visibility_outlined
+ : Icons.visibility_off_outlined),
+ onPressed: state._connecting ? null : state._toggleObscureToken,
+ ),
+ ),
+ onSubmitted: (_) => state._connect(),
+ ),
+ if (state._errorText != null) ...[
+ const SizedBox(height: 12),
+ Row(children: [
+ Icon(Icons.error_outline_rounded, size: 18, color: cs.error),
+ const SizedBox(width: 8),
+ Expanded(
+ child: Text(
+ state._errorText!,
+ style: tt.bodySmall?.copyWith(color: cs.error),
+ ),
+ ),
+ ]),
+ ] else if (state._connectedAsName != null) ...[
+ const SizedBox(height: 12),
+ Row(children: [
+ Icon(Icons.check_circle_rounded, size: 18, color: cs.primary),
+ const SizedBox(width: 8),
+ Expanded(
+ child: Text(
+ l.rmabConfigConnectedAs(state._connectedAsName!),
+ style: tt.bodySmall?.copyWith(color: cs.primary),
+ ),
+ ),
+ ]),
+ ],
+ const SizedBox(height: 20),
+ Row(
+ mainAxisAlignment: MainAxisAlignment.end,
+ children: [
+ TextButton(
+ onPressed: state._connecting
+ ? null
+ : () => Navigator.of(context)
+ .pop(_resultForCurrentState(state)),
+ child: Text(l.cancel),
+ ),
+ const SizedBox(width: 8),
+ FilledButton(
+ onPressed: state._connecting ? null : state._connect,
+ child: state._connecting
+ ? SizedBox(
+ width: 18,
+ height: 18,
+ child: CircularProgressIndicator(
+ strokeWidth: 2,
+ color: cs.onPrimary,
+ ),
+ )
+ : Text(l.rmabConfigConnect),
+ ),
+ ],
+ ),
+ if (state._wasConfigured) ...[
+ const SizedBox(height: 8),
+ const Divider(height: 24),
+ Row(children: [
+ Expanded(
+ child: OutlinedButton.icon(
+ onPressed: state._connecting ? null : state._openWebView,
+ icon: const Icon(Icons.open_in_browser_rounded, size: 18),
+ label: Text(l.rmabConfigOpenWebView),
+ ),
+ ),
+ const SizedBox(width: 12),
+ TextButton(
+ onPressed: state._connecting ? null : state._disconnect,
+ style: TextButton.styleFrom(foregroundColor: cs.error),
+ child: Text(l.rmabConfigDisconnect),
+ ),
+ ]),
+ ],
+ ],
+ );
+ }
+
+ /// If the user changed credentials without a disconnect, signal `changed: true`
+ /// so the caller refreshes its tile state.
+ RmabConfigResult _resultForCurrentState(_RmabConfigSheetState s) {
+ return s._connectedAsName != null
+ ? const RmabConfigResult(changed: true)
+ : const RmabConfigResult();
+ }
+}
+
+class _SetupTab extends StatelessWidget {
+ const _SetupTab({required this.state});
+ final _RmabConfigSheetState state;
+
+ @override
+ Widget build(BuildContext context) {
+ final mediaQuery = MediaQuery.of(context);
+ return Padding(
+ padding: EdgeInsets.only(bottom: mediaQuery.viewInsets.bottom),
+ child: SingleChildScrollView(
+ padding: const EdgeInsets.fromLTRB(20, 16, 20, 24),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ _ExplainerBlock(state: state),
+ const SizedBox(height: 20),
+ _SetupForm(state: state),
+ ],
+ ),
+ ),
+ );
+ }
+}
+
+// ─── My Requests tab ─────────────────────────────────────────────
+
+class _MyRequestsTab extends StatefulWidget {
+ const _MyRequestsTab({
+ super.key,
+ required this.state,
+ required this.scrollController,
+ });
+ final _RmabConfigSheetState state;
+ final ScrollController scrollController;
+
+ @override
+ State<_MyRequestsTab> createState() => _MyRequestsTabState();
+}
+
+class _MyRequestsTabState extends State<_MyRequestsTab>
+ with AutomaticKeepAliveClientMixin {
+ @override
+ bool get wantKeepAlive => true;
+
+ bool _loading = true;
+ String? _error;
+ RmabRequestsPage? _page;
+
+ @override
+ void initState() {
+ super.initState();
+ _fetch();
+ }
+
+ Future<void> _fetch() async {
+ debugPrint('[RMAB] my-requests tab fetching');
+ final base = await ScopedPrefs.getString(kRmabBaseUrlKey);
+ final token = await ScopedPrefs.getString(kRmabApiTokenKey);
+ if (!mounted) return;
+ if (base == null || base.isEmpty || token == null || token.isEmpty) {
+ debugPrint('[RMAB] my-requests: no creds, showing error');
+ setState(() {
+ _loading = false;
+ _error = AppLocalizations.of(context)!.rmabConfigErrorUnauthorized;
+ });
+ return;
+ }
+ setState(() {
+ _loading = true;
+ _error = null;
+ });
+ try {
+ final page = await RmabService(baseUrl: base, apiToken: token)
+ .listRequests(myOnly: true, take: 50);
+ if (!mounted) return;
+ setState(() {
+ _page = page;
+ _loading = false;
+ });
+ } on RmabException catch (e) {
+ if (!mounted) return;
+ debugPrint('[RMAB] my-requests error: ${e.kind} ${e.message}');
+ setState(() {
+ _error = _msgForException(e);
+ _loading = false;
+ });
+ } catch (e) {
+ if (!mounted) return;
+ debugPrint('[RMAB] my-requests unexpected: $e');
+ setState(() {
+ _error = e.toString();
+ _loading = false;
+ });
+ }
+ }
+
+ String _msgForException(RmabException e) {
+ final l = AppLocalizations.of(context)!;
+ switch (e.kind) {
+ case RmabErrorKind.unauthorized:
+ return l.rmabRequestErrorTokenRejected;
+ case RmabErrorKind.network:
+ return l.rmabConfigErrorNetwork;
+ default:
+ return '${l.rmabMyRequestsError}: ${e.message}';
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ super.build(context);
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ final l = AppLocalizations.of(context)!;
+
+ return Column(
+ children: [
+ // ── Tab toolbar ────────────────────────────────
+ Padding(
+ padding: const EdgeInsets.fromLTRB(20, 8, 8, 4),
+ child: Row(children: [
+ Expanded(
+ child: Text(
+ _page == null
+ ? ''
+ : _countLabel(_page!.counts.all, l),
+ style: tt.labelMedium
+ ?.copyWith(color: cs.onSurfaceVariant),
+ ),
+ ),
+ IconButton(
+ icon: const Icon(Icons.refresh_rounded),
+ tooltip: l.rmabMyRequestsRefresh,
+ onPressed: _loading ? null : _fetch,
+ ),
+ ]),
+ ),
+ Expanded(child: _buildBody(cs, tt, l)),
+ ],
+ );
+ }
+
+ String _countLabel(int n, AppLocalizations l) {
+ return n == 1 ? '1 request' : '$n requests';
+ }
+
+ Widget _buildBody(
+ ColorScheme cs, TextTheme tt, AppLocalizations l) {
+ if (_loading) {
+ // Wrap the spinner in a scrollable so drag-to-dismiss still works
+ // while we're fetching. AlwaysScrollableScrollPhysics ensures the
+ // gesture bubbles up to the DraggableScrollableSheet for dismissal.
+ return ListView(
+ controller: widget.scrollController,
+ physics: const AlwaysScrollableScrollPhysics(),
+ padding: const EdgeInsets.fromLTRB(24, 80, 24, 24),
+ children: const [
+ Center(child: CircularProgressIndicator(strokeWidth: 2)),
+ ],
+ );
+ }
+ if (_error != null) {
+ return ListView(
+ controller: widget.scrollController,
+ physics: const AlwaysScrollableScrollPhysics(),
+ padding: const EdgeInsets.fromLTRB(24, 60, 24, 24),
+ children: [
+ Icon(Icons.error_outline_rounded, size: 40, color: cs.error),
+ const SizedBox(height: 12),
+ Center(
+ child: Text(
+ _error!,
+ textAlign: TextAlign.center,
+ style: tt.bodyMedium?.copyWith(color: cs.error),
+ ),
+ ),
+ const SizedBox(height: 16),
+ Center(
+ child: TextButton.icon(
+ icon: const Icon(Icons.refresh_rounded, size: 18),
+ label: Text(l.rmabMyRequestsRefresh),
+ onPressed: _fetch,
+ ),
+ ),
+ ],
+ );
+ }
+ final requests = _page?.requests ?? const <RmabRequest>[];
+ if (requests.isEmpty) {
+ return ListView(
+ controller: widget.scrollController,
+ physics: const AlwaysScrollableScrollPhysics(),
+ padding: const EdgeInsets.fromLTRB(24, 60, 24, 24),
+ children: [
+ Icon(Icons.inbox_rounded,
+ size: 40, color: cs.onSurfaceVariant.withValues(alpha: 0.5)),
+ const SizedBox(height: 12),
+ Center(
+ child: Text(
+ l.rmabMyRequestsEmpty,
+ textAlign: TextAlign.center,
+ style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant),
+ ),
+ ),
+ ],
+ );
+ }
+ return ListView.builder(
+ controller: widget.scrollController,
+ physics: const AlwaysScrollableScrollPhysics(),
+ padding: EdgeInsets.fromLTRB(
+ 16, 4, 16, 16 + MediaQuery.of(context).viewPadding.bottom),
+ itemCount: requests.length,
+ itemBuilder: (_, i) => _RequestRow(
+ request: requests[i],
+ onTap: () => _openRequestDetail(requests[i]),
+ ),
+ );
+ }
+
+ void _openRequestDetail(RmabRequest req) {
+ showModalBottomSheet<void>(
+ context: context,
+ isScrollControlled: true,
+ showDragHandle: true,
+ backgroundColor: Theme.of(context).colorScheme.surface,
+ shape: const RoundedRectangleBorder(
+ borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
+ ),
+ builder: (_) => _RequestDetailSheet(request: req),
+ );
+ }
+}
+
+class _RequestRow extends StatelessWidget {
+ const _RequestRow({required this.request, required this.onTap});
+ final RmabRequest request;
+ final VoidCallback onTap;
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ final book = request.audiobook;
+ return Padding(
+ padding: const EdgeInsets.only(bottom: 10),
+ child: Material(
+ color: cs.surfaceContainerHighest.withValues(alpha: 0.4),
+ borderRadius: BorderRadius.circular(12),
+ clipBehavior: Clip.antiAlias,
+ child: InkWell(
+ onTap: onTap,
+ child: Padding(
+ padding: const EdgeInsets.all(10),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ ClipRRect(
+ borderRadius: BorderRadius.circular(8),
+ child: SizedBox(
+ width: 56,
+ height: 56,
+ child: (book.coverArtUrl == null ||
+ book.coverArtUrl!.isEmpty)
+ ? Container(
+ color: cs.surfaceContainerHighest,
+ child: Icon(Icons.menu_book_rounded,
+ color: cs.onSurfaceVariant, size: 20),
+ )
+ : CachedNetworkImage(
+ imageUrl: book.coverArtUrl!,
+ fit: BoxFit.cover,
+ placeholder: (_, __) => Container(
+ color: cs.surfaceContainerHighest),
+ errorWidget: (_, __, ___) => Container(
+ color: cs.surfaceContainerHighest,
+ child: Icon(Icons.broken_image_rounded,
+ color: cs.onSurfaceVariant, size: 20),
+ ),
+ ),
+ ),
+ ),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ book.title,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: tt.bodyMedium
+ ?.copyWith(fontWeight: FontWeight.w600),
+ ),
+ if (book.author.isNotEmpty) ...[
+ const SizedBox(height: 2),
+ Text(
+ book.author,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: tt.bodySmall
+ ?.copyWith(color: cs.onSurfaceVariant),
+ ),
+ ],
+ const SizedBox(height: 6),
+ Row(children: [
+ RmabRequestStatusChip(rawStatus: request.status),
+ const SizedBox(width: 8),
+ Expanded(
+ child: Text(
+ _formatRelative(request.createdAt),
+ style: tt.labelSmall?.copyWith(
+ color: cs.onSurfaceVariant
+ .withValues(alpha: 0.7)),
+ ),
+ ),
+ ]),
+ ],
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ String _formatRelative(DateTime dt) {
+ final now = DateTime.now();
+ final diff = now.difference(dt);
+ if (diff.inMinutes < 1) return 'just now';
+ if (diff.inHours < 1) return '${diff.inMinutes}m ago';
+ if (diff.inDays < 1) return '${diff.inHours}h ago';
+ if (diff.inDays < 30) return '${diff.inDays}d ago';
+ final months = diff.inDays ~/ 30;
+ if (months < 12) return '${months}mo ago';
+ final years = diff.inDays ~/ 365;
+ return '${years}y ago';
+ }
+}
+
+// ─── Request detail sub-sheet ────────────────────────────────────
+
+class _RequestDetailSheet extends StatelessWidget {
+ const _RequestDetailSheet({required this.request});
+ final RmabRequest request;
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ final l = AppLocalizations.of(context)!;
+ final book = request.audiobook;
+
+ return Padding(
+ padding: const EdgeInsets.fromLTRB(20, 4, 20, 32),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(l.rmabRequestDetailTitle,
+ style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600)),
+ const SizedBox(height: 12),
+ Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ ClipRRect(
+ borderRadius: BorderRadius.circular(10),
+ child: SizedBox(
+ width: 88,
+ height: 88,
+ child: (book.coverArtUrl == null ||
+ book.coverArtUrl!.isEmpty)
+ ? Container(
+ color: cs.surfaceContainerHighest,
+ child: Icon(Icons.menu_book_rounded,
+ color: cs.onSurfaceVariant, size: 28),
+ )
+ : CachedNetworkImage(
+ imageUrl: book.coverArtUrl!,
+ fit: BoxFit.cover,
+ placeholder: (_, __) => Container(
+ color: cs.surfaceContainerHighest),
+ errorWidget: (_, __, ___) => Container(
+ color: cs.surfaceContainerHighest,
+ child: Icon(Icons.broken_image_rounded,
+ color: cs.onSurfaceVariant, size: 28),
+ ),
+ ),
+ ),
+ ),
+ const SizedBox(width: 14),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(book.title,
+ style: tt.titleSmall
+ ?.copyWith(fontWeight: FontWeight.w600)),
+ if (book.author.isNotEmpty) ...[
+ const SizedBox(height: 2),
+ Text(book.author,
+ style: tt.bodySmall
+ ?.copyWith(color: cs.onSurfaceVariant)),
+ ],
+ if (book.narrator != null && book.narrator!.isNotEmpty) ...[
+ const SizedBox(height: 2),
+ Text(l.narratedBy(book.narrator!),
+ style: tt.bodySmall
+ ?.copyWith(color: cs.onSurfaceVariant)),
+ ],
+ const SizedBox(height: 8),
+ RmabRequestStatusChip(
+ rawStatus: request.status, dense: false),
+ ],
+ ),
+ ),
+ ]),
+ const SizedBox(height: 18),
+ _kvRow(context, l.rmabRequestDetailRequestedOn,
+ _formatDate(request.createdAt)),
+ if (request.completedAt != null)
+ _kvRow(context, l.rmabRequestDetailCompletedOn,
+ _formatDate(request.completedAt!)),
+ if (request.statusGroup == RmabStatusGroup.active &&
+ request.progress > 0)
+ Padding(
+ padding: const EdgeInsets.only(top: 12),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(l.rmabRequestDetailProgress,
+ style: tt.labelMedium
+ ?.copyWith(color: cs.onSurfaceVariant)),
+ const SizedBox(height: 6),
+ ClipRRect(
+ borderRadius: BorderRadius.circular(4),
+ child: LinearProgressIndicator(
+ value: (request.progress / 100).clamp(0, 1).toDouble(),
+ minHeight: 6,
+ ),
+ ),
+ ],
+ ),
+ ),
+ if (request.errorMessage != null &&
+ request.errorMessage!.isNotEmpty) ...[
+ const SizedBox(height: 14),
+ Container(
+ padding: const EdgeInsets.all(12),
+ decoration: BoxDecoration(
+ color: cs.errorContainer.withValues(alpha: 0.5),
+ borderRadius: BorderRadius.circular(10),
+ ),
+ child: Text(request.errorMessage!,
+ style: tt.bodySmall?.copyWith(color: cs.onErrorContainer)),
+ ),
+ ],
+ ],
+ ),
+ );
+ }
+
+ Widget _kvRow(BuildContext context, String label, String value) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ return Padding(
+ padding: const EdgeInsets.only(bottom: 6),
+ child: Row(children: [
+ SizedBox(
+ width: 110,
+ child: Text(label,
+ style: tt.labelMedium
+ ?.copyWith(color: cs.onSurfaceVariant)),
+ ),
+ Expanded(
+ child: Text(value, style: tt.bodyMedium),
+ ),
+ ]),
+ );
+ }
+
+ String _formatDate(DateTime dt) {
+ // YYYY-MM-DD HH:mm in local time, matches the rest of the app's
+ // unfussy date rendering.
+ String two(int v) => v.toString().padLeft(2, '0');
+ final l = dt.toLocal();
+ return '${l.year}-${two(l.month)}-${two(l.day)} '
+ '${two(l.hour)}:${two(l.minute)}';
+ }
+}
diff --git a/lib/widgets/rmab_request_status_chip.dart b/lib/widgets/rmab_request_status_chip.dart
new file mode 100644
index 00000000..473152c3
--- /dev/null
+++ b/lib/widgets/rmab_request_status_chip.dart
@@ -0,0 +1,101 @@
+import 'package:flutter/material.dart';
+
+import '../l10n/app_localizations.dart';
+import '../services/rmab_service.dart';
+
+/// Small status pill for an RMAB request, used in search result rows, request
+/// list rows, and book detail banners. Maps the raw server status string to a
+/// visual group + label.
+class RmabRequestStatusChip extends StatelessWidget {
+ const RmabRequestStatusChip({
+ super.key,
+ required this.rawStatus,
+ this.dense = true,
+ });
+
+ /// Raw status string from the server (e.g. `pending`, `downloading`).
+ final String rawStatus;
+
+ /// `true` for compact in-list use; `false` for a more prominent banner-style
+ /// chip with a leading icon.
+ final bool dense;
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ final l = AppLocalizations.of(context)!;
+
+ final spec = _specFor(rawStatus, cs, l);
+
+ final bg = spec.color.withValues(alpha: 0.16);
+ final fg = spec.color;
+
+ return Container(
+ padding: dense
+ ? const EdgeInsets.symmetric(horizontal: 8, vertical: 3)
+ : const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
+ decoration: BoxDecoration(
+ color: bg,
+ borderRadius: BorderRadius.circular(dense ? 6 : 8),
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ if (!dense) ...[
+ Icon(spec.icon, size: 14, color: fg),
+ const SizedBox(width: 6),
+ ],
+ Text(
+ spec.label,
+ style: (dense ? tt.labelSmall : tt.labelMedium)?.copyWith(
+ color: fg,
+ fontWeight: FontWeight.w600,
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+
+ _ChipSpec _specFor(String raw, ColorScheme cs, AppLocalizations l) {
+ final group = raw.rmabGroup;
+ switch (group) {
+ case RmabStatusGroup.active:
+ return _ChipSpec(l.rmabStatusActive, cs.primary, Icons.sync_rounded);
+ case RmabStatusGroup.waiting:
+ return _ChipSpec(
+ l.rmabStatusWaiting,
+ cs.tertiary,
+ Icons.hourglass_top_rounded,
+ );
+ case RmabStatusGroup.completed:
+ // Distinguish 'available' (matched in library) from 'downloaded'
+ final label = raw == 'available'
+ ? l.rmabStatusAvailable
+ : l.rmabStatusDownloaded;
+ return _ChipSpec(label, Colors.green.shade600, Icons.check_circle_rounded);
+ case RmabStatusGroup.failed:
+ return _ChipSpec(l.rmabStatusFailed, cs.error, Icons.error_outline_rounded);
+ case RmabStatusGroup.cancelled:
+ final label = raw == 'denied'
+ ? l.rmabStatusDenied
+ : l.rmabStatusCancelled;
+ return _ChipSpec(label, cs.onSurfaceVariant, Icons.block_rounded);
+ case null:
+ // `warn` falls here, plus anything unknown
+ return _ChipSpec(
+ raw.isEmpty ? l.rmabStatusUnknown : raw,
+ cs.tertiary,
+ Icons.info_outline_rounded,
+ );
+ }
+ }
+}
+
+class _ChipSpec {
+ const _ChipSpec(this.label, this.color, this.icon);
+ final String label;
+ final Color color;
+ final IconData icon;
+}
diff --git a/lib/widgets/rmab_search_results_sheet.dart b/lib/widgets/rmab_search_results_sheet.dart
new file mode 100644
index 00000000..0304291c
--- /dev/null
+++ b/lib/widgets/rmab_search_results_sheet.dart
@@ -0,0 +1,474 @@
+import 'dart:async';
+
+import 'package:cached_network_image/cached_network_image.dart';
+import 'package:flutter/material.dart';
+
+import '../l10n/app_localizations.dart';
+import '../services/rmab_service.dart';
+import '../services/scoped_prefs.dart';
+import 'rmab_book_detail_sheet.dart';
+import 'rmab_config_sheet.dart' show kRmabBaseUrlKey, kRmabApiTokenKey;
+import 'rmab_request_status_chip.dart';
+import 'stackable_sheet.dart';
+
+/// Open the RMAB search-results sheet, prefilled with [initialQuery] and
+/// running the first search automatically when the query is non-empty.
+Future<void> showRmabSearchResultsSheet(
+ BuildContext context, {
+ required String initialQuery,
+}) {
+ return showStackableSheet<void>(
+ context: context,
+ initialChildSize: 0.85,
+ maxChildSize: 0.95,
+ showHandle: true,
+ backgroundColor: Theme.of(context).colorScheme.surface,
+ useSafeArea: true,
+ builder: (ctx, sc) => _RmabSearchSheetContent(
+ initialQuery: initialQuery,
+ scrollController: sc,
+ ),
+ );
+}
+
+class _RmabSearchSheetContent extends StatefulWidget {
+ const _RmabSearchSheetContent({
+ required this.initialQuery,
+ required this.scrollController,
+ });
+
+ final String initialQuery;
+ final ScrollController scrollController;
+
+ @override
+ State<_RmabSearchSheetContent> createState() =>
+ _RmabSearchSheetContentState();
+}
+
+class _RmabSearchSheetContentState extends State<_RmabSearchSheetContent> {
+ late final TextEditingController _controller =
+ TextEditingController(text: widget.initialQuery);
+ final _focus = FocusNode();
+ Timer? _debounce;
+
+ bool _loadingPrefs = true;
+ String? _baseUrl;
+ String? _apiToken;
+
+ bool _searching = false;
+ String? _error;
+ List<RmabSearchResult> _results = [];
+
+ /// Query that produced the current [_results] — used to ignore stale
+ /// responses after the user has typed something new.
+ String _lastQuery = '';
+
+ @override
+ void initState() {
+ super.initState();
+ _loadCreds();
+ }
+
+ Future<void> _loadCreds() async {
+ final base = await ScopedPrefs.getString(kRmabBaseUrlKey);
+ final token = await ScopedPrefs.getString(kRmabApiTokenKey);
+ if (!mounted) return;
+ debugPrint('[RMAB] search sheet opened '
+ '(initialQuery="${widget.initialQuery}" '
+ 'configured=${(base ?? '').isNotEmpty && (token ?? '').isNotEmpty})');
+ setState(() {
+ _baseUrl = base;
+ _apiToken = token;
+ _loadingPrefs = false;
+ });
+ if (base != null &&
+ base.isNotEmpty &&
+ token != null &&
+ token.isNotEmpty &&
+ widget.initialQuery.trim().isNotEmpty) {
+ _runSearch(widget.initialQuery.trim());
+ }
+ }
+
+ @override
+ void dispose() {
+ _debounce?.cancel();
+ _controller.dispose();
+ _focus.dispose();
+ super.dispose();
+ }
+
+ void _onQueryChanged(String value) {
+ _debounce?.cancel();
+ final trimmed = value.trim();
+ if (trimmed.isEmpty) {
+ setState(() {
+ _results = [];
+ _error = null;
+ _searching = false;
+ _lastQuery = '';
+ });
+ return;
+ }
+ _debounce = Timer(const Duration(milliseconds: 400), () {
+ _runSearch(trimmed);
+ });
+ }
+
+ Future<void> _runSearch(String query) async {
+ final base = _baseUrl;
+ final token = _apiToken;
+ if (base == null || base.isEmpty || token == null || token.isEmpty) {
+ return;
+ }
+ setState(() {
+ _searching = true;
+ _error = null;
+ });
+ try {
+ final res =
+ await RmabService(baseUrl: base, apiToken: token).search(query);
+ if (!mounted) return;
+ // Drop stale results
+ if (_controller.text.trim() != query) return;
+ setState(() {
+ _results = res.results;
+ _searching = false;
+ _lastQuery = query;
+ });
+ } on RmabException catch (e) {
+ if (!mounted) return;
+ debugPrint('[RMAB] search sheet error: ${e.kind} ${e.message}');
+ setState(() {
+ _searching = false;
+ _error = _errorTextFor(e);
+ });
+ } catch (e) {
+ if (!mounted) return;
+ debugPrint('[RMAB] search sheet unexpected error: $e');
+ setState(() {
+ _searching = false;
+ _error = e.toString();
+ });
+ }
+ }
+
+ String _errorTextFor(RmabException e) {
+ final l = AppLocalizations.of(context)!;
+ switch (e.kind) {
+ case RmabErrorKind.unauthorized:
+ return l.rmabRequestErrorTokenRejected;
+ case RmabErrorKind.network:
+ return l.rmabConfigErrorNetwork;
+ default:
+ return '${l.rmabSearchError}: ${e.message}';
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ final l = AppLocalizations.of(context)!;
+
+ return ClipRRect(
+ borderRadius:
+ const BorderRadius.vertical(top: Radius.circular(24)),
+ child: Container(
+ color: cs.surface,
+ child: Column(
+ children: [
+ // ── Header row ────────────────────────────
+ Padding(
+ padding: const EdgeInsets.fromLTRB(20, 4, 12, 4),
+ child: Row(
+ children: [
+ Icon(Icons.menu_book_rounded,
+ color: cs.primary, size: 22),
+ const SizedBox(width: 10),
+ Expanded(
+ child: Text(
+ l.rmabSearchHeader,
+ style: tt.titleMedium
+ ?.copyWith(fontWeight: FontWeight.w600),
+ ),
+ ),
+ IconButton(
+ icon: const Icon(Icons.close_rounded),
+ onPressed: () => Navigator.of(context).pop(),
+ tooltip: l.cancel,
+ ),
+ ],
+ ),
+ ),
+
+ // ── Search field ──────────────────────────
+ Padding(
+ padding: const EdgeInsets.fromLTRB(20, 0, 20, 12),
+ child: TextField(
+ controller: _controller,
+ focusNode: _focus,
+ autocorrect: false,
+ onChanged: _onQueryChanged,
+ onSubmitted: (v) => _runSearch(v.trim()),
+ decoration: InputDecoration(
+ hintText: l.rmabSearchHint,
+ prefixIcon: const Icon(Icons.search_rounded),
+ suffixIcon: _controller.text.isEmpty
+ ? null
+ : IconButton(
+ icon: const Icon(Icons.clear_rounded),
+ onPressed: () {
+ _controller.clear();
+ _onQueryChanged('');
+ _focus.requestFocus();
+ },
+ ),
+ border: const OutlineInputBorder(),
+ isDense: true,
+ ),
+ ),
+ ),
+
+ const Divider(height: 1),
+
+ // ── Body ──────────────────────────────────
+ Expanded(child: _buildBody(cs, tt, l)),
+ ],
+ ),
+ ),
+ );
+ }
+
+ Widget _buildBody(
+ ColorScheme cs, TextTheme tt, AppLocalizations l) {
+ if (_loadingPrefs) {
+ return const Center(child: CircularProgressIndicator(strokeWidth: 2));
+ }
+ if (_searching) {
+ return ListView(
+ controller: widget.scrollController,
+ children: const [
+ SizedBox(height: 80),
+ Center(child: CircularProgressIndicator(strokeWidth: 2)),
+ ],
+ );
+ }
+ if (_error != null) {
+ return ListView(
+ controller: widget.scrollController,
+ padding: const EdgeInsets.fromLTRB(24, 80, 24, 24),
+ children: [
+ Icon(Icons.error_outline_rounded,
+ size: 40, color: cs.error),
+ const SizedBox(height: 12),
+ Center(
+ child: Text(
+ _error!,
+ textAlign: TextAlign.center,
+ style: tt.bodyMedium?.copyWith(color: cs.error),
+ ),
+ ),
+ ],
+ );
+ }
+ if (_lastQuery.isEmpty) {
+ return ListView(
+ controller: widget.scrollController,
+ padding: const EdgeInsets.fromLTRB(24, 80, 24, 24),
+ children: [
+ Icon(Icons.search_rounded,
+ size: 40, color: cs.onSurfaceVariant.withValues(alpha: 0.5)),
+ const SizedBox(height: 12),
+ Center(
+ child: Text(
+ l.rmabSearchPrompt,
+ textAlign: TextAlign.center,
+ style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant),
+ ),
+ ),
+ ],
+ );
+ }
+ if (_results.isEmpty) {
+ return ListView(
+ controller: widget.scrollController,
+ padding: const EdgeInsets.fromLTRB(24, 80, 24, 24),
+ children: [
+ Icon(Icons.search_off_rounded,
+ size: 40, color: cs.onSurfaceVariant.withValues(alpha: 0.5)),
+ const SizedBox(height: 12),
+ Center(
+ child: Text(
+ l.rmabSearchEmpty,
+ textAlign: TextAlign.center,
+ style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant),
+ ),
+ ),
+ ],
+ );
+ }
+
+ return ListView.builder(
+ controller: widget.scrollController,
+ padding: EdgeInsets.fromLTRB(
+ 16, 8, 16, 24 + MediaQuery.of(context).viewPadding.bottom),
+ itemCount: _results.length,
+ itemBuilder: (_, i) => _RmabResultRow(
+ book: _results[i],
+ onTap: () => showRmabBookDetailSheet(context, book: _results[i]),
+ ),
+ );
+ }
+}
+
+class _RmabResultRow extends StatelessWidget {
+ const _RmabResultRow({required this.book, required this.onTap});
+ final RmabSearchResult book;
+ final VoidCallback onTap;
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ final l = AppLocalizations.of(context)!;
+
+ // Merge the server's view with our session-local cache so a freshly
+ // requested book shows the status chip immediately, even before the
+ // next search round-trip refreshes the data.
+ final cachedStatus = RmabLocalRequestCache.statusFor(book.asin);
+ final effectiveStatus = book.requestStatus ?? cachedStatus;
+ final effectiveRequested = book.isRequested || cachedStatus != null;
+
+ return Padding(
+ padding: const EdgeInsets.only(bottom: 10),
+ child: Material(
+ color: cs.surfaceContainerHighest.withValues(alpha: 0.4),
+ borderRadius: BorderRadius.circular(12),
+ clipBehavior: Clip.antiAlias,
+ child: InkWell(
+ onTap: onTap,
+ child: Padding(
+ padding: const EdgeInsets.all(10),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ ClipRRect(
+ borderRadius: BorderRadius.circular(8),
+ child: SizedBox(
+ width: 64,
+ height: 64,
+ child: (book.coverArtUrl == null ||
+ book.coverArtUrl!.isEmpty)
+ ? Container(
+ color: cs.surfaceContainerHighest,
+ child: Icon(Icons.menu_book_rounded,
+ color: cs.onSurfaceVariant, size: 22),
+ )
+ : CachedNetworkImage(
+ imageUrl: book.coverArtUrl!,
+ fit: BoxFit.cover,
+ placeholder: (_, __) => Container(
+ color: cs.surfaceContainerHighest),
+ errorWidget: (_, __, ___) => Container(
+ color: cs.surfaceContainerHighest,
+ child: Icon(Icons.broken_image_rounded,
+ color: cs.onSurfaceVariant, size: 22),
+ ),
+ ),
+ ),
+ ),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ book.title,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: tt.bodyMedium
+ ?.copyWith(fontWeight: FontWeight.w600),
+ ),
+ if (book.author.isNotEmpty) ...[
+ const SizedBox(height: 2),
+ Text(
+ book.author,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: tt.bodySmall
+ ?.copyWith(color: cs.onSurfaceVariant),
+ ),
+ ],
+ if (book.narrator != null &&
+ book.narrator!.isNotEmpty) ...[
+ const SizedBox(height: 1),
+ Text(
+ l.narratedBy(book.narrator!),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: tt.bodySmall?.copyWith(
+ color: cs.onSurfaceVariant
+ .withValues(alpha: 0.7)),
+ ),
+ ],
+ const SizedBox(height: 6),
+ Wrap(
+ spacing: 6,
+ runSpacing: 4,
+ children: [
+ if (book.releaseYear != null)
+ _miniTag(
+ cs, tt, Icons.event_rounded,
+ '${book.releaseYear}'),
+ if (book.isAvailable)
+ _miniTag(
+ cs,
+ tt,
+ Icons.check_circle_rounded,
+ l.rmabBookAlreadyAvailable,
+ color: Colors.green.shade600,
+ ),
+ if (effectiveRequested && effectiveStatus != null)
+ RmabRequestStatusChip(
+ rawStatus: effectiveStatus),
+ ],
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ Widget _miniTag(
+ ColorScheme cs,
+ TextTheme tt,
+ IconData icon,
+ String label, {
+ Color? color,
+ }) {
+ final c = color ?? cs.onSurfaceVariant;
+ return Container(
+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
+ decoration: BoxDecoration(
+ color: c.withValues(alpha: 0.14),
+ borderRadius: BorderRadius.circular(6),
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(icon, size: 12, color: c),
+ const SizedBox(width: 4),
+ Text(label,
+ style:
+ tt.labelSmall?.copyWith(color: c, fontWeight: FontWeight.w600)),
+ ],
+ ),
+ );
+ }
+}