A cross platform Audiobookshelf client for Android and iOS
Dart
Add scan schedules, metadata source ordering, a server logs screen, and podcast episode limits to the admin pages
Barnabas724f53660537
diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arbindex 5e0156bd..aee25b13 100644--- a/lib/l10n/app_en.arb+++ b/lib/l10n/app_en.arb@@ -1706,6 +1706,7 @@"saved": "Downloaded","selectLibrary": "Select Library","switchLibraryTooltip": "Switch library",+ "refreshTooltip": "Refresh","noBooksFound": "No books found","userFallback": "User","rootAdmin": "Root Admin",@@ -2597,6 +2598,10 @@"adminPodcastsAutoDownloadOnSubtitle": "Server downloads new episodes automatically","adminPodcastsAutoDownloadOffSubtitle": "New episodes are not auto-downloaded","adminPodcastsFailedAutoDownloadUpdate": "Failed to update auto-download setting",+ "adminPodcastsMaxEpisodesToKeep": "Max episodes to keep",+ "adminPodcastsMaxEpisodesToKeepHelp": "0 keeps every episode. After a new episode is auto-downloaded, Audiobookshelf removes the oldest episode when the show is over this limit.",+ "adminPodcastsNoEpisodeLimit": "No limit",+ "adminPodcastsEpisodeLimitInvalid": "Enter 0 or a whole number","adminPodcastsCheckSchedule": "Check Schedule","adminPodcastsFrequency": "Frequency","adminPodcastsFreqHourly": "Hourly",diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dartindex 7064b285..cc9b77d5 100644--- a/lib/l10n/app_localizations.dart+++ b/lib/l10n/app_localizations.dart@@ -6400,6 +6400,12 @@ abstract class AppLocalizations {/// **'Switch library'**String get switchLibraryTooltip;+ /// No description provided for @refreshTooltip.+ ///+ /// In en, this message translates to:+ /// **'Refresh'**+ String get refreshTooltip;+/// No description provided for @noBooksFound.////// In en, this message translates to:@@ -8438,6 +8444,30 @@ abstract class AppLocalizations {/// **'Failed to update auto-download setting'**String get adminPodcastsFailedAutoDownloadUpdate;+ /// No description provided for @adminPodcastsMaxEpisodesToKeep.+ ///+ /// In en, this message translates to:+ /// **'Max episodes to keep'**+ String get adminPodcastsMaxEpisodesToKeep;++ /// No description provided for @adminPodcastsMaxEpisodesToKeepHelp.+ ///+ /// In en, this message translates to:+ /// **'0 keeps every episode. After a new episode is auto-downloaded, Audiobookshelf removes the oldest episode when the show is over this limit.'**+ String get adminPodcastsMaxEpisodesToKeepHelp;++ /// No description provided for @adminPodcastsNoEpisodeLimit.+ ///+ /// In en, this message translates to:+ /// **'No limit'**+ String get adminPodcastsNoEpisodeLimit;++ /// No description provided for @adminPodcastsEpisodeLimitInvalid.+ ///+ /// In en, this message translates to:+ /// **'Enter 0 or a whole number'**+ String get adminPodcastsEpisodeLimitInvalid;+/// No description provided for @adminPodcastsCheckSchedule.////// In en, this message translates to:diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dartindex e130a0c5..a5059494 100644--- a/lib/l10n/app_localizations_de.dart+++ b/lib/l10n/app_localizations_de.dart@@ -3548,6 +3548,9 @@ class AppLocalizationsDe extends AppLocalizations {@overrideString get switchLibraryTooltip => 'Bibliothek wechseln';+ @override+ String get refreshTooltip => 'Refresh';+@overrideString get noBooksFound => 'Keine Bücher gefunden';@@ -4770,6 +4773,19 @@ class AppLocalizationsDe extends AppLocalizations {String get adminPodcastsFailedAutoDownloadUpdate =>'Auto-Download-Einstellung konnte nicht aktualisiert werden';+ @override+ String get adminPodcastsMaxEpisodesToKeep => 'Max episodes to keep';++ @override+ String get adminPodcastsMaxEpisodesToKeepHelp =>+ '0 keeps every episode. After a new episode is auto-downloaded, Audiobookshelf removes the oldest episode when the show is over this limit.';++ @override+ String get adminPodcastsNoEpisodeLimit => 'No limit';++ @override+ String get adminPodcastsEpisodeLimitInvalid => 'Enter 0 or a whole number';+@overrideString get adminPodcastsCheckSchedule => 'Prüfplan';diff --git a/lib/l10n/app_localizations_el.dart b/lib/l10n/app_localizations_el.dartindex 1d82cdce..63f58093 100644--- a/lib/l10n/app_localizations_el.dart+++ b/lib/l10n/app_localizations_el.dart@@ -3500,6 +3500,9 @@ class AppLocalizationsEl extends AppLocalizations {@overrideString get switchLibraryTooltip => 'Switch library';+ @override+ String get refreshTooltip => 'Refresh';+@overrideString get noBooksFound => 'No books found';@@ -4707,6 +4710,19 @@ class AppLocalizationsEl extends AppLocalizations {String get adminPodcastsFailedAutoDownloadUpdate =>'Failed to update auto-download setting';+ @override+ String get adminPodcastsMaxEpisodesToKeep => 'Max episodes to keep';++ @override+ String get adminPodcastsMaxEpisodesToKeepHelp =>+ '0 keeps every episode. After a new episode is auto-downloaded, Audiobookshelf removes the oldest episode when the show is over this limit.';++ @override+ String get adminPodcastsNoEpisodeLimit => 'No limit';++ @override+ String get adminPodcastsEpisodeLimitInvalid => 'Enter 0 or a whole number';+@overrideString get adminPodcastsCheckSchedule => 'Check Schedule';diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dartindex 5c2ea142..59e12402 100644--- a/lib/l10n/app_localizations_en.dart+++ b/lib/l10n/app_localizations_en.dart@@ -3500,6 +3500,9 @@ class AppLocalizationsEn extends AppLocalizations {@overrideString get switchLibraryTooltip => 'Switch library';+ @override+ String get refreshTooltip => 'Refresh';+@overrideString get noBooksFound => 'No books found';@@ -4707,6 +4710,19 @@ class AppLocalizationsEn extends AppLocalizations {String get adminPodcastsFailedAutoDownloadUpdate =>'Failed to update auto-download setting';+ @override+ String get adminPodcastsMaxEpisodesToKeep => 'Max episodes to keep';++ @override+ String get adminPodcastsMaxEpisodesToKeepHelp =>+ '0 keeps every episode. After a new episode is auto-downloaded, Audiobookshelf removes the oldest episode when the show is over this limit.';++ @override+ String get adminPodcastsNoEpisodeLimit => 'No limit';++ @override+ String get adminPodcastsEpisodeLimitInvalid => 'Enter 0 or a whole number';+@overrideString get adminPodcastsCheckSchedule => 'Check Schedule';diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dartindex 90d00757..e58b5646 100644--- a/lib/l10n/app_localizations_es.dart+++ b/lib/l10n/app_localizations_es.dart@@ -3502,6 +3502,9 @@ class AppLocalizationsEs extends AppLocalizations {@overrideString get switchLibraryTooltip => 'Switch library';+ @override+ String get refreshTooltip => 'Refresh';+@overrideString get noBooksFound => 'No books found';@@ -4709,6 +4712,19 @@ class AppLocalizationsEs extends AppLocalizations {String get adminPodcastsFailedAutoDownloadUpdate =>'Failed to update auto-download setting';+ @override+ String get adminPodcastsMaxEpisodesToKeep => 'Max episodes to keep';++ @override+ String get adminPodcastsMaxEpisodesToKeepHelp =>+ '0 keeps every episode. After a new episode is auto-downloaded, Audiobookshelf removes the oldest episode when the show is over this limit.';++ @override+ String get adminPodcastsNoEpisodeLimit => 'No limit';++ @override+ String get adminPodcastsEpisodeLimitInvalid => 'Enter 0 or a whole number';+@overrideString get adminPodcastsCheckSchedule => 'Check Schedule';diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dartindex 7aa8ba4b..4d09c3e1 100644--- a/lib/l10n/app_localizations_fr.dart+++ b/lib/l10n/app_localizations_fr.dart@@ -3547,6 +3547,9 @@ class AppLocalizationsFr extends AppLocalizations {@overrideString get switchLibraryTooltip => 'Switch library';+ @override+ String get refreshTooltip => 'Refresh';+@overrideString get noBooksFound => 'No books found';@@ -4754,6 +4757,19 @@ class AppLocalizationsFr extends AppLocalizations {String get adminPodcastsFailedAutoDownloadUpdate =>'Failed to update auto-download setting';+ @override+ String get adminPodcastsMaxEpisodesToKeep => 'Max episodes to keep';++ @override+ String get adminPodcastsMaxEpisodesToKeepHelp =>+ '0 keeps every episode. After a new episode is auto-downloaded, Audiobookshelf removes the oldest episode when the show is over this limit.';++ @override+ String get adminPodcastsNoEpisodeLimit => 'No limit';++ @override+ String get adminPodcastsEpisodeLimitInvalid => 'Enter 0 or a whole number';+@overrideString get adminPodcastsCheckSchedule => 'Check Schedule';diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dartindex 6091dfdd..269a6996 100644--- a/lib/l10n/app_localizations_it.dart+++ b/lib/l10n/app_localizations_it.dart@@ -3500,6 +3500,9 @@ class AppLocalizationsIt extends AppLocalizations {@overrideString get switchLibraryTooltip => 'Switch library';+ @override+ String get refreshTooltip => 'Refresh';+@overrideString get noBooksFound => 'No books found';@@ -4707,6 +4710,19 @@ class AppLocalizationsIt extends AppLocalizations {String get adminPodcastsFailedAutoDownloadUpdate =>'Failed to update auto-download setting';+ @override+ String get adminPodcastsMaxEpisodesToKeep => 'Max episodes to keep';++ @override+ String get adminPodcastsMaxEpisodesToKeepHelp =>+ '0 keeps every episode. After a new episode is auto-downloaded, Audiobookshelf removes the oldest episode when the show is over this limit.';++ @override+ String get adminPodcastsNoEpisodeLimit => 'No limit';++ @override+ String get adminPodcastsEpisodeLimitInvalid => 'Enter 0 or a whole number';+@overrideString get adminPodcastsCheckSchedule => 'Check Schedule';diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dartindex 92a56d96..de66685f 100644--- a/lib/l10n/app_localizations_ja.dart+++ b/lib/l10n/app_localizations_ja.dart@@ -3500,6 +3500,9 @@ class AppLocalizationsJa extends AppLocalizations {@overrideString get switchLibraryTooltip => 'Switch library';+ @override+ String get refreshTooltip => 'Refresh';+@overrideString get noBooksFound => 'No books found';@@ -4707,6 +4710,19 @@ class AppLocalizationsJa extends AppLocalizations {String get adminPodcastsFailedAutoDownloadUpdate =>'Failed to update auto-download setting';+ @override+ String get adminPodcastsMaxEpisodesToKeep => 'Max episodes to keep';++ @override+ String get adminPodcastsMaxEpisodesToKeepHelp =>+ '0 keeps every episode. After a new episode is auto-downloaded, Audiobookshelf removes the oldest episode when the show is over this limit.';++ @override+ String get adminPodcastsNoEpisodeLimit => 'No limit';++ @override+ String get adminPodcastsEpisodeLimitInvalid => 'Enter 0 or a whole number';+@overrideString get adminPodcastsCheckSchedule => 'Check Schedule';diff --git a/lib/l10n/app_localizations_no.dart b/lib/l10n/app_localizations_no.dartindex 3ae93e59..a90d53fc 100644--- a/lib/l10n/app_localizations_no.dart+++ b/lib/l10n/app_localizations_no.dart@@ -3500,6 +3500,9 @@ class AppLocalizationsNo extends AppLocalizations {@overrideString get switchLibraryTooltip => 'Switch library';+ @override+ String get refreshTooltip => 'Refresh';+@overrideString get noBooksFound => 'No books found';@@ -4707,6 +4710,19 @@ class AppLocalizationsNo extends AppLocalizations {String get adminPodcastsFailedAutoDownloadUpdate =>'Failed to update auto-download setting';+ @override+ String get adminPodcastsMaxEpisodesToKeep => 'Max episodes to keep';++ @override+ String get adminPodcastsMaxEpisodesToKeepHelp =>+ '0 keeps every episode. After a new episode is auto-downloaded, Audiobookshelf removes the oldest episode when the show is over this limit.';++ @override+ String get adminPodcastsNoEpisodeLimit => 'No limit';++ @override+ String get adminPodcastsEpisodeLimitInvalid => 'Enter 0 or a whole number';+@overrideString get adminPodcastsCheckSchedule => 'Check Schedule';diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dartindex 29e41aba..b8a77fd8 100644--- a/lib/l10n/app_localizations_pt.dart+++ b/lib/l10n/app_localizations_pt.dart@@ -3500,6 +3500,9 @@ class AppLocalizationsPt extends AppLocalizations {@overrideString get switchLibraryTooltip => 'Switch library';+ @override+ String get refreshTooltip => 'Refresh';+@overrideString get noBooksFound => 'No books found';@@ -4707,6 +4710,19 @@ class AppLocalizationsPt extends AppLocalizations {String get adminPodcastsFailedAutoDownloadUpdate =>'Failed to update auto-download setting';+ @override+ String get adminPodcastsMaxEpisodesToKeep => 'Max episodes to keep';++ @override+ String get adminPodcastsMaxEpisodesToKeepHelp =>+ '0 keeps every episode. After a new episode is auto-downloaded, Audiobookshelf removes the oldest episode when the show is over this limit.';++ @override+ String get adminPodcastsNoEpisodeLimit => 'No limit';++ @override+ String get adminPodcastsEpisodeLimitInvalid => 'Enter 0 or a whole number';+@overrideString get adminPodcastsCheckSchedule => 'Check Schedule';diff --git a/lib/l10n/app_localizations_ro.dart b/lib/l10n/app_localizations_ro.dartindex 56520ad0..311b9f79 100644--- a/lib/l10n/app_localizations_ro.dart+++ b/lib/l10n/app_localizations_ro.dart@@ -3500,6 +3500,9 @@ class AppLocalizationsRo extends AppLocalizations {@overrideString get switchLibraryTooltip => 'Switch library';+ @override+ String get refreshTooltip => 'Refresh';+@overrideString get noBooksFound => 'No books found';@@ -4707,6 +4710,19 @@ class AppLocalizationsRo extends AppLocalizations {String get adminPodcastsFailedAutoDownloadUpdate =>'Failed to update auto-download setting';+ @override+ String get adminPodcastsMaxEpisodesToKeep => 'Max episodes to keep';++ @override+ String get adminPodcastsMaxEpisodesToKeepHelp =>+ '0 keeps every episode. After a new episode is auto-downloaded, Audiobookshelf removes the oldest episode when the show is over this limit.';++ @override+ String get adminPodcastsNoEpisodeLimit => 'No limit';++ @override+ String get adminPodcastsEpisodeLimitInvalid => 'Enter 0 or a whole number';+@overrideString get adminPodcastsCheckSchedule => 'Check Schedule';diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dartindex f5ca6b1f..b883b845 100644--- a/lib/l10n/app_localizations_ru.dart+++ b/lib/l10n/app_localizations_ru.dart@@ -3504,6 +3504,9 @@ class AppLocalizationsRu extends AppLocalizations {@overrideString get switchLibraryTooltip => 'Switch library';+ @override+ String get refreshTooltip => 'Refresh';+@overrideString get noBooksFound => 'No books found';@@ -4711,6 +4714,19 @@ class AppLocalizationsRu extends AppLocalizations {String get adminPodcastsFailedAutoDownloadUpdate =>'Failed to update auto-download setting';+ @override+ String get adminPodcastsMaxEpisodesToKeep => 'Max episodes to keep';++ @override+ String get adminPodcastsMaxEpisodesToKeepHelp =>+ '0 keeps every episode. After a new episode is auto-downloaded, Audiobookshelf removes the oldest episode when the show is over this limit.';++ @override+ String get adminPodcastsNoEpisodeLimit => 'No limit';++ @override+ String get adminPodcastsEpisodeLimitInvalid => 'Enter 0 or a whole number';+@overrideString get adminPodcastsCheckSchedule => 'Check Schedule';diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dartindex 19dbe813..11f106be 100644--- a/lib/l10n/app_localizations_zh.dart+++ b/lib/l10n/app_localizations_zh.dart@@ -3425,6 +3425,9 @@ class AppLocalizationsZh extends AppLocalizations {@overrideString get switchLibraryTooltip => '切换媒体库';+ @override+ String get refreshTooltip => 'Refresh';+@overrideString get noBooksFound => '未找到书籍';@@ -4626,6 +4629,19 @@ class AppLocalizationsZh extends AppLocalizations {String get adminPodcastsFailedAutoDownloadUpdate =>'Failed to update auto-download setting';+ @override+ String get adminPodcastsMaxEpisodesToKeep => 'Max episodes to keep';++ @override+ String get adminPodcastsMaxEpisodesToKeepHelp =>+ '0 keeps every episode. After a new episode is auto-downloaded, Audiobookshelf removes the oldest episode when the show is over this limit.';++ @override+ String get adminPodcastsNoEpisodeLimit => 'No limit';++ @override+ String get adminPodcastsEpisodeLimitInvalid => 'Enter 0 or a whole number';+@overrideString get adminPodcastsCheckSchedule => 'Check Schedule';diff --git a/lib/screens/admin_api_keys_screen.dart b/lib/screens/admin_api_keys_screen.dartindex d9e842f2..ea024390 100644--- a/lib/screens/admin_api_keys_screen.dart+++ b/lib/screens/admin_api_keys_screen.dart@@ -5,6 +5,7 @@ import 'package:provider/provider.dart';import '../l10n/app_localizations.dart';import '../providers/auth_provider.dart';import '../widgets/absorb_page_header.dart';+import '../widgets/adaptive_modal.dart';import '../widgets/overlay_toast.dart';class AdminApiKeysScreen extends StatefulWidget {@@ -183,7 +184,8 @@ class _AdminApiKeysScreenState extends State<AdminApiKeysScreen> {}void _showEditor() {- showModalBottomSheet(context: context, isScrollControlled: true, useSafeArea: true, backgroundColor: Colors.transparent,+ showAdaptiveActionMenu(context: context, isScrollControlled: true, useSafeArea: true, backgroundColor: Colors.transparent,+ desktopWidth: 560, desktopScrollWrap: false,builder: (_) => _ApiKeyEditorSheet(users: widget.users, onCreated: _load));}@@ -323,7 +325,8 @@ class _ApiKeyEditorSheetState extends State<_ApiKeyEditorSheet> {if (created != null && token != null) {widget.onCreated();Navigator.pop(context);- showModalBottomSheet(context: context, isScrollControlled: true, useSafeArea: true, backgroundColor: Colors.transparent,+ showAdaptiveActionMenu(context: context, isScrollControlled: true, useSafeArea: true, backgroundColor: Colors.transparent,+ desktopWidth: 560,builder: (_) => _ApiKeyCreatedSheet(name: name, token: token));} else {showOverlayToast(context, l.adminApiKeysFailedCreate, icon: Icons.error_outline_rounded);diff --git a/lib/screens/admin_email_screen.dart b/lib/screens/admin_email_screen.dartindex 53f70c23..6674392a 100644--- a/lib/screens/admin_email_screen.dart+++ b/lib/screens/admin_email_screen.dart@@ -6,6 +6,7 @@ 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/adaptive_modal.dart';import '../widgets/overlay_toast.dart';class AdminEmailScreen extends StatefulWidget {@@ -160,13 +161,15 @@ class _AdminEmailScreenState extends State<AdminEmailScreen> {...((existing?['users'] as List<dynamic>?) ?? []).cast<String>(),};- return showModalBottomSheet<Map<String, dynamic>>(+ return showAdaptiveActionMenu<Map<String, dynamic>>(context: context,isScrollControlled: true,backgroundColor: Theme.of(context).bottomSheetTheme.backgroundColor,shape: const RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(24)),),+ desktopWidth: 560,+ desktopScrollWrap: false,builder: (ctx) {return StatefulBuilder(builder: (ctx, setSheet) {return SafeArea(diff --git a/lib/screens/admin_library_edit_screen.dart b/lib/screens/admin_library_edit_screen.dartindex a0fbc3c1..3fa0509d 100644--- a/lib/screens/admin_library_edit_screen.dart+++ b/lib/screens/admin_library_edit_screen.dart@@ -7,11 +7,21 @@ import '../widgets/absorb_page_header.dart';import '../widgets/filesystem_picker_screen.dart';import '../widgets/overlay_toast.dart';+enum _LibraryEditorSection { details, settings, scanner, schedule, tools }++class _MetadataSource {+ final String id;+ bool enabled;++ _MetadataSource(this.id, {required this.enabled});+}+/// Create or edit a library. Pass [library] (the GET /api/libraries object) to/// edit; omit it to create. Returns true via Navigator.pop when a change was/// saved so the caller can refresh.class AdminLibraryEditScreen extends StatefulWidget {final Map<String, dynamic>? library;+const AdminLibraryEditScreen({super.key, this.library});@override@@ -19,34 +29,72 @@ class AdminLibraryEditScreen extends StatefulWidget {}class _AdminLibraryEditScreenState extends State<AdminLibraryEditScreen> {- // The full ABS library icon set (client store globals.js libraryIcons).static const _icons = [- 'database', 'audiobookshelf', 'books-1', 'books-2', 'book-1', 'microphone-1',- 'microphone-3', 'radio', 'podcast', 'rss', 'headphones', 'music', 'file-picture',- 'rocket', 'power', 'star', 'heart',+ 'database',+ 'audiobookshelf',+ 'books-1',+ 'books-2',+ 'book-1',+ 'microphone-1',+ 'microphone-3',+ 'radio',+ 'podcast',+ 'rss',+ 'headphones',+ 'music',+ 'file-picture',+ 'rocket',+ 'power',+ 'star',+ 'heart',+ ];++ static const _defaultMetadataPrecedence = [+ 'folderStructure',+ 'audioMetatags',+ 'nfoFile',+ 'txtFiles',+ 'opfFile',+ 'absMetadata',];- // ABS uses its own icon font; map each name to the nearest Material icon for display.static IconData _absIcon(String name) {switch (name) {- case 'audiobookshelf': return Icons.library_books_rounded;- case 'books-1': return Icons.menu_book_rounded;- case 'books-2': return Icons.auto_stories_rounded;- case 'book-1': return Icons.book_rounded;- case 'microphone-1': return Icons.mic_rounded;- case 'microphone-3': return Icons.mic_external_on_rounded;- case 'radio': return Icons.radio_rounded;- case 'podcast': return Icons.podcasts_rounded;- case 'rss': return Icons.rss_feed_rounded;- case 'headphones': return Icons.headphones_rounded;- case 'music': return Icons.music_note_rounded;- case 'file-picture': return Icons.image_rounded;- case 'rocket': return Icons.rocket_launch_rounded;- case 'power': return Icons.power_rounded;- case 'star': return Icons.star_rounded;- case 'heart': return Icons.favorite_rounded;+ case 'audiobookshelf':+ return Icons.library_books_rounded;+ case 'books-1':+ return Icons.menu_book_rounded;+ case 'books-2':+ return Icons.auto_stories_rounded;+ case 'book-1':+ return Icons.book_rounded;+ case 'microphone-1':+ return Icons.mic_rounded;+ case 'microphone-3':+ return Icons.mic_external_on_rounded;+ case 'radio':+ return Icons.radio_rounded;+ case 'podcast':+ return Icons.podcasts_rounded;+ case 'rss':+ return Icons.rss_feed_rounded;+ case 'headphones':+ return Icons.headphones_rounded;+ case 'music':+ return Icons.music_note_rounded;+ case 'file-picture':+ return Icons.image_rounded;+ case 'rocket':+ return Icons.rocket_launch_rounded;+ case 'power':+ return Icons.power_rounded;+ case 'star':+ return Icons.star_rounded;+ case 'heart':+ return Icons.favorite_rounded;case 'database':- default: return Icons.storage_rounded;+ default:+ return Icons.storage_rounded;}}@@ -56,11 +104,10 @@ class _AdminLibraryEditScreenState extends State<AdminLibraryEditScreen> {String _mediaType = 'book';String _provider = 'google';String _icon = 'database';- // Each folder: existing -> {id, fullPath}; new -> {fullPath}.List<Map<String, dynamic>> _folders = [];List<String> _originalFolderIds = [];+ Map<String, dynamic> _originalSettings = {};- // settingsnum _coverAspectRatio = 1.0;bool _disableWatcher = false;bool _skipAsin = false;@@ -72,10 +119,30 @@ class _AdminLibraryEditScreenState extends State<AdminLibraryEditScreen> {final _podcastRegion = TextEditingController();final _markPercent = TextEditingController();final _markTime = TextEditingController();+ String _finishedMode = 'time';+final _autoScan = TextEditingController();+ final _sectionScrollController = ScrollController();+ bool _scheduleEnabled = false;+ String _scheduleMode = 'weekly';+ int _scheduleMinute = 0;+ TimeOfDay _scheduleTime = const TimeOfDay(hour: 0, minute: 0);+ int _scheduleWeekday = DateTime.monday;- List<String> _providers = const ['google', 'audible', 'openlibrary', 'itunes', 'audnexus', 'fantlab'];+ List<_MetadataSource> _metadataSources = [];+ _LibraryEditorSection _selectedSection = _LibraryEditorSection.details;+ List<String> _providers = const [+ 'google',+ 'audible',+ 'openlibrary',+ 'itunes',+ 'audnexus',+ 'fantlab',+ ];bool _saving = false;+ String? _removingMetadataExtension;++ bool get _interactionLocked => _saving || _removingMetadataExtension != null;@overridevoid initState() {@@ -88,26 +155,56 @@ class _AdminLibraryEditScreenState extends State<AdminLibraryEditScreen> {_icon = (lib['icon'] as String?) ?? 'database';_folders = ((lib['folders'] as List?) ?? []).whereType<Map>()- .map((f) => {'id': f['id'], 'fullPath': f['fullPath']})+ .map(+ (folder) => <String, dynamic>{+ 'id': folder['id'],+ 'fullPath': folder['fullPath'],+ },+ ).toList();- _originalFolderIds = _folders.map((f) => f['id'].toString()).toList();- final s = (lib['settings'] as Map?)?.cast<String, dynamic>() ?? {};- _coverAspectRatio = (s['coverAspectRatio'] as num?) ?? 1;- _disableWatcher = s['disableWatcher'] as bool? ?? false;- _skipAsin = s['skipMatchingMediaWithAsin'] as bool? ?? false;- _skipIsbn = s['skipMatchingMediaWithIsbn'] as bool? ?? false;- _hideSingleSeries = s['hideSingleBookSeries'] as bool? ?? false;- _audiobooksOnly = s['audiobooksOnly'] as bool? ?? false;- _epubScripted = s['epubsAllowScriptedContent'] as bool? ?? false;- _laterBooksOnly = s['onlyShowLaterBooksInContinueSeries'] as bool? ?? false;- _podcastRegion.text = (s['podcastSearchRegion'] as String?) ?? 'us';- final pct = s['markAsFinishedPercentComplete'];- _markPercent.text = pct == null ? '' : '$pct';- _markTime.text = '${s['markAsFinishedTimeRemaining'] ?? 10}';- _autoScan.text = (s['autoScanCronExpression'] as String?) ?? '';+ _originalFolderIds = _folders+ .map((folder) => folder['id'].toString())+ .toList();+ _originalSettings = Map<String, dynamic>.from(+ (lib['settings'] as Map?)?.cast<String, dynamic>() ?? const {},+ );++ final settings = _originalSettings;+ _coverAspectRatio = (settings['coverAspectRatio'] as num?) ?? 1;+ _disableWatcher = settings['disableWatcher'] as bool? ?? false;+ _skipAsin = settings['skipMatchingMediaWithAsin'] as bool? ?? false;+ _skipIsbn = settings['skipMatchingMediaWithIsbn'] as bool? ?? false;+ _hideSingleSeries = settings['hideSingleBookSeries'] as bool? ?? false;+ _audiobooksOnly = settings['audiobooksOnly'] as bool? ?? false;+ _epubScripted = settings['epubsAllowScriptedContent'] as bool? ?? false;+ _laterBooksOnly =+ settings['onlyShowLaterBooksInContinueSeries'] as bool? ?? false;+ _podcastRegion.text =+ (settings['podcastSearchRegion'] as String?) ?? 'us';++ final timeRemaining = settings['markAsFinishedTimeRemaining'];+ final percentComplete = settings['markAsFinishedPercentComplete'];+ if (timeRemaining != null) {+ _finishedMode = 'time';+ _markTime.text = '$timeRemaining';+ _markPercent.text = percentComplete == null ? '90' : '$percentComplete';+ } else if (percentComplete != null) {+ _finishedMode = 'percent';+ _markPercent.text = '$percentComplete';+ _markTime.text = '10';+ } else {+ _markTime.text = '10';+ _markPercent.text = '90';+ }++ _initializeSchedule(settings['autoScanCronExpression']);+ _initializeMetadataSources(settings['metadataPrecedence']);} else {_markTime.text = '10';+ _markPercent.text = '90';_podcastRegion.text = 'us';+ _initializeSchedule(null);+ _resetMetadataSources();}_loadProviders();}@@ -119,7 +216,136 @@ class _AdminLibraryEditScreenState extends State<AdminLibraryEditScreen> {if (!mounted) return;setState(() {_providers = list;- if (!_providers.contains(_provider)) _providers = [_provider, ..._providers];+ if (!_providers.contains(_provider)) {+ _providers = [_provider, ..._providers];+ }+ });+ }++ void _initializeMetadataSources(dynamic rawPrecedence) {+ if (rawPrecedence is! List) {+ _resetMetadataSources();+ return;+ }+ final stored = rawPrecedence.map((value) => value.toString()).toList();+ if (stored.isEmpty) {+ _metadataSources = _defaultMetadataPrecedence.reversed+ .map((id) => _MetadataSource(id, enabled: false))+ .toList();+ return;+ }++ final seen = <String>{};+ final activeDisplayOrder = stored.reversed+ .where((id) => seen.add(id))+ .map((id) => _MetadataSource(id, enabled: true))+ .toList();+ for (final id in _defaultMetadataPrecedence.reversed) {+ if (seen.add(id)) {+ activeDisplayOrder.add(_MetadataSource(id, enabled: false));+ }+ }+ _metadataSources = activeDisplayOrder;+ }++ void _resetMetadataSources() {+ _metadataSources = _defaultMetadataPrecedence.reversed+ .map((id) => _MetadataSource(id, enabled: true))+ .toList();+ }++ void _initializeSchedule(dynamic rawCron) {+ final cron = rawCron?.toString().trim() ?? '';+ _autoScan.text = cron;+ _scheduleEnabled = cron.isNotEmpty;+ if (!_scheduleEnabled) return;++ final parts = cron.split(RegExp(r'\s+'));+ if (parts.length != 5) {+ _scheduleMode = 'advanced';+ return;+ }++ final minute = int.tryParse(parts[0]);+ final hour = int.tryParse(parts[1]);+ final dayOfWeek = int.tryParse(parts[4]);+ final validMinute = minute != null && minute >= 0 && minute <= 59;+ final validHour = hour != null && hour >= 0 && hour <= 23;++ if (validMinute &&+ parts[1] == '*' &&+ parts[2] == '*' &&+ parts[3] == '*' &&+ parts[4] == '*') {+ _scheduleMode = 'hourly';+ _scheduleMinute = minute;+ } else if (validMinute &&+ validHour &&+ parts[2] == '*' &&+ parts[3] == '*' &&+ parts[4] == '*') {+ _scheduleMode = 'daily';+ _scheduleTime = TimeOfDay(hour: hour, minute: minute);+ } else if (validMinute &&+ validHour &&+ parts[2] == '*' &&+ parts[3] == '*' &&+ dayOfWeek != null &&+ dayOfWeek >= 0 &&+ dayOfWeek <= 6) {+ _scheduleMode = 'weekly';+ _scheduleTime = TimeOfDay(hour: hour, minute: minute);+ _scheduleWeekday = dayOfWeek == 0 ? DateTime.sunday : dayOfWeek;+ } else {+ _scheduleMode = 'advanced';+ }+ }++ void _setScheduleEnabled(bool enabled) {+ setState(() {+ _scheduleEnabled = enabled;+ if (enabled && _autoScan.text.trim().isEmpty) {+ _scheduleMode = 'weekly';+ _scheduleTime = const TimeOfDay(hour: 0, minute: 0);+ _scheduleWeekday = DateTime.monday;+ _rebuildCron();+ }+ });+ }++ void _setScheduleMode(String mode) {+ setState(() {+ _scheduleMode = mode;+ if (mode != 'advanced') _rebuildCron();+ });+ }++ void _rebuildCron() {+ switch (_scheduleMode) {+ case 'hourly':+ _autoScan.text = '$_scheduleMinute * * * *';+ case 'daily':+ _autoScan.text = '${_scheduleTime.minute} ${_scheduleTime.hour} * * *';+ case 'weekly':+ final cronDay = _scheduleWeekday == DateTime.sunday+ ? 0+ : _scheduleWeekday;+ _autoScan.text =+ '${_scheduleTime.minute} ${_scheduleTime.hour} * * $cronDay';+ case 'advanced':+ break;+ }+ }++ Future<void> _pickScheduleTime() async {+ final picked = await showTimePicker(+ context: context,+ initialTime: _scheduleTime,+ );+ if (picked == null || !mounted) return;+ setState(() {+ _scheduleTime = picked;+ _rebuildCron();});}@@ -130,20 +356,30 @@ class _AdminLibraryEditScreenState extends State<AdminLibraryEditScreen> {_markPercent.dispose();_markTime.dispose();_autoScan.dispose();+ _sectionScrollController.dispose();super.dispose();}Map<String, dynamic> _settings() {- final pctText = _markPercent.text.trim();- final base = <String, dynamic>{+ final base = Map<String, dynamic>.from(_originalSettings);+ final percentText = _markPercent.text.trim();+ final timeText = _markTime.text.trim();+ base.addAll({'coverAspectRatio': _coverAspectRatio,'disableWatcher': _disableWatcher,- 'markAsFinishedPercentComplete': pctText.isEmpty ? null : num.tryParse(pctText),- 'markAsFinishedTimeRemaining': num.tryParse(_markTime.text.trim()) ?? 10,- 'autoScanCronExpression': _autoScan.text.trim().isEmpty ? null : _autoScan.text.trim(),- };+ 'markAsFinishedPercentComplete': _finishedMode == 'percent'+ ? num.tryParse(percentText)+ : null,+ 'markAsFinishedTimeRemaining': _finishedMode == 'time'+ ? (num.tryParse(timeText) ?? 10)+ : null,+ 'autoScanCronExpression': _scheduleEnabled ? _autoScan.text.trim() : null,+ });+if (_mediaType == 'podcast') {- base['podcastSearchRegion'] = _podcastRegion.text.trim().isEmpty ? 'us' : _podcastRegion.text.trim();+ base['podcastSearchRegion'] = _podcastRegion.text.trim().isEmpty+ ? 'us'+ : _podcastRegion.text.trim();} else {base.addAll({'skipMatchingMediaWithAsin': _skipAsin,@@ -152,6 +388,12 @@ class _AdminLibraryEditScreenState extends State<AdminLibraryEditScreen> {'audiobooksOnly': _audiobooksOnly,'epubsAllowScriptedContent': _epubScripted,'onlyShowLaterBooksInContinueSeries': _laterBooksOnly,+ 'metadataPrecedence': _metadataSources+ .where((source) => source.enabled)+ .map((source) => source.id)+ .toList()+ .reversed+ .toList(),});}return base;@@ -163,43 +405,100 @@ class _AdminLibraryEditScreenState extends State<AdminLibraryEditScreen> {MaterialPageRoute(builder: (_) => const FilesystemPickerScreen()),);if (path == null || !mounted) return;- if (_folders.any((f) => f['fullPath'] == path)) return;- setState(() => _folders = [..._folders, {'fullPath': path}]);+ if (_folders.any((folder) => folder['fullPath'] == path)) return;+ setState(+ () => _folders = [+ ..._folders,+ {'fullPath': path},+ ],+ );+ }++ bool _hasValidCron() {+ if (!_scheduleEnabled) return true;+ final cron = _autoScan.text.trim();+ return cron.isNotEmpty && cron.split(RegExp(r'\s+')).length == 5;}Future<void> _save() async {final l = AppLocalizations.of(context)!;if (_name.text.trim().isEmpty) {- showOverlayToast(context, l.libNameRequired, icon: Icons.error_outline_rounded);+ showOverlayToast(+ context,+ l.libNameRequired,+ icon: Icons.error_outline_rounded,+ );+ _selectSection(_LibraryEditorSection.details);return;}if (_folders.isEmpty) {- showOverlayToast(context, l.libNoFolders, icon: Icons.error_outline_rounded);+ showOverlayToast(+ context,+ l.libNoFolders,+ icon: Icons.error_outline_rounded,+ );+ _selectSection(_LibraryEditorSection.details);+ return;+ }+ if (!_hasValidCron()) {+ showOverlayToast(+ context,+ 'Enter a five-part cron expression before saving.',+ icon: Icons.error_outline_rounded,+ );+ _selectSection(_LibraryEditorSection.schedule);return;}- // Warn before removing folders on edit (server cascades item deletion).+ final api = context.read<AuthProvider>().apiService;+ if (api == null) return;+ final cron = _autoScan.text.trim();+ final originalCron =+ _originalSettings['autoScanCronExpression']?.toString().trim() ?? '';+ if (_scheduleEnabled &&+ _scheduleMode == 'advanced' &&+ cron != originalCron) {+ setState(() => _saving = true);+ final cronError = await api.validateCronExpression(cron);+ if (!mounted) return;+ setState(() => _saving = false);+ if (cronError != null) {+ showOverlayToast(context, cronError, icon: Icons.error_outline_rounded);+ _selectSection(_LibraryEditorSection.schedule);+ return;+ }+ }+if (_isEdit) {- final keptIds = _folders.where((f) => f['id'] != null).map((f) => f['id'].toString()).toSet();- final removed = _originalFolderIds.where((id) => !keptIds.contains(id)).toList();+ final keptIds = _folders+ .where((folder) => folder['id'] != null)+ .map((folder) => folder['id'].toString())+ .toSet();+ final removed = _originalFolderIds+ .where((id) => !keptIds.contains(id))+ .toList();if (removed.isNotEmpty) {- final ok = await showDialog<bool>(+ final confirmed = await showDialog<bool>(context: context,- builder: (ctx) => AlertDialog(+ builder: (dialogContext) => AlertDialog(title: Text(l.libRemoveFoldersTitle),content: Text(l.libRemoveFoldersBody),actions: [- TextButton(onPressed: () => Navigator.pop(ctx, false), child: Text(l.cancel)),- FilledButton(onPressed: () => Navigator.pop(ctx, true), child: Text(l.remove)),+ TextButton(+ onPressed: () => Navigator.pop(dialogContext, false),+ child: Text(l.cancel),+ ),+ FilledButton(+ onPressed: () => Navigator.pop(dialogContext, true),+ child: Text(l.remove),+ ),],),);- if (ok != true) return;+ if (confirmed != true) return;}}- final api = context.read<AuthProvider>().apiService;- if (api == null) return;setState(() => _saving = true);final body = <String, dynamic>{@@ -211,237 +510,1040 @@ class _AdminLibraryEditScreenState extends State<AdminLibraryEditScreen> {'settings': _settings(),};- bool ok;+ bool succeeded;if (_isEdit) {- ok = await api.updateLibrary(widget.library!['id'].toString(), body);+ succeeded = await api.updateLibrary(+ widget.library!['id'].toString(),+ body,+ );} else {- // folders on create only need fullPath- body['folders'] = _folders.map((f) => {'fullPath': f['fullPath']}).toList();- ok = (await api.createLibrary(body)) != null;+ body['folders'] = _folders+ .map((folder) => {'fullPath': folder['fullPath']})+ .toList();+ succeeded = (await api.createLibrary(body)) != null;}if (!mounted) return;setState(() => _saving = false);- final msg = _isEdit- ? (ok ? l.libUpdated : l.libUpdateFailed)- : (ok ? l.libCreated : l.libCreateFailed);- showOverlayToast(context, msg,- icon: ok ? Icons.check_circle_outline_rounded : Icons.error_outline_rounded);- if (ok) Navigator.pop(context, true);+ final message = _isEdit+ ? (succeeded ? l.libUpdated : l.libUpdateFailed)+ : (succeeded ? l.libCreated : l.libCreateFailed);+ showOverlayToast(+ context,+ message,+ icon: succeeded+ ? Icons.check_circle_outline_rounded+ : Icons.error_outline_rounded,+ );+ if (succeeded) Navigator.pop(context, true);+ }++ Future<void> _removeMetadataFiles(String extension) async {+ final l = AppLocalizations.of(context)!;+ final filename = 'metadata.$extension';+ final confirmed = await showDialog<bool>(+ context: context,+ builder: (dialogContext) => AlertDialog(+ title: Text('Remove all $filename files?'),+ content: Text(+ 'This permanently removes $filename from every item folder in this library. The media files are not changed.',+ ),+ actions: [+ TextButton(+ onPressed: () => Navigator.pop(dialogContext, false),+ child: Text(l.cancel),+ ),+ FilledButton(+ onPressed: () => Navigator.pop(dialogContext, true),+ child: Text(l.remove),+ ),+ ],+ ),+ );+ if (confirmed != true || !mounted) return;++ final api = context.read<AuthProvider>().apiService;+ if (api == null) return;+ setState(() => _removingMetadataExtension = extension);+ final result = await api.removeLibraryMetadataFiles(+ widget.library!['id'].toString(),+ extension,+ );+ if (!mounted) return;+ setState(() => _removingMetadataExtension = null);++ if (result == null) {+ showOverlayToast(+ context,+ 'Could not remove $filename files.',+ icon: Icons.error_outline_rounded,+ );+ } else if (result.found == 0) {+ showOverlayToast(+ context,+ 'No $filename files were found.',+ icon: Icons.info_outline_rounded,+ );+ } else if (result.removed == 0) {+ showOverlayToast(+ context,+ '${result.found} $filename files were found, but none could be removed.',+ icon: Icons.error_outline_rounded,+ );+ } else {+ showOverlayToast(+ context,+ 'Removed ${result.removed} of ${result.found} $filename files.',+ icon: Icons.check_circle_outline_rounded,+ );+ }+ }++ List<_LibraryEditorSection> get _availableSections => [+ _LibraryEditorSection.details,+ _LibraryEditorSection.settings,+ if (_mediaType == 'book') _LibraryEditorSection.scanner,+ _LibraryEditorSection.schedule,+ if (_isEdit) _LibraryEditorSection.tools,+ ];++ String _sectionLabel(_LibraryEditorSection section, AppLocalizations l) {+ return switch (section) {+ _LibraryEditorSection.details => l.details,+ _LibraryEditorSection.settings => l.settingsTitle,+ _LibraryEditorSection.scanner => l.srvScannerSection,+ _LibraryEditorSection.schedule => 'Schedule',+ _LibraryEditorSection.tools => 'Tools',+ };+ }++ IconData _sectionIcon(_LibraryEditorSection section) {+ return switch (section) {+ _LibraryEditorSection.details => Icons.info_outline_rounded,+ _LibraryEditorSection.settings => Icons.tune_rounded,+ _LibraryEditorSection.scanner => Icons.document_scanner_outlined,+ _LibraryEditorSection.schedule => Icons.schedule_rounded,+ _LibraryEditorSection.tools => Icons.build_outlined,+ };+ }++ void _selectSection(_LibraryEditorSection section) {+ if (_interactionLocked) return;+ setState(() => _selectedSection = section);+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (!mounted || !_sectionScrollController.hasClients) return;+ _sectionScrollController.jumpTo(0);+ });}@overrideWidget build(BuildContext context) {- final cs = Theme.of(context).colorScheme;- final tt = Theme.of(context).textTheme;+ final colors = Theme.of(context).colorScheme;final l = AppLocalizations.of(context)!;- final isPodcast = _mediaType == 'podcast';return Scaffold(backgroundColor: Theme.of(context).scaffoldBackgroundColor,body: SafeArea(- child: Column(children: [- Padding(- padding: const EdgeInsets.fromLTRB(20, 12, 8, 0),- child: Row(children: [- Expanded(child: AbsorbPageHeader(- title: _isEdit ? l.libEditTitle : l.libNewTitle, 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.fromLTRB(16, 0, 16, 100),- children: [- TextField(controller: _name,- decoration: InputDecoration(labelText: l.libName)),- const SizedBox(height: 16),-- // Media type — fixed once a library has items.- Text(l.libMediaType, style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),- const SizedBox(height: 6),- if (_isEdit)- Chip(label: Text(isPodcast ? l.libMediaPodcast : l.libMediaBook))- else- SegmentedButton<String>(- segments: [- ButtonSegment(value: 'book', label: Text(l.libMediaBook), icon: const Icon(Icons.menu_book_rounded)),- ButtonSegment(value: 'podcast', label: Text(l.libMediaPodcast), icon: const Icon(Icons.podcasts_rounded)),- ],- selected: {_mediaType},- onSelectionChanged: (s) => setState(() => _mediaType = s.first),+ child: Column(+ children: [+ Padding(+ padding: const EdgeInsets.fromLTRB(20, 12, 8, 0),+ child: Row(+ children: [+ Expanded(+ child: AbsorbPageHeader(+ title: _isEdit ? l.libEditTitle : l.libNewTitle,+ padding: EdgeInsets.zero,+ ),),- const SizedBox(height: 16),-- Row(children: [- Expanded(child: _labeledDropdown(cs, tt, l.libProvider, _provider, _providers,- (v) => setState(() => _provider = v))),- const SizedBox(width: 12),- Expanded(child: _iconDropdown(cs, tt, _icon,- _icons.contains(_icon) ? _icons : [_icon, ..._icons],- (v) => setState(() => _icon = v))),- ]),- const SizedBox(height: 20),-- // ── Folders ──- Text(l.libFolders, style: tt.labelLarge?.copyWith(- color: cs.onSurfaceVariant.withValues(alpha: 0.7), fontWeight: FontWeight.w600)),- const SizedBox(height: 8),- Container(- decoration: BoxDecoration(color: cs.surfaceContainerHigh, borderRadius: BorderRadius.circular(16)),- padding: const EdgeInsets.symmetric(vertical: 4),- child: Column(children: [- if (_folders.isEmpty)- Padding(- padding: const EdgeInsets.all(20),- child: Text(l.libNoFolders,- style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant.withValues(alpha: 0.6))),- ),- ..._folders.map((f) => ListTile(- dense: true,- leading: Icon(Icons.folder_rounded, color: cs.primary.withValues(alpha: 0.8)),- title: Text(f['fullPath']?.toString() ?? '', maxLines: 2, overflow: TextOverflow.ellipsis),- trailing: IconButton(- icon: Icon(Icons.close_rounded, size: 18, color: cs.onSurfaceVariant),- onPressed: () => setState(() => _folders = _folders.where((x) => x != f).toList()),- ),- )),- TextButton.icon(- onPressed: _addFolder,- icon: const Icon(Icons.add_rounded),- label: Text(l.libAddFolder),+ IconButton(+ icon: Icon(+ Icons.close_rounded,+ color: colors.onSurfaceVariant,),- ]),- ),- const SizedBox(height: 16),-- // ── Advanced ──- Theme(- data: Theme.of(context).copyWith(dividerColor: Colors.transparent),- child: ExpansionTile(- tilePadding: EdgeInsets.zero,- childrenPadding: EdgeInsets.zero,- title: Text(l.libAdvanced, style: tt.titleSmall),- children: [- _coverShape(cs, tt, l),- _switch(tt, l.libDisableWatcher, _disableWatcher, (v) => setState(() => _disableWatcher = v)),- if (!isPodcast) ...[- _switch(tt, l.libSkipAsin, _skipAsin, (v) => setState(() => _skipAsin = v)),- _switch(tt, l.libSkipIsbn, _skipIsbn, (v) => setState(() => _skipIsbn = v)),- _switch(tt, l.libHideSingleSeries, _hideSingleSeries, (v) => setState(() => _hideSingleSeries = v)),- _switch(tt, l.libAudiobooksOnly, _audiobooksOnly, (v) => setState(() => _audiobooksOnly = v)),- _switch(tt, l.libEpubScripted, _epubScripted, (v) => setState(() => _epubScripted = v)),- _switch(tt, l.libLaterBooksOnly, _laterBooksOnly, (v) => setState(() => _laterBooksOnly = v)),- ],- if (isPodcast) ...[- const SizedBox(height: 8),- TextField(controller: _podcastRegion,- decoration: InputDecoration(labelText: l.libPodcastRegion, hintText: 'us')),+ onPressed: _interactionLocked+ ? null+ : () => Navigator.pop(context),+ ),+ ],+ ),+ ),+ const SizedBox(height: 12),+ Expanded(+ child: LayoutBuilder(+ builder: (context, constraints) {+ final desktop = constraints.maxWidth >= 760;+ if (desktop) {+ return Row(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ SizedBox(width: 220, child: _desktopNavigation(l)),+ VerticalDivider(+ width: 1,+ color: colors.outlineVariant.withValues(alpha: 0.5),+ ),+ Expanded(child: _sectionScrollView()),],- const SizedBox(height: 12),- Row(children: [- Expanded(child: TextField(- controller: _markPercent,- keyboardType: TextInputType.number,- decoration: InputDecoration(labelText: l.libMarkPercent),- )),- const SizedBox(width: 12),- Expanded(child: TextField(- controller: _markTime,- keyboardType: TextInputType.number,- decoration: InputDecoration(labelText: l.libMarkTime),- )),- ]),- const SizedBox(height: 12),- TextField(controller: _autoScan,- decoration: InputDecoration(labelText: l.libAutoScan, hintText: '0 0 * * *')),+ );+ }+ return Column(+ children: [+ _mobileNavigation(l),const SizedBox(height: 8),+ Expanded(child: _sectionScrollView()),],+ );+ },+ ),+ ),+ if (_selectedSection != _LibraryEditorSection.tools)+ Padding(+ padding: const EdgeInsets.fromLTRB(16, 10, 16, 16),+ child: Align(+ alignment: Alignment.centerRight,+ child: ConstrainedBox(+ constraints: const BoxConstraints(maxWidth: 320),+ child: SizedBox(+ width: double.infinity,+ child: FilledButton.icon(+ onPressed: _interactionLocked ? null : _save,+ icon: _saving+ ? SizedBox(+ width: 14,+ height: 14,+ child: CircularProgressIndicator(+ strokeWidth: 2,+ color: colors.onPrimary,+ ),+ )+ : const Icon(Icons.save_rounded, size: 18),+ label: Text(_isEdit ? l.libUpdate : l.libCreate),+ ),+ ),),),- const SizedBox(height: 16),- SizedBox(- width: double.infinity,- child: FilledButton.icon(- onPressed: _saving ? null : _save,- icon: _saving- ? SizedBox(width: 14, height: 14,- child: CircularProgressIndicator(strokeWidth: 2, color: cs.onPrimary))- : const Icon(Icons.save_rounded, size: 18),- label: Text(_isEdit ? l.libUpdate : l.libCreate),- ),- ),- ],+ ),+ ],+ ),+ ),+ );+ }++ Widget _desktopNavigation(AppLocalizations l) {+ final colors = Theme.of(context).colorScheme;+ return ListView(+ padding: const EdgeInsets.fromLTRB(12, 4, 12, 16),+ children: [+ for (final section in _availableSections)+ Padding(+ padding: const EdgeInsets.only(bottom: 4),+ child: ListTile(+ shape: RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(12),+ ),+ selected: _selectedSection == section,+ selectedTileColor: colors.secondaryContainer,+ leading: Icon(_sectionIcon(section), size: 20),+ title: Text(_sectionLabel(section, l)),+ onTap: _interactionLocked ? null : () => _selectSection(section),),),- ]),+ ],+ );+ }++ Widget _mobileNavigation(AppLocalizations l) {+ return SingleChildScrollView(+ scrollDirection: Axis.horizontal,+ padding: const EdgeInsets.symmetric(horizontal: 16),+ child: Row(+ children: [+ for (final section in _availableSections)+ Padding(+ padding: const EdgeInsets.only(right: 8),+ child: ChoiceChip(+ avatar: Icon(_sectionIcon(section), size: 17),+ label: Text(_sectionLabel(section, l)),+ selected: _selectedSection == section,+ onSelected: _interactionLocked+ ? null+ : (_) => _selectSection(section),+ ),+ ),+ ],),);}- Widget _coverShape(ColorScheme cs, TextTheme tt, AppLocalizations l) => Padding(- padding: const EdgeInsets.symmetric(vertical: 8),- child: Row(children: [- Expanded(child: Text(l.libCoverShape, style: tt.bodyMedium)),- // ABS BookCoverAspectRatio enum: SQUARE = 1, STANDARD = 0.- SegmentedButton<num>(+ Widget _sectionScrollView() {+ return ListView(+ controller: _sectionScrollController,+ padding: const EdgeInsets.fromLTRB(16, 4, 16, 32),+ children: [+ Align(+ alignment: Alignment.topCenter,+ child: ConstrainedBox(+ constraints: const BoxConstraints(maxWidth: 900),+ child: SizedBox(width: double.infinity, child: _sectionContent()),+ ),+ ),+ ],+ );+ }++ Widget _sectionContent() {+ return switch (_selectedSection) {+ _LibraryEditorSection.details => _detailsSection(),+ _LibraryEditorSection.settings => _settingsSection(),+ _LibraryEditorSection.scanner =>+ _mediaType == 'book' ? _scannerSection() : _settingsSection(),+ _LibraryEditorSection.schedule => _scheduleSection(),+ _LibraryEditorSection.tools =>+ _isEdit ? _toolsSection() : _detailsSection(),+ };+ }++ Widget _sectionHeading(String title, String description) {+ final textTheme = Theme.of(context).textTheme;+ final colors = Theme.of(context).colorScheme;+ return Padding(+ padding: const EdgeInsets.only(bottom: 20),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(title, style: textTheme.headlineSmall),+ const SizedBox(height: 4),+ Text(+ description,+ style: textTheme.bodyMedium?.copyWith(+ color: colors.onSurfaceVariant,+ ),+ ),+ ],+ ),+ );+ }++ Widget _detailsSection() {+ final colors = Theme.of(context).colorScheme;+ final textTheme = Theme.of(context).textTheme;+ final l = AppLocalizations.of(context)!;+ final isPodcast = _mediaType == 'podcast';+ return Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ _sectionHeading(+ l.details,+ 'Set the library name, media type, provider, icon, and folders.',+ ),+ TextField(+ controller: _name,+ decoration: InputDecoration(labelText: l.libName),+ ),+ const SizedBox(height: 16),+ Text(+ l.libMediaType,+ style: textTheme.bodySmall?.copyWith(color: colors.onSurfaceVariant),+ ),+ const SizedBox(height: 6),+ if (_isEdit)+ Chip(label: Text(isPodcast ? l.libMediaPodcast : l.libMediaBook))+ else+ SegmentedButton<String>(segments: [- ButtonSegment(value: 1, label: Text(l.libCoverSquare)),- ButtonSegment(value: 0, label: Text(l.libCoverStandard)),+ ButtonSegment(+ value: 'book',+ label: Text(l.libMediaBook),+ icon: const Icon(Icons.menu_book_rounded),+ ),+ ButtonSegment(+ value: 'podcast',+ label: Text(l.libMediaPodcast),+ icon: const Icon(Icons.podcasts_rounded),+ ),],- selected: {_coverAspectRatio == 0 ? 0 : 1},- onSelectionChanged: (s) => setState(() => _coverAspectRatio = s.first),+ selected: {_mediaType},+ onSelectionChanged: (selection) {+ setState(() {+ _mediaType = selection.first;+ if (_mediaType == 'podcast' &&+ _selectedSection == _LibraryEditorSection.scanner) {+ _selectedSection = _LibraryEditorSection.settings;+ }+ });+ },),- ]),- );-- Widget _switch(TextTheme tt, String label, bool value, ValueChanged<bool> onChanged) =>- SwitchListTile(- contentPadding: EdgeInsets.zero,- title: Text(label, style: tt.bodyMedium),- value: value,- onChanged: onChanged,- );+ const SizedBox(height: 16),+ LayoutBuilder(+ builder: (context, constraints) {+ final stack = constraints.maxWidth < 520;+ final provider = _labeledDropdown(+ colors,+ textTheme,+ l.libProvider,+ _provider,+ _providers,+ (value) => setState(() => _provider = value),+ );+ final icon = _iconDropdown(+ colors,+ textTheme,+ _icon,+ _icons.contains(_icon) ? _icons : [_icon, ..._icons],+ (value) => setState(() => _icon = value),+ );+ if (stack) {+ return Column(+ children: [provider, const SizedBox(height: 12), icon],+ );+ }+ return Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Expanded(child: provider),+ const SizedBox(width: 16),+ Expanded(child: icon),+ ],+ );+ },+ ),+ const SizedBox(height: 24),+ Text(+ l.libFolders,+ style: textTheme.labelLarge?.copyWith(+ color: colors.onSurfaceVariant.withValues(alpha: 0.7),+ fontWeight: FontWeight.w600,+ ),+ ),+ const SizedBox(height: 8),+ Container(+ decoration: BoxDecoration(+ color: colors.surfaceContainerHigh,+ borderRadius: BorderRadius.circular(16),+ ),+ padding: const EdgeInsets.symmetric(vertical: 4),+ child: Column(+ children: [+ if (_folders.isEmpty)+ Padding(+ padding: const EdgeInsets.all(20),+ child: Text(+ l.libNoFolders,+ style: textTheme.bodyMedium?.copyWith(+ color: colors.onSurfaceVariant.withValues(alpha: 0.6),+ ),+ ),+ ),+ ..._folders.asMap().entries.map(+ (entry) => ListTile(+ dense: true,+ leading: Icon(+ Icons.folder_rounded,+ color: colors.primary.withValues(alpha: 0.8),+ ),+ title: Text(+ entry.value['fullPath']?.toString() ?? '',+ maxLines: 2,+ overflow: TextOverflow.ellipsis,+ ),+ trailing: IconButton(+ icon: Icon(+ Icons.close_rounded,+ size: 18,+ color: colors.onSurfaceVariant,+ ),+ onPressed: () => setState(() {+ _folders = [..._folders]..removeAt(entry.key);+ }),+ ),+ ),+ ),+ TextButton.icon(+ onPressed: _addFolder,+ icon: const Icon(Icons.add_rounded),+ label: Text(l.libAddFolder),+ ),+ ],+ ),+ ),+ ],+ );+ }- Widget _iconDropdown(ColorScheme cs, TextTheme tt, String value,- List<String> options, ValueChanged<String> onChanged) =>- Column(crossAxisAlignment: CrossAxisAlignment.start, children: [- Text(AppLocalizations.of(context)!.libIcon, style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),- DropdownButton<String>(- value: options.contains(value) ? value : options.first,- isExpanded: true,- borderRadius: BorderRadius.circular(12),- items: options- .map((o) => DropdownMenuItem(- value: o,- child: Row(children: [- Icon(_absIcon(o), size: 18, color: cs.onSurfaceVariant),- const SizedBox(width: 10),- Flexible(child: Text(o, overflow: TextOverflow.ellipsis)),- ]),- ))- .toList(),- onChanged: (v) {- if (v != null) onChanged(v);+ Widget _settingsSection() {+ final textTheme = Theme.of(context).textTheme;+ final l = AppLocalizations.of(context)!;+ final isPodcast = _mediaType == 'podcast';+ final watcherDisabledGlobally =+ context+ .watch<AuthProvider>()+ .serverSettings?['scannerDisableWatcher'] ==+ true;+ return Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ _sectionHeading(+ l.settingsTitle,+ 'Control cover display, matching, completion, and library behavior.',+ ),+ _coverShape(textTheme, l),+ _switch(+ textTheme,+ l.libDisableWatcher,+ watcherDisabledGlobally ? true : _disableWatcher,+ watcherDisabledGlobally+ ? null+ : (value) => setState(() => _disableWatcher = value),+ subtitle: watcherDisabledGlobally+ ? 'The folder watcher is disabled in the server scanner settings.'+ : null,+ ),+ if (!isPodcast) ...[+ _switch(+ textTheme,+ l.libSkipAsin,+ _skipAsin,+ (value) => setState(() => _skipAsin = value),+ ),+ _switch(+ textTheme,+ l.libSkipIsbn,+ _skipIsbn,+ (value) => setState(() => _skipIsbn = value),+ ),+ _switch(+ textTheme,+ l.libHideSingleSeries,+ _hideSingleSeries,+ (value) => setState(() => _hideSingleSeries = value),+ ),+ _switch(+ textTheme,+ l.libAudiobooksOnly,+ _audiobooksOnly,+ (value) => setState(() => _audiobooksOnly = value),+ ),+ _switch(+ textTheme,+ l.libEpubScripted,+ _epubScripted,+ (value) => setState(() => _epubScripted = value),+ ),+ _switch(+ textTheme,+ l.libLaterBooksOnly,+ _laterBooksOnly,+ (value) => setState(() => _laterBooksOnly = value),+ ),+ ],+ if (isPodcast) ...[+ const SizedBox(height: 12),+ TextField(+ controller: _podcastRegion,+ decoration: InputDecoration(+ labelText: l.libPodcastRegion,+ hintText: 'us',+ ),+ ),+ ],+ const SizedBox(height: 20),+ Text('Mark finished', style: textTheme.titleMedium),+ const SizedBox(height: 8),+ DropdownButtonFormField<String>(+ value: _finishedMode,+ decoration: const InputDecoration(labelText: 'Completion rule'),+ items: [+ DropdownMenuItem(value: 'time', child: Text(l.libMarkTime)),+ DropdownMenuItem(value: 'percent', child: Text(l.libMarkPercent)),+ ],+ onChanged: (value) {+ if (value != null) setState(() => _finishedMode = value);},),- ]);-- Widget _labeledDropdown(ColorScheme cs, TextTheme tt, String label, String value,- List<String> options, ValueChanged<String> onChanged) =>- Column(crossAxisAlignment: CrossAxisAlignment.start, children: [- Text(label, style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),- DropdownButton<String>(- value: options.contains(value) ? value : options.first,- isExpanded: true,- borderRadius: BorderRadius.circular(12),- items: options.map((o) => DropdownMenuItem(value: o, child: Text(o, overflow: TextOverflow.ellipsis))).toList(),- onChanged: (v) {- if (v != null) onChanged(v);+ const SizedBox(height: 12),+ if (_finishedMode == 'time')+ TextField(+ controller: _markTime,+ keyboardType: TextInputType.number,+ decoration: InputDecoration(labelText: l.libMarkTime),+ )+ else+ TextField(+ controller: _markPercent,+ keyboardType: TextInputType.number,+ decoration: InputDecoration(labelText: l.libMarkPercent),+ ),+ ],+ );+ }++ Widget _scannerSection() {+ final colors = Theme.of(context).colorScheme;+ final textTheme = Theme.of(context).textTheme;+ final l = AppLocalizations.of(context)!;+ final activeSources = _metadataSources+ .where((source) => source.enabled)+ .toList(growable: false);+ return Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ _sectionHeading(+ l.srvScannerSection,+ 'Choose which metadata sources are used. Drag them from highest to lowest priority.',+ ),+ Align(+ alignment: Alignment.centerRight,+ child: TextButton.icon(+ onPressed: () => setState(_resetMetadataSources),+ icon: const Icon(Icons.restart_alt_rounded),+ label: Text(l.resetToDefault),+ ),+ ),+ const SizedBox(height: 8),+ ReorderableListView.builder(+ shrinkWrap: true,+ physics: const NeverScrollableScrollPhysics(),+ buildDefaultDragHandles: false,+ itemCount: _metadataSources.length,+ onReorder: (oldIndex, newIndex) {+ setState(() {+ if (newIndex > oldIndex) newIndex--;+ final source = _metadataSources.removeAt(oldIndex);+ _metadataSources.insert(newIndex, source);+ });},+ itemBuilder: (context, index) {+ final source = _metadataSources[index];+ final activeIndex = activeSources.indexOf(source);+ final priority = !source.enabled+ ? 'Ignored'+ : activeIndex == 0+ ? 'Highest priority'+ : activeIndex == activeSources.length - 1+ ? 'Lowest priority'+ : 'Priority ${activeIndex + 1}';+ return Container(+ key: ValueKey(source.id),+ margin: const EdgeInsets.only(bottom: 8),+ decoration: BoxDecoration(+ color: colors.surfaceContainerHigh,+ borderRadius: BorderRadius.circular(14),+ ),+ child: ListTile(+ leading: Switch(+ value: source.enabled,+ onChanged: (enabled) {+ setState(() => source.enabled = enabled);+ },+ ),+ title: Text(_metadataSourceLabel(source.id)),+ subtitle: Text(priority),+ trailing: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ IconButton(+ tooltip: 'Move up',+ onPressed: index == 0+ ? null+ : () => _moveMetadataSource(index, -1),+ icon: const Icon(Icons.keyboard_arrow_up_rounded),+ ),+ IconButton(+ tooltip: 'Move down',+ onPressed: index == _metadataSources.length - 1+ ? null+ : () => _moveMetadataSource(index, 1),+ icon: const Icon(Icons.keyboard_arrow_down_rounded),+ ),+ ReorderableDragStartListener(+ index: index,+ child: const Padding(+ padding: EdgeInsets.all(8),+ child: Icon(Icons.drag_handle_rounded),+ ),+ ),+ ],+ ),+ ),+ );+ },+ ),+ const SizedBox(height: 8),+ Text(+ 'Disabled sources are ignored when the scanner reads metadata.',+ style: textTheme.bodySmall?.copyWith(color: colors.onSurfaceVariant),+ ),+ ],+ );+ }++ void _moveMetadataSource(int index, int offset) {+ final target = index + offset;+ if (target < 0 || target >= _metadataSources.length) return;+ setState(() {+ final source = _metadataSources.removeAt(index);+ _metadataSources.insert(target, source);+ });+ }++ String _metadataSourceLabel(String id) {+ return switch (id) {+ 'folderStructure' => 'Folder structure',+ 'audioMetatags' =>+ _mediaType == 'book'+ ? 'Audio file metadata or ebook metadata'+ : 'Audio file metadata',+ 'nfoFile' => 'NFO file',+ 'txtFiles' => 'desc.txt and reader.txt files',+ 'opfFile' => 'OPF file',+ 'absMetadata' => 'Audiobookshelf metadata file',+ _ => id,+ };+ }++ Widget _scheduleSection() {+ final colors = Theme.of(context).colorScheme;+ final textTheme = Theme.of(context).textTheme;+ final l = AppLocalizations.of(context)!;+ final serverTimeZone =+ context.watch<AuthProvider>().serverSettings?['timeZone'] as String?;++ return Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ _sectionHeading(+ 'Schedule',+ 'Run a library scan automatically on a recurring schedule.',+ ),+ _switch(+ textTheme,+ l.libAutoScan,+ _scheduleEnabled,+ _setScheduleEnabled,+ ),+ if (_scheduleEnabled) ...[+ const SizedBox(height: 12),+ DropdownButtonFormField<String>(+ value: _scheduleMode,+ decoration: InputDecoration(labelText: l.adminPodcastsFrequency),+ items: [+ DropdownMenuItem(+ value: 'hourly',+ child: Text(l.adminPodcastsFreqHourly),+ ),+ DropdownMenuItem(+ value: 'daily',+ child: Text(l.adminPodcastsFreqDaily),+ ),+ DropdownMenuItem(+ value: 'weekly',+ child: Text(l.adminPodcastsFreqWeekly),+ ),+ const DropdownMenuItem(+ value: 'advanced',+ child: Text('Advanced cron'),+ ),+ ],+ onChanged: (value) {+ if (value != null) _setScheduleMode(value);+ },+ ),+ const SizedBox(height: 16),+ if (_scheduleMode == 'hourly') ...[+ Text('Minute ${_scheduleMinute.toString().padLeft(2, '0')}'),+ Slider(+ min: 0,+ max: 59,+ divisions: 59,+ label: _scheduleMinute.toString(),+ value: _scheduleMinute.toDouble(),+ onChanged: (value) {+ setState(() {+ _scheduleMinute = value.round();+ _rebuildCron();+ });+ },+ ),+ ],+ if (_scheduleMode == 'daily' || _scheduleMode == 'weekly') ...[+ if (_scheduleMode == 'weekly') ...[+ DropdownButtonFormField<int>(+ value: _scheduleWeekday,+ decoration: InputDecoration(labelText: l.adminPodcastsDay),+ items: _weekdayLabels(l).entries+ .map(+ (entry) => DropdownMenuItem(+ value: entry.key,+ child: Text(entry.value),+ ),+ )+ .toList(),+ onChanged: (value) {+ if (value == null) return;+ setState(() {+ _scheduleWeekday = value;+ _rebuildCron();+ });+ },+ ),+ const SizedBox(height: 12),+ ],+ ListTile(+ contentPadding: EdgeInsets.zero,+ title: const Text('Time'),+ subtitle: Text(_scheduleTime.format(context)),+ trailing: const Icon(Icons.schedule_rounded),+ onTap: _pickScheduleTime,+ ),+ ],+ if (_scheduleMode == 'advanced')+ TextField(+ controller: _autoScan,+ decoration: InputDecoration(+ labelText: l.libAutoScan,+ hintText: '0 0 * * *',+ helperText: 'Minute Hour Day Month Weekday',+ ),+ )+ else+ Container(+ width: double.infinity,+ padding: const EdgeInsets.all(14),+ decoration: BoxDecoration(+ color: colors.surfaceContainerHigh,+ borderRadius: BorderRadius.circular(12),+ ),+ child: SelectableText(+ _autoScan.text,+ style: textTheme.bodyLarge?.copyWith(fontFamily: 'monospace'),+ ),+ ),+ const SizedBox(height: 12),+ Text(+ serverTimeZone == null || serverTimeZone.isEmpty+ ? l.podcastScheduleServerTimeUnknown+ : l.podcastScheduleServerTime(serverTimeZone),+ style: textTheme.bodySmall?.copyWith(+ color: colors.onSurfaceVariant,+ ),+ ),+ ],+ ],+ );+ }++ Map<int, String> _weekdayLabels(AppLocalizations l) => {+ DateTime.sunday: l.adminPodcastsDaySun,+ DateTime.monday: l.adminPodcastsDayMon,+ DateTime.tuesday: l.adminPodcastsDayTue,+ DateTime.wednesday: l.adminPodcastsDayWed,+ DateTime.thursday: l.adminPodcastsDayThu,+ DateTime.friday: l.adminPodcastsDayFri,+ DateTime.saturday: l.adminPodcastsDaySat,+ };++ Widget _toolsSection() {+ final colors = Theme.of(context).colorScheme;+ return Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ _sectionHeading(+ 'Tools',+ 'Clean up generated sidecar metadata files across this library.',+ ),+ _metadataRemovalCard(+ colors,+ extension: 'json',+ description:+ 'Remove every metadata.json file found in the library item folders.',+ ),+ const SizedBox(height: 12),+ _metadataRemovalCard(+ colors,+ extension: 'abs',+ description:+ 'Remove every metadata.abs file found in the library item folders.',),- ]);+ ],+ );+ }++ Widget _metadataRemovalCard(+ ColorScheme colors, {+ required String extension,+ required String description,+ }) {+ final busy = _removingMetadataExtension == extension;+ final anyBusy = _removingMetadataExtension != null;+ return Container(+ padding: const EdgeInsets.all(16),+ decoration: BoxDecoration(+ color: colors.surfaceContainerHigh,+ borderRadius: BorderRadius.circular(16),+ ),+ child: LayoutBuilder(+ builder: (context, constraints) {+ final button = OutlinedButton.icon(+ onPressed: anyBusy ? null : () => _removeMetadataFiles(extension),+ icon: busy+ ? const SizedBox(+ width: 16,+ height: 16,+ child: CircularProgressIndicator(strokeWidth: 2),+ )+ : const Icon(Icons.delete_outline_rounded),+ label: Text('Remove metadata.$extension'),+ );+ final copy = Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ 'metadata.$extension',+ style: Theme.of(context).textTheme.titleMedium,+ ),+ const SizedBox(height: 4),+ Text(description),+ ],+ );+ if (constraints.maxWidth < 600) {+ return Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [copy, const SizedBox(height: 14), button],+ );+ }+ return Row(+ children: [+ Expanded(child: copy),+ const SizedBox(width: 20),+ button,+ ],+ );+ },+ ),+ );+ }++ Widget _coverShape(TextTheme textTheme, AppLocalizations l) => Padding(+ padding: const EdgeInsets.symmetric(vertical: 8),+ child: LayoutBuilder(+ builder: (context, constraints) {+ final selector = SegmentedButton<num>(+ segments: [+ ButtonSegment(value: 1, label: Text(l.libCoverSquare)),+ ButtonSegment(value: 0, label: Text(l.libCoverStandard)),+ ],+ selected: {_coverAspectRatio == 0 ? 0 : 1},+ onSelectionChanged: (selection) {+ setState(() => _coverAspectRatio = selection.first);+ },+ );+ if (constraints.maxWidth < 500) {+ return Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(l.libCoverShape, style: textTheme.bodyMedium),+ const SizedBox(height: 8),+ selector,+ ],+ );+ }+ return Row(+ children: [+ Expanded(child: Text(l.libCoverShape, style: textTheme.bodyMedium)),+ selector,+ ],+ );+ },+ ),+ );++ Widget _switch(+ TextTheme textTheme,+ String label,+ bool value,+ ValueChanged<bool>? onChanged, {+ String? subtitle,+ }) => SwitchListTile(+ contentPadding: EdgeInsets.zero,+ title: Text(label, style: textTheme.bodyMedium),+ subtitle: subtitle == null ? null : Text(subtitle),+ value: value,+ onChanged: onChanged,+ );++ Widget _iconDropdown(+ ColorScheme colors,+ TextTheme textTheme,+ String value,+ List<String> options,+ ValueChanged<String> onChanged,+ ) => Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ AppLocalizations.of(context)!.libIcon,+ style: textTheme.bodySmall?.copyWith(color: colors.onSurfaceVariant),+ ),+ DropdownButton<String>(+ value: options.contains(value) ? value : options.first,+ isExpanded: true,+ borderRadius: BorderRadius.circular(12),+ items: options+ .map(+ (option) => DropdownMenuItem(+ value: option,+ child: Row(+ children: [+ Icon(+ _absIcon(option),+ size: 18,+ color: colors.onSurfaceVariant,+ ),+ const SizedBox(width: 10),+ Flexible(+ child: Text(option, overflow: TextOverflow.ellipsis),+ ),+ ],+ ),+ ),+ )+ .toList(),+ onChanged: (newValue) {+ if (newValue != null) onChanged(newValue);+ },+ ),+ ],+ );++ Widget _labeledDropdown(+ ColorScheme colors,+ TextTheme textTheme,+ String label,+ String value,+ List<String> options,+ ValueChanged<String> onChanged,+ ) => Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ label,+ style: textTheme.bodySmall?.copyWith(color: colors.onSurfaceVariant),+ ),+ DropdownButton<String>(+ value: options.contains(value) ? value : options.first,+ isExpanded: true,+ borderRadius: BorderRadius.circular(12),+ items: options+ .map(+ (option) => DropdownMenuItem(+ value: option,+ child: Text(option, overflow: TextOverflow.ellipsis),+ ),+ )+ .toList(),+ onChanged: (newValue) {+ if (newValue != null) onChanged(newValue);+ },+ ),+ ],+ );}diff --git a/lib/screens/admin_podcasts_screen.dart b/lib/screens/admin_podcasts_screen.dartindex 0bc819f9..ca9153b1 100644--- a/lib/screens/admin_podcasts_screen.dart+++ b/lib/screens/admin_podcasts_screen.dart@@ -7,10 +7,13 @@ import '../providers/auth_provider.dart';import '../services/socket_service.dart';import 'podcast_edit_screen.dart';import '../widgets/absorb_page_header.dart';+import '../widgets/adaptive_modal.dart';+import '../widgets/desktop_page_body.dart';import '../widgets/delete_confirm_dialog.dart';import '../widgets/html_description.dart';import '../widgets/overlay_toast.dart';import '../l10n/app_localizations.dart';+import '../utils/desktop_workspace.dart';import '../utils/duration_format.dart';/// Opens the podcast lookup used by the admin podcast manager.@@ -24,11 +27,13 @@ Future<void> showAddPodcastSheet(required VoidCallback onAdded,String initialQuery = '',}) {- return showModalBottomSheet<void>(+ return showAdaptiveActionMenu<void>(context: context,isScrollControlled: true,useSafeArea: true,backgroundColor: Colors.transparent,+ desktopWidth: 640,+ desktopScrollWrap: false,builder: (_) => _PodcastSearchSheet(libraryId: libraryId,folderId: folderId,@@ -45,13 +50,21 @@ Future<void> showPodcastAdminSettings(required VoidCallback onChanged,}) async {if (!context.read<AuthProvider>().isAdmin) return;- await Navigator.of(context).push<void>(+ final navigator = contentNavigator(context);+ final sourceContext = context;+ final sourceRoute = ModalRoute.of(context);+ if (isDesktopWorkspace(context) && sourceRoute is PopupRoute<dynamic>) {+ Navigator.of(context, rootNavigator: true).removeRoute(sourceRoute);+ }+ await navigator.push<void>(MaterialPageRoute<void>(builder: (_) => _PodcastDetailScreen(item: item,libraryId: libraryId,initialTab: 2,- onChanged: onChanged,+ onChanged: () {+ if (sourceContext.mounted) onChanged();+ },),),);@@ -136,7 +149,7 @@ class _AdminPodcastsScreenState extends State<AdminPodcastsScreen> {onPressed: () => _showSearchSheet(),child: Icon(Icons.add_rounded, color: cs.onPrimary),),- body: SafeArea(child: Column(children: [+ body: DesktopPageBody(maxWidth: 1040, child: SafeArea(child: Column(children: [Padding(padding: const EdgeInsets.fromLTRB(20, 12, 8, 0),child: Row(children: [@@ -157,7 +170,7 @@ class _AdminPodcastsScreenState extends State<AdminPodcastsScreen> {? const Center(child: CircularProgressIndicator(strokeWidth: 2)): RefreshIndicator(onRefresh: _loadShows, child: _buildShowList(cs, tt)),),- ])),+ ]))),);}@@ -242,7 +255,7 @@ class _AdminPodcastsScreenState extends State<AdminPodcastsScreen> {// ─── Show Detail ────────────────────────────────────────────void _openShowDetail(Map<String, dynamic> item) {- Navigator.push(context, MaterialPageRoute(+ Navigator.of(context).push(MaterialPageRoute(builder: (_) => _PodcastDetailScreen(item: item, libraryId: _libraryId, onChanged: _loadShows)));}}@@ -437,11 +450,12 @@ class _PodcastSearchSheetState extends State<_PodcastSearchSheet> {color: cs.surfaceContainerHigh,borderRadius: const BorderRadius.vertical(top: Radius.circular(20)),),- child: DraggableScrollableSheet(+ child: AdaptiveDraggableScrollableSheet(initialChildSize: 0.85,minChildSize: 0.05,maxChildSize: 0.95,expand: false,+ desktopMaxHeight: 680,builder: (ctx, sc) {return Column(children: [@@ -804,7 +818,7 @@ class _PodcastPreviewScreenState extends State<_PodcastPreviewScreen> {return Scaffold(backgroundColor: Theme.of(context).scaffoldBackgroundColor,- body: SafeArea(+ body: DesktopPageBody(maxWidth: 1040, child: SafeArea(child: Column(children: [// Header@@ -963,7 +977,7 @@ class _PodcastPreviewScreenState extends State<_PodcastPreviewScreen> {),],),- ),+ )),);}@@ -1106,6 +1120,90 @@ class _PodcastDetailScreenState extends State<_PodcastDetailScreen> with SingleT} catch (_) {}}+ Future<void> _editMaxEpisodesToKeep() async {+ final l = AppLocalizations.of(context)!;+ final rawCurrent = _media['maxEpisodesToKeep'];+ final current = rawCurrent is num && rawCurrent >= 0+ ? rawCurrent.toInt()+ : 0;+ final controller = TextEditingController(text: '$current');+ String? errorText;++ final value = await showDialog<int>(+ context: context,+ builder: (dialogContext) => StatefulBuilder(+ builder: (context, setDialogState) {+ void submit() {+ final parsed = int.tryParse(controller.text.trim());+ if (parsed == null || parsed < 0) {+ setDialogState(() => errorText = l.adminPodcastsEpisodeLimitInvalid);+ return;+ }+ Navigator.of(dialogContext).pop(parsed);+ }++ return AlertDialog(+ title: Text(l.adminPodcastsMaxEpisodesToKeep),+ content: SizedBox(+ width: 360,+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ l.adminPodcastsMaxEpisodesToKeepHelp,+ style: Theme.of(context).textTheme.bodyMedium,+ ),+ const SizedBox(height: 16),+ TextField(+ controller: controller,+ autofocus: true,+ keyboardType: TextInputType.number,+ textInputAction: TextInputAction.done,+ decoration: InputDecoration(+ labelText: l.adminPodcastsMaxEpisodesToKeep,+ errorText: errorText,+ border: const OutlineInputBorder(),+ ),+ onChanged: (_) {+ if (errorText != null) {+ setDialogState(() => errorText = null);+ }+ },+ onSubmitted: (_) => submit(),+ ),+ ],+ ),+ ),+ actions: [+ TextButton(+ onPressed: () => Navigator.of(dialogContext).pop(),+ child: Text(l.cancel),+ ),+ FilledButton(onPressed: submit, child: Text(l.save)),+ ],+ );+ },+ ),+ );+ controller.dispose();+ if (value == null || value == current || !mounted) return;++ final api = context.read<AuthProvider>().apiService;+ if (api == null) return;+ final ok = await api.updatePodcastMedia(+ _podcastId,+ {'maxEpisodesToKeep': value},+ );+ if (!mounted) return;+ if (ok) {+ setState(() => _media['maxEpisodesToKeep'] = value);+ widget.onChanged();+ } else {+ _msg(l.adminPodcastsFailedAutoDownloadUpdate);+ }+ }+Future<void> _loadFeed() async {if (_feedUrl.isEmpty) { _msg(AppLocalizations.of(context)!.adminPodcastsNoFeedAvailable); return; }final api = context.read<AuthProvider>().apiService; if (api == null) return;@@ -1219,7 +1317,7 @@ class _PodcastDetailScreenState extends State<_PodcastDetailScreen> with SingleTreturn Scaffold(backgroundColor: Theme.of(context).scaffoldBackgroundColor,- body: SafeArea(child: Column(children: [+ body: DesktopPageBody(maxWidth: 1040, child: SafeArea(child: Column(children: [// Back buttonPadding(padding: const EdgeInsets.fromLTRB(4, 4, 8, 0),child: Row(children: [@@ -1294,7 +1392,7 @@ class _PodcastDetailScreenState extends State<_PodcastDetailScreen> with SingleT_buildFeedTab(cs, tt),_buildSettingsTab(cs, tt),])),- ])),+ ]))),);}@@ -1925,6 +2023,11 @@ class _PodcastDetailScreenState extends State<_PodcastDetailScreen> with SingleTif (autoDownload)StatefulBuilder(builder: (ctx, setScheduleState) {final currentCron = _media['autoDownloadSchedule'] as String? ?? '0 * * * *';+ final rawMaxEpisodesToKeep = _media['maxEpisodesToKeep'];+ final maxEpisodesToKeep =+ rawMaxEpisodesToKeep is num && rawMaxEpisodesToKeep >= 0+ ? rawMaxEpisodesToKeep.toInt()+ : 0;final parsed = _parseCron(currentCron);final freq = parsed.$1; // 'hourly', 'daily', 'weekly'final hour = parsed.$2; // 0-23@@ -1985,6 +2088,39 @@ class _PodcastDetailScreenState extends State<_PodcastDetailScreen> with SingleT: l.podcastScheduleServerTime(serverTimeZone),style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),),+ const SizedBox(height: 14),+ Row(crossAxisAlignment: CrossAxisAlignment.center, children: [+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ l.adminPodcastsMaxEpisodesToKeep,+ style: tt.bodySmall?.copyWith(+ color: cs.onSurface,+ fontWeight: FontWeight.w600,+ ),+ ),+ const SizedBox(height: 2),+ Text(+ l.adminPodcastsMaxEpisodesToKeepHelp,+ style: tt.labelSmall?.copyWith(+ color: cs.onSurfaceVariant,+ ),+ ),+ ],+ ),+ ),+ const SizedBox(width: 12),+ OutlinedButton(+ onPressed: _editMaxEpisodesToKeep,+ child: Text(+ maxEpisodesToKeep == 0+ ? l.adminPodcastsNoEpisodeLimit+ : '$maxEpisodesToKeep',+ ),+ ),+ ]),const SizedBox(height: 10),// FrequencyText(l.adminPodcastsFrequency, style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant, fontSize: 10)),@@ -2062,7 +2198,7 @@ class _PodcastDetailScreenState extends State<_PodcastDetailScreen> with SingleTvoid _openEditInfo() {final tags = (_media['tags'] as List<dynamic>?)?.whereType<String>().toList() ?? <String>[];- Navigator.push(context, MaterialPageRoute(+ Navigator.of(context).push(MaterialPageRoute(builder: (_) => PodcastEditScreen(itemId: _podcastId,metadata: Map<String, dynamic>.from(_metadata),@@ -2076,11 +2212,13 @@ class _PodcastDetailScreenState extends State<_PodcastDetailScreen> with SingleT}void _showMatchSheet(ColorScheme cs, TextTheme tt) {- showModalBottomSheet(+ showAdaptiveActionMenu(context: context,isScrollControlled: true,useSafeArea: true,backgroundColor: Colors.transparent,+ desktopWidth: 640,+ desktopScrollWrap: false,builder: (_) => _PodcastMatchSheet(podcastId: _podcastId,initialQuery: _title,@@ -2094,11 +2232,13 @@ class _PodcastDetailScreenState extends State<_PodcastDetailScreen> with SingleTvoid _showEpisodeDetail(Map<String, dynamic> ep, bool alreadyDownloaded) {final canDownload = context.read<AuthProvider>().isAdmin;- showModalBottomSheet(+ showAdaptiveActionMenu(context: context,isScrollControlled: true,useSafeArea: true,backgroundColor: Colors.transparent,+ desktopWidth: 640,+ desktopScrollWrap: false,builder: (_) => _EpisodeDetailSheet(episode: ep,alreadyDownloaded: alreadyDownloaded,@@ -2114,11 +2254,13 @@ class _PodcastDetailScreenState extends State<_PodcastDetailScreen> with SingleTvoid _showDownloadedEpisodeDetail(Map<String, dynamic> ep) {final epId = ep['id']?.toString() ?? '';final epTitle = ep['title']?.toString() ?? AppLocalizations.of(context)!.adminPodcastsEpisodeFallback;- showModalBottomSheet(+ showAdaptiveActionMenu(context: context,isScrollControlled: true,useSafeArea: true,backgroundColor: Colors.transparent,+ desktopWidth: 640,+ desktopScrollWrap: false,builder: (_) => _DownloadedEpisodeDetailSheet(episode: ep,isDeleting: _deleting.contains(epId),@@ -2566,11 +2708,12 @@ class _PodcastMatchSheetState extends State<_PodcastMatchSheet> {color: cs.surfaceContainerHigh,borderRadius: const BorderRadius.vertical(top: Radius.circular(20)),),- child: DraggableScrollableSheet(+ child: AdaptiveDraggableScrollableSheet(initialChildSize: 0.75,minChildSize: 0.05,maxChildSize: 0.95,expand: false,+ desktopMaxHeight: 680,builder: (ctx, sc) => Column(children: [Padding(padding: const EdgeInsets.fromLTRB(20, 14, 8, 0),diff --git a/lib/screens/admin_screen.dart b/lib/screens/admin_screen.dartindex 9f19fd84..0cb3e615 100644--- a/lib/screens/admin_screen.dart+++ b/lib/screens/admin_screen.dart@@ -5,11 +5,14 @@ import '../providers/auth_provider.dart';import '../services/scoped_prefs.dart';import '../services/server_task_tracker.dart';import '../services/socket_service.dart';+import '../widgets/admin_adaptive_frame.dart';import '../widgets/admin_task_indicator.dart';import '../widgets/absorb_page_header.dart';import '../widgets/rmab_config_sheet.dart';import '../widgets/overlay_toast.dart';import '../l10n/app_localizations.dart';+import '../utils/desktop_workspace.dart';+import '../widgets/desktop_page_body.dart';import 'admin_users_screen.dart';import 'admin_upload_screen.dart';import 'admin_podcasts_screen.dart';@@ -18,16 +21,56 @@ import 'admin_email_screen.dart';import 'admin_api_keys_screen.dart';import 'admin_libraries_screen.dart';import 'admin_server_settings_screen.dart';+import 'admin_server_logs_screen.dart';import 'admin_stats_screen.dart';import 'admin_sessions_screen.dart';+class _AdminNavigatorObserver extends NavigatorObserver {+ final VoidCallback onStackChanged;+ int routeDepth = 0;++ _AdminNavigatorObserver(this.onStackChanged);++ @override+ void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {+ super.didPush(route, previousRoute);+ routeDepth++;+ onStackChanged();+ }++ @override+ void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {+ super.didPop(route, previousRoute);+ routeDepth--;+ onStackChanged();+ }++ @override+ void didRemove(Route<dynamic> route, Route<dynamic>? previousRoute) {+ super.didRemove(route, previousRoute);+ routeDepth--;+ onStackChanged();+ }++ @override+ void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) {+ super.didReplace(newRoute: newRoute, oldRoute: oldRoute);+ onStackChanged();+ }+}+class AdminScreen extends StatefulWidget {- const AdminScreen({super.key});+ final ServerTaskTracker? taskTracker;++ const AdminScreen({super.key, this.taskTracker});@override State<AdminScreen> createState() => _AdminScreenState();}class _AdminScreenState extends State<AdminScreen> with WidgetsBindingObserver {+ static const _overviewSection = 'overview';+bool _loading = true;+ bool _loadedOnce = false;List<dynamic> _users = [];List<dynamic> _onlineUsers = [];List<dynamic> _libraries = [];@@ -44,33 +87,61 @@ class _AdminScreenState extends State<AdminScreen> with WidgetsBindingObserver {bool _creatingBackup = false;bool _purgingCache = false;late final ServerTaskTracker _taskTracker;+ late final bool _ownsTaskTracker;Timer? _issuesDebounce;Timer? _taskRefreshTimer;bool _refreshingTasks = false;+ final GlobalKey<NavigatorState> _desktopNavigatorKey = GlobalKey<NavigatorState>();+ late final _AdminNavigatorObserver _desktopNavigatorObserver;+ String _desktopSection = _overviewSection;+ bool _desktopNavigatorCanPop = false;+ bool _desktopNavigationChanging = false;+ int _desktopNavigationSerial = 0;+ bool _desktopUsersDirty = false;+ bool _desktopLibrariesDirty = false;+ bool _desktopOverviewDirty = false;+ int _desktopUsersDirtyGeneration = 0;+ int _desktopLibrariesDirtyGeneration = 0;+ int _desktopOverviewDirtyGeneration = 0;+ bool _desktopOverviewRefreshActive = false;+ Future<void>? _desktopUsersRefresh;+ Future<void>? _desktopLibrariesRefresh;+ bool? _desktopPresentation;@overridevoid initState() {super.initState();WidgetsBinding.instance.addObserver(this);- _taskTracker = ServerTaskTracker();- _startTaskRefreshTimer();+ _desktopNavigatorObserver = _AdminNavigatorObserver(_onDesktopStackChanged);+ DesktopWorkspaceNavigator.registerExitGuard(this, _prepareForDesktopPaneReset);+ _ownsTaskTracker = widget.taskTracker == null;+ _taskTracker = widget.taskTracker ?? ServerTaskTracker();+ if (_ownsTaskTracker) _startTaskRefreshTimer();_loadAll();SocketService().addItemsChangedListener(_onItemsChanged);}+ @override+ void didChangeDependencies() {+ super.didChangeDependencies();+ _desktopPresentation ??= isDesktopWorkspace(context);+ }+@overridevoid dispose() {WidgetsBinding.instance.removeObserver(this);+ DesktopWorkspaceNavigator.unregisterExitGuard(this);SocketService().removeItemsChangedListener(_onItemsChanged);_issuesDebounce?.cancel();_taskRefreshTimer?.cancel();- _taskTracker.dispose();+ if (_ownsTaskTracker) _taskTracker.dispose();super.dispose();}@overridevoid didChangeAppLifecycleState(AppLifecycleState state) {+ if (!_ownsTaskTracker) return;if (state == AppLifecycleState.resumed) {_startTaskRefreshTimer();unawaited(_refreshServerTasks());@@ -119,15 +190,19 @@ class _AdminScreenState extends State<AdminScreen> with WidgetsBindingObserver {}Future<void> _loadAll() async {+ final usersGeneration = _desktopUsersDirtyGeneration;+ final librariesGeneration = _desktopLibrariesDirtyGeneration;+ final overviewGeneration = _desktopOverviewDirtyGeneration;final api = context.read<AuthProvider>().apiService;if (api == null) return;- setState(() => _loading = true);+ if (!_loadedOnce) setState(() => _loading = true);final taskRefresh = _refreshServerTasks();final futures = await Future.wait([api.getUsers(), api.getOnlineUsers(), api.getLibraries(), api.getBackups(), api.getAllSessions(limit: 10),]);await taskRefresh;+ if (!mounted) return;_users = futures[0];_onlineUsers = futures[1];_libraries = futures[2];@@ -139,13 +214,30 @@ class _AdminScreenState extends State<AdminScreen> with WidgetsBindingObserver {final id = lib['id'] as String? ?? '';if (id.isNotEmpty) {final stats = await api.getLibraryStats(id);+ if (!mounted) return;if (stats != null) _libraryStats[id] = stats;_libraryIssues[id] = await api.getIssueItemCount(id);+ if (!mounted) return;}}_rmabBaseUrl = await ScopedPrefs.getString(kRmabBaseUrlKey);+ if (!mounted) return;_rmabApiToken = await ScopedPrefs.getString(kRmabApiTokenKey);- if (mounted) setState(() => _loading = false);+ if (!mounted) return;+ if (_desktopUsersDirtyGeneration == usersGeneration) {+ _desktopUsersDirty = false;+ }+ if (_desktopLibrariesDirtyGeneration == librariesGeneration) {+ _desktopLibrariesDirty = false;+ }+ if (_desktopOverviewDirtyGeneration == overviewGeneration) {+ _desktopOverviewDirty = false;+ }+ setState(() {+ _loadedOnce = true;+ _loading = false;+ });+ _leaveUnavailablePodcastSection();}bool get _hasRmab =>@@ -165,15 +257,23 @@ class _AdminScreenState extends State<AdminScreen> with WidgetsBindingObserver {final tt = Theme.of(context).textTheme;final l = AppLocalizations.of(context)!;+ final desktopPresentation = _desktopPresentation ?? false;+ if (desktopPresentation) {+ return _buildDesktopScaffold(context, l);+ }+return Scaffold(backgroundColor: Theme.of(context).scaffoldBackgroundColor,body: SafeArea(child: _loading? const Center(child: CircularProgressIndicator(strokeWidth: 2))- : RefreshIndicator(+ : DesktopPageBody(+ child: RefreshIndicator(onRefresh: _loadAll,+ notificationPredicate: (n) => !desktopPresentation && n.depth == 0,child: ListView(- padding: const EdgeInsets.only(bottom: 80),+ padding: EdgeInsets.only(+ bottom: desktopPresentation ? 24 : 80),children: [// ── Header ──Padding(@@ -187,6 +287,12 @@ class _AdminScreenState extends State<AdminScreen> with WidgetsBindingObserver {onPressed: () => showAdminTasksSheet(context, _taskTracker),),),+ if (desktopPresentation)+ IconButton(+ tooltip: l.refreshTooltip,+ icon: Icon(Icons.refresh_rounded, color: cs.onSurfaceVariant),+ onPressed: _loadAll,+ ),IconButton(icon: Icon(Icons.close_rounded, color: cs.onSurfaceVariant), onPressed: () => Navigator.pop(context)),]),),@@ -304,6 +410,16 @@ class _AdminScreenState extends State<AdminScreen> with WidgetsBindingObserver {},),const SizedBox(height: 10),+ _navButton(cs, tt,+ icon: Icons.description_outlined,+ label: 'Server logs',+ subtitle: l.sendLogsSubtitle,+ onTap: () {+ Navigator.push(context, MaterialPageRoute(+ builder: (_) => const AdminServerLogsScreen()));+ },+ ),+ const SizedBox(height: 10),_navButton(cs, tt,icon: Icons.bar_chart_rounded,label: l.adminStats,@@ -350,12 +466,452 @@ class _AdminScreenState extends State<AdminScreen> with WidgetsBindingObserver {],),),+ ),),);}// ─── Shared Widgets ─────────────────────────────────────────+ Widget _buildDesktopScaffold(BuildContext context, AppLocalizations l) {+ final outerNavigator = Navigator.of(context);+ final destinations = <AdminSectionDestination>[+ AdminSectionDestination(_overviewSection, Icons.dashboard_rounded, l.adminServer),+ AdminSectionDestination('users', Icons.people_rounded, l.adminUsers),+ AdminSectionDestination('upload', Icons.cloud_upload_rounded, l.adminUploadTitle),+ if (_hasPodcastLibrary || _desktopSection == 'podcasts')+ AdminSectionDestination('podcasts', Icons.podcasts_rounded, l.adminPodcasts),+ AdminSectionDestination('email', Icons.email_rounded, l.adminEmail),+ AdminSectionDestination('api-keys', Icons.vpn_key_rounded, l.adminApiKeys),+ AdminSectionDestination('libraries', Icons.library_books_rounded, l.adminLibrariesManage),+ AdminSectionDestination('server-settings', Icons.tune_rounded, l.adminServerSettings),+ const AdminSectionDestination('logs', Icons.description_outlined, 'Server logs'),+ AdminSectionDestination('stats', Icons.bar_chart_rounded, l.adminStats),+ AdminSectionDestination('sessions', Icons.history_rounded, l.adminAllSessions),+ ];++ return Scaffold(+ backgroundColor: Theme.of(context).scaffoldBackgroundColor,+ body: SafeArea(+ child: _loading+ ? const Center(child: CircularProgressIndicator(strokeWidth: 2))+ : PopScope(+ canPop: !_desktopNavigatorCanPop,+ onPopInvokedWithResult: (didPop, result) {+ if (didPop) return;+ final navigator = _desktopNavigatorKey.currentState;+ if (navigator != null) unawaited(navigator.maybePop(result));+ },+ child: AdminAdaptiveFrame(+ desktopMode: true,+ title: l.adminTitle,+ selectedSection: _desktopSection,+ destinations: destinations,+ onSectionSelected: (section) => unawaited(_selectDesktopSection(section)),+ child: Navigator(+ key: _desktopNavigatorKey,+ observers: [_desktopNavigatorObserver],+ onDidRemovePage: (_) {},+ pages: [+ MaterialPage<void>(+ key: const ValueKey('admin-overview-page'),+ name: '/admin/overview',+ child: Builder(+ builder: (pageContext) => _buildDesktopOverview(+ pageContext,+ onClose: () => outerNavigator.pop(),+ ),+ ),+ ),+ ],+ ),+ ),+ ),+ ),+ );+ }++ Widget _buildDesktopOverview(BuildContext pageContext, {required VoidCallback onClose}) {+ final cs = Theme.of(pageContext).colorScheme;+ final tt = Theme.of(pageContext).textTheme;+ final l = AppLocalizations.of(pageContext)!;++ return DesktopPageBody(+ maxWidth: 1040,+ child: RefreshIndicator(+ onRefresh: _loadAll,+ notificationPredicate: (_) => false,+ child: ListView(+ padding: const EdgeInsets.only(bottom: 24),+ children: [+ Padding(+ padding: const EdgeInsets.fromLTRB(20, 12, 8, 0),+ child: Row(children: [+ Expanded(child: AbsorbPageHeader(title: l.adminTitle, padding: EdgeInsets.zero)),+ IconButton(+ tooltip: l.refreshTooltip,+ icon: Icon(Icons.refresh_rounded, color: cs.onSurfaceVariant),+ onPressed: _loadAll,+ ),+ IconButton(+ icon: Icon(Icons.close_rounded, color: cs.onSurfaceVariant),+ onPressed: onClose,+ ),+ ]),+ ),+ const SizedBox(height: 20),+ _section(cs, tt, l.adminServer),+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: 16),+ child: Container(+ padding: const EdgeInsets.all(16),+ decoration: _cardDeco(cs),+ child: Row(children: [+ _stat(tt, cs, Icons.dns_rounded, _serverVersion ?? '–', l.adminVersion),+ _stat(tt, cs, Icons.people_rounded, '${_users.length}', l.adminUsers),+ _stat(tt, cs, Icons.wifi_rounded, '${_onlineUsers.length}', l.adminOnline),+ _stat(tt, cs, Icons.backup_rounded, '${_backups.length}', l.adminBackupsLabel),+ ]),+ ),+ ),+ const SizedBox(height: 8),+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: 16),+ child: Row(children: [+ Expanded(child: _actionBtn(cs, tt, Icons.backup_rounded, l.adminBackup, _creatingBackup, _createBackup)),+ const SizedBox(width: 10),+ Expanded(child: _actionBtn(cs, tt, Icons.cleaning_services_rounded, l.adminPurgeCache, _purgingCache, _purgeCache)),+ ]),+ ),+ const SizedBox(height: 28),+ _section(cs, tt, l.adminRmab),+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: 16),+ child: _hasRmab ? _rmabTile(cs, tt) : _rmabAddRow(cs, tt),+ ),+ const SizedBox(height: 28),+ if (_activeSessions.isNotEmpty) ...[+ _section(cs, tt, l.adminListeningNow),+ ..._activeSessions.map((session) => _sessionCard(cs, tt, session)),+ const SizedBox(height: 18),+ ],+ _section(cs, tt, l.adminLibraries),+ ListenableBuilder(+ listenable: _taskTracker,+ builder: (_, __) => Column(+ children: _libraries.map((library) => _libraryCard(cs, tt, library)).toList(),+ ),+ ),+ ],+ ),+ ),+ );+ }++ void _onDesktopStackChanged() {+ DesktopWorkspaceNavigator.notifyExitGuardChanged();+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (!mounted) return;+ final canPop = _desktopNavigatorKey.currentState?.canPop() ?? false;+ if (canPop != _desktopNavigatorCanPop) {+ setState(() => _desktopNavigatorCanPop = canPop);+ }+ });+ }++ Future<void> _selectDesktopSection(String section) async {+ final navigator = _desktopNavigatorKey.currentState;+ if (navigator == null || _desktopNavigationChanging) return;+ if (section == _desktopSection &&+ (section != _overviewSection || !navigator.canPop())) return;++ final previousSection = _desktopSection;+ final previousSerial = _desktopNavigationSerial;+ _desktopNavigationChanging = true;+ final navigationSerial = ++_desktopNavigationSerial;++ try {+ if (!await _popDesktopNavigatorToOverview(navigator)) {+ _desktopNavigationSerial = previousSerial;+ return;+ }+ if (!mounted || _desktopNavigatorKey.currentState != navigator) return;+ _markDesktopSectionDirty(previousSection);++ if (section == _overviewSection) {+ if (_desktopSection != _overviewSection || _desktopNavigatorCanPop) {+ setState(() {+ _desktopSection = _overviewSection;+ _desktopNavigatorCanPop = false;+ });+ }+ unawaited(_refreshDesktopOverviewIfNeeded());+ return;+ }++ setState(() {+ _desktopSection = section;+ _desktopNavigatorCanPop = true;+ });+ final sectionPreparation = _prepareDesktopSectionInputs(section);+ final route = MaterialPageRoute<void>(+ settings: RouteSettings(name: '/admin/$section'),+ builder: (routeContext) => _buildPreparedDesktopSectionPage(+ routeContext,+ section,+ sectionPreparation,+ ),+ );+ unawaited(navigator.push(route).then((_) {+ if (!mounted || navigationSerial != _desktopNavigationSerial) return;+ setState(() {+ _desktopSection = _overviewSection;+ _desktopNavigatorCanPop = false;+ });+ _markDesktopSectionDirty(section);+ unawaited(_refreshDesktopOverviewIfNeeded());+ }));+ } finally {+ _desktopNavigationChanging = false;+ }+ }++ Future<bool> _prepareForDesktopPaneReset() async {+ if (!mounted || _desktopPresentation != true) return true;+ final navigator = _desktopNavigatorKey.currentState;+ if (navigator == null || !navigator.canPop()) return true;+ if (_desktopNavigationChanging) return false;++ final previousSerial = _desktopNavigationSerial;+ _desktopNavigationChanging = true;+ _desktopNavigationSerial++;+ try {+ if (!await _popDesktopNavigatorToOverview(navigator)) {+ _desktopNavigationSerial = previousSerial;+ return false;+ }+ if (mounted) {+ setState(() {+ _desktopSection = _overviewSection;+ _desktopNavigatorCanPop = false;+ });+ }+ return true;+ } finally {+ _desktopNavigationChanging = false;+ }+ }++ Future<bool> _popDesktopNavigatorToOverview(+ NavigatorState navigator,+ ) async {+ while (navigator.canPop()) {+ final routeDepth = _desktopNavigatorObserver.routeDepth;+ await navigator.maybePop();+ if (_desktopNavigatorObserver.routeDepth >= routeDepth) return false;+ }+ return true;+ }++ void _markDesktopSectionDirty(String section) {+ if (section == 'users') {+ _desktopUsersDirty = true;+ _desktopUsersDirtyGeneration++;+ _desktopOverviewDirty = true;+ _desktopOverviewDirtyGeneration++;+ } else if (section == 'libraries') {+ _desktopLibrariesDirty = true;+ _desktopLibrariesDirtyGeneration++;+ _desktopOverviewDirty = true;+ _desktopOverviewDirtyGeneration++;+ } else if (section == 'sessions') {+ _desktopOverviewDirty = true;+ _desktopOverviewDirtyGeneration++;+ }+ }++ Future<void> _refreshDesktopOverviewIfNeeded() async {+ if (!_desktopOverviewDirty || _desktopOverviewRefreshActive) return;+ _desktopOverviewRefreshActive = true;+ try {+ do {+ await _loadAll();+ } while (mounted && _desktopOverviewDirty);+ } catch (error) {+ debugPrint('[Admin] Could not refresh overview: $error');+ } finally {+ _desktopOverviewRefreshActive = false;+ }+ }++ Future<void>? _prepareDesktopSectionInputs(String nextSection) {+ if (_desktopUsersDirty &&+ (nextSection == 'email' ||+ nextSection == 'api-keys' ||+ nextSection == 'sessions')) {+ return _refreshDesktopUsers();+ }+ if (_desktopLibrariesDirty &&+ (nextSection == 'users' ||+ nextSection == 'upload' ||+ nextSection == 'podcasts')) {+ return _refreshDesktopLibraries();+ }+ return null;+ }++ Future<void> _refreshDesktopUsers() {+ final activeRefresh = _desktopUsersRefresh;+ if (activeRefresh != null) return activeRefresh;+ final refresh = _runDesktopUsersRefresh();+ _desktopUsersRefresh = refresh;+ unawaited(refresh.whenComplete(() {+ if (identical(_desktopUsersRefresh, refresh)) {+ _desktopUsersRefresh = null;+ }+ }));+ return refresh;+ }++ Future<void> _runDesktopUsersRefresh() async {+ if (!mounted) return;+ final api = context.read<AuthProvider>().apiService;+ if (api == null) return;+ try {+ do {+ final generation = _desktopUsersDirtyGeneration;+ final results = await Future.wait([+ api.getUsers(),+ api.getOnlineUsers(),+ ]);+ if (!mounted) return;+ setState(() {+ _users = results[0];+ _onlineUsers = results[1];+ if (_desktopUsersDirtyGeneration == generation) {+ _desktopUsersDirty = false;+ }+ });+ } while (mounted && _desktopUsersDirty);+ } catch (error) {+ debugPrint('[Admin] Could not refresh users: $error');+ }+ }++ Future<void> _refreshDesktopLibraries() {+ final activeRefresh = _desktopLibrariesRefresh;+ if (activeRefresh != null) return activeRefresh;+ final refresh = _runDesktopLibrariesRefresh();+ _desktopLibrariesRefresh = refresh;+ unawaited(refresh.whenComplete(() {+ if (identical(_desktopLibrariesRefresh, refresh)) {+ _desktopLibrariesRefresh = null;+ }+ }));+ return refresh;+ }++ Future<void> _runDesktopLibrariesRefresh() async {+ if (!mounted) return;+ final api = context.read<AuthProvider>().apiService;+ if (api == null) return;+ try {+ do {+ final generation = _desktopLibrariesDirtyGeneration;+ final libraries = await api.getLibraries();+ if (!mounted) return;+ setState(() {+ _libraries = libraries;+ if (_desktopLibrariesDirtyGeneration == generation) {+ _desktopLibrariesDirty = false;+ }+ });+ } while (mounted && _desktopLibrariesDirty);+ _leaveUnavailablePodcastSection();+ } catch (error) {+ debugPrint('[Admin] Could not refresh libraries: $error');+ }+ }++ void _leaveUnavailablePodcastSection() {+ if (_desktopPresentation != true ||+ _desktopSection != 'podcasts' ||+ _hasPodcastLibrary) {+ return;+ }+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (!mounted ||+ _desktopSection != 'podcasts' ||+ _hasPodcastLibrary) {+ return;+ }+ unawaited(_selectDesktopSection(_overviewSection));+ });+ }++ Widget _buildPreparedDesktopSectionPage(+ BuildContext routeContext,+ String section,+ Future<void>? preparation,+ ) {+ if (preparation == null) {+ return _buildDesktopSectionPage(routeContext, section);+ }+ return FutureBuilder<void>(+ future: preparation,+ builder: (context, snapshot) {+ if (snapshot.connectionState != ConnectionState.done) {+ return Scaffold(+ backgroundColor: Theme.of(context).scaffoldBackgroundColor,+ body: const Center(+ child: CircularProgressIndicator(strokeWidth: 2),+ ),+ );+ }+ return _buildDesktopSectionPage(context, section);+ },+ );+ }++ Widget _buildDesktopSectionPage(BuildContext routeContext, String section) {+ switch (section) {+ case 'users':+ return AdminUsersScreen(users: _users, onlineUsers: _onlineUsers, libraries: _libraries);+ case 'upload':+ return AdminUploadScreen(+ libraries: _libraries,+ initialLibraryId: routeContext.read<AuthProvider>().defaultLibraryId,+ apiService: routeContext.read<AuthProvider>().apiService,+ onNavigationGuardChanged:+ DesktopWorkspaceNavigator.notifyExitGuardChanged,+ );+ case 'podcasts':+ final podcastLibrary = _libraries.firstWhere(+ (library) => library['mediaType'] == 'podcast',+ orElse: () => null,+ );+ return podcastLibrary == null+ ? const SizedBox.shrink()+ : AdminPodcastsScreen(library: podcastLibrary);+ case 'email':+ return AdminEmailScreen(users: _users);+ case 'api-keys':+ return AdminApiKeysScreen(users: _users);+ case 'libraries':+ return AdminLibrariesScreen(libraries: _libraries);+ case 'server-settings':+ return const AdminServerSettingsScreen();+ case 'logs':+ return const AdminServerLogsScreen();+ case 'stats':+ return const AdminStatsScreen();+ case 'sessions':+ return AdminSessionsScreen(users: _users);+ default:+ return const SizedBox.shrink();+ }+ }+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)));@@ -507,7 +1063,8 @@ class _AdminScreenState extends State<AdminScreen> with WidgetsBindingObserver {final l = AppLocalizations.of(context)!;return GestureDetector(onTap: () async {- await Navigator.push(context, MaterialPageRoute(+ final navigator = _desktopNavigatorKey.currentState ?? Navigator.of(context);+ await navigator.push(MaterialPageRoute(builder: (_) => AdminMissingItemsScreen(library: Map<String, dynamic>.from(lib as Map))));_loadAll();},diff --git a/lib/screens/admin_server_logs_screen.dart b/lib/screens/admin_server_logs_screen.dartnew file mode 100644index 00000000..d8093259--- /dev/null+++ b/lib/screens/admin_server_logs_screen.dart@@ -0,0 +1,663 @@+import 'package:flutter/material.dart';+import 'package:provider/provider.dart';++import '../l10n/app_localizations.dart';+import '../providers/auth_provider.dart';+import '../services/server_log_export_service.dart';+import '../services/socket_service.dart';+import '../widgets/absorb_page_header.dart';+import '../widgets/overlay_toast.dart';++class AdminServerLogsScreen extends StatefulWidget {+ const AdminServerLogsScreen({super.key});++ @override+ State<AdminServerLogsScreen> createState() => _AdminServerLogsScreenState();+}++class _AdminServerLogsScreenState extends State<AdminServerLogsScreen> {+ static const _maxLogs = 5000;+ static const _serverLevels = <int, String>{+ 0: 'Trace',+ 1: 'Debug',+ 2: 'Info',+ 3: 'Warning',+ };+ static const _filterLevels = <int, String>{+ -1: 'All levels',+ 0: 'Trace and higher',+ 1: 'Debug and higher',+ 2: 'Info and higher',+ 3: 'Warning and higher',+ 4: 'Error and higher',+ };++ final _searchController = TextEditingController();+ final _scrollController = ScrollController();+ final _socket = SocketService();+ late final void Function(Map<String, dynamic>) _socketLogHandler;++ List<_ServerLogEntry> _logs = [];+ bool _loading = true;+ bool _refreshing = false;+ bool _loadFailed = false;+ bool _savingLogLevel = false;+ int _serverLogLevel = 2;+ int _visibleMinimumLevel = -1;+ String _searchText = '';++ @override+ void initState() {+ super.initState();+ _socketLogHandler = _onServerLog;+ final rawLevel = context.read<AuthProvider>().serverSettings?['logLevel'];+ _serverLogLevel = _parseServerLevel(rawLevel);+ _socket.addServerLogListener(_socketLogHandler, level: _serverLogLevel);+ _loadLogs();+ }++ @override+ void dispose() {+ _socket.removeServerLogListener(_socketLogHandler);+ _searchController.dispose();+ _scrollController.dispose();+ super.dispose();+ }++ int _parseServerLevel(dynamic value) {+ final parsed = value is num+ ? value.toInt()+ : int.tryParse(value?.toString() ?? '');+ return _serverLevels.containsKey(parsed) ? parsed! : 2;+ }++ List<_ServerLogEntry> get _visibleLogs {+ final query = _searchText.trim().toLowerCase();+ return _logs+ .where((log) {+ if (_visibleMinimumLevel >= 0 && log.level < _visibleMinimumLevel) {+ return false;+ }+ return query.isEmpty || log.searchText.contains(query);+ })+ .toList(growable: false);+ }++ Future<void> _loadLogs() async {+ final api = context.read<AuthProvider>().apiService;+ if (api == null) {+ setState(() {+ _loading = false;+ _loadFailed = true;+ });+ return;+ }++ setState(() {+ if (_logs.isEmpty) {+ _loading = true;+ } else {+ _refreshing = true;+ }+ _loadFailed = false;+ });+ final rawLogs = await api.getServerLogs();+ if (!mounted) return;++ if (rawLogs == null) {+ setState(() {+ _loading = false;+ _refreshing = false;+ _loadFailed = true;+ });+ return;+ }++ final loaded = rawLogs+ .map(_ServerLogEntry.fromMap)+ .whereType<_ServerLogEntry>();+ final merged = <String, _ServerLogEntry>{};+ for (final log in [...loaded, ..._logs]) {+ merged[log.identity] = log;+ }+ var values = merged.values.toList(growable: false);+ if (values.length > _maxLogs) {+ values = values.sublist(values.length - _maxLogs);+ }+ setState(() {+ _logs = values;+ _loading = false;+ _refreshing = false;+ });+ _scrollToBottom(jump: true);+ }++ void _onServerLog(Map<String, dynamic> rawLog) {+ final log = _ServerLogEntry.fromMap(rawLog);+ if (log == null || !mounted) return;+ final shouldFollow =+ !_scrollController.hasClients ||+ _scrollController.position.maxScrollExtent -+ _scrollController.position.pixels <+ 96;+ setState(() {+ _logs = [..._logs, log];+ if (_logs.length > _maxLogs + 50) {+ _logs = _logs.sublist(_logs.length - _maxLogs);+ }+ });+ if (shouldFollow) _scrollToBottom();+ }++ void _scrollToBottom({bool jump = false}) {+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (!mounted || !_scrollController.hasClients) return;+ final target = _scrollController.position.maxScrollExtent;+ if (jump) {+ _scrollController.jumpTo(target);+ } else {+ _scrollController.animateTo(+ target,+ duration: const Duration(milliseconds: 180),+ curve: Curves.easeOut,+ );+ }+ });+ }++ Future<void> _changeServerLogLevel(int level) async {+ if (_savingLogLevel || level == _serverLogLevel) return;+ final auth = context.read<AuthProvider>();+ final api = auth.apiService;+ if (api == null) return;+ final previous = _serverLogLevel;+ setState(() {+ _serverLogLevel = level;+ _savingLogLevel = true;+ });++ final updated = await api.updateServerSettings({'logLevel': level});+ if (!mounted) return;+ if (updated == null) {+ setState(() {+ _serverLogLevel = previous;+ _savingLogLevel = false;+ });+ showOverlayToast(+ context,+ AppLocalizations.of(context)!.srvSaveFailed,+ icon: Icons.error_outline_rounded,+ );+ return;+ }++ auth.applyServerSettings(updated);+ _socket.updateServerLogListenerLevel(_socketLogHandler, level);+ setState(() => _savingLogLevel = false);+ }++ Future<void> _exportVisibleLogs(BuildContext buttonContext) async {+ final logs = _visibleLogs;+ if (logs.isEmpty) return;+ final now = DateTime.now();+ String two(int value) => value.toString().padLeft(2, '0');+ final fileName =+ 'audiobookshelf_server_logs_${now.year}-${two(now.month)}-${two(now.day)}_${two(now.hour)}-${two(now.minute)}-${two(now.second)}.txt';+ final content = StringBuffer()+ ..writeln('Audiobookshelf server logs')+ ..writeln('Exported: ${now.toIso8601String()}')+ ..writeln('Server log level: ${_serverLevels[_serverLogLevel]}')+ ..writeln('Visible entries: ${logs.length} of ${_logs.length}')+ ..writeln(+ 'Display filter: ${_filterLevels[_visibleMinimumLevel] ?? 'All levels'}',+ );+ if (_searchText.trim().isNotEmpty) {+ content.writeln('Search: ${_searchText.trim()}');+ }+ content.writeln();+ for (final log in logs) {+ content.writeln(log.exportLine);+ }++ final box = buttonContext.findRenderObject();+ final origin = box is RenderBox+ ? box.localToGlobal(Offset.zero) & box.size+ : null;+ try {+ await ServerLogExportService.exportText(+ fileName: fileName,+ content: content.toString(),+ sharePositionOrigin: origin,+ );+ } catch (error) {+ if (!mounted) return;+ showOverlayToast(+ context,+ AppLocalizations.of(context)!.failedToShare(error.toString()),+ icon: Icons.error_outline_rounded,+ );+ }+ }++ @override+ Widget build(BuildContext context) {+ final cs = Theme.of(context).colorScheme;+ final tt = Theme.of(context).textTheme;+ final l = AppLocalizations.of(context)!;+ final visibleLogs = _visibleLogs;++ return Scaffold(+ backgroundColor: Theme.of(context).scaffoldBackgroundColor,+ body: SafeArea(+ child: Column(+ children: [+ Padding(+ padding: const EdgeInsets.fromLTRB(20, 12, 8, 0),+ child: Row(+ children: [+ const Expanded(+ child: AbsorbPageHeader(+ title: 'Server logs',+ padding: EdgeInsets.zero,+ ),+ ),+ if (_refreshing)+ const Padding(+ padding: EdgeInsets.symmetric(horizontal: 12),+ child: SizedBox(+ width: 16,+ height: 16,+ child: CircularProgressIndicator(strokeWidth: 2),+ ),+ )+ else+ IconButton(+ tooltip: l.refreshTooltip,+ onPressed: _loadLogs,+ icon: Icon(+ Icons.refresh_rounded,+ color: cs.onSurfaceVariant,+ ),+ ),+ Builder(+ builder: (buttonContext) => IconButton(+ tooltip: l.sendLogs,+ onPressed: visibleLogs.isEmpty+ ? null+ : () => _exportVisibleLogs(buttonContext),+ icon: const Icon(Icons.download_rounded),+ ),+ ),+ IconButton(+ icon: Icon(Icons.close_rounded, color: cs.onSurfaceVariant),+ onPressed: () => Navigator.pop(context),+ ),+ ],+ ),+ ),+ Padding(+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 12),+ child: _buildControls(cs, tt, l),+ ),+ Expanded(+ child: Padding(+ padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),+ child: _buildLogPanel(cs, tt, l, visibleLogs),+ ),+ ),+ ],+ ),+ ),+ );+ }++ Widget _buildControls(ColorScheme cs, TextTheme tt, AppLocalizations l) {+ final search = TextField(+ controller: _searchController,+ onChanged: (value) => setState(() => _searchText = value),+ decoration: InputDecoration(+ labelText: l.search,+ prefixIcon: const Icon(Icons.search_rounded),+ suffixIcon: _searchText.isEmpty+ ? null+ : IconButton(+ onPressed: () {+ _searchController.clear();+ setState(() => _searchText = '');+ },+ icon: const Icon(Icons.close_rounded),+ ),+ ),+ );+ final displayFilter = _dropdown(+ cs,+ tt,+ label: 'Display',+ value: _visibleMinimumLevel,+ options: _filterLevels,+ onChanged: (value) => setState(() => _visibleMinimumLevel = value),+ );+ final serverLevel = _dropdown(+ cs,+ tt,+ label: _savingLogLevel ? 'Saving log level…' : 'Server log level',+ value: _serverLogLevel,+ options: _serverLevels,+ onChanged: _savingLogLevel ? null : _changeServerLogLevel,+ );++ return LayoutBuilder(+ builder: (context, constraints) {+ if (constraints.maxWidth >= 720) {+ return Row(+ crossAxisAlignment: CrossAxisAlignment.end,+ children: [+ Expanded(child: search),+ const SizedBox(width: 12),+ SizedBox(width: 190, child: displayFilter),+ const SizedBox(width: 12),+ SizedBox(width: 180, child: serverLevel),+ ],+ );+ }+ return Column(+ children: [+ search,+ const SizedBox(height: 10),+ Row(+ children: [+ Expanded(child: displayFilter),+ const SizedBox(width: 10),+ Expanded(child: serverLevel),+ ],+ ),+ ],+ );+ },+ );+ }++ Widget _dropdown(+ ColorScheme cs,+ TextTheme tt, {+ required String label,+ required int value,+ required Map<int, String> options,+ required ValueChanged<int>? onChanged,+ }) {+ return InputDecorator(+ decoration: InputDecoration(labelText: label),+ child: DropdownButtonHideUnderline(+ child: DropdownButton<int>(+ value: value,+ isDense: true,+ isExpanded: true,+ borderRadius: BorderRadius.circular(12),+ style: tt.bodyMedium?.copyWith(color: cs.onSurface),+ items: options.entries+ .map(+ (entry) => DropdownMenuItem<int>(+ value: entry.key,+ child: Text(+ entry.value,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ ),+ ),+ )+ .toList(growable: false),+ onChanged: onChanged == null+ ? null+ : (selected) {+ if (selected != null) onChanged(selected);+ },+ ),+ ),+ );+ }++ Widget _buildLogPanel(+ ColorScheme cs,+ TextTheme tt,+ AppLocalizations l,+ List<_ServerLogEntry> visibleLogs,+ ) {+ if (_loading) {+ return const Center(child: CircularProgressIndicator(strokeWidth: 2));+ }+ if (_loadFailed && _logs.isEmpty) {+ return Center(+ child: Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ Icon(+ Icons.error_outline_rounded,+ size: 42,+ color: cs.error.withValues(alpha: 0.7),+ ),+ const SizedBox(height: 12),+ Text(+ 'Couldn’t load the server logs',+ style: tt.titleSmall?.copyWith(color: cs.onSurface),+ ),+ const SizedBox(height: 8),+ OutlinedButton(onPressed: _loadLogs, child: Text(l.retry)),+ ],+ ),+ );+ }++ return Container(+ clipBehavior: Clip.antiAlias,+ decoration: BoxDecoration(+ color: cs.surfaceContainerHighest.withValues(alpha: 0.72),+ borderRadius: BorderRadius.circular(16),+ border: Border.all(color: cs.outlineVariant.withValues(alpha: 0.35)),+ ),+ child: visibleLogs.isEmpty+ ? Center(+ child: Text(+ _logs.isEmpty ? 'No server logs yet' : 'No logs match',+ style: tt.bodyMedium?.copyWith(+ color: cs.onSurfaceVariant.withValues(alpha: 0.7),+ ),+ ),+ )+ : LayoutBuilder(+ builder: (context, constraints) {+ final wide = constraints.maxWidth >= 760;+ return SelectionArea(+ child: Scrollbar(+ controller: _scrollController,+ thumbVisibility: wide,+ child: ListView.separated(+ controller: _scrollController,+ padding: const EdgeInsets.symmetric(vertical: 6),+ itemCount: visibleLogs.length,+ separatorBuilder: (_, __) => Divider(+ height: 1,+ thickness: 1,+ color: cs.outlineVariant.withValues(alpha: 0.18),+ ),+ itemBuilder: (_, index) =>+ _logRow(cs, tt, visibleLogs[index], wide: wide),+ ),+ ),+ );+ },+ ),+ );+ }++ Widget _logRow(+ ColorScheme cs,+ TextTheme tt,+ _ServerLogEntry log, {+ required bool wide,+ }) {+ final levelColor = _levelColor(cs, log.level);+ final level = Container(+ padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 2),+ decoration: BoxDecoration(+ color: levelColor.withValues(alpha: 0.12),+ borderRadius: BorderRadius.circular(6),+ ),+ child: Text(+ log.levelName,+ style: tt.labelSmall?.copyWith(+ color: levelColor,+ fontWeight: FontWeight.w700,+ fontSize: 10,+ ),+ ),+ );++ if (!wide) {+ return Padding(+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 9),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Row(+ children: [+ Expanded(+ child: Text(+ log.timestamp,+ style: tt.labelSmall?.copyWith(+ color: cs.onSurfaceVariant.withValues(alpha: 0.7),+ fontFamily: 'monospace',+ ),+ ),+ ),+ level,+ ],+ ),+ if (log.source.isNotEmpty) ...[+ const SizedBox(height: 3),+ Text(+ log.source,+ style: tt.labelSmall?.copyWith(+ color: cs.primary.withValues(alpha: 0.7),+ fontFamily: 'monospace',+ ),+ ),+ ],+ const SizedBox(height: 5),+ Text(+ log.message,+ style: tt.bodySmall?.copyWith(+ color: cs.onSurface.withValues(alpha: 0.88),+ fontFamily: 'monospace',+ height: 1.35,+ ),+ ),+ ],+ ),+ );+ }++ return Padding(+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 7),+ child: Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ SizedBox(+ width: 176,+ child: Text(+ log.timestamp,+ style: tt.labelSmall?.copyWith(+ color: cs.onSurfaceVariant.withValues(alpha: 0.65),+ fontFamily: 'monospace',+ ),+ ),+ ),+ SizedBox(+ width: 82,+ child: Align(alignment: Alignment.topLeft, child: level),+ ),+ if (log.source.isNotEmpty)+ SizedBox(+ width: 150,+ child: Padding(+ padding: const EdgeInsets.only(right: 12),+ child: Text(+ log.source,+ maxLines: 2,+ overflow: TextOverflow.ellipsis,+ style: tt.labelSmall?.copyWith(+ color: cs.primary.withValues(alpha: 0.7),+ fontFamily: 'monospace',+ ),+ ),+ ),+ ),+ Expanded(+ child: Text(+ log.message,+ style: tt.bodySmall?.copyWith(+ color: cs.onSurface.withValues(alpha: 0.88),+ fontFamily: 'monospace',+ height: 1.35,+ ),+ ),+ ),+ ],+ ),+ );+ }++ Color _levelColor(ColorScheme cs, int level) {+ return switch (level) {+ 0 => cs.onSurfaceVariant,+ 1 => cs.secondary,+ 2 => cs.primary,+ 3 => Colors.amber.shade700,+ 4 => cs.error,+ 5 => Colors.red.shade900,+ 6 => cs.tertiary,+ _ => cs.onSurfaceVariant,+ };+ }+}++class _ServerLogEntry {+ final String timestamp;+ final String source;+ final String message;+ final String levelName;+ final int level;++ const _ServerLogEntry({+ required this.timestamp,+ required this.source,+ required this.message,+ required this.levelName,+ required this.level,+ });++ static _ServerLogEntry? fromMap(Map<String, dynamic> raw) {+ final rawMessage = raw['message'];+ if (rawMessage == null) return null;+ final rawLevel = raw['level'];+ final level = rawLevel is num+ ? rawLevel.toInt()+ : int.tryParse(rawLevel?.toString() ?? '') ?? 0;+ return _ServerLogEntry(+ timestamp: raw['timestamp']?.toString() ?? '',+ source: raw['source']?.toString() ?? '',+ message: rawMessage.toString(),+ levelName: raw['levelName']?.toString().toUpperCase() ?? 'UNKNOWN',+ level: level,+ );+ }++ String get identity => '$timestamp\u0000$level\u0000$source\u0000$message';++ String get searchText =>+ '$timestamp $levelName $source $message'.toLowerCase();++ String get exportLine {+ final sourceText = source.isEmpty ? '' : ' [$source]';+ return '$timestamp ${levelName.padRight(5)}$sourceText $message';+ }+}diff --git a/lib/screens/admin_sessions_screen.dart b/lib/screens/admin_sessions_screen.dartindex 8b658603..27483dee 100644--- a/lib/screens/admin_sessions_screen.dart+++ b/lib/screens/admin_sessions_screen.dart@@ -4,6 +4,7 @@ import 'package:provider/provider.dart';import '../l10n/app_localizations.dart';import '../providers/auth_provider.dart';import '../widgets/absorb_page_header.dart';+import '../widgets/adaptive_modal.dart';import 'stats_screen.dart' show SessionDetailsSheet;/// Admin view of every user's listening sessions. View + delete any session;@@ -91,10 +92,12 @@ class _AdminSessionsScreenState extends State<AdminSessionsScreen> {final myId = context.read<AuthProvider>().userId;final ownerId = s['userId'] as String? ??(s['user'] as Map<String, dynamic>?)?['id'] as String?;- final changed = await showModalBottomSheet<bool>(+ final changed = await showAdaptiveActionMenu<bool>(context: context,isScrollControlled: true,backgroundColor: Colors.transparent,+ desktopWidth: 520,+ desktopScrollWrap: false,builder: (_) =>SessionDetailsSheet(session: s, allowEdit: ownerId == myId),);diff --git a/lib/screens/admin_upload_screen.dart b/lib/screens/admin_upload_screen.dartindex 6b488118..6d78d4eb 100644--- a/lib/screens/admin_upload_screen.dart+++ b/lib/screens/admin_upload_screen.dart@@ -40,6 +40,7 @@ class AdminUploadScreen extends StatefulWidget {final UploadPathChecker? pathChecker;final MediaUploader? uploader;final BookMetadataSearcher? metadataSearcher;+ final VoidCallback? onNavigationGuardChanged;const AdminUploadScreen({super.key,@@ -50,6 +51,7 @@ class AdminUploadScreen extends StatefulWidget {this.pathChecker,this.uploader,this.metadataSearcher,+ this.onNavigationGuardChanged,});@override@@ -508,6 +510,7 @@ class _AdminUploadScreenState extends State<AdminUploadScreen> {_uploading = true;_progress = null;});+ widget.onNavigationGuardChanged?.call();final pathResult = widget.pathChecker != null? await widget.pathChecker!(request.directory, _folderPath)@@ -518,11 +521,13 @@ class _AdminUploadScreenState extends State<AdminUploadScreen> {if (!mounted) return;if (!pathResult.success) {setState(() => _uploading = false);+ widget.onNavigationGuardChanged?.call();_showError(l.adminUploadPathCheckFailed);return;}if (pathResult.exists) {setState(() => _uploading = false);+ widget.onNavigationGuardChanged?.call();final existingTitle = pathResult.libraryItemTitle;_showError(existingTitle == null || existingTitle.isEmpty@@ -559,6 +564,7 @@ class _AdminUploadScreenState extends State<AdminUploadScreen> {_files = [];}});+ widget.onNavigationGuardChanged?.call();if (result.success) {showOverlayToast(@@ -608,9 +614,11 @@ class _AdminUploadScreenState extends State<AdminUploadScreen> {final tt = Theme.of(context).textTheme;final l = AppLocalizations.of(context)!;- return Scaffold(- backgroundColor: Theme.of(context).scaffoldBackgroundColor,- body: SafeArea(+ return PopScope(+ canPop: !_uploading,+ child: Scaffold(+ backgroundColor: Theme.of(context).scaffoldBackgroundColor,+ body: SafeArea(child: Column(children: [Padding(@@ -711,6 +719,7 @@ class _AdminUploadScreenState extends State<AdminUploadScreen> {),],),+ ),),);}diff --git a/lib/screens/admin_users_screen.dart b/lib/screens/admin_users_screen.dartindex 96c93bf8..5600ecca 100644--- a/lib/screens/admin_users_screen.dart+++ b/lib/screens/admin_users_screen.dart@@ -12,10 +12,12 @@ import '../services/backup_service.dart';import '../services/setup_link_service.dart';import '../widgets/absorb_page_header.dart';import '../widgets/absorb_wave_icon.dart';+import '../widgets/adaptive_modal.dart';import '../widgets/overlay_toast.dart';import '../widgets/setup_link_share_sheet.dart';import '../l10n/app_localizations.dart';import '../utils/duration_format.dart';+import '../utils/app_platform.dart';class AdminUsersScreen extends StatefulWidget {final List<dynamic> users;@@ -208,7 +210,8 @@ class _AdminUsersScreenState extends State<AdminUsersScreen> {}void _showEditor(Map<String, dynamic>? user) {- showModalBottomSheet(context: context, isScrollControlled: true, useSafeArea: true, backgroundColor: Colors.transparent,+ showAdaptiveActionMenu(context: context, isScrollControlled: true, useSafeArea: true, backgroundColor: Colors.transparent,+ desktopWidth: 560, desktopScrollWrap: false,builder: (_) => _UserEditorSheet(user: user, libraries: widget.libraries, onSaved: _reload));}}@@ -739,10 +742,12 @@ class _UserDetailScreenState extends State<_UserDetailScreen> {}void _showSessionDetails(Map<String, dynamic> session) {- showModalBottomSheet(+ showAdaptiveActionMenu(context: context,isScrollControlled: true,backgroundColor: Colors.transparent,+ desktopWidth: 560,+ desktopScrollWrap: false,builder: (_) => _AdminSessionDetailsSheet(session: session),);}@@ -779,7 +784,8 @@ class _UserDetailScreenState extends State<_UserDetailScreen> {);void _showEditor() {- showModalBottomSheet(context: context, isScrollControlled: true, useSafeArea: true, backgroundColor: Colors.transparent,+ showAdaptiveActionMenu(context: context, isScrollControlled: true, useSafeArea: true, backgroundColor: Colors.transparent,+ desktopWidth: 560, desktopScrollWrap: false,builder: (_) => _UserEditorSheet(user: widget.user, libraries: widget.libraries, onSaved: () {widget.onChanged();_load();@@ -854,11 +860,13 @@ class _UserDetailScreenState extends State<_UserDetailScreen> {final setupLink = SetupLinkService.createLink(payload);if (!mounted) return;- await showModalBottomSheet<void>(+ await showAdaptiveActionMenu<void>(context: context,isScrollControlled: true,useSafeArea: true,showDragHandle: false,+ desktopWidth: 560,+ desktopScrollWrap: false,builder: (sheetContext) => SetupLinkShareSheet(username: username,setupLink: setupLink,@@ -905,7 +913,7 @@ class _UserDetailScreenState extends State<_UserDetailScreen> {);if (result == null) return;- if (Platform.isWindows || Platform.isLinux || Platform.isMacOS) {+ if (AppPlatform.isDesktop) {await File(result).writeAsString(jsonStr);}if (mounted) {@@ -1239,6 +1247,7 @@ class _AdminSessionDetailsSheet extends StatelessWidget {final cs = Theme.of(context).colorScheme;final tt = Theme.of(context).textTheme;final l = AppLocalizations.of(context)!;+ final desktopMode = ModalSurface.isDesktopOf(context);final s = session;final meta = s['mediaMetadata'] as Map<String, dynamic>? ?? {};@@ -1280,7 +1289,7 @@ class _AdminSessionDetailsSheet extends StatelessWidget {final lib = context.read<LibraryProvider>();final coverUrl = itemId != null ? lib.getCoverUrl(itemId) : null;- return DraggableScrollableSheet(+ return AdaptiveDraggableScrollableSheet(initialChildSize: 0.6,minChildSize: 0.4,maxChildSize: 0.95,@@ -1289,20 +1298,37 @@ class _AdminSessionDetailsSheet extends StatelessWidget {return Container(decoration: BoxDecoration(color: cs.surface,- borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),+ borderRadius: desktopMode+ ? BorderRadius.zero+ : const BorderRadius.vertical(top: Radius.circular(24)),),child: Column(children: [- Padding(- padding: const EdgeInsets.only(top: 10, bottom: 4),- child: Container(- width: 36,- height: 4,- decoration: BoxDecoration(- color: cs.onSurface.withValues(alpha: 0.2),- borderRadius: BorderRadius.circular(2),+ if (desktopMode)+ Align(+ alignment: Alignment.centerRight,+ child: Padding(+ padding: const EdgeInsets.fromLTRB(8, 6, 8, 0),+ child: IconButton(+ tooltip: MaterialLocalizations.of(+ context,+ ).closeButtonTooltip,+ onPressed: () => Navigator.pop(context),+ icon: const Icon(Icons.close_rounded),+ ),+ ),+ )+ else+ Padding(+ padding: const EdgeInsets.only(top: 10, bottom: 4),+ child: Container(+ width: 36,+ height: 4,+ decoration: BoxDecoration(+ color: cs.onSurface.withValues(alpha: 0.2),+ borderRadius: BorderRadius.circular(2),+ ),),),- ),Expanded(child: ListView(controller: scrollController,diff --git a/lib/services/api_service.dart b/lib/services/api_service.dartindex fda5e6bd..1fd83722 100644--- a/lib/services/api_service.dart+++ b/lib/services/api_service.dart@@ -84,6 +84,16 @@ class MediaUploadResult {const MediaUploadResult({required this.success, this.error});}+class LibraryMetadataRemovalResult {+ final int found;+ final int removed;++ const LibraryMetadataRemovalResult({+ required this.found,+ required this.removed,+ });+}+enum _RefreshOutcome {refreshed,rejected,@@ -105,6 +115,77 @@ class PasswordChangeResult {}class ApiService {+ /// Remove sidecar metadata files from every item in a library (admin only).+ /// [extension] is the server-supported sidecar type: `json` or `abs`.+ Future<LibraryMetadataRemovalResult?> removeLibraryMetadataFiles(+ String libraryId,+ String extension,+ ) async {+ if (extension != 'json' && extension != 'abs') {+ throw ArgumentError.value(extension, 'extension', 'Must be json or abs');+ }+ try {+ final uri = Uri.parse(+ '$_cleanBaseUrl/api/libraries/$libraryId/remove-metadata',+ ).replace(queryParameters: {'ext': extension});+ final r = await _authPost(uri, timeout: const Duration(minutes: 30));+ if (r.statusCode != 200) {+ debugPrint('[API] removeLibraryMetadataFiles failed: ${r.statusCode}');+ return null;+ }+ final data = jsonDecode(r.body) as Map<String, dynamic>;+ return LibraryMetadataRemovalResult(+ found: (data['found'] as num?)?.toInt() ?? 0,+ removed: (data['removed'] as num?)?.toInt() ?? 0,+ );+ } catch (e) {+ debugPrint('[API] removeLibraryMetadataFiles error: $e');+ return null;+ }+ }++ Future<String?> validateCronExpression(String expression) async {+ try {+ final r = await _authPost(+ Uri.parse('$_cleanBaseUrl/api/validate-cron'),+ body: jsonEncode({'expression': expression}),+ );+ if (r.statusCode == 200) return null;+ final message = r.body.trim();+ return message.isEmpty ? 'Invalid cron expression' : message;+ } catch (e) {+ debugPrint('[API] validateCronExpression error: $e');+ return 'Could not validate the cron expression';+ }+ }++ /// Get the server's current daily log entries (admin only).+ ///+ /// GET /api/logger-data returns `{ currentDailyLogs: [...] }`. A nullable+ /// result distinguishes a request failure from a valid empty log file.+ Future<List<Map<String, dynamic>>?> getServerLogs() async {+ try {+ final r = await _authGet(Uri.parse('$_cleanBaseUrl/api/logger-data'));+ if (r.statusCode != 200) {+ debugPrint('[API] getServerLogs failed: ${r.statusCode}');+ return null;+ }+ final decoded = jsonDecode(r.body);+ if (decoded is! Map) return const <Map<String, dynamic>>[];+ final rawLogs = decoded['currentDailyLogs'];+ if (rawLogs is! List) return const <Map<String, dynamic>>[];+ return rawLogs+ .whereType<Map>()+ .map(+ (log) => log.map((key, value) => MapEntry(key.toString(), value)),+ )+ .toList(growable: false);+ } catch (e) {+ debugPrint('[API] getServerLogs error: $e');+ return null;+ }+ }+static String appVersion = '1.3.0'; // fallback; overwritten by initVersion()static String appBuild = ''; // build number; set by initVersion()diff --git a/lib/services/backup_service.dart b/lib/services/backup_service.dartindex cb713884..74170cb5 100644--- a/lib/services/backup_service.dart+++ b/lib/services/backup_service.dart@@ -408,7 +408,9 @@ class BackupService {// when we write settings below. saveAccount() sets the active scope key.final accounts = data['accounts'] as List<dynamic>?;if (accounts != null) {- for (final a in accounts) {+ // saveAccount inserts at the front. Restore in reverse so the backup's+ // first (active) account stays first and owns the scoped settings below.+ for (final a in accounts.reversed) {final map = a as Map<String, dynamic>;await UserAccountService().saveAccount(SavedAccount.fromJson(map,diff --git a/lib/services/scoped_prefs.dart b/lib/services/scoped_prefs.dartindex 6a1026ad..1da0cac6 100644--- a/lib/services/scoped_prefs.dart+++ b/lib/services/scoped_prefs.dart@@ -31,6 +31,7 @@ class ScopedPrefs {'loggingEnabled', 'manual_offline_mode','custom_download_path', 'custom_download_uri', 'downloads','absorb_device_id',+ 'desktop_sidebar_pinned','widget_item_id', 'widget_episode_id','cached_stats', 'cached_sessions','update_last_check', 'update_dismissed_version',diff --git a/lib/services/server_log_export_service.dart b/lib/services/server_log_export_service.dartnew file mode 100644index 00000000..98318769--- /dev/null+++ b/lib/services/server_log_export_service.dart@@ -0,0 +1,33 @@+import 'dart:convert';+import 'dart:ui';++import 'package:flutter/foundation.dart';+import 'package:share_plus/share_plus.dart';++import '../utils/text_file_download.dart';++class ServerLogExportService {+ const ServerLogExportService._();++ static Future<void> exportText({+ required String fileName,+ required String content,+ Rect? sharePositionOrigin,+ }) async {+ if (kIsWeb) {+ await downloadTextFile(fileName: fileName, content: content);+ return;+ }++ final file = XFile.fromData(+ Uint8List.fromList(utf8.encode(content)),+ name: fileName,+ mimeType: 'text/plain',+ );+ await Share.shareXFiles(+ [file],+ subject: 'Audiobookshelf server logs',+ sharePositionOrigin: sharePositionOrigin,+ );+ }+}diff --git a/lib/services/server_task_tracker.dart b/lib/services/server_task_tracker.dartindex 0f54bc9b..23d78365 100644--- a/lib/services/server_task_tracker.dart+++ b/lib/services/server_task_tracker.dart@@ -109,6 +109,8 @@ class ServerTaskTracker extends ChangeNotifier {final Set<String> _finishedTaskIds = {};var _eventRevision = 0;var _disposed = false;+ Future<void>? _refreshInFlight;+ ApiService? _refreshApi;ServerTaskTracker({SocketService? socketService}): _socketService = socketService ?? SocketService() {@@ -142,6 +144,26 @@ class ServerTaskTracker extends ChangeNotifier {}Future<void> refresh(ApiService api) async {+ final activeRefresh = _refreshInFlight;+ if (activeRefresh != null) {+ if (identical(api, _refreshApi)) return activeRefresh;+ await activeRefresh;+ return refresh(api);+ }++ late final Future<void> operation;+ operation = _performRefresh(api).whenComplete(() {+ if (identical(_refreshInFlight, operation)) {+ _refreshInFlight = null;+ _refreshApi = null;+ }+ });+ _refreshApi = api;+ _refreshInFlight = operation;+ return operation;+ }++ Future<void> _performRefresh(ApiService api) async {if (_disposed) return;final revisionBeforeRequest = _eventRevision;final rawTasks = await api.getServerTasks();diff --git a/lib/services/socket_service.dart b/lib/services/socket_service.dartindex 531a79f0..b74da0f1 100644--- a/lib/services/socket_service.dart+++ b/lib/services/socket_service.dart@@ -133,6 +133,71 @@ class SocketService {}}+ // Server log fan-out. Each consumer keeps its own minimum level so opening+ // another log surface later cannot steal or disable an existing listener.+ // The server is subscribed at the lowest requested threshold and entries+ // are filtered again before delivery to each consumer.+ final Map<void Function(Map<String, dynamic>), int> _serverLogListeners = {};++ void addServerLogListener(+ void Function(Map<String, dynamic>) fn, {+ required int level,+ }) {+ _serverLogListeners[fn] = _validLogLevel(level);+ _syncServerLogSubscription();+ }++ void updateServerLogListenerLevel(+ void Function(Map<String, dynamic>) fn,+ int level,+ ) {+ if (!_serverLogListeners.containsKey(fn)) return;+ _serverLogListeners[fn] = _validLogLevel(level);+ _syncServerLogSubscription();+ }++ void removeServerLogListener(void Function(Map<String, dynamic>) fn) {+ if (_serverLogListeners.remove(fn) == null) return;+ _syncServerLogSubscription();+ }++ int _validLogLevel(int level) => level.clamp(0, 6).toInt();++ int? get _lowestRequestedLogLevel {+ if (_serverLogListeners.isEmpty) return null;+ var lowest = _serverLogListeners.values.first;+ for (final level in _serverLogListeners.values.skip(1)) {+ if (level < lowest) lowest = level;+ }+ return lowest;+ }++ void _syncServerLogSubscription() {+ if (_socket?.connected != true) return;+ final level = _lowestRequestedLogLevel;+ if (level == null) {+ _socket!.emit('remove_log_listener');+ } else {+ _socket!.emit('set_log_listener', level);+ }+ }++ void _handleServerLog(dynamic data) {+ final log = normalizeSocketMap(data);+ if (log == null) return;+ final rawLevel = log['level'];+ final level = rawLevel is num+ ? rawLevel.toInt()+ : int.tryParse(rawLevel?.toString() ?? '') ?? 0;+ for (final listener in Map.of(_serverLogListeners).entries) {+ if (level >= listener.value) listener.key(log);+ }+ }++ void _registerServerLogEvents() {+ _socket!.on('log', _handleServerLog);+ }+@visibleForTestingstatic Map<String, dynamic>? normalizeSocketMap(Object? data) {if (data is Map<String, dynamic>) return data;@@ -276,6 +341,7 @@ class SocketService {_socket!.on('init', (_) {debugPrint('[Socket] Authenticated - user is online');+ _syncServerLogSubscription();});_socket!.on('auth_failed', (_) {@@ -383,6 +449,8 @@ class SocketService {_socket!.on('task_progress', _handleTaskProgress);_socket!.on('task_finished', _handleTaskFinished);+ _registerServerLogEvents();+// 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) {@@ -478,6 +546,7 @@ class SocketService {_socket!.on('init', (_) {debugPrint('[Socket] Authenticated - user is online');+ _syncServerLogSubscription();});_socket!.on('auth_failed', (_) {@@ -540,6 +609,8 @@ class SocketService {_socket!.on('task_progress', _handleTaskProgress);_socket!.on('task_finished', _handleTaskFinished);+ _registerServerLogEvents();+_socket!.on('ereader-devices-updated', (data) {if (data is! Map) return;final raw = data['ereaderDevices'] as List<dynamic>?;diff --git a/lib/utils/app_platform.dart b/lib/utils/app_platform.dartnew file mode 100644index 00000000..7d5c7ee7--- /dev/null+++ b/lib/utils/app_platform.dart@@ -0,0 +1,15 @@+import 'dart:io';++import 'package:flutter/foundation.dart';++abstract final class AppPlatform {+ static bool get isWeb => kIsWeb;+ static bool get isAndroid => !kIsWeb && Platform.isAndroid;+ static bool get isIOS => !kIsWeb && Platform.isIOS;+ static bool get isMacOS => !kIsWeb && Platform.isMacOS;+ static bool get isWindows => !kIsWeb && Platform.isWindows;+ static bool get isLinux => !kIsWeb && Platform.isLinux;++ static bool get isDesktop => isMacOS || isWindows || isLinux;+ static bool get isMobile => isAndroid || isIOS;+}diff --git a/lib/utils/desktop_workspace.dart b/lib/utils/desktop_workspace.dartnew file mode 100644index 00000000..04659dbc--- /dev/null+++ b/lib/utils/desktop_workspace.dart@@ -0,0 +1,98 @@+import 'package:flutter/foundation.dart';+import 'package:flutter/widgets.dart';+import 'app_platform.dart';++const double kDesktopWorkspaceBreakpoint = 960;+const double kStandardWorkspaceBreakpoint = 1200;+const double kWideWorkspaceBreakpoint = 1440;++enum WorkspaceLayoutTier { mobile, compact, standard, wide }++WorkspaceLayoutTier workspaceLayoutTierForWidth(double width) {+ if (width < kDesktopWorkspaceBreakpoint) {+ return WorkspaceLayoutTier.mobile;+ }+ if (width < kStandardWorkspaceBreakpoint) {+ return WorkspaceLayoutTier.compact;+ }+ if (width < kWideWorkspaceBreakpoint) {+ return WorkspaceLayoutTier.standard;+ }+ return WorkspaceLayoutTier.wide;+}++bool usesExtendedDesktopSidebar(WorkspaceLayoutTier tier) =>+ tier == WorkspaceLayoutTier.standard || tier == WorkspaceLayoutTier.wide;++double desktopSidebarWidth(WorkspaceLayoutTier tier) =>+ usesExtendedDesktopSidebar(tier) ? 248 : 72;++/// Registration point for the desktop workspace's content-pane navigator.+/// AppShell registers a resolver on mount; anything that pushes full pages+/// resolves through [contentNavigator] so pages land inside the pane on+/// desktop and on the root navigator everywhere else.+abstract final class DesktopWorkspaceNavigator {+ static NavigatorState? Function()? _resolver;+ static Object? _exitGuardOwner;+ static Future<bool> Function()? _exitGuard;+ static final ValueNotifier<int> _exitGuardChanges = ValueNotifier<int>(0);++ static ValueListenable<int> get exitGuardChanges => _exitGuardChanges;++ static void register(NavigatorState? Function() resolver) =>+ _resolver = resolver;++ static void registerExitGuard(Object owner, Future<bool> Function() guard) {+ _exitGuardOwner = owner;+ _exitGuard = guard;+ notifyExitGuardChanged();+ }++ static void unregisterExitGuard(Object owner) {+ if (!identical(_exitGuardOwner, owner)) return;+ _exitGuardOwner = null;+ _exitGuard = null;+ notifyExitGuardChanged();+ }++ static void notifyExitGuardChanged() => _exitGuardChanges.value++;++ static Future<bool> prepareForPaneReset() =>+ _exitGuard?.call() ?? Future.value(true);++ static void unregister() {+ _resolver = null;+ _exitGuardOwner = null;+ _exitGuard = null;+ notifyExitGuardChanged();+ }+}++class DesktopWorkspaceScope extends InheritedWidget {+ const DesktopWorkspaceScope({super.key, required super.child});++ static bool isActive(BuildContext context) =>+ context.dependOnInheritedWidgetOfExactType<DesktopWorkspaceScope>() !=+ null;++ @override+ bool updateShouldNotify(DesktopWorkspaceScope oldWidget) => false;+}++NavigatorState contentNavigator(BuildContext context) =>+ DesktopWorkspaceNavigator._resolver?.call() ??+ Navigator.of(context, rootNavigator: true);++/// Whether the app is showing the desktop web workspace (sidebar shell).+/// Measures the window via the View, not MediaQuery: pages run inside a+/// MediaQuery whose size is overridden to the content pane, which would+/// disagree with the shell's own breakpoint between 960 and ~1208px.+bool isDesktopWorkspace(BuildContext context) {+ if (!AppPlatform.isWeb) return false;+ if (DesktopWorkspaceScope.isActive(context)) return true;+ // Subscribe to size changes so callers rebuild on window resize.+ MediaQuery.sizeOf(context);+ final view = View.of(context);+ final width = view.physicalSize.width / view.devicePixelRatio;+ return workspaceLayoutTierForWidth(width) != WorkspaceLayoutTier.mobile;+}diff --git a/lib/utils/text_file_download.dart b/lib/utils/text_file_download.dartnew file mode 100644index 00000000..6772213c--- /dev/null+++ b/lib/utils/text_file_download.dart@@ -0,0 +1,2 @@+export 'text_file_download_stub.dart'+ if (dart.library.js_interop) 'text_file_download_web.dart';diff --git a/lib/utils/text_file_download_stub.dart b/lib/utils/text_file_download_stub.dartnew file mode 100644index 00000000..b036d443--- /dev/null+++ b/lib/utils/text_file_download_stub.dart@@ -0,0 +1,4 @@+Future<void> downloadTextFile({+ required String fileName,+ required String content,+}) => throw UnsupportedError('Text file downloads are only available on web.');diff --git a/lib/utils/text_file_download_web.dart b/lib/utils/text_file_download_web.dartnew file mode 100644index 00000000..94ffbb15--- /dev/null+++ b/lib/utils/text_file_download_web.dart@@ -0,0 +1,27 @@+import 'dart:convert';+import 'dart:js_interop';+import 'dart:typed_data';++import 'package:web/web.dart' as web;++Future<void> downloadTextFile({+ required String fileName,+ required String content,+}) async {+ final bytes = Uint8List.fromList(utf8.encode(content));+ final blob = web.Blob(+ <JSUint8Array>[bytes.toJS].toJS,+ web.BlobPropertyBag(type: 'text/plain;charset=utf-8'),+ );+ final url = web.URL.createObjectURL(blob);+ final anchor = web.HTMLAnchorElement()+ ..href = url+ ..download = fileName+ ..style.display = 'none';++ web.document.body?.appendChild(anchor);+ anchor.click();+ anchor.remove();+ await Future<void>.delayed(Duration.zero);+ web.URL.revokeObjectURL(url);+}diff --git a/lib/widgets/absorb_page_header.dart b/lib/widgets/absorb_page_header.dartindex b2616761..8e17f715 100644--- a/lib/widgets/absorb_page_header.dart+++ b/lib/widgets/absorb_page_header.dart@@ -1,5 +1,6 @@import 'package:flutter/material.dart';import '../l10n/app_localizations.dart';+import '../utils/desktop_workspace.dart';/// Consistent page header used across all screens.///@@ -13,6 +14,7 @@ class AbsorbPageHeader extends StatelessWidget {final Color? titleColor;final List<Widget>? actions;final Widget? trailing;+ final bool? showBranding;final EdgeInsetsGeometry padding;const AbsorbPageHeader({@@ -22,6 +24,7 @@ class AbsorbPageHeader extends StatelessWidget {this.titleColor,this.actions,this.trailing,+ this.showBranding,this.padding = const EdgeInsets.fromLTRB(20, 12, 20, 0),});@@ -32,44 +35,64 @@ class AbsorbPageHeader extends StatelessWidget {final l = AppLocalizations.of(context)!;final bColor = brandingColor ?? cs.onSurfaceVariant;final tColor = titleColor ?? cs.onSurface;+ final headerActions = actions;+ final shouldShowBranding = showBranding ?? !isDesktopWorkspace(context);return Padding(padding: padding,child: Column(crossAxisAlignment: CrossAxisAlignment.start,children: [- // Branding row — ABSORB + optional actionsLayoutBuilder(- builder: (ctx, lc) {+ builder: (context, constraints) {+ final reservedWidth = shouldShowBranding ? 140.0 : 200.0;+ final maxActionWidth = (constraints.maxWidth - reservedWidth)+ .clamp(0.0, double.infinity)+ .toDouble();return ConstrainedBox(constraints: const BoxConstraints(minHeight: 32),child: Row(children: [- Text(- l.appTitle,- style: tt.labelSmall?.copyWith(- color: bColor,- letterSpacing: 4,- fontWeight: FontWeight.w300,+ if (shouldShowBranding)+ Text(+ l.appTitle,+ style: tt.labelSmall?.copyWith(+ color: bColor,+ letterSpacing: 4,+ fontWeight: FontWeight.w300,+ ),+ )+ else+ Expanded(+ child: Text(+ title,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: tt.headlineMedium?.copyWith(+ fontWeight: FontWeight.w700,+ color: tColor,+ letterSpacing: -0.5,+ ),+ ),),- ),if (trailing != null) ...[const SizedBox(width: 8),trailing!,],- const Spacer(),- if (actions != null)+ if (shouldShowBranding)+ const Spacer()+ else+ const SizedBox(width: 12),+ if (headerActions != null && headerActions.isNotEmpty)ConstrainedBox(- constraints: BoxConstraints(- maxWidth: (lc.maxWidth - 140).clamp(0.0, double.infinity),- ),+ constraints: BoxConstraints(maxWidth: maxActionWidth),child: FittedBox(fit: BoxFit.scaleDown,alignment: Alignment.centerRight,child: Row(mainAxisSize: MainAxisSize.min,spacing: 8,- children: actions!,+ children: headerActions,),),),@@ -78,16 +101,17 @@ class AbsorbPageHeader extends StatelessWidget {);},),- const SizedBox(height: 4),- // Page title- Text(- title,- style: tt.headlineMedium?.copyWith(- fontWeight: FontWeight.w700,- color: tColor,- letterSpacing: -0.5,+ if (shouldShowBranding) ...[+ const SizedBox(height: 4),+ Text(+ title,+ style: tt.headlineMedium?.copyWith(+ fontWeight: FontWeight.w700,+ color: tColor,+ letterSpacing: -0.5,+ ),),- ),+ ],],),);diff --git a/lib/widgets/adaptive_modal.dart b/lib/widgets/adaptive_modal.dartnew file mode 100644index 00000000..ee1723f4--- /dev/null+++ b/lib/widgets/adaptive_modal.dart@@ -0,0 +1,357 @@+import 'package:flutter/material.dart';+import '../utils/desktop_workspace.dart';+import 'desktop_wheel_scroll_region.dart';++enum DialogWidthClass {+ action(480),+ content(720);++ const DialogWidthClass(this.width);+ final double width;+}++/// Marks which surface a modal's content is rendered in so shared content can+/// adapt (hide drag handles, square off sheet corners) without new params.+class ModalSurface extends InheritedWidget {+ const ModalSurface({super.key, required this.desktop, required super.child});++ final bool desktop;++ static bool isDesktopOf(BuildContext context) =>+ context.dependOnInheritedWidgetOfExactType<ModalSurface>()?.desktop ??+ false;++ @override+ bool updateShouldNotify(ModalSurface oldWidget) =>+ oldWidget.desktop != desktop;+}++/// Keeps sheet-style content draggable on mobile while giving it a finite,+/// conventional dialog height on desktop. The same builder and scroll+/// controller work in both surfaces.+class AdaptiveDraggableScrollableSheet extends StatelessWidget {+ const AdaptiveDraggableScrollableSheet({+ super.key,+ required this.builder,+ this.initialChildSize = 0.5,+ this.minChildSize = 0.25,+ this.maxChildSize = 1.0,+ this.expand = true,+ this.desktopHeightFraction = 0.76,+ this.desktopMaxHeight = 720,+ });++ final ScrollableWidgetBuilder builder;+ final double initialChildSize;+ final double minChildSize;+ final double maxChildSize;+ final bool expand;+ final double desktopHeightFraction;+ final double desktopMaxHeight;++ @override+ Widget build(BuildContext context) {+ if (ModalSurface.isDesktopOf(context)) {+ final availableHeight =+ MediaQuery.sizeOf(context).height * desktopHeightFraction;+ final height = availableHeight < desktopMaxHeight+ ? availableHeight+ : desktopMaxHeight;+ return SizedBox(+ height: height,+ child: _SheetDialogScrollHost(builder: builder),+ );+ }++ return DraggableScrollableSheet(+ initialChildSize: initialChildSize,+ minChildSize: minChildSize,+ maxChildSize: maxChildSize,+ expand: expand,+ builder: builder,+ );+ }+}++/// Scrollable browse/detail surface: draggable bottom sheet on mobile,+/// centered dialog on the desktop workspace. The builder's ScrollController+/// comes from the DraggableScrollableSheet on mobile and a dialog-owned+/// controller on desktop, so existing sheet bodies work unchanged.+Future<T?> showAdaptiveSheetDialog<T>({+ required BuildContext context,+ required Widget Function(BuildContext, ScrollController) builder,+ DialogWidthClass widthClass = DialogWidthClass.content,+ double desktopMaxHeightFraction = 0.85,+ bool desktopCloseButton = true,+ double initialChildSize = 0.7,+ double minChildSize = 0.5,+ double maxChildSize = 1.0,+ bool snap = false,+ bool expand = false,+ bool useSafeArea = true,+ Color? backgroundColor,+ bool isDismissible = true,+ bool showDragHandle = false,+}) {+ if (isDesktopWorkspace(context)) {+ return showDesktopSheetDialog<T>(+ context: context,+ builder: builder,+ maxWidth: widthClass.width,+ maxHeightFraction: desktopMaxHeightFraction,+ closeButton: desktopCloseButton,+ backgroundColor: backgroundColor,+ isDismissible: isDismissible,+ );+ }+ return showModalBottomSheet<T>(+ context: context,+ isScrollControlled: true,+ useSafeArea: useSafeArea,+ backgroundColor: backgroundColor,+ isDismissible: isDismissible,+ showDragHandle: showDragHandle,+ builder: (ctx) => DraggableScrollableSheet(+ expand: expand,+ initialChildSize: initialChildSize,+ minChildSize: minChildSize,+ maxChildSize: maxChildSize,+ snap: snap,+ builder: (c, sc) => ModalSurface(desktop: false, child: builder(c, sc)),+ ),+ );+}++/// Intrinsic-height action menu / picker: plain bottom sheet on mobile, small+/// centered dialog on the desktop workspace. Set [desktopScrollWrap] false+/// when the content manages its own scrolling.+Future<T?> showAdaptiveActionMenu<T>({+ required BuildContext context,+ required WidgetBuilder builder,+ double desktopWidth = 480,+ double desktopMaxHeightFraction = 0.85,+ bool desktopScrollWrap = true,+ bool isScrollControlled = false,+ bool useSafeArea = false,+ Color? backgroundColor,+ ShapeBorder? shape,+ bool isDismissible = true,+ bool showDragHandle = false,+ BoxConstraints? constraints,+}) {+ if (isDesktopWorkspace(context)) {+ return showDesktopModalDialog<T>(+ context: context,+ maxWidth: desktopWidth,+ maxHeightFraction: desktopMaxHeightFraction,+ closeButton: false,+ backgroundColor: backgroundColor,+ isDismissible: isDismissible,+ builder: desktopScrollWrap+ ? (ctx) => SingleChildScrollView(child: Builder(builder: builder))+ : builder,+ );+ }+ return showModalBottomSheet<T>(+ context: context,+ isScrollControlled: isScrollControlled,+ useSafeArea: useSafeArea,+ backgroundColor: backgroundColor,+ shape: shape,+ isDismissible: isDismissible,+ showDragHandle: showDragHandle,+ constraints: constraints,+ builder: (ctx) => ModalSurface(desktop: false, child: builder(ctx)),+ );+}++/// Desktop dialog surface for sheet-style builders that expect a+/// ScrollController. Used by the adaptive helpers and showStackableSheet.+Future<T?> showDesktopSheetDialog<T>({+ required BuildContext context,+ required Widget Function(BuildContext, ScrollController) builder,+ double maxWidth = 720,+ double maxHeightFraction = 0.85,+ bool closeButton = true,+ Color? backgroundColor,+ bool isDismissible = true,+ void Function(Route<dynamic>)? onRouteCaptured,+ void Function(Route<dynamic>)? onRouteDisposed,+}) => showDesktopModalDialog<T>(+ context: context,+ maxWidth: maxWidth,+ maxHeightFraction: maxHeightFraction,+ closeButton: closeButton,+ backgroundColor: backgroundColor,+ isDismissible: isDismissible,+ onRouteCaptured: onRouteCaptured,+ onRouteDisposed: onRouteDisposed,+ builder: (ctx) => _SheetDialogScrollHost(builder: builder),+);++/// Centered dialog with the shared desktop modal chrome (matches the+/// settings surfaces). Always presents on the root navigator so it covers+/// the whole window.+Future<T?> showDesktopModalDialog<T>({+ required BuildContext context,+ required WidgetBuilder builder,+ double maxWidth = 720,+ double maxHeightFraction = 0.85,+ bool closeButton = true,+ Color? backgroundColor,+ bool isDismissible = true,+ void Function(Route<dynamic>)? onRouteCaptured,+ void Function(Route<dynamic>)? onRouteDisposed,+}) {+ final cs = Theme.of(context).colorScheme;+ // Transparent means "the sheet body paints its own rounded container";+ // inside a clipped dialog that container needs a real backdrop instead.+ final bg = backgroundColor == null || backgroundColor == Colors.transparent+ ? cs.surfaceContainerHigh+ : backgroundColor;+ return showDialog<T>(+ context: context,+ useRootNavigator: true,+ barrierDismissible: isDismissible,+ builder: (dialogContext) => DesktopWheelScrollRegion(+ child: Stack(+ fit: StackFit.expand,+ children: [+ GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: isDismissible+ ? () => Navigator.of(dialogContext).maybePop()+ : null,+ ),+ Dialog(+ backgroundColor: bg,+ clipBehavior: Clip.antiAlias,+ insetPadding: const EdgeInsets.all(24),+ shape: RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(20),+ side: BorderSide(color: cs.outlineVariant.withValues(alpha: 0.4)),+ ),+ child: ConstrainedBox(+ constraints: BoxConstraints(+ maxHeight:+ MediaQuery.sizeOf(dialogContext).height * maxHeightFraction,+ ),+ child: SizedBox(+ width: maxWidth,+ child: _DesktopDialogBody(+ builder: builder,+ closeButton: closeButton,+ onRouteCaptured: onRouteCaptured,+ onRouteDisposed: onRouteDisposed,+ ),+ ),+ ),+ ),+ ],+ ),+ ),+ );+}++class _SheetDialogScrollHost extends StatefulWidget {+ const _SheetDialogScrollHost({required this.builder});++ final Widget Function(BuildContext, ScrollController) builder;++ @override+ State<_SheetDialogScrollHost> createState() => _SheetDialogScrollHostState();+}++class _SheetDialogScrollHostState extends State<_SheetDialogScrollHost> {+ final _controller = ScrollController();++ @override+ void dispose() {+ _controller.dispose();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) => widget.builder(context, _controller);+}++class _DesktopDialogBody extends StatefulWidget {+ const _DesktopDialogBody({+ required this.builder,+ required this.closeButton,+ this.onRouteCaptured,+ this.onRouteDisposed,+ });++ final WidgetBuilder builder;+ final bool closeButton;+ final void Function(Route<dynamic>)? onRouteCaptured;+ final void Function(Route<dynamic>)? onRouteDisposed;++ @override+ State<_DesktopDialogBody> createState() => _DesktopDialogBodyState();+}++class _DesktopDialogBodyState extends State<_DesktopDialogBody> {+ Route<dynamic>? _route;++ @override+ void initState() {+ super.initState();+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (!mounted) return;+ _route = ModalRoute.of(context);+ if (_route != null) widget.onRouteCaptured?.call(_route!);+ });+ }++ @override+ void dispose() {+ if (_route != null) widget.onRouteDisposed?.call(_route!);+ super.dispose();+ }++ @override+ Widget build(BuildContext context) {+ final cs = Theme.of(context).colorScheme;+ final content = ModalSurface(+ desktop: true,+ child: Builder(builder: widget.builder),+ );+ if (!widget.closeButton) return content;+ return ModalSurface(+ desktop: true,+ child: Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ SizedBox(+ key: const ValueKey('desktop-dialog-chrome'),+ height: 48,+ child: Align(+ alignment: Alignment.centerRight,+ child: Padding(+ padding: const EdgeInsets.only(right: 8),+ child: Material(+ color: cs.surfaceContainerHighest.withValues(alpha: 0.85),+ shape: const CircleBorder(),+ clipBehavior: Clip.antiAlias,+ child: IconButton(+ key: const ValueKey('desktop-dialog-close-button'),+ visualDensity: VisualDensity.compact,+ icon: Icon(+ Icons.close_rounded,+ size: 20,+ color: cs.onSurfaceVariant,+ ),+ onPressed: () => Navigator.of(context).pop(),+ ),+ ),+ ),+ ),+ ),+ Flexible(child: Builder(builder: widget.builder)),+ ],+ ),+ );+ }+}diff --git a/lib/widgets/admin_adaptive_frame.dart b/lib/widgets/admin_adaptive_frame.dartnew file mode 100644index 00000000..dc3c8bd6--- /dev/null+++ b/lib/widgets/admin_adaptive_frame.dart@@ -0,0 +1,152 @@+import 'package:flutter/material.dart';+import 'desktop_wheel_scroll_region.dart';++class AdminSectionDestination {+ final String id;+ final IconData icon;+ final String label;++ const AdminSectionDestination(this.id, this.icon, this.label);+}++class AdminAdaptiveFrame extends StatelessWidget {+ final bool desktopMode;+ final String title;+ final String selectedSection;+ final List<AdminSectionDestination> destinations;+ final ValueChanged<String> onSectionSelected;+ final Widget child;++ const AdminAdaptiveFrame({+ super.key,+ required this.desktopMode,+ required this.title,+ required this.selectedSection,+ required this.destinations,+ required this.onSectionSelected,+ required this.child,+ });++ @override+ Widget build(BuildContext context) {+ if (!desktopMode) return child;+ final cs = Theme.of(context).colorScheme;+ final tt = Theme.of(context).textTheme;++ return LayoutBuilder(+ builder: (context, constraints) {+ // The desktop shell may stay mounted briefly below its breakpoint so+ // an in-progress upload cannot be abandoned. Give the upload pane the+ // full narrow width instead of squeezing it between two sidebars.+ if (constraints.maxWidth < 720) return child;++ return Row(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ SizedBox(+ key: const Key('admin-desktop-sidebar'),+ width: 224,+ child: Material(+ color: cs.surface.withValues(alpha: 0.38),+ child: ListView(+ padding: const EdgeInsets.fromLTRB(14, 20, 14, 20),+ children: [+ Padding(+ padding: const EdgeInsets.fromLTRB(12, 0, 12, 12),+ child: Text(+ title,+ style: tt.labelMedium?.copyWith(+ color: cs.onSurfaceVariant,+ fontWeight: FontWeight.w700,+ letterSpacing: 0.8,+ ),+ ),+ ),+ for (final destination in destinations)+ Padding(+ padding: const EdgeInsets.only(bottom: 4),+ child: Material(+ color: selectedSection == destination.id+ ? cs.primary.withValues(alpha: 0.14)+ : Colors.transparent,+ borderRadius: BorderRadius.circular(11),+ clipBehavior: Clip.antiAlias,+ child: InkWell(+ key: ValueKey(+ 'admin-destination-${destination.id}',+ ),+ onTap: () => onSectionSelected(destination.id),+ child: Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: 12,+ vertical: 11,+ ),+ child: Row(+ children: [+ Icon(+ destination.icon,+ size: 19,+ color: selectedSection == destination.id+ ? cs.primary+ : cs.onSurfaceVariant,+ ),+ const SizedBox(width: 11),+ Expanded(+ child: Text(+ destination.label,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: tt.bodyMedium?.copyWith(+ color: selectedSection == destination.id+ ? cs.onSurface+ : cs.onSurfaceVariant,+ fontWeight:+ selectedSection == destination.id+ ? FontWeight.w700+ : FontWeight.w500,+ ),+ ),+ ),+ ],+ ),+ ),+ ),+ ),+ ),+ ],+ ),+ ),+ ),+ VerticalDivider(+ width: 1,+ thickness: 1,+ color: cs.outlineVariant.withValues(alpha: 0.35),+ ),+ Expanded(+ key: const Key('admin-desktop-content'),+ child: DesktopWheelScrollRegion(+ child: Align(+ alignment: Alignment.topCenter,+ child: ConstrainedBox(+ constraints: const BoxConstraints(maxWidth: 1040),+ child: LayoutBuilder(+ builder: (context, constraints) => MediaQuery(+ data: MediaQuery.of(context).copyWith(+ size: Size(+ constraints.maxWidth,+ constraints.maxHeight,+ ),+ ),+ child: ClipRect(child: SizedBox.expand(child: child)),+ ),+ ),+ ),+ ),+ ),+ ),+ ],+ );+ },+ );+ }+}diff --git a/lib/widgets/admin_task_indicator.dart b/lib/widgets/admin_task_indicator.dartindex ffdae4fd..2897cb1c 100644--- a/lib/widgets/admin_task_indicator.dart+++ b/lib/widgets/admin_task_indicator.dart@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';import '../l10n/app_localizations.dart';import '../services/server_task_tracker.dart';+import 'adaptive_modal.dart';class AdminTaskIndicator extends StatelessWidget {static const indicatorKey = Key('admin-task-indicator');@@ -82,11 +83,13 @@ Future<void> showAdminTasksSheet(BuildContext context,ServerTaskTracker tracker,) {- return showModalBottomSheet<void>(+ return showAdaptiveActionMenu<void>(context: context,isScrollControlled: true,useSafeArea: true,backgroundColor: Colors.transparent,+ desktopWidth: 560,+ desktopScrollWrap: false,builder: (sheetContext) => ListenableBuilder(listenable: tracker,builder: (_, __) => AdminTasksSheet(tasks: tracker.visibleTasks),diff --git a/lib/widgets/desktop_page_body.dart b/lib/widgets/desktop_page_body.dartnew file mode 100644index 00000000..ace9ebf3--- /dev/null+++ b/lib/widgets/desktop_page_body.dart@@ -0,0 +1,25 @@+import 'package:flutter/material.dart';+import '../utils/desktop_workspace.dart';+import 'desktop_wheel_scroll_region.dart';++/// Centers a pushed page's content in a readable column on the desktop+/// workspace; returns the child untouched everywhere else.+class DesktopPageBody extends StatelessWidget {+ final Widget child;+ final double maxWidth;++ const DesktopPageBody({super.key, required this.child, this.maxWidth = 840});++ @override+ Widget build(BuildContext context) {+ if (!isDesktopWorkspace(context)) return child;+ return DesktopWheelScrollRegion(+ child: Center(+ child: ConstrainedBox(+ constraints: BoxConstraints(maxWidth: maxWidth),+ child: child,+ ),+ ),+ );+ }+}diff --git a/lib/widgets/desktop_wheel_scroll_region.dart b/lib/widgets/desktop_wheel_scroll_region.dartnew file mode 100644index 00000000..bc294afc--- /dev/null+++ b/lib/widgets/desktop_wheel_scroll_region.dart@@ -0,0 +1,173 @@+import 'package:flutter/gestures.dart';+import 'package:flutter/material.dart';++/// Lets a desktop pane's empty gutters scroll its primary content.+class DesktopWheelScrollRegion extends StatefulWidget {+ const DesktopWheelScrollRegion({+ super.key,+ required this.child,+ this.controller,+ });++ final Widget child;+ final ScrollController? controller;++ @override+ State<DesktopWheelScrollRegion> createState() =>+ _DesktopWheelScrollRegionState();+}++class _DesktopWheelScrollRegionState extends State<DesktopWheelScrollRegion> {+ final List<_DiscoveredScrollable> _discoveredScrollables = [];++ _WheelTarget? _targetFor(PointerScrollEvent event) {+ final controller = widget.controller;+ if (controller != null) {+ if (!controller.hasClients || controller.positions.length != 1) {+ return null;+ }+ return _targetForPosition(controller.position, event);+ }++ _discoveredScrollables.removeWhere(+ (candidate) => !candidate.scrollable.mounted,+ );+ _WheelTarget? bestTarget;+ var bestDepth = 1 << 20;+ var bestVisibleArea = -1.0;+ final preferredAxis =+ event.scrollDelta.dy.abs() >= event.scrollDelta.dx.abs()+ ? Axis.vertical+ : Axis.horizontal;+ for (final candidate in _discoveredScrollables) {+ final scrollable = candidate.scrollable;+ if (!_isActive(scrollable)) continue;+ final position = scrollable.position;+ if (axisDirectionToAxis(position.axisDirection) != preferredAxis) {+ continue;+ }+ final target = _targetForPosition(position, event);+ if (target == null) continue;+ final visibleArea = _visibleArea(scrollable);+ if (visibleArea <= 0) continue;+ if (candidate.depth < bestDepth ||+ (candidate.depth == bestDepth && visibleArea > bestVisibleArea)) {+ bestTarget = target;+ bestDepth = candidate.depth;+ bestVisibleArea = visibleArea;+ }+ }+ return bestTarget;+ }++ double _visibleArea(ScrollableState scrollable) {+ final regionObject = context.findRenderObject();+ final scrollObject = scrollable.context.findRenderObject();+ if (regionObject is! RenderBox ||+ scrollObject is! RenderBox ||+ !regionObject.attached ||+ !scrollObject.attached) {+ return 0;+ }+ final scrollBounds = MatrixUtils.transformRect(+ scrollObject.getTransformTo(regionObject),+ scrollObject.paintBounds,+ );+ final visibleBounds = scrollBounds.intersect(+ Offset.zero & regionObject.size,+ );+ if (visibleBounds.isEmpty) return 0;+ return visibleBounds.width * visibleBounds.height;+ }++ _WheelTarget? _targetForPosition(+ ScrollPosition position,+ PointerScrollEvent event,+ ) {+ if (!position.hasContentDimensions ||+ !position.physics.shouldAcceptUserOffset(position)) {+ return null;+ }+ final axis = axisDirectionToAxis(position.axisDirection);+ var delta = axis == Axis.vertical+ ? event.scrollDelta.dy+ : event.scrollDelta.dx;+ if (axisDirectionIsReversed(position.axisDirection)) delta = -delta;+ final target = (position.pixels + delta).clamp(+ position.minScrollExtent,+ position.maxScrollExtent,+ );+ if (delta == 0 || target == position.pixels) return null;+ return _WheelTarget(position, delta);+ }++ bool _isActive(ScrollableState scrollable) {+ final renderObject = scrollable.context.findRenderObject();+ if (!(renderObject?.attached ?? false)) return false;+ final route = ModalRoute.of(scrollable.context);+ return (route == null || route.isCurrent) &&+ TickerMode.of(scrollable.context);+ }++ void _rememberPosition(BuildContext? notificationContext, int depth) {+ if (notificationContext == null) return;+ final scrollable = Scrollable.maybeOf(notificationContext);+ if (scrollable == null) return;+ _discoveredScrollables+ ..removeWhere((candidate) => candidate.scrollable == scrollable)+ ..insert(0, _DiscoveredScrollable(scrollable, depth));+ }++ bool _handleMetricsNotification(ScrollMetricsNotification notification) {+ _rememberPosition(notification.context, notification.depth);+ return false;+ }++ bool _handleScrollNotification(ScrollNotification notification) {+ _rememberPosition(notification.context, notification.depth);+ return false;+ }++ void _handlePointerSignal(PointerSignalEvent event) {+ if (event is! PointerScrollEvent) return;+ final target = _targetFor(event);+ if (target == null) return;++ GestureBinding.instance.pointerSignalResolver.register(event, (+ resolvedEvent,+ ) {+ if (resolvedEvent is! PointerScrollEvent) return;+ target.position.pointerScroll(target.delta);+ resolvedEvent.respond(allowPlatformDefault: false);+ });+ }++ @override+ Widget build(BuildContext context) {+ return Listener(+ behavior: HitTestBehavior.opaque,+ onPointerSignal: _handlePointerSignal,+ child: NotificationListener<ScrollMetricsNotification>(+ onNotification: _handleMetricsNotification,+ child: NotificationListener<ScrollNotification>(+ onNotification: _handleScrollNotification,+ child: widget.child,+ ),+ ),+ );+ }+}++class _DiscoveredScrollable {+ const _DiscoveredScrollable(this.scrollable, this.depth);++ final ScrollableState scrollable;+ final int depth;+}++class _WheelTarget {+ const _WheelTarget(this.position, this.delta);++ final ScrollPosition position;+ final double delta;+}diff --git a/lib/widgets/rmab_config_sheet.dart b/lib/widgets/rmab_config_sheet.dartindex ef38d44c..ae01bc07 100644--- a/lib/widgets/rmab_config_sheet.dart+++ b/lib/widgets/rmab_config_sheet.dart@@ -9,6 +9,8 @@ import '../l10n/app_localizations.dart';import '../screens/admin_rmab_screen.dart';import '../services/rmab_service.dart';import '../services/scoped_prefs.dart';+import '../utils/desktop_workspace.dart';+import 'adaptive_modal.dart';import 'rmab_request_status_chip.dart';import 'stackable_sheet.dart';@@ -346,7 +348,11 @@ class _RmabConfigSheetState extends State<_RmabConfigSheet> {setState(() => _errorText = l.rmabConfigErrorInvalidUrl);return;}- Navigator.of(context).push(MaterialPageRoute(+ final nav = contentNavigator(context);+ if (isDesktopWorkspace(context)) {+ Navigator.of(context, rootNavigator: true).popUntil((r) => r.isFirst);+ }+ nav.push(MaterialPageRoute(builder: (_) => AdminRmabScreen(url: target),));}@@ -1001,7 +1007,7 @@ class _MyRequestsTabState extends State<_MyRequestsTab>}void _openRequestDetail(RmabRequest req) {- showModalBottomSheet<void>(+ showAdaptiveActionMenu<void>(context: context,isScrollControlled: true,showDragHandle: true,@@ -1009,6 +1015,7 @@ class _MyRequestsTabState extends State<_MyRequestsTab>shape: const RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(24)),),+ desktopWidth: 560,builder: (_) => _RequestDetailSheet(request: req),);}diff --git a/pubspec.lock b/pubspec.lockindex 701e8758..dee53550 100644--- a/pubspec.lock+++ b/pubspec.lock@@ -1376,7 +1376,7 @@ packages:source: hostedversion: "15.0.0"web:- dependency: transitive+ dependency: "direct main"description:name: websha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a"diff --git a/pubspec.yaml b/pubspec.yamlindex 0c52c561..730b60b8 100644--- a/pubspec.yaml+++ b/pubspec.yaml@@ -79,6 +79,7 @@ dependencies:# Log sharingshare_plus: ^10.0.0+ web: ^1.1.1app_links: ^7.2.1qr_flutter: ^4.1.0