Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Send to e-reader, admin email page, and admins can do most admin actions

Barnabase72225cdb51d
diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb
index 250fb726..92b54a6e 100644
--- a/lib/l10n/app_en.arb
+++ b/lib/l10n/app_en.arb
@@ -853,6 +853,8 @@
"collectionNotFound": "Collection not found",
"deleteCollection": "Delete Collection",
"deleteCollectionContent": "Are you sure you want to delete this collection?",
+ "deleteCollectionFailed": "Couldn't delete the collection",
+ "deletePermissionRequired": "Delete permission required. Ask the root admin to grant you the delete permission.",
"playlistNotFound": "Playlist not found",
"deletePlaylist": "Delete Playlist",
"deletePlaylistContent": "Are you sure you want to delete this playlist?",
@@ -993,6 +995,47 @@
"updateDownloading": "Downloading update...",
"updateInstallPermissionDenied": "Install permission denied. Enable \"Install unknown apps\" for Absorb in system settings.",
"updateOpeningInBrowser": "In-app update failed, opening browser",
+ "sendToEreader": "Send to E-Reader",
+ "sendingToEreader": "Sending to {device}...",
+ "@sendingToEreader": { "placeholders": { "device": { "type": "String" } } },
+ "sendToEreaderSuccess": "Sent to {device}",
+ "@sendToEreaderSuccess": { "placeholders": { "device": { "type": "String" } } },
+ "sendToEreaderFailed": "Couldn't send the ebook",
+ "pickEreaderDevice": "Pick a device",
+ "adminEmail": "Email",
+ "adminEmailSubtitle": "SMTP and e-reader devices",
+ "smtpSection": "SMTP",
+ "smtpSetupGuide": "Setup guide",
+ "smtpHost": "Host",
+ "smtpPort": "Port",
+ "smtpSecure": "Secure",
+ "smtpRejectUnauthorized": "Reject unauthorized TLS",
+ "smtpUser": "Username",
+ "smtpPass": "Password",
+ "smtpFromAddress": "From address",
+ "smtpTestAddress": "Test address",
+ "smtpSendTest": "Send test",
+ "smtpSaveSettings": "Save",
+ "smtpSaved": "Email settings saved",
+ "smtpSaveFailed": "Couldn't save email settings",
+ "smtpTestSent": "Test email sent",
+ "smtpTestFailed": "Test email failed",
+ "ereaderDevicesTitle": "E-Reader devices",
+ "ereaderDevicesEmpty": "No devices yet. Add one below.",
+ "addEreaderDevice": "Add device",
+ "editEreaderDevice": "Edit device",
+ "deleteEreaderDevice": "Delete",
+ "ereaderDeviceName": "Name",
+ "ereaderDeviceEmail": "Email",
+ "ereaderAvailability": "Who can use this device",
+ "ereaderAvailAdminOrUp": "Admins only",
+ "ereaderAvailUserOrUp": "All users",
+ "ereaderAvailGuestOrUp": "Everyone",
+ "ereaderAvailSpecificUsers": "Specific users",
+ "ereaderSpecificUsersN": "Specific users ({count})",
+ "@ereaderSpecificUsersN": { "placeholders": { "count": { "type": "int" } } },
+ "ereaderDevicesSaved": "Devices saved",
+ "ereaderDevicesSaveFailed": "Couldn't save devices",
"libraryCountOne": "{count} library",
"@libraryCountOne": { "placeholders": { "count": { "type": "int" } } },
"libraryCountOther": "{count} libraries",
diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart
index 775ae5b2..6236721b 100644
--- a/lib/l10n/app_localizations.dart
+++ b/lib/l10n/app_localizations.dart
@@ -4594,6 +4594,18 @@ abstract class AppLocalizations {
/// **'Are you sure you want to delete this collection?'**
String get deleteCollectionContent;
+ /// No description provided for @deleteCollectionFailed.
+ ///
+ /// In en, this message translates to:
+ /// **'Couldn\'t delete the collection'**
+ String get deleteCollectionFailed;
+
+ /// No description provided for @deletePermissionRequired.
+ ///
+ /// In en, this message translates to:
+ /// **'Delete permission required. Ask the root admin to grant you the delete permission.'**
+ String get deletePermissionRequired;
+
/// No description provided for @playlistNotFound.
///
/// In en, this message translates to:
@@ -5285,6 +5297,234 @@ abstract class AppLocalizations {
/// **'In-app update failed, opening browser'**
String get updateOpeningInBrowser;
+ /// No description provided for @sendToEreader.
+ ///
+ /// In en, this message translates to:
+ /// **'Send to E-Reader'**
+ String get sendToEreader;
+
+ /// No description provided for @sendingToEreader.
+ ///
+ /// In en, this message translates to:
+ /// **'Sending to {device}...'**
+ String sendingToEreader(String device);
+
+ /// No description provided for @sendToEreaderSuccess.
+ ///
+ /// In en, this message translates to:
+ /// **'Sent to {device}'**
+ String sendToEreaderSuccess(String device);
+
+ /// No description provided for @sendToEreaderFailed.
+ ///
+ /// In en, this message translates to:
+ /// **'Couldn\'t send the ebook'**
+ String get sendToEreaderFailed;
+
+ /// No description provided for @pickEreaderDevice.
+ ///
+ /// In en, this message translates to:
+ /// **'Pick a device'**
+ String get pickEreaderDevice;
+
+ /// No description provided for @adminEmail.
+ ///
+ /// In en, this message translates to:
+ /// **'Email'**
+ String get adminEmail;
+
+ /// No description provided for @adminEmailSubtitle.
+ ///
+ /// In en, this message translates to:
+ /// **'SMTP and e-reader devices'**
+ String get adminEmailSubtitle;
+
+ /// No description provided for @smtpSection.
+ ///
+ /// In en, this message translates to:
+ /// **'SMTP'**
+ String get smtpSection;
+
+ /// No description provided for @smtpSetupGuide.
+ ///
+ /// In en, this message translates to:
+ /// **'Setup guide'**
+ String get smtpSetupGuide;
+
+ /// No description provided for @smtpHost.
+ ///
+ /// In en, this message translates to:
+ /// **'Host'**
+ String get smtpHost;
+
+ /// No description provided for @smtpPort.
+ ///
+ /// In en, this message translates to:
+ /// **'Port'**
+ String get smtpPort;
+
+ /// No description provided for @smtpSecure.
+ ///
+ /// In en, this message translates to:
+ /// **'Secure'**
+ String get smtpSecure;
+
+ /// No description provided for @smtpRejectUnauthorized.
+ ///
+ /// In en, this message translates to:
+ /// **'Reject unauthorized TLS'**
+ String get smtpRejectUnauthorized;
+
+ /// No description provided for @smtpUser.
+ ///
+ /// In en, this message translates to:
+ /// **'Username'**
+ String get smtpUser;
+
+ /// No description provided for @smtpPass.
+ ///
+ /// In en, this message translates to:
+ /// **'Password'**
+ String get smtpPass;
+
+ /// No description provided for @smtpFromAddress.
+ ///
+ /// In en, this message translates to:
+ /// **'From address'**
+ String get smtpFromAddress;
+
+ /// No description provided for @smtpTestAddress.
+ ///
+ /// In en, this message translates to:
+ /// **'Test address'**
+ String get smtpTestAddress;
+
+ /// No description provided for @smtpSendTest.
+ ///
+ /// In en, this message translates to:
+ /// **'Send test'**
+ String get smtpSendTest;
+
+ /// No description provided for @smtpSaveSettings.
+ ///
+ /// In en, this message translates to:
+ /// **'Save'**
+ String get smtpSaveSettings;
+
+ /// No description provided for @smtpSaved.
+ ///
+ /// In en, this message translates to:
+ /// **'Email settings saved'**
+ String get smtpSaved;
+
+ /// No description provided for @smtpSaveFailed.
+ ///
+ /// In en, this message translates to:
+ /// **'Couldn\'t save email settings'**
+ String get smtpSaveFailed;
+
+ /// No description provided for @smtpTestSent.
+ ///
+ /// In en, this message translates to:
+ /// **'Test email sent'**
+ String get smtpTestSent;
+
+ /// No description provided for @smtpTestFailed.
+ ///
+ /// In en, this message translates to:
+ /// **'Test email failed'**
+ String get smtpTestFailed;
+
+ /// No description provided for @ereaderDevicesTitle.
+ ///
+ /// In en, this message translates to:
+ /// **'E-Reader devices'**
+ String get ereaderDevicesTitle;
+
+ /// No description provided for @ereaderDevicesEmpty.
+ ///
+ /// In en, this message translates to:
+ /// **'No devices yet. Add one below.'**
+ String get ereaderDevicesEmpty;
+
+ /// No description provided for @addEreaderDevice.
+ ///
+ /// In en, this message translates to:
+ /// **'Add device'**
+ String get addEreaderDevice;
+
+ /// No description provided for @editEreaderDevice.
+ ///
+ /// In en, this message translates to:
+ /// **'Edit device'**
+ String get editEreaderDevice;
+
+ /// No description provided for @deleteEreaderDevice.
+ ///
+ /// In en, this message translates to:
+ /// **'Delete'**
+ String get deleteEreaderDevice;
+
+ /// No description provided for @ereaderDeviceName.
+ ///
+ /// In en, this message translates to:
+ /// **'Name'**
+ String get ereaderDeviceName;
+
+ /// No description provided for @ereaderDeviceEmail.
+ ///
+ /// In en, this message translates to:
+ /// **'Email'**
+ String get ereaderDeviceEmail;
+
+ /// No description provided for @ereaderAvailability.
+ ///
+ /// In en, this message translates to:
+ /// **'Who can use this device'**
+ String get ereaderAvailability;
+
+ /// No description provided for @ereaderAvailAdminOrUp.
+ ///
+ /// In en, this message translates to:
+ /// **'Admins only'**
+ String get ereaderAvailAdminOrUp;
+
+ /// No description provided for @ereaderAvailUserOrUp.
+ ///
+ /// In en, this message translates to:
+ /// **'All users'**
+ String get ereaderAvailUserOrUp;
+
+ /// No description provided for @ereaderAvailGuestOrUp.
+ ///
+ /// In en, this message translates to:
+ /// **'Everyone'**
+ String get ereaderAvailGuestOrUp;
+
+ /// No description provided for @ereaderAvailSpecificUsers.
+ ///
+ /// In en, this message translates to:
+ /// **'Specific users'**
+ String get ereaderAvailSpecificUsers;
+
+ /// No description provided for @ereaderSpecificUsersN.
+ ///
+ /// In en, this message translates to:
+ /// **'Specific users ({count})'**
+ String ereaderSpecificUsersN(int count);
+
+ /// No description provided for @ereaderDevicesSaved.
+ ///
+ /// In en, this message translates to:
+ /// **'Devices saved'**
+ String get ereaderDevicesSaved;
+
+ /// No description provided for @ereaderDevicesSaveFailed.
+ ///
+ /// In en, this message translates to:
+ /// **'Couldn\'t save devices'**
+ String get ereaderDevicesSaveFailed;
+
/// No description provided for @libraryCountOne.
///
/// In en, this message translates to:
diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart
index 30d7e55e..0f123db7 100644
--- a/lib/l10n/app_localizations_de.dart
+++ b/lib/l10n/app_localizations_de.dart
@@ -2507,6 +2507,13 @@ class AppLocalizationsDe extends AppLocalizations {
String get deleteCollectionContent =>
'Möchtest du diese Sammlung wirklich löschen?';
+ @override
+ String get deleteCollectionFailed => 'Couldn\'t delete the collection';
+
+ @override
+ String get deletePermissionRequired =>
+ 'Delete permission required. Ask the root admin to grant you the delete permission.';
+
@override
String get playlistNotFound => 'Playlist nicht gefunden';
@@ -2909,6 +2916,126 @@ class AppLocalizationsDe extends AppLocalizations {
@override
String get updateOpeningInBrowser => 'In-app update failed, opening browser';
+ @override
+ String get sendToEreader => 'Send to E-Reader';
+
+ @override
+ String sendingToEreader(String device) {
+ return 'Sending to $device...';
+ }
+
+ @override
+ String sendToEreaderSuccess(String device) {
+ return 'Sent to $device';
+ }
+
+ @override
+ String get sendToEreaderFailed => 'Couldn\'t send the ebook';
+
+ @override
+ String get pickEreaderDevice => 'Pick a device';
+
+ @override
+ String get adminEmail => 'Email';
+
+ @override
+ String get adminEmailSubtitle => 'SMTP and e-reader devices';
+
+ @override
+ String get smtpSection => 'SMTP';
+
+ @override
+ String get smtpSetupGuide => 'Setup guide';
+
+ @override
+ String get smtpHost => 'Host';
+
+ @override
+ String get smtpPort => 'Port';
+
+ @override
+ String get smtpSecure => 'Secure';
+
+ @override
+ String get smtpRejectUnauthorized => 'Reject unauthorized TLS';
+
+ @override
+ String get smtpUser => 'Username';
+
+ @override
+ String get smtpPass => 'Password';
+
+ @override
+ String get smtpFromAddress => 'From address';
+
+ @override
+ String get smtpTestAddress => 'Test address';
+
+ @override
+ String get smtpSendTest => 'Send test';
+
+ @override
+ String get smtpSaveSettings => 'Save';
+
+ @override
+ String get smtpSaved => 'Email settings saved';
+
+ @override
+ String get smtpSaveFailed => 'Couldn\'t save email settings';
+
+ @override
+ String get smtpTestSent => 'Test email sent';
+
+ @override
+ String get smtpTestFailed => 'Test email failed';
+
+ @override
+ String get ereaderDevicesTitle => 'E-Reader devices';
+
+ @override
+ String get ereaderDevicesEmpty => 'No devices yet. Add one below.';
+
+ @override
+ String get addEreaderDevice => 'Add device';
+
+ @override
+ String get editEreaderDevice => 'Edit device';
+
+ @override
+ String get deleteEreaderDevice => 'Delete';
+
+ @override
+ String get ereaderDeviceName => 'Name';
+
+ @override
+ String get ereaderDeviceEmail => 'Email';
+
+ @override
+ String get ereaderAvailability => 'Who can use this device';
+
+ @override
+ String get ereaderAvailAdminOrUp => 'Admins only';
+
+ @override
+ String get ereaderAvailUserOrUp => 'All users';
+
+ @override
+ String get ereaderAvailGuestOrUp => 'Everyone';
+
+ @override
+ String get ereaderAvailSpecificUsers => 'Specific users';
+
+ @override
+ String ereaderSpecificUsersN(int count) {
+ return 'Specific users ($count)';
+ }
+
+ @override
+ String get ereaderDevicesSaved => 'Devices saved';
+
+ @override
+ String get ereaderDevicesSaveFailed => 'Couldn\'t save devices';
+
@override
String libraryCountOne(int count) {
return '$count Bibliothek';
diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart
index a4c1114a..0ea6c255 100644
--- a/lib/l10n/app_localizations_en.dart
+++ b/lib/l10n/app_localizations_en.dart
@@ -2483,6 +2483,13 @@ class AppLocalizationsEn extends AppLocalizations {
String get deleteCollectionContent =>
'Are you sure you want to delete this collection?';
+ @override
+ String get deleteCollectionFailed => 'Couldn\'t delete the collection';
+
+ @override
+ String get deletePermissionRequired =>
+ 'Delete permission required. Ask the root admin to grant you the delete permission.';
+
@override
String get playlistNotFound => 'Playlist not found';
@@ -2883,6 +2890,126 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get updateOpeningInBrowser => 'In-app update failed, opening browser';
+ @override
+ String get sendToEreader => 'Send to E-Reader';
+
+ @override
+ String sendingToEreader(String device) {
+ return 'Sending to $device...';
+ }
+
+ @override
+ String sendToEreaderSuccess(String device) {
+ return 'Sent to $device';
+ }
+
+ @override
+ String get sendToEreaderFailed => 'Couldn\'t send the ebook';
+
+ @override
+ String get pickEreaderDevice => 'Pick a device';
+
+ @override
+ String get adminEmail => 'Email';
+
+ @override
+ String get adminEmailSubtitle => 'SMTP and e-reader devices';
+
+ @override
+ String get smtpSection => 'SMTP';
+
+ @override
+ String get smtpSetupGuide => 'Setup guide';
+
+ @override
+ String get smtpHost => 'Host';
+
+ @override
+ String get smtpPort => 'Port';
+
+ @override
+ String get smtpSecure => 'Secure';
+
+ @override
+ String get smtpRejectUnauthorized => 'Reject unauthorized TLS';
+
+ @override
+ String get smtpUser => 'Username';
+
+ @override
+ String get smtpPass => 'Password';
+
+ @override
+ String get smtpFromAddress => 'From address';
+
+ @override
+ String get smtpTestAddress => 'Test address';
+
+ @override
+ String get smtpSendTest => 'Send test';
+
+ @override
+ String get smtpSaveSettings => 'Save';
+
+ @override
+ String get smtpSaved => 'Email settings saved';
+
+ @override
+ String get smtpSaveFailed => 'Couldn\'t save email settings';
+
+ @override
+ String get smtpTestSent => 'Test email sent';
+
+ @override
+ String get smtpTestFailed => 'Test email failed';
+
+ @override
+ String get ereaderDevicesTitle => 'E-Reader devices';
+
+ @override
+ String get ereaderDevicesEmpty => 'No devices yet. Add one below.';
+
+ @override
+ String get addEreaderDevice => 'Add device';
+
+ @override
+ String get editEreaderDevice => 'Edit device';
+
+ @override
+ String get deleteEreaderDevice => 'Delete';
+
+ @override
+ String get ereaderDeviceName => 'Name';
+
+ @override
+ String get ereaderDeviceEmail => 'Email';
+
+ @override
+ String get ereaderAvailability => 'Who can use this device';
+
+ @override
+ String get ereaderAvailAdminOrUp => 'Admins only';
+
+ @override
+ String get ereaderAvailUserOrUp => 'All users';
+
+ @override
+ String get ereaderAvailGuestOrUp => 'Everyone';
+
+ @override
+ String get ereaderAvailSpecificUsers => 'Specific users';
+
+ @override
+ String ereaderSpecificUsersN(int count) {
+ return 'Specific users ($count)';
+ }
+
+ @override
+ String get ereaderDevicesSaved => 'Devices saved';
+
+ @override
+ String get ereaderDevicesSaveFailed => 'Couldn\'t save devices';
+
@override
String libraryCountOne(int count) {
return '$count library';
diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart
index ee7faa3d..dde943c4 100644
--- a/lib/l10n/app_localizations_zh.dart
+++ b/lib/l10n/app_localizations_zh.dart
@@ -2410,6 +2410,13 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get deleteCollectionContent => '你确定要删除此收藏集吗?';
+ @override
+ String get deleteCollectionFailed => 'Couldn\'t delete the collection';
+
+ @override
+ String get deletePermissionRequired =>
+ 'Delete permission required. Ask the root admin to grant you the delete permission.';
+
@override
String get playlistNotFound => '未找到播放列表';
@@ -2807,6 +2814,126 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get updateOpeningInBrowser => 'In-app update failed, opening browser';
+ @override
+ String get sendToEreader => 'Send to E-Reader';
+
+ @override
+ String sendingToEreader(String device) {
+ return 'Sending to $device...';
+ }
+
+ @override
+ String sendToEreaderSuccess(String device) {
+ return 'Sent to $device';
+ }
+
+ @override
+ String get sendToEreaderFailed => 'Couldn\'t send the ebook';
+
+ @override
+ String get pickEreaderDevice => 'Pick a device';
+
+ @override
+ String get adminEmail => 'Email';
+
+ @override
+ String get adminEmailSubtitle => 'SMTP and e-reader devices';
+
+ @override
+ String get smtpSection => 'SMTP';
+
+ @override
+ String get smtpSetupGuide => 'Setup guide';
+
+ @override
+ String get smtpHost => 'Host';
+
+ @override
+ String get smtpPort => 'Port';
+
+ @override
+ String get smtpSecure => 'Secure';
+
+ @override
+ String get smtpRejectUnauthorized => 'Reject unauthorized TLS';
+
+ @override
+ String get smtpUser => 'Username';
+
+ @override
+ String get smtpPass => 'Password';
+
+ @override
+ String get smtpFromAddress => 'From address';
+
+ @override
+ String get smtpTestAddress => 'Test address';
+
+ @override
+ String get smtpSendTest => 'Send test';
+
+ @override
+ String get smtpSaveSettings => 'Save';
+
+ @override
+ String get smtpSaved => 'Email settings saved';
+
+ @override
+ String get smtpSaveFailed => 'Couldn\'t save email settings';
+
+ @override
+ String get smtpTestSent => 'Test email sent';
+
+ @override
+ String get smtpTestFailed => 'Test email failed';
+
+ @override
+ String get ereaderDevicesTitle => 'E-Reader devices';
+
+ @override
+ String get ereaderDevicesEmpty => 'No devices yet. Add one below.';
+
+ @override
+ String get addEreaderDevice => 'Add device';
+
+ @override
+ String get editEreaderDevice => 'Edit device';
+
+ @override
+ String get deleteEreaderDevice => 'Delete';
+
+ @override
+ String get ereaderDeviceName => 'Name';
+
+ @override
+ String get ereaderDeviceEmail => 'Email';
+
+ @override
+ String get ereaderAvailability => 'Who can use this device';
+
+ @override
+ String get ereaderAvailAdminOrUp => 'Admins only';
+
+ @override
+ String get ereaderAvailUserOrUp => 'All users';
+
+ @override
+ String get ereaderAvailGuestOrUp => 'Everyone';
+
+ @override
+ String get ereaderAvailSpecificUsers => 'Specific users';
+
+ @override
+ String ereaderSpecificUsersN(int count) {
+ return 'Specific users ($count)';
+ }
+
+ @override
+ String get ereaderDevicesSaved => 'Devices saved';
+
+ @override
+ String get ereaderDevicesSaveFailed => 'Couldn\'t save devices';
+
@override
String libraryCountOne(int count) {
return '$count library';
diff --git a/lib/providers/_lp_core.dart b/lib/providers/_lp_core.dart
index 079f4461..bbfba841 100644
--- a/lib/providers/_lp_core.dart
+++ b/lib/providers/_lp_core.dart
@@ -1450,17 +1450,19 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
return false;
}
- Future<bool> deleteCollection(String collectionId) async {
- if (_api == null) return false;
- final ok = await _api!.deleteCollection(collectionId);
- if (ok) {
+ /// Returns HTTP status code from the server (0 on exception, 200 on
+ /// success, 403 when caller lacks the `delete` permission flag).
+ Future<int> deleteCollection(String collectionId) async {
+ if (_api == null) return 0;
+ final status = await _api!.deleteCollection(collectionId);
+ if (status == 200) {
_collections = _collections.where((c) => (c as Map)['id'] != collectionId).toList();
_hiddenSectionIds.remove('collection:$collectionId');
_sectionOrder.remove('collection:$collectionId');
await _saveSectionPrefs();
notifyListeners();
}
- return ok;
+ return status;
}
// ── Section customization ──
diff --git a/lib/providers/auth_provider.dart b/lib/providers/auth_provider.dart
index 080e58c5..6727aae7 100644
--- a/lib/providers/auth_provider.dart
+++ b/lib/providers/auth_provider.dart
@@ -25,6 +25,10 @@ class AuthProvider extends ChangeNotifier {
Map<String, dynamic>? _userJson;
Map<String, dynamic>? _serverSettings;
String? _serverVersion;
+ // Ereader devices come on the login response (top-level, NOT inside user).
+ // /api/me doesn't include them, so cache to prefs so the list survives
+ // cold restarts until the next login.
+ List<Map<String, dynamic>> _ereaderDevices = const [];
bool __serverReachable = true;
bool get _serverReachable => __serverReachable;
set _serverReachable(bool value) {
@@ -81,6 +85,81 @@ class AuthProvider extends ChangeNotifier {
return perms?['update'] == true;
}
+ /// True when the server will accept a destructive call from this user.
+ /// Root has `permissions.delete = true` by default; admins do NOT (they
+ /// need root to grant it explicitly), so most delete actions are
+ /// effectively root-only on a fresh install.
+ bool get canDelete {
+ final perms = _userJson?['permissions'] as Map<String, dynamic>?;
+ return perms?['delete'] == true;
+ }
+
+ /// E-reader devices the current user is allowed to send ebooks to.
+ /// Populated from the login response (top-level `ereaderDevices`, NOT
+ /// nested inside the user object) and persisted across restarts since
+ /// /api/me doesn't include them.
+ List<Map<String, dynamic>> get ereaderDevices => _ereaderDevices;
+
+ /// Replace the cached ereader devices list and persist it. Call this
+ /// after an admin edit so the book detail sheet sees fresh devices
+ /// without waiting for a re-login.
+ Future<void> setEreaderDevices(List<Map<String, dynamic>> devices) async {
+ _ereaderDevices = List<Map<String, dynamic>>.from(devices);
+ await _persistEreaderDevices();
+ notifyListeners();
+ }
+
+ Future<void> _persistEreaderDevices() async {
+ try {
+ final prefs = await SharedPreferences.getInstance();
+ if (_ereaderDevices.isEmpty) {
+ await prefs.remove('ereader_devices');
+ } else {
+ await prefs.setString('ereader_devices', jsonEncode(_ereaderDevices));
+ }
+ } catch (e) {
+ debugPrint('[Auth] _persistEreaderDevices error: $e');
+ }
+ }
+
+ Future<void> _restoreEreaderDevices() async {
+ try {
+ final prefs = await SharedPreferences.getInstance();
+ final raw = prefs.getString('ereader_devices');
+ if (raw == null || raw.isEmpty) return;
+ final list = jsonDecode(raw) as List<dynamic>;
+ _ereaderDevices = list.cast<Map<String, dynamic>>();
+ } catch (e) {
+ debugPrint('[Auth] _restoreEreaderDevices error: $e');
+ }
+ }
+
+ /// Apply the same access filter ABS uses server-side. Used after an
+ /// admin updates the full device list to figure out what THIS user can
+ /// still see.
+ List<Map<String, dynamic>> filterDevicesForCurrentUser(
+ List<Map<String, dynamic>> all) {
+ final id = _userId;
+ final type = _userJson?['type'] as String? ?? 'user';
+ final isAdminLike = type == 'admin' || type == 'root';
+ return all.where((d) {
+ final opt = d['availabilityOption'] as String? ?? 'adminOrUp';
+ switch (opt) {
+ case 'adminOrUp':
+ return isAdminLike;
+ case 'userOrUp':
+ return isAdminLike || type == 'user';
+ case 'guestOrUp':
+ return true;
+ case 'specificUsers':
+ final users = (d['users'] as List<dynamic>?) ?? const [];
+ return id != null && users.contains(id);
+ default:
+ return false;
+ }
+ }).toList();
+ }
+
ApiService? get apiService {
final url = activeServerUrl;
if (url != null && _accessToken != null) {
@@ -144,6 +223,9 @@ class AuthProvider extends ChangeNotifier {
final savedRefreshToken = prefs.getString('refresh_token');
final savedUsername = prefs.getString('username');
final savedLibraryId = prefs.getString('default_library_id');
+ // Restore ereader devices alongside other session data. /api/me doesn't
+ // return them, so without this they'd stay empty until next login.
+ await _restoreEreaderDevices();
debugPrint('[Auth] saved credentials: url=${savedUrl != null}, token=${savedToken != null}, refreshToken=${savedRefreshToken != null}');
@@ -211,14 +293,36 @@ class AuthProvider extends ChangeNotifier {
onTokensRefreshed: _onTokensRefreshed,
onAuthExpired: _onAuthExpired,
);
- final me = await api.getMe();
- if (me != null) {
- _userJson = me;
- _userId = me['id'] as String?;
+ // Prefer /api/authorize over /api/me because it returns the
+ // full login payload (including ereaderDevices) — /api/me drops
+ // those extras. Fall back to /api/me if authorize fails (older
+ // server versions).
+ final auth = await api.authorize();
+ if (auth != null) {
+ final user = auth['user'] as Map<String, dynamic>?;
+ if (user != null) {
+ _userJson = user;
+ _userId = user['id'] as String?;
+ }
+ final devicesRaw = auth['ereaderDevices'] as List<dynamic>?;
+ if (devicesRaw != null) {
+ _ereaderDevices = devicesRaw.cast<Map<String, dynamic>>();
+ await _persistEreaderDevices();
+ }
+ final sSettings = auth['serverSettings'] as Map<String, dynamic>?;
+ if (sSettings != null) _serverSettings = sSettings;
+ final defaultLib = auth['userDefaultLibraryId'] as String?;
+ if (defaultLib != null) _defaultLibraryId = defaultLib;
} else {
- debugPrint('[Auth] /me returned null (token may be invalid)');
+ final me = await api.getMe();
+ if (me != null) {
+ _userJson = me;
+ _userId = me['id'] as String?;
+ } else {
+ debugPrint('[Auth] /me returned null (token may be invalid)');
+ }
}
- debugPrint('[Auth] /me done (${sw.elapsedMilliseconds}ms)');
+ debugPrint('[Auth] authorize/me done (${sw.elapsedMilliseconds}ms)');
} catch (_) {}
_fetchServerVersion(activeServerUrl!);
}
@@ -302,6 +406,10 @@ class AuthProvider extends ChangeNotifier {
_userJson = user;
_serverSettings = result['serverSettings'] as Map<String, dynamic>?;
_customHeaders = customHeaders;
+ // Ereader devices come at the top level of the login response.
+ final devicesRaw = result['ereaderDevices'] as List<dynamic>?;
+ _ereaderDevices = devicesRaw?.cast<Map<String, dynamic>>() ?? const [];
+ await _persistEreaderDevices();
// Try to get version from login response first, fall back to /status
final loginVersion = result['serverVersion'] as String?
@@ -477,6 +585,9 @@ class AuthProvider extends ChangeNotifier {
_userJson = user;
_serverSettings = result['serverSettings'] as Map<String, dynamic>?;
_serverReachable = true;
+ final devicesRaw = result['ereaderDevices'] as List<dynamic>?;
+ _ereaderDevices = devicesRaw?.cast<Map<String, dynamic>>() ?? const [];
+ await _persistEreaderDevices();
// Try to get version from response first, fall back to /status
final oidcVersion = result['serverVersion'] as String?
@@ -668,6 +779,8 @@ class AuthProvider extends ChangeNotifier {
_serverSettings = null;
_serverVersion = null;
_errorMessage = null;
+ _ereaderDevices = const [];
+ await _persistEreaderDevices();
try {
if (logoutServer != null && logoutUser != null) {
@@ -771,10 +884,24 @@ class AuthProvider extends ChangeNotifier {
onTokensRefreshed: _onTokensRefreshed,
onAuthExpired: _onAuthExpired,
);
- final me = await api.getMe();
- if (me != null) {
- _userJson = me;
- _userId = me['id'] as String?;
+ final auth = await api.authorize();
+ if (auth != null) {
+ final user = auth['user'] as Map<String, dynamic>?;
+ if (user != null) {
+ _userJson = user;
+ _userId = user['id'] as String?;
+ }
+ final devicesRaw = auth['ereaderDevices'] as List<dynamic>?;
+ if (devicesRaw != null) {
+ _ereaderDevices = devicesRaw.cast<Map<String, dynamic>>();
+ await _persistEreaderDevices();
+ }
+ } else {
+ final me = await api.getMe();
+ if (me != null) {
+ _userJson = me;
+ _userId = me['id'] as String?;
+ }
}
} catch (_) {
_serverReachable = false;
diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dart
index fb476242..bf7a0cec 100644
--- a/lib/providers/library_provider.dart
+++ b/lib/providers/library_provider.dart
@@ -167,6 +167,12 @@ class LibraryProvider extends ChangeNotifier
socket.onUserUpdated = _onRemoteUserUpdated;
socket.onReconnectFailed = _onSocketReconnectFailed;
socket.onEncodeFinished = _onEncodeFinished;
+ socket.onEreaderDevicesUpdated = (devices) {
+ // Admin broadcasts deliver the FULL unfiltered list; the per-user
+ // emit is already filtered. Run the same filter here either way -
+ // it's a no-op on an already-filtered list.
+ auth.setEreaderDevices(auth.filterDevicesForCurrentUser(devices));
+ };
socket.connect(auth.serverUrl!, auth.token!, customHeaders: auth.customHeaders);
}
debugPrint('[Library] Calling loadLibraries()');
diff --git a/lib/screens/admin_email_screen.dart b/lib/screens/admin_email_screen.dart
new file mode 100644
index 00000000..53f70c23
--- /dev/null
+++ b/lib/screens/admin_email_screen.dart
@@ -0,0 +1,482 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:provider/provider.dart';
+import 'package:url_launcher/url_launcher.dart';
+
+import '../l10n/app_localizations.dart';
+import '../providers/auth_provider.dart';
+import '../widgets/absorb_page_header.dart';
+import '../widgets/overlay_toast.dart';
+
+class AdminEmailScreen extends StatefulWidget {
+ final List<dynamic> users;
+ const AdminEmailScreen({super.key, required this.users});
+
+ @override
+ State<AdminEmailScreen> createState() => _AdminEmailScreenState();
+}
+
+class _AdminEmailScreenState extends State<AdminEmailScreen> {
+ bool _loading = true;
+ bool _saving = false;
+ bool _testing = false;
+
+ final _host = TextEditingController();
+ final _port = TextEditingController();
+ final _user = TextEditingController();
+ final _pass = TextEditingController();
+ final _fromAddress = TextEditingController();
+ final _testAddress = TextEditingController();
+ bool _secure = true;
+ bool _rejectUnauthorized = true;
+ bool _showPass = false;
+
+ List<Map<String, dynamic>> _devices = [];
+
+ @override
+ void initState() {
+ super.initState();
+ _load();
+ }
+
+ @override
+ void dispose() {
+ _host.dispose();
+ _port.dispose();
+ _user.dispose();
+ _pass.dispose();
+ _fromAddress.dispose();
+ _testAddress.dispose();
+ super.dispose();
+ }
+
+ Future<void> _load() async {
+ final api = context.read<AuthProvider>().apiService;
+ if (api == null) return;
+ final settings = await api.getEmailSettings();
+ if (!mounted) return;
+ setState(() {
+ _loading = false;
+ _host.text = (settings?['host'] as String?) ?? '';
+ _port.text = (settings?['port'] as num?)?.toString() ?? '465';
+ _secure = settings?['secure'] as bool? ?? true;
+ _rejectUnauthorized = settings?['rejectUnauthorized'] as bool? ?? true;
+ _user.text = (settings?['user'] as String?) ?? '';
+ _pass.text = (settings?['pass'] as String?) ?? '';
+ _fromAddress.text = (settings?['fromAddress'] as String?) ?? '';
+ _testAddress.text = (settings?['testAddress'] as String?) ?? '';
+ final devices = settings?['ereaderDevices'] as List<dynamic>?;
+ _devices = devices?.cast<Map<String, dynamic>>().map((d) =>
+ Map<String, dynamic>.from(d)).toList() ?? [];
+ });
+ }
+
+ Map<String, dynamic> _smtpPayload() => {
+ 'host': _host.text.trim(),
+ 'port': int.tryParse(_port.text.trim()) ?? 465,
+ 'secure': _secure,
+ 'rejectUnauthorized': _rejectUnauthorized,
+ 'user': _user.text.trim(),
+ 'pass': _pass.text,
+ 'fromAddress': _fromAddress.text.trim(),
+ 'testAddress': _testAddress.text.trim(),
+ };
+
+ Future<void> _save() async {
+ final api = context.read<AuthProvider>().apiService;
+ if (api == null) return;
+ final l = AppLocalizations.of(context)!;
+ setState(() => _saving = true);
+ final ok = await api.updateEmailSettings(_smtpPayload());
+ if (!mounted) return;
+ setState(() => _saving = false);
+ showOverlayToast(context,
+ ok ? l.smtpSaved : l.smtpSaveFailed,
+ icon: ok ? Icons.check_circle_outline_rounded : Icons.error_outline_rounded);
+ }
+
+ Future<void> _test() async {
+ final api = context.read<AuthProvider>().apiService;
+ if (api == null) return;
+ final l = AppLocalizations.of(context)!;
+ setState(() => _testing = true);
+ // Save first so the server tests against the values shown on screen.
+ final saved = await api.updateEmailSettings(_smtpPayload());
+ final ok = saved ? await api.sendTestEmail() : false;
+ if (!mounted) return;
+ setState(() => _testing = false);
+ showOverlayToast(context,
+ ok ? l.smtpTestSent : l.smtpTestFailed,
+ icon: ok ? Icons.mark_email_read_rounded : Icons.error_outline_rounded);
+ }
+
+ Future<void> _saveDevices(List<Map<String, dynamic>> next) async {
+ final auth = context.read<AuthProvider>();
+ final api = auth.apiService;
+ if (api == null) return;
+ final l = AppLocalizations.of(context)!;
+ final ok = await api.updateEReaderDevices(next);
+ if (!mounted) return;
+ if (ok) {
+ setState(() => _devices = next);
+ // Push the freshly filtered list into AuthProvider so the book detail
+ // sheet's "Send to E-Reader" entry sees changes without a re-login.
+ await auth.setEreaderDevices(auth.filterDevicesForCurrentUser(next));
+ if (!mounted) return;
+ showOverlayToast(context, l.ereaderDevicesSaved,
+ icon: Icons.check_circle_outline_rounded);
+ } else {
+ showOverlayToast(context, l.ereaderDevicesSaveFailed,
+ icon: Icons.error_outline_rounded);
+ }
+ }
+
+ Future<void> _addOrEditDevice([int? index]) async {
+ final existing = index != null ? _devices[index] : null;
+ final result = await _showDeviceEditor(existing);
+ if (result == null) return;
+ final next = List<Map<String, dynamic>>.from(_devices);
+ if (result['_delete'] == true) {
+ if (index != null) next.removeAt(index);
+ } else {
+ result.remove('_delete');
+ if (index != null) {
+ next[index] = result;
+ } else {
+ next.add(result);
+ }
+ }
+ await _saveDevices(next);
+ }
+
+ Future<Map<String, dynamic>?> _showDeviceEditor(
+ Map<String, dynamic>? existing) async {
+ final cs = Theme.of(context).colorScheme;
+ final l = AppLocalizations.of(context)!;
+ final nameCtrl = TextEditingController(text: existing?['name'] as String? ?? '');
+ final emailCtrl = TextEditingController(text: existing?['email'] as String? ?? '');
+ String availability = (existing?['availabilityOption'] as String?) ?? 'adminOrUp';
+ final specificUsers = <String>{
+ ...((existing?['users'] as List<dynamic>?) ?? []).cast<String>(),
+ };
+
+ return showModalBottomSheet<Map<String, dynamic>>(
+ context: context,
+ isScrollControlled: true,
+ backgroundColor: Theme.of(context).bottomSheetTheme.backgroundColor,
+ shape: const RoundedRectangleBorder(
+ borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
+ ),
+ builder: (ctx) {
+ return StatefulBuilder(builder: (ctx, setSheet) {
+ return SafeArea(
+ child: Padding(
+ padding: EdgeInsets.fromLTRB(16, 8, 16,
+ 16 + MediaQuery.of(ctx).viewInsets.bottom),
+ child: SingleChildScrollView(
+ child: Column(mainAxisSize: MainAxisSize.min, children: [
+ Center(child: Container(width: 40, height: 4,
+ margin: const EdgeInsets.only(bottom: 16),
+ decoration: BoxDecoration(
+ color: cs.onSurface.withValues(alpha: 0.24),
+ borderRadius: BorderRadius.circular(2)))),
+ Align(alignment: Alignment.centerLeft, child: Text(
+ existing == null ? l.addEreaderDevice : l.editEreaderDevice,
+ style: Theme.of(ctx).textTheme.titleMedium?.copyWith(
+ fontWeight: FontWeight.w600))),
+ const SizedBox(height: 16),
+ TextField(
+ controller: nameCtrl,
+ decoration: InputDecoration(labelText: l.ereaderDeviceName),
+ ),
+ const SizedBox(height: 12),
+ TextField(
+ controller: emailCtrl,
+ keyboardType: TextInputType.emailAddress,
+ decoration: InputDecoration(labelText: l.ereaderDeviceEmail),
+ ),
+ const SizedBox(height: 20),
+ Align(alignment: Alignment.centerLeft, child: Text(
+ l.ereaderAvailability,
+ style: Theme.of(ctx).textTheme.labelLarge?.copyWith(
+ color: cs.onSurfaceVariant))),
+ const SizedBox(height: 8),
+ _availabilityChoices(cs, availability, (v) {
+ setSheet(() => availability = v);
+ }),
+ if (availability == 'specificUsers') ...[
+ const SizedBox(height: 16),
+ Align(alignment: Alignment.centerLeft, child: Text(
+ l.ereaderAvailSpecificUsers,
+ style: Theme.of(ctx).textTheme.labelMedium?.copyWith(
+ color: cs.onSurfaceVariant))),
+ const SizedBox(height: 8),
+ Wrap(spacing: 8, runSpacing: 8, children: widget.users.map((u) {
+ final id = u['id'] as String? ?? '';
+ final name = u['username'] as String? ?? id;
+ final selected = specificUsers.contains(id);
+ return FilterChip(
+ label: Text(name),
+ selected: selected,
+ onSelected: (v) => setSheet(() {
+ if (v) {
+ specificUsers.add(id);
+ } else {
+ specificUsers.remove(id);
+ }
+ }),
+ );
+ }).toList()),
+ ],
+ const SizedBox(height: 24),
+ Row(children: [
+ if (existing != null)
+ TextButton.icon(
+ onPressed: () {
+ Navigator.pop(ctx, {'_delete': true});
+ },
+ icon: Icon(Icons.delete_outline_rounded, color: cs.error),
+ label: Text(l.deleteEreaderDevice,
+ style: TextStyle(color: cs.error)),
+ ),
+ const Spacer(),
+ TextButton(
+ onPressed: () => Navigator.pop(ctx),
+ child: Text(l.cancel),
+ ),
+ const SizedBox(width: 8),
+ FilledButton(
+ onPressed: () {
+ final name = nameCtrl.text.trim();
+ final email = emailCtrl.text.trim();
+ if (name.isEmpty || email.isEmpty) return;
+ Navigator.pop(ctx, <String, dynamic>{
+ 'name': name,
+ 'email': email,
+ 'availabilityOption': availability,
+ 'users': availability == 'specificUsers'
+ ? specificUsers.toList()
+ : <String>[],
+ });
+ },
+ child: Text(l.save),
+ ),
+ ]),
+ ]),
+ ),
+ ),
+ );
+ });
+ },
+ );
+ }
+
+ Widget _availabilityChoices(
+ ColorScheme cs, String current, ValueChanged<String> onChange) {
+ final l = AppLocalizations.of(context)!;
+ final options = <(String, String)>[
+ ('adminOrUp', l.ereaderAvailAdminOrUp),
+ ('userOrUp', l.ereaderAvailUserOrUp),
+ ('guestOrUp', l.ereaderAvailGuestOrUp),
+ ('specificUsers', l.ereaderAvailSpecificUsers),
+ ];
+ return Wrap(spacing: 8, runSpacing: 8, children: options.map((opt) {
+ final selected = opt.$1 == current;
+ return ChoiceChip(
+ label: Text(opt.$2),
+ selected: selected,
+ onSelected: (_) => onChange(opt.$1),
+ );
+ }).toList());
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ final l = AppLocalizations.of(context)!;
+
+ return Scaffold(
+ backgroundColor: Theme.of(context).scaffoldBackgroundColor,
+ body: SafeArea(
+ child: _loading
+ ? const Center(child: CircularProgressIndicator(strokeWidth: 2))
+ : Column(children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(20, 12, 8, 0),
+ child: Row(children: [
+ Expanded(child: AbsorbPageHeader(
+ title: l.adminEmail, padding: EdgeInsets.zero)),
+ IconButton(icon: Icon(Icons.close_rounded,
+ color: cs.onSurfaceVariant),
+ onPressed: () => Navigator.pop(context)),
+ ]),
+ ),
+ const SizedBox(height: 12),
+ Expanded(
+ child: ListView(
+ padding: const EdgeInsets.only(bottom: 80),
+ children: [
+ _section(cs, tt, l.smtpSection),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: Container(
+ padding: const EdgeInsets.all(16),
+ decoration: _cardDeco(cs),
+ child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
+ Align(
+ alignment: Alignment.centerLeft,
+ child: TextButton.icon(
+ style: TextButton.styleFrom(
+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
+ visualDensity: VisualDensity.compact,
+ ),
+ onPressed: () => launchUrl(
+ Uri.parse('https://www.audiobookshelf.org/guides/send_to_ereader/'),
+ mode: LaunchMode.externalApplication,
+ ),
+ icon: const Icon(Icons.menu_book_rounded, size: 16),
+ label: Text(l.smtpSetupGuide),
+ ),
+ ),
+ const SizedBox(height: 8),
+ TextField(controller: _host,
+ decoration: InputDecoration(labelText: l.smtpHost)),
+ const SizedBox(height: 12),
+ Row(children: [
+ Expanded(child: TextField(
+ controller: _port,
+ keyboardType: TextInputType.number,
+ inputFormatters: [FilteringTextInputFormatter.digitsOnly],
+ decoration: InputDecoration(labelText: l.smtpPort))),
+ const SizedBox(width: 16),
+ Expanded(child: SwitchListTile(
+ contentPadding: EdgeInsets.zero,
+ title: Text(l.smtpSecure,
+ style: tt.bodyMedium),
+ value: _secure,
+ onChanged: (v) => setState(() => _secure = v))),
+ ]),
+ SwitchListTile(
+ contentPadding: EdgeInsets.zero,
+ title: Text(l.smtpRejectUnauthorized,
+ style: tt.bodyMedium),
+ value: _rejectUnauthorized,
+ onChanged: (v) => setState(() => _rejectUnauthorized = v),
+ ),
+ TextField(controller: _user,
+ decoration: InputDecoration(labelText: l.smtpUser)),
+ const SizedBox(height: 12),
+ TextField(
+ controller: _pass,
+ obscureText: !_showPass,
+ decoration: InputDecoration(
+ labelText: l.smtpPass,
+ suffixIcon: IconButton(
+ icon: Icon(_showPass
+ ? Icons.visibility_off_rounded
+ : Icons.visibility_rounded),
+ onPressed: () => setState(() => _showPass = !_showPass),
+ )),
+ ),
+ const SizedBox(height: 12),
+ TextField(controller: _fromAddress,
+ keyboardType: TextInputType.emailAddress,
+ decoration: InputDecoration(labelText: l.smtpFromAddress)),
+ const SizedBox(height: 12),
+ TextField(controller: _testAddress,
+ keyboardType: TextInputType.emailAddress,
+ decoration: InputDecoration(labelText: l.smtpTestAddress)),
+ const SizedBox(height: 20),
+ Row(children: [
+ Expanded(child: OutlinedButton.icon(
+ onPressed: _testing || _saving ? null : _test,
+ icon: _testing
+ ? const SizedBox(width: 14, height: 14,
+ child: CircularProgressIndicator(strokeWidth: 2))
+ : const Icon(Icons.send_rounded, size: 16),
+ label: Text(l.smtpSendTest))),
+ const SizedBox(width: 12),
+ Expanded(child: FilledButton.icon(
+ onPressed: _saving || _testing ? null : _save,
+ icon: _saving
+ ? SizedBox(width: 14, height: 14,
+ child: CircularProgressIndicator(
+ strokeWidth: 2, color: cs.onPrimary))
+ : const Icon(Icons.save_rounded, size: 16),
+ label: Text(l.smtpSaveSettings))),
+ ]),
+ ]),
+ ),
+ ),
+ const SizedBox(height: 28),
+ _section(cs, tt, l.ereaderDevicesTitle),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: Container(
+ decoration: _cardDeco(cs),
+ padding: const EdgeInsets.symmetric(vertical: 8),
+ child: Column(children: [
+ if (_devices.isEmpty)
+ Padding(
+ padding: const EdgeInsets.all(24),
+ child: Text(l.ereaderDevicesEmpty,
+ style: tt.bodyMedium?.copyWith(
+ color: cs.onSurfaceVariant.withValues(alpha: 0.6))),
+ ),
+ ..._devices.asMap().entries.map((e) =>
+ _deviceTile(cs, tt, e.key, e.value)),
+ const SizedBox(height: 4),
+ TextButton.icon(
+ onPressed: () => _addOrEditDevice(),
+ icon: const Icon(Icons.add_rounded),
+ label: Text(l.addEreaderDevice),
+ ),
+ ]),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ]),
+ ),
+ );
+ }
+
+ Widget _deviceTile(ColorScheme cs, TextTheme tt, int idx, Map<String, dynamic> d) {
+ final l = AppLocalizations.of(context)!;
+ final name = d['name'] as String? ?? '';
+ final email = d['email'] as String? ?? '';
+ final availability = d['availabilityOption'] as String? ?? 'adminOrUp';
+ final users = (d['users'] as List<dynamic>?)?.length ?? 0;
+
+ final availabilityLabel = switch (availability) {
+ 'userOrUp' => l.ereaderAvailUserOrUp,
+ 'guestOrUp' => l.ereaderAvailGuestOrUp,
+ 'specificUsers' => l.ereaderSpecificUsersN(users),
+ _ => l.ereaderAvailAdminOrUp,
+ };
+
+ return ListTile(
+ leading: Icon(Icons.send_to_mobile_rounded, color: cs.onSurfaceVariant),
+ title: Text(name),
+ subtitle: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Text(email, style: TextStyle(color: cs.onSurface.withValues(alpha: 0.5))),
+ const SizedBox(height: 2),
+ Text(availabilityLabel,
+ style: tt.labelSmall?.copyWith(color: cs.primary.withValues(alpha: 0.7))),
+ ]),
+ trailing: Icon(Icons.edit_rounded, size: 18, color: cs.onSurfaceVariant),
+ onTap: () => _addOrEditDevice(idx),
+ );
+ }
+
+ Widget _section(ColorScheme cs, TextTheme tt, String t) => Padding(
+ padding: const EdgeInsets.fromLTRB(20, 0, 20, 10),
+ child: Text(t, style: tt.labelLarge?.copyWith(
+ color: cs.onSurfaceVariant.withValues(alpha: 0.6),
+ fontWeight: FontWeight.w600, letterSpacing: 0.5)));
+
+ BoxDecoration _cardDeco(ColorScheme cs) => BoxDecoration(
+ color: cs.surfaceContainerHigh, borderRadius: BorderRadius.circular(16));
+}
diff --git a/lib/screens/admin_podcasts_screen.dart b/lib/screens/admin_podcasts_screen.dart
index 3f3224bd..ef035e74 100644
--- a/lib/screens/admin_podcasts_screen.dart
+++ b/lib/screens/admin_podcasts_screen.dart
@@ -982,10 +982,11 @@ class _PodcastDetailScreenState extends State<_PodcastDetailScreen> with SingleT
));
if (yes != true) return;
final api = context.read<AuthProvider>().apiService; if (api == null) return;
- final ok = await api.deleteLibraryItem(_podcastId);
+ final status = await api.deleteLibraryItem(_podcastId);
if (mounted) {
final l2 = AppLocalizations.of(context)!;
- if (ok) { _msg(l2.adminPodcastsRemovedShow(_title)); widget.onChanged(); Navigator.pop(context); }
+ if (status == 200) { _msg(l2.adminPodcastsRemovedShow(_title)); widget.onChanged(); Navigator.pop(context); }
+ else if (status == 403) _msg(l2.deletePermissionRequired);
else _msg(l2.adminPodcastsFailedRemoveShow);
}
}
@@ -1070,12 +1071,13 @@ class _PodcastDetailScreenState extends State<_PodcastDetailScreen> with SingleT
if (yes != true) return;
final api = context.read<AuthProvider>().apiService; if (api == null) return;
setState(() => _deleting.add(episodeId));
- final ok = await api.deletePodcastEpisode(_podcastId, episodeId);
+ final status = await api.deletePodcastEpisode(_podcastId, episodeId);
if (mounted) {
final l2 = AppLocalizations.of(context)!;
setState(() => _deleting.remove(episodeId));
- _msg(ok ? l2.adminPodcastsDeleted : l2.adminPodcastsFailed);
- if (ok) { _reloadItem(); widget.onChanged(); }
+ if (status == 200) { _msg(l2.adminPodcastsDeleted); _reloadItem(); widget.onChanged(); }
+ else if (status == 403) _msg(l2.deletePermissionRequired);
+ else _msg(l2.adminPodcastsFailed);
}
}
@@ -1112,7 +1114,7 @@ class _PodcastDetailScreenState extends State<_PodcastDetailScreen> with SingleT
}
}),
),
- if (auth.isRoot)
+ if (auth.isAdmin)
IconButton(icon: Icon(Icons.delete_outline_rounded, color: Colors.red.shade300, size: 22), tooltip: l.adminPodcastsRemoveShowTooltip, onPressed: _removeShow),
])),
@@ -1202,12 +1204,16 @@ class _PodcastDetailScreenState extends State<_PodcastDetailScreen> with SingleT
final ids = Set<String>.from(_selectedDownloadedIds);
setState(() => _selectedDownloadedIds.clear());
int deleted = 0;
+ bool forbidden = false;
for (final id in ids) {
- final ok = await api.deletePodcastEpisode(_podcastId, id);
- if (ok) deleted++;
+ final status = await api.deletePodcastEpisode(_podcastId, id);
+ if (status == 200) deleted++;
+ else if (status == 403) { forbidden = true; break; }
}
if (mounted) {
- _msg(AppLocalizations.of(context)!.adminPodcastsDeletedEpisodes(deleted));
+ final l2 = AppLocalizations.of(context)!;
+ if (forbidden && deleted == 0) _msg(l2.deletePermissionRequired);
+ else _msg(l2.adminPodcastsDeletedEpisodes(deleted));
_reloadItem();
widget.onChanged();
}
@@ -1857,7 +1863,7 @@ class _PodcastDetailScreenState extends State<_PodcastDetailScreen> with SingleT
}
void _showEpisodeDetail(Map<String, dynamic> ep, bool alreadyDownloaded) {
- final isRoot = context.read<AuthProvider>().isRoot;
+ final canDownload = context.read<AuthProvider>().isAdmin;
showModalBottomSheet(
context: context,
isScrollControlled: true,
@@ -1866,7 +1872,7 @@ class _PodcastDetailScreenState extends State<_PodcastDetailScreen> with SingleT
builder: (_) => _EpisodeDetailSheet(
episode: ep,
alreadyDownloaded: alreadyDownloaded,
- canDownload: isRoot,
+ canDownload: canDownload,
onDownload: () {
Navigator.pop(context);
_downloadEpisode(ep);
diff --git a/lib/screens/admin_screen.dart b/lib/screens/admin_screen.dart
index 4badc246..f6f7607b 100644
--- a/lib/screens/admin_screen.dart
+++ b/lib/screens/admin_screen.dart
@@ -7,6 +7,7 @@ import '../widgets/rmab_config_sheet.dart';
import '../l10n/app_localizations.dart';
import 'admin_users_screen.dart';
import 'admin_podcasts_screen.dart';
+import 'admin_email_screen.dart';
class AdminScreen extends StatefulWidget {
const AdminScreen({super.key});
@@ -153,6 +154,16 @@ class _AdminScreenState extends State<AdminScreen> {
},
),
if (_hasPodcastLibrary) const SizedBox(height: 10),
+ _navButton(cs, tt,
+ icon: Icons.email_rounded,
+ label: l.adminEmail,
+ subtitle: l.adminEmailSubtitle,
+ onTap: () {
+ Navigator.push(context, MaterialPageRoute(
+ builder: (_) => AdminEmailScreen(users: _users)));
+ },
+ ),
+ const SizedBox(height: 10),
if (_hasRmab) _rmabTile(cs, tt) else _rmabAddRow(cs, tt),
]),
),
diff --git a/lib/screens/library_screen.dart b/lib/screens/library_screen.dart
index b1b076ed..816a9495 100644
--- a/lib/screens/library_screen.dart
+++ b/lib/screens/library_screen.dart
@@ -1622,7 +1622,7 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
mainAxisSize: MainAxisSize.min,
children: [
_buildFloatingSortButton(cs, tt),
- if (context.read<AuthProvider>().isRoot) ...[
+ if (context.read<AuthProvider>().isAdmin) ...[
const SizedBox(width: 8),
_buildFloatingManageButton(cs),
],
diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart
index c57e1dd9..25371c4e 100644
--- a/lib/screens/settings_screen.dart
+++ b/lib/screens/settings_screen.dart
@@ -690,7 +690,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
),
// ── Admin Controls ──
- if (auth.isRoot)
+ if (auth.isAdmin)
Padding(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 0),
child: Material(
diff --git a/lib/services/api_service.dart b/lib/services/api_service.dart
index a6b26a8c..f6aa460c 100644
--- a/lib/services/api_service.dart
+++ b/lib/services/api_service.dart
@@ -388,6 +388,25 @@ class ApiService {
return url;
}
+ /// POST /api/authorize - validates the current token and returns the same
+ /// payload shape as /login: { user, userDefaultLibraryId, serverSettings,
+ /// ereaderDevices, Source }. Use on cold-start restore when you need the
+ /// top-level extras (especially ereaderDevices, since /api/me drops them).
+ Future<Map<String, dynamic>?> authorize() async {
+ try {
+ final response = await _authPost(
+ Uri.parse('$_cleanBaseUrl/api/authorize'),
+ timeout: const Duration(seconds: 10));
+ if (response.statusCode == 200) {
+ return jsonDecode(response.body) as Map<String, dynamic>;
+ }
+ debugPrint('[API] authorize failed: ${response.statusCode}');
+ } catch (e) {
+ debugPrint('[API] authorize error: $e');
+ }
+ return null;
+ }
+
/// Get current user info including all mediaProgress.
Future<Map<String, dynamic>?> getMe() async {
try {
@@ -1177,6 +1196,75 @@ class ApiService {
return false;
}
+ // ─── Email / E-Reader ──────────────────────────────────────────────
+
+ /// Send the ebook file for [libraryItemId] to a configured ereader.
+ /// POST /api/emails/send-ebook-to-device body: { libraryItemId, deviceName }
+ Future<bool> sendEBookToDevice({
+ required String libraryItemId,
+ required String deviceName,
+ }) async {
+ try {
+ final r = await _authPost(
+ Uri.parse('$_cleanBaseUrl/api/emails/send-ebook-to-device'),
+ body: jsonEncode({'libraryItemId': libraryItemId, 'deviceName': deviceName}),
+ );
+ return r.statusCode == 200;
+ } catch (e) { debugPrint('[API] sendEBookToDevice error: $e'); }
+ return false;
+ }
+
+ /// GET /api/emails/settings (admin only)
+ Future<Map<String, dynamic>?> getEmailSettings() async {
+ try {
+ final r = await _authGet(Uri.parse('$_cleanBaseUrl/api/emails/settings'));
+ if (r.statusCode != 200) return null;
+ final body = jsonDecode(r.body);
+ if (body is Map<String, dynamic>) {
+ // ABS wraps the settings in `settings` on this endpoint.
+ final settings = body['settings'];
+ if (settings is Map<String, dynamic>) return settings;
+ return body;
+ }
+ return null;
+ } catch (e) { debugPrint('[API] getEmailSettings error: $e'); }
+ return null;
+ }
+
+ /// PATCH /api/emails/settings (admin only)
+ Future<bool> updateEmailSettings(Map<String, dynamic> patch) async {
+ try {
+ final r = await _authPatch(
+ Uri.parse('$_cleanBaseUrl/api/emails/settings'),
+ body: jsonEncode(patch),
+ );
+ return r.statusCode == 200;
+ } catch (e) { debugPrint('[API] updateEmailSettings error: $e'); }
+ return false;
+ }
+
+ /// POST /api/emails/test (admin only)
+ Future<bool> sendTestEmail() async {
+ try {
+ final r = await _authPost(Uri.parse('$_cleanBaseUrl/api/emails/test'));
+ return r.statusCode == 200;
+ } catch (e) { debugPrint('[API] sendTestEmail error: $e'); }
+ return false;
+ }
+
+ /// Replace the full ereader devices list (admin only).
+ /// POST /api/emails/ereader-devices body: { ereaderDevices: [{name, email, availabilityOption, users}, ...] }
+ Future<bool> updateEReaderDevices(List<Map<String, dynamic>> devices) async {
+ try {
+ final r = await _authPost(
+ Uri.parse('$_cleanBaseUrl/api/emails/ereader-devices'),
+ body: jsonEncode({'ereaderDevices': devices}),
+ );
+ return r.statusCode == 200;
+ } catch (e) { debugPrint('[API] updateEReaderDevices error: $e'); }
+ return false;
+ }
+
/// Get a single series with its books (paginated).
/// If [onPageLoaded] is provided, it's called after each page with the
/// cumulative results and total so the UI can show books as they arrive.
@@ -2084,25 +2172,28 @@ class ApiService {
}
/// Delete a podcast episode
- Future<bool> deletePodcastEpisode(String podcastId, String episodeId) async {
+ /// Returns the HTTP status code (0 on exception). 200 = success;
+ /// 403 = caller lacks the `delete` permission flag on the server. Callers
+ /// should surface 403 with a "needs delete permission" message.
+ Future<int> deletePodcastEpisode(String podcastId, String episodeId) async {
try {
final r = await _authDelete(
Uri.parse('$_cleanBaseUrl/api/podcasts/$podcastId/episode/$episodeId'),
);
- return r.statusCode == 200;
+ return r.statusCode;
} catch (e) { debugPrint('deletePodcastEpisode error: $e'); }
- return false;
+ return 0;
}
- /// Delete a library item (e.g. remove a podcast show)
- Future<bool> deleteLibraryItem(String itemId) async {
+ /// Delete a library item (e.g. remove a podcast show). See [deletePodcastEpisode] for status semantics.
+ Future<int> deleteLibraryItem(String itemId) async {
try {
final r = await _authDelete(
Uri.parse('$_cleanBaseUrl/api/items/$itemId'),
);
- return r.statusCode == 200;
+ return r.statusCode;
} catch (e) { debugPrint('deleteLibraryItem error: $e'); }
- return false;
+ return 0;
}
// ── Playlists ──────────────────────────────────────────────────────────
@@ -2304,15 +2395,17 @@ class ApiService {
return null;
}
- /// DELETE /api/collections/:id
- Future<bool> deleteCollection(String collectionId) async {
+ /// DELETE /api/collections/:id. Returns the HTTP status code
+ /// (0 on exception). 200 = success; 403 = caller lacks the `delete`
+ /// permission flag on the server.
+ Future<int> deleteCollection(String collectionId) async {
try {
final resp = await _authDelete(
Uri.parse('$_cleanBaseUrl/api/collections/$collectionId'),
timeout: const Duration(seconds: 10));
- return resp.statusCode == 200;
+ return resp.statusCode;
} catch (_) {}
- return false;
+ return 0;
}
/// POST /api/collections/:id/books
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index c4a86c89..54573e7c 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -1560,6 +1560,13 @@ class AudioPlayerService extends ChangeNotifier {
return 'Player failed to initialize';
}
+ // Alpha: catalog every playItem caller so we can find the phantom
+ // resume that fires after an AA disconnect without going through
+ // Handler.play() / Service.play(). Strip before next beta.
+ debugPrint('[PlayItemEntry] itemId=$itemId episodeId=$episodeId '
+ 'startTime=$startTime forceStartTime=$forceStartTime\n'
+ 'Caller:\n${StackTrace.current}');
+
// Don't start local playback while casting
final cast = ChromecastService();
if (cast.isCasting) {
diff --git a/lib/services/home_widget_service.dart b/lib/services/home_widget_service.dart
index 0c5cc262..13bed7fd 100644
--- a/lib/services/home_widget_service.dart
+++ b/lib/services/home_widget_service.dart
@@ -101,6 +101,7 @@ class HomeWidgetService {
// Check if the app was cold-started from a widget tap
final launchUri = await HomeWidget.initiallyLaunchedFromHomeWidget();
+ debugPrint('[HomeWidget] initiallyLaunchedFromHomeWidget=$launchUri');
if (launchUri != null) {
_onWidgetClicked(launchUri);
}
@@ -216,7 +217,8 @@ class HomeWidgetService {
Future<void> _handlePlayPause() async {
final player = AudioPlayerService();
debugPrint(
- '[WidgetDebug] _handlePlayPause hasBook=${player.hasBook} isPlaying=${player.isPlaying}');
+ '[WidgetDebug] _handlePlayPause hasBook=${player.hasBook} isPlaying=${player.isPlaying}\n'
+ 'Caller:\n${StackTrace.current}');
// When there's an active session the widget uses a MediaSession media button
// instead of launching the app, so this path is only hit for cold resume.
diff --git a/lib/services/socket_service.dart b/lib/services/socket_service.dart
index d0266a73..51ee7ff0 100644
--- a/lib/services/socket_service.dart
+++ b/lib/services/socket_service.dart
@@ -56,6 +56,11 @@ class SocketService {
/// Payload: serialized Task object including action and data.libraryItemId.
void Function(Map<String, dynamic> data)? onEncodeFinished;
+ /// Called when ereader devices change. Server emits this both for the
+ /// per-user update (always) and admin-wide updates (only to admins).
+ /// Payload shape: { ereaderDevices: [...] } already filtered for this user.
+ void Function(List<Map<String, dynamic>> devices)? onEreaderDevicesUpdated;
+
/// Update the stored token (e.g. after a JWT refresh) and re-auth if connected.
void updateToken(String newToken) {
_token = newToken;
@@ -157,6 +162,16 @@ class SocketService {
}
});
+ // Ereader device list changed (admin-wide or per-user). Payload carries
+ // the list already filtered for this connection's user.
+ _socket!.on('ereader-devices-updated', (data) {
+ if (data is! Map) return;
+ final raw = data['ereaderDevices'] as List<dynamic>?;
+ if (raw == null) return;
+ debugPrint('[Socket] ereader-devices-updated (${raw.length} devices)');
+ onEreaderDevicesUpdated?.call(raw.cast<Map<String, dynamic>>());
+ });
+
_socket!.onDisconnect((reason) {
final duration = _connectedAt != null
? DateTime.now().difference(_connectedAt!).inSeconds
@@ -197,6 +212,7 @@ class SocketService {
onUserUpdated = null;
onReconnectFailed = null;
onEncodeFinished = null;
+ onEreaderDevicesUpdated = null;
}
/// Disconnect the socket but keep callbacks and credentials so we can
@@ -282,6 +298,13 @@ class SocketService {
}
});
+ _socket!.on('ereader-devices-updated', (data) {
+ if (data is! Map) return;
+ final raw = data['ereaderDevices'] as List<dynamic>?;
+ if (raw == null) return;
+ onEreaderDevicesUpdated?.call(raw.cast<Map<String, dynamic>>());
+ });
+
_socket!.onDisconnect((reason) {
final duration = _connectedAt != null
? DateTime.now().difference(_connectedAt!).inSeconds
diff --git a/lib/widgets/author_books_sheet.dart b/lib/widgets/author_books_sheet.dart
index 8ab6d0f7..e36933f4 100644
--- a/lib/widgets/author_books_sheet.dart
+++ b/lib/widgets/author_books_sheet.dart
@@ -138,7 +138,7 @@ class _AuthorBooksSheetState extends State<AuthorBooksSheet> {
final lib = context.read<LibraryProvider>();
final auth = context.watch<AuthProvider>();
final headers = lib.mediaHeaders;
- final canEdit = auth.isRoot && !lib.isOffline;
+ final canEdit = auth.isAdmin && !lib.isOffline;
if (_isLoading) {
return Column(
diff --git a/lib/widgets/book_detail_sheet.dart b/lib/widgets/book_detail_sheet.dart
index 4768cb72..2ebe34b8 100644
--- a/lib/widgets/book_detail_sheet.dart
+++ b/lib/widgets/book_detail_sheet.dart
@@ -711,7 +711,7 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
Navigator.pop(ctx);
PlaylistPickerSheet.show(context, widget.itemId);
}),
- if (!lib.isOffline && !lib.isPodcastLibrary && auth.isRoot)
+ if (!lib.isOffline && !lib.isPodcastLibrary && auth.isAdmin)
_moreItem(cs, Icons.collections_bookmark_rounded, l.addToCollection,
onTap: () {
Navigator.pop(ctx);
@@ -721,6 +721,12 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
_moreItem(cs, _ebookSaved ? Icons.download_done_rounded : Icons.save_alt_rounded,
_ebookSaved ? l.downloadEbookAgain : l.downloadEbook,
onTap: () { Navigator.pop(ctx); _saveEbook(context, auth, ebookFile, title); }),
+ if (ebookFile != null && auth.ereaderDevices.isNotEmpty)
+ _moreItem(cs, Icons.send_to_mobile_rounded, l.sendToEreader,
+ onTap: () {
+ Navigator.pop(ctx);
+ _sendToEreader(context, auth);
+ }),
if (progress > 0 || isFinished)
_moreItem(cs, Icons.restart_alt_rounded, l.resetProgress,
onTap: () { Navigator.pop(ctx); _resetProgress(context, auth, duration); }),
@@ -1217,6 +1223,77 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
}
}
+ Future<void> _sendToEreader(BuildContext context, AuthProvider auth) async {
+ final api = auth.apiService;
+ final devices = auth.ereaderDevices;
+ if (api == null || devices.isEmpty) return;
+ final l = AppLocalizations.of(context)!;
+
+ String? deviceName;
+ if (devices.length == 1) {
+ deviceName = devices.first['name'] as String?;
+ } else {
+ deviceName = await _pickEreaderDevice(context, devices);
+ }
+ if (deviceName == null || !context.mounted) return;
+
+ showOverlayToast(context, l.sendingToEreader(deviceName),
+ icon: Icons.send_to_mobile_rounded);
+
+ final ok = await api.sendEBookToDevice(
+ libraryItemId: widget.itemId,
+ deviceName: deviceName,
+ );
+ if (!context.mounted) return;
+ if (ok) {
+ showOverlayToast(context, l.sendToEreaderSuccess(deviceName),
+ icon: Icons.check_circle_outline_rounded);
+ } else {
+ showOverlayToast(context, l.sendToEreaderFailed,
+ icon: Icons.error_outline_rounded);
+ }
+ }
+
+ Future<String?> _pickEreaderDevice(
+ BuildContext context, List<Map<String, dynamic>> devices) {
+ final cs = Theme.of(context).colorScheme;
+ final l = AppLocalizations.of(context)!;
+ return showModalBottomSheet<String>(
+ context: context,
+ backgroundColor: Theme.of(context).bottomSheetTheme.backgroundColor,
+ shape: const RoundedRectangleBorder(
+ borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
+ ),
+ builder: (ctx) {
+ return SafeArea(
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(16, 8, 16, 16),
+ child: Column(mainAxisSize: MainAxisSize.min, children: [
+ Center(child: Container(width: 40, height: 4, margin: const EdgeInsets.only(bottom: 16),
+ decoration: BoxDecoration(color: cs.onSurface.withValues(alpha: 0.24), borderRadius: BorderRadius.circular(2)))),
+ Padding(
+ padding: const EdgeInsets.only(bottom: 8),
+ child: Text(l.pickEreaderDevice,
+ style: Theme.of(ctx).textTheme.titleSmall?.copyWith(
+ color: cs.onSurfaceVariant, fontWeight: FontWeight.w600)),
+ ),
+ ...devices.map((d) {
+ final name = d['name'] as String? ?? '';
+ final email = d['email'] as String? ?? '';
+ return ListTile(
+ leading: Icon(Icons.send_to_mobile_rounded, color: cs.onSurfaceVariant),
+ title: Text(name),
+ subtitle: Text(email, style: TextStyle(color: cs.onSurface.withValues(alpha: 0.5))),
+ onTap: () => Navigator.pop(ctx, name),
+ );
+ }),
+ ]),
+ ),
+ );
+ },
+ );
+ }
+
Future<void> _startAbsorb(BuildContext context, {required AuthProvider auth, required String title, required String author, required String? coverUrl, required double duration, required List<dynamic> chapters}) async {
final player = AudioPlayerService();
// Grab the root navigator before we pop the sheet
diff --git a/lib/widgets/collection_detail_sheet.dart b/lib/widgets/collection_detail_sheet.dart
index 7699ae9b..493ea5eb 100644
--- a/lib/widgets/collection_detail_sheet.dart
+++ b/lib/widgets/collection_detail_sheet.dart
@@ -69,8 +69,17 @@ class _CollectionDetailSheetState extends State<CollectionDetailSheet> {
),
);
if (confirmed == true && context.mounted) {
- await lib.deleteCollection(widget.collectionId);
- if (context.mounted) Navigator.pop(context);
+ final status = await lib.deleteCollection(widget.collectionId);
+ if (!context.mounted) return;
+ if (status == 200) {
+ Navigator.pop(context);
+ } else if (status == 403) {
+ showOverlayToast(context, l.deletePermissionRequired,
+ icon: Icons.lock_outline_rounded);
+ } else {
+ showOverlayToast(context, l.deleteCollectionFailed,
+ icon: Icons.error_outline_rounded);
+ }
}
}
@@ -107,7 +116,11 @@ class _CollectionDetailSheetState extends State<CollectionDetailSheet> {
final tt = Theme.of(context).textTheme;
final l = AppLocalizations.of(context)!;
final lib = context.watch<LibraryProvider>();
- final isRoot = context.read<AuthProvider>().isRoot;
+ final auth = context.read<AuthProvider>();
+ // Both gated at isAdmin in the UI; server returns 403 when admin lacks
+ // the `delete` permission flag and we show a friendly toast then.
+ final canEditCollection = auth.isAdmin;
+ final canDeleteCollection = auth.isAdmin;
final collection = lib.collections.cast<Map<String, dynamic>>().where(
(c) => c['id'] == widget.collectionId,
@@ -145,7 +158,7 @@ class _CollectionDetailSheetState extends State<CollectionDetailSheet> {
)),
),
] else ...[
- if (isRoot) ...[
+ if (canDeleteCollection) ...[
GestureDetector(
onTap: () => _deleteCollection(context, lib),
child: Icon(Icons.delete_outline_rounded, size: 20,
@@ -170,7 +183,7 @@ class _CollectionDetailSheetState extends State<CollectionDetailSheet> {
_gridView ? Icons.view_list_rounded : Icons.grid_view_rounded,
size: 20, color: cs.onSurfaceVariant),
),
- if (isRoot && books.length > 1) ...[
+ if (canEditCollection && books.length > 1) ...[
const SizedBox(width: 12),
GestureDetector(
onTap: () => _startReorder(books),
@@ -200,7 +213,7 @@ class _CollectionDetailSheetState extends State<CollectionDetailSheet> {
? _buildReorderList(cs, tt, lib, l)
: _gridView
? _buildGrid(cs, tt, lib, books, l)
- : _buildItemList(cs, tt, lib, books, l, isRoot: isRoot),
+ : _buildItemList(cs, tt, lib, books, l, canEditCollection: canEditCollection),
),
]);
}
@@ -270,7 +283,7 @@ class _CollectionDetailSheetState extends State<CollectionDetailSheet> {
);
}
- Widget _buildItemList(ColorScheme cs, TextTheme tt, LibraryProvider lib, List<dynamic> books, AppLocalizations l, {required bool isRoot}) {
+ Widget _buildItemList(ColorScheme cs, TextTheme tt, LibraryProvider lib, List<dynamic> books, AppLocalizations l, {required bool canEditCollection}) {
final isDark = Theme.of(context).brightness == Brightness.dark;
final doneColor = isDark ? Colors.greenAccent[400]! : Colors.green.shade700;
@@ -401,7 +414,7 @@ class _CollectionDetailSheetState extends State<CollectionDetailSheet> {
final isOnAbsorbing = lib.isOnAbsorbingList(itemId);
- if (!isRoot) {
+ if (!canEditCollection) {
return Dismissible(
key: ValueKey('absorb-$itemId'),
direction: isOnAbsorbing ? DismissDirection.none : DismissDirection.startToEnd,