Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Add a dedicated Podcasts tab, an episode feed, bottom bar long-press shortcuts, and new episode notifications that download automatically (Android only)

Barnabas5afaff4643bd
diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb
index f405e152..938dd7bf 100644
--- a/lib/l10n/app_en.arb
+++ b/lib/l10n/app_en.arb
@@ -467,6 +467,37 @@
"appShellSettingsTab": "Settings",
"appShellDiscoverTab": "Discover",
"appShellShowsTab": "Shows",
+ "appShellPodcastsTab": "Podcasts",
+ "libraryTabEpisodes": "Episodes",
+ "filterAllEpisodes": "All",
+ "filterUnplayed": "Unplayed",
+ "episodeFeedEmpty": "No episodes match this filter",
+ "settingsPodcastTab": "Podcasts tab",
+ "settingsPodcastTabDesc": "Give one podcast library its own tab in the bottom bar",
+ "settingsPodcastTabLibrary": "Podcasts tab library",
+ "settingsMergeImpliedByPodcastTab": "Always on while the Podcasts tab is enabled",
+ "settingsEpisodeNotifs": "New episode notifications",
+ "settingsEpisodeNotifsDesc": "Check subscribed shows in the background",
+ "notifIntervalOff": "Off",
+ "notifIntervalMinutes": "Every {n} minutes",
+ "@notifIntervalMinutes": {
+ "placeholders": {
+ "n": {
+ "type": "int"
+ }
+ }
+ },
+ "notifIntervalHour": "Every hour",
+ "notifIntervalHours": "Every {n} hours",
+ "@notifIntervalHours": {
+ "placeholders": {
+ "n": {
+ "type": "int"
+ }
+ }
+ },
+ "settingsBatteryUnrestricted": "Allow unrestricted battery use",
+ "settingsBatteryUnrestrictedDesc": "Keeps the system from pausing background checks on some phones",
"appShellPressBackToExit": "Press back again to exit",
"settingsTitle": "Settings",
"sectionAppearance": "Appearance",
diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart
index 7aec6c50..fb7a473d 100644
--- a/lib/l10n/app_localizations.dart
+++ b/lib/l10n/app_localizations.dart
@@ -1750,6 +1750,108 @@ abstract class AppLocalizations {
/// **'Shows'**
String get appShellShowsTab;
+ /// No description provided for @appShellPodcastsTab.
+ ///
+ /// In en, this message translates to:
+ /// **'Podcasts'**
+ String get appShellPodcastsTab;
+
+ /// No description provided for @libraryTabEpisodes.
+ ///
+ /// In en, this message translates to:
+ /// **'Episodes'**
+ String get libraryTabEpisodes;
+
+ /// No description provided for @filterAllEpisodes.
+ ///
+ /// In en, this message translates to:
+ /// **'All'**
+ String get filterAllEpisodes;
+
+ /// No description provided for @filterUnplayed.
+ ///
+ /// In en, this message translates to:
+ /// **'Unplayed'**
+ String get filterUnplayed;
+
+ /// No description provided for @episodeFeedEmpty.
+ ///
+ /// In en, this message translates to:
+ /// **'No episodes match this filter'**
+ String get episodeFeedEmpty;
+
+ /// No description provided for @settingsPodcastTab.
+ ///
+ /// In en, this message translates to:
+ /// **'Podcasts tab'**
+ String get settingsPodcastTab;
+
+ /// No description provided for @settingsPodcastTabDesc.
+ ///
+ /// In en, this message translates to:
+ /// **'Give one podcast library its own tab in the bottom bar'**
+ String get settingsPodcastTabDesc;
+
+ /// No description provided for @settingsPodcastTabLibrary.
+ ///
+ /// In en, this message translates to:
+ /// **'Podcasts tab library'**
+ String get settingsPodcastTabLibrary;
+
+ /// No description provided for @settingsMergeImpliedByPodcastTab.
+ ///
+ /// In en, this message translates to:
+ /// **'Always on while the Podcasts tab is enabled'**
+ String get settingsMergeImpliedByPodcastTab;
+
+ /// No description provided for @settingsEpisodeNotifs.
+ ///
+ /// In en, this message translates to:
+ /// **'New episode notifications'**
+ String get settingsEpisodeNotifs;
+
+ /// No description provided for @settingsEpisodeNotifsDesc.
+ ///
+ /// In en, this message translates to:
+ /// **'Check subscribed shows in the background'**
+ String get settingsEpisodeNotifsDesc;
+
+ /// No description provided for @notifIntervalOff.
+ ///
+ /// In en, this message translates to:
+ /// **'Off'**
+ String get notifIntervalOff;
+
+ /// No description provided for @notifIntervalMinutes.
+ ///
+ /// In en, this message translates to:
+ /// **'Every {n} minutes'**
+ String notifIntervalMinutes(int n);
+
+ /// No description provided for @notifIntervalHour.
+ ///
+ /// In en, this message translates to:
+ /// **'Every hour'**
+ String get notifIntervalHour;
+
+ /// No description provided for @notifIntervalHours.
+ ///
+ /// In en, this message translates to:
+ /// **'Every {n} hours'**
+ String notifIntervalHours(int n);
+
+ /// No description provided for @settingsBatteryUnrestricted.
+ ///
+ /// In en, this message translates to:
+ /// **'Allow unrestricted battery use'**
+ String get settingsBatteryUnrestricted;
+
+ /// No description provided for @settingsBatteryUnrestrictedDesc.
+ ///
+ /// In en, this message translates to:
+ /// **'Keeps the system from pausing background checks on some phones'**
+ String get settingsBatteryUnrestrictedDesc;
+
/// No description provided for @appShellPressBackToExit.
///
/// In en, this message translates to:
diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart
index 00f1fad2..5e79199a 100644
--- a/lib/l10n/app_localizations_de.dart
+++ b/lib/l10n/app_localizations_de.dart
@@ -912,6 +912,65 @@ class AppLocalizationsDe extends AppLocalizations {
@override
String get appShellShowsTab => 'Sendungen';
+ @override
+ String get appShellPodcastsTab => 'Podcasts';
+
+ @override
+ String get libraryTabEpisodes => 'Episodes';
+
+ @override
+ String get filterAllEpisodes => 'All';
+
+ @override
+ String get filterUnplayed => 'Unplayed';
+
+ @override
+ String get episodeFeedEmpty => 'No episodes match this filter';
+
+ @override
+ String get settingsPodcastTab => 'Podcasts tab';
+
+ @override
+ String get settingsPodcastTabDesc =>
+ 'Give one podcast library its own tab in the bottom bar';
+
+ @override
+ String get settingsPodcastTabLibrary => 'Podcasts tab library';
+
+ @override
+ String get settingsMergeImpliedByPodcastTab =>
+ 'Always on while the Podcasts tab is enabled';
+
+ @override
+ String get settingsEpisodeNotifs => 'New episode notifications';
+
+ @override
+ String get settingsEpisodeNotifsDesc =>
+ 'Check subscribed shows in the background';
+
+ @override
+ String get notifIntervalOff => 'Off';
+
+ @override
+ String notifIntervalMinutes(int n) {
+ return 'Every $n minutes';
+ }
+
+ @override
+ String get notifIntervalHour => 'Every hour';
+
+ @override
+ String notifIntervalHours(int n) {
+ return 'Every $n hours';
+ }
+
+ @override
+ String get settingsBatteryUnrestricted => 'Allow unrestricted battery use';
+
+ @override
+ String get settingsBatteryUnrestrictedDesc =>
+ 'Keeps the system from pausing background checks on some phones';
+
@override
String get appShellPressBackToExit => 'Erneut zurück drücken zum Beenden';
diff --git a/lib/l10n/app_localizations_el.dart b/lib/l10n/app_localizations_el.dart
index a6ba576d..0547569d 100644
--- a/lib/l10n/app_localizations_el.dart
+++ b/lib/l10n/app_localizations_el.dart
@@ -907,6 +907,65 @@ class AppLocalizationsEl extends AppLocalizations {
@override
String get appShellShowsTab => 'Shows';
+ @override
+ String get appShellPodcastsTab => 'Podcasts';
+
+ @override
+ String get libraryTabEpisodes => 'Episodes';
+
+ @override
+ String get filterAllEpisodes => 'All';
+
+ @override
+ String get filterUnplayed => 'Unplayed';
+
+ @override
+ String get episodeFeedEmpty => 'No episodes match this filter';
+
+ @override
+ String get settingsPodcastTab => 'Podcasts tab';
+
+ @override
+ String get settingsPodcastTabDesc =>
+ 'Give one podcast library its own tab in the bottom bar';
+
+ @override
+ String get settingsPodcastTabLibrary => 'Podcasts tab library';
+
+ @override
+ String get settingsMergeImpliedByPodcastTab =>
+ 'Always on while the Podcasts tab is enabled';
+
+ @override
+ String get settingsEpisodeNotifs => 'New episode notifications';
+
+ @override
+ String get settingsEpisodeNotifsDesc =>
+ 'Check subscribed shows in the background';
+
+ @override
+ String get notifIntervalOff => 'Off';
+
+ @override
+ String notifIntervalMinutes(int n) {
+ return 'Every $n minutes';
+ }
+
+ @override
+ String get notifIntervalHour => 'Every hour';
+
+ @override
+ String notifIntervalHours(int n) {
+ return 'Every $n hours';
+ }
+
+ @override
+ String get settingsBatteryUnrestricted => 'Allow unrestricted battery use';
+
+ @override
+ String get settingsBatteryUnrestrictedDesc =>
+ 'Keeps the system from pausing background checks on some phones';
+
@override
String get appShellPressBackToExit => 'Press back again to exit';
diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart
index b880068b..2b321886 100644
--- a/lib/l10n/app_localizations_en.dart
+++ b/lib/l10n/app_localizations_en.dart
@@ -907,6 +907,65 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get appShellShowsTab => 'Shows';
+ @override
+ String get appShellPodcastsTab => 'Podcasts';
+
+ @override
+ String get libraryTabEpisodes => 'Episodes';
+
+ @override
+ String get filterAllEpisodes => 'All';
+
+ @override
+ String get filterUnplayed => 'Unplayed';
+
+ @override
+ String get episodeFeedEmpty => 'No episodes match this filter';
+
+ @override
+ String get settingsPodcastTab => 'Podcasts tab';
+
+ @override
+ String get settingsPodcastTabDesc =>
+ 'Give one podcast library its own tab in the bottom bar';
+
+ @override
+ String get settingsPodcastTabLibrary => 'Podcasts tab library';
+
+ @override
+ String get settingsMergeImpliedByPodcastTab =>
+ 'Always on while the Podcasts tab is enabled';
+
+ @override
+ String get settingsEpisodeNotifs => 'New episode notifications';
+
+ @override
+ String get settingsEpisodeNotifsDesc =>
+ 'Check subscribed shows in the background';
+
+ @override
+ String get notifIntervalOff => 'Off';
+
+ @override
+ String notifIntervalMinutes(int n) {
+ return 'Every $n minutes';
+ }
+
+ @override
+ String get notifIntervalHour => 'Every hour';
+
+ @override
+ String notifIntervalHours(int n) {
+ return 'Every $n hours';
+ }
+
+ @override
+ String get settingsBatteryUnrestricted => 'Allow unrestricted battery use';
+
+ @override
+ String get settingsBatteryUnrestrictedDesc =>
+ 'Keeps the system from pausing background checks on some phones';
+
@override
String get appShellPressBackToExit => 'Press back again to exit';
diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart
index 69384720..3a771bad 100644
--- a/lib/l10n/app_localizations_es.dart
+++ b/lib/l10n/app_localizations_es.dart
@@ -907,6 +907,65 @@ class AppLocalizationsEs extends AppLocalizations {
@override
String get appShellShowsTab => 'Shows';
+ @override
+ String get appShellPodcastsTab => 'Podcasts';
+
+ @override
+ String get libraryTabEpisodes => 'Episodes';
+
+ @override
+ String get filterAllEpisodes => 'All';
+
+ @override
+ String get filterUnplayed => 'Unplayed';
+
+ @override
+ String get episodeFeedEmpty => 'No episodes match this filter';
+
+ @override
+ String get settingsPodcastTab => 'Podcasts tab';
+
+ @override
+ String get settingsPodcastTabDesc =>
+ 'Give one podcast library its own tab in the bottom bar';
+
+ @override
+ String get settingsPodcastTabLibrary => 'Podcasts tab library';
+
+ @override
+ String get settingsMergeImpliedByPodcastTab =>
+ 'Always on while the Podcasts tab is enabled';
+
+ @override
+ String get settingsEpisodeNotifs => 'New episode notifications';
+
+ @override
+ String get settingsEpisodeNotifsDesc =>
+ 'Check subscribed shows in the background';
+
+ @override
+ String get notifIntervalOff => 'Off';
+
+ @override
+ String notifIntervalMinutes(int n) {
+ return 'Every $n minutes';
+ }
+
+ @override
+ String get notifIntervalHour => 'Every hour';
+
+ @override
+ String notifIntervalHours(int n) {
+ return 'Every $n hours';
+ }
+
+ @override
+ String get settingsBatteryUnrestricted => 'Allow unrestricted battery use';
+
+ @override
+ String get settingsBatteryUnrestrictedDesc =>
+ 'Keeps the system from pausing background checks on some phones';
+
@override
String get appShellPressBackToExit => 'Press back again to exit';
diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart
index 1a5220e5..f64e4044 100644
--- a/lib/l10n/app_localizations_fr.dart
+++ b/lib/l10n/app_localizations_fr.dart
@@ -909,6 +909,65 @@ class AppLocalizationsFr extends AppLocalizations {
@override
String get appShellShowsTab => 'Shows';
+ @override
+ String get appShellPodcastsTab => 'Podcasts';
+
+ @override
+ String get libraryTabEpisodes => 'Episodes';
+
+ @override
+ String get filterAllEpisodes => 'All';
+
+ @override
+ String get filterUnplayed => 'Unplayed';
+
+ @override
+ String get episodeFeedEmpty => 'No episodes match this filter';
+
+ @override
+ String get settingsPodcastTab => 'Podcasts tab';
+
+ @override
+ String get settingsPodcastTabDesc =>
+ 'Give one podcast library its own tab in the bottom bar';
+
+ @override
+ String get settingsPodcastTabLibrary => 'Podcasts tab library';
+
+ @override
+ String get settingsMergeImpliedByPodcastTab =>
+ 'Always on while the Podcasts tab is enabled';
+
+ @override
+ String get settingsEpisodeNotifs => 'New episode notifications';
+
+ @override
+ String get settingsEpisodeNotifsDesc =>
+ 'Check subscribed shows in the background';
+
+ @override
+ String get notifIntervalOff => 'Off';
+
+ @override
+ String notifIntervalMinutes(int n) {
+ return 'Every $n minutes';
+ }
+
+ @override
+ String get notifIntervalHour => 'Every hour';
+
+ @override
+ String notifIntervalHours(int n) {
+ return 'Every $n hours';
+ }
+
+ @override
+ String get settingsBatteryUnrestricted => 'Allow unrestricted battery use';
+
+ @override
+ String get settingsBatteryUnrestrictedDesc =>
+ 'Keeps the system from pausing background checks on some phones';
+
@override
String get appShellPressBackToExit => 'Press back again to exit';
diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart
index 56ac08af..ad55d18a 100644
--- a/lib/l10n/app_localizations_it.dart
+++ b/lib/l10n/app_localizations_it.dart
@@ -907,6 +907,65 @@ class AppLocalizationsIt extends AppLocalizations {
@override
String get appShellShowsTab => 'Shows';
+ @override
+ String get appShellPodcastsTab => 'Podcasts';
+
+ @override
+ String get libraryTabEpisodes => 'Episodes';
+
+ @override
+ String get filterAllEpisodes => 'All';
+
+ @override
+ String get filterUnplayed => 'Unplayed';
+
+ @override
+ String get episodeFeedEmpty => 'No episodes match this filter';
+
+ @override
+ String get settingsPodcastTab => 'Podcasts tab';
+
+ @override
+ String get settingsPodcastTabDesc =>
+ 'Give one podcast library its own tab in the bottom bar';
+
+ @override
+ String get settingsPodcastTabLibrary => 'Podcasts tab library';
+
+ @override
+ String get settingsMergeImpliedByPodcastTab =>
+ 'Always on while the Podcasts tab is enabled';
+
+ @override
+ String get settingsEpisodeNotifs => 'New episode notifications';
+
+ @override
+ String get settingsEpisodeNotifsDesc =>
+ 'Check subscribed shows in the background';
+
+ @override
+ String get notifIntervalOff => 'Off';
+
+ @override
+ String notifIntervalMinutes(int n) {
+ return 'Every $n minutes';
+ }
+
+ @override
+ String get notifIntervalHour => 'Every hour';
+
+ @override
+ String notifIntervalHours(int n) {
+ return 'Every $n hours';
+ }
+
+ @override
+ String get settingsBatteryUnrestricted => 'Allow unrestricted battery use';
+
+ @override
+ String get settingsBatteryUnrestrictedDesc =>
+ 'Keeps the system from pausing background checks on some phones';
+
@override
String get appShellPressBackToExit => 'Press back again to exit';
diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart
index a7c14b75..8c1bc29b 100644
--- a/lib/l10n/app_localizations_ja.dart
+++ b/lib/l10n/app_localizations_ja.dart
@@ -907,6 +907,65 @@ class AppLocalizationsJa extends AppLocalizations {
@override
String get appShellShowsTab => 'Shows';
+ @override
+ String get appShellPodcastsTab => 'Podcasts';
+
+ @override
+ String get libraryTabEpisodes => 'Episodes';
+
+ @override
+ String get filterAllEpisodes => 'All';
+
+ @override
+ String get filterUnplayed => 'Unplayed';
+
+ @override
+ String get episodeFeedEmpty => 'No episodes match this filter';
+
+ @override
+ String get settingsPodcastTab => 'Podcasts tab';
+
+ @override
+ String get settingsPodcastTabDesc =>
+ 'Give one podcast library its own tab in the bottom bar';
+
+ @override
+ String get settingsPodcastTabLibrary => 'Podcasts tab library';
+
+ @override
+ String get settingsMergeImpliedByPodcastTab =>
+ 'Always on while the Podcasts tab is enabled';
+
+ @override
+ String get settingsEpisodeNotifs => 'New episode notifications';
+
+ @override
+ String get settingsEpisodeNotifsDesc =>
+ 'Check subscribed shows in the background';
+
+ @override
+ String get notifIntervalOff => 'Off';
+
+ @override
+ String notifIntervalMinutes(int n) {
+ return 'Every $n minutes';
+ }
+
+ @override
+ String get notifIntervalHour => 'Every hour';
+
+ @override
+ String notifIntervalHours(int n) {
+ return 'Every $n hours';
+ }
+
+ @override
+ String get settingsBatteryUnrestricted => 'Allow unrestricted battery use';
+
+ @override
+ String get settingsBatteryUnrestrictedDesc =>
+ 'Keeps the system from pausing background checks on some phones';
+
@override
String get appShellPressBackToExit => 'Press back again to exit';
diff --git a/lib/l10n/app_localizations_no.dart b/lib/l10n/app_localizations_no.dart
index bfe94733..ea26b0a7 100644
--- a/lib/l10n/app_localizations_no.dart
+++ b/lib/l10n/app_localizations_no.dart
@@ -907,6 +907,65 @@ class AppLocalizationsNo extends AppLocalizations {
@override
String get appShellShowsTab => 'Shows';
+ @override
+ String get appShellPodcastsTab => 'Podcasts';
+
+ @override
+ String get libraryTabEpisodes => 'Episodes';
+
+ @override
+ String get filterAllEpisodes => 'All';
+
+ @override
+ String get filterUnplayed => 'Unplayed';
+
+ @override
+ String get episodeFeedEmpty => 'No episodes match this filter';
+
+ @override
+ String get settingsPodcastTab => 'Podcasts tab';
+
+ @override
+ String get settingsPodcastTabDesc =>
+ 'Give one podcast library its own tab in the bottom bar';
+
+ @override
+ String get settingsPodcastTabLibrary => 'Podcasts tab library';
+
+ @override
+ String get settingsMergeImpliedByPodcastTab =>
+ 'Always on while the Podcasts tab is enabled';
+
+ @override
+ String get settingsEpisodeNotifs => 'New episode notifications';
+
+ @override
+ String get settingsEpisodeNotifsDesc =>
+ 'Check subscribed shows in the background';
+
+ @override
+ String get notifIntervalOff => 'Off';
+
+ @override
+ String notifIntervalMinutes(int n) {
+ return 'Every $n minutes';
+ }
+
+ @override
+ String get notifIntervalHour => 'Every hour';
+
+ @override
+ String notifIntervalHours(int n) {
+ return 'Every $n hours';
+ }
+
+ @override
+ String get settingsBatteryUnrestricted => 'Allow unrestricted battery use';
+
+ @override
+ String get settingsBatteryUnrestrictedDesc =>
+ 'Keeps the system from pausing background checks on some phones';
+
@override
String get appShellPressBackToExit => 'Press back again to exit';
diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart
index 9617136c..3b092a7d 100644
--- a/lib/l10n/app_localizations_pt.dart
+++ b/lib/l10n/app_localizations_pt.dart
@@ -907,6 +907,65 @@ class AppLocalizationsPt extends AppLocalizations {
@override
String get appShellShowsTab => 'Shows';
+ @override
+ String get appShellPodcastsTab => 'Podcasts';
+
+ @override
+ String get libraryTabEpisodes => 'Episodes';
+
+ @override
+ String get filterAllEpisodes => 'All';
+
+ @override
+ String get filterUnplayed => 'Unplayed';
+
+ @override
+ String get episodeFeedEmpty => 'No episodes match this filter';
+
+ @override
+ String get settingsPodcastTab => 'Podcasts tab';
+
+ @override
+ String get settingsPodcastTabDesc =>
+ 'Give one podcast library its own tab in the bottom bar';
+
+ @override
+ String get settingsPodcastTabLibrary => 'Podcasts tab library';
+
+ @override
+ String get settingsMergeImpliedByPodcastTab =>
+ 'Always on while the Podcasts tab is enabled';
+
+ @override
+ String get settingsEpisodeNotifs => 'New episode notifications';
+
+ @override
+ String get settingsEpisodeNotifsDesc =>
+ 'Check subscribed shows in the background';
+
+ @override
+ String get notifIntervalOff => 'Off';
+
+ @override
+ String notifIntervalMinutes(int n) {
+ return 'Every $n minutes';
+ }
+
+ @override
+ String get notifIntervalHour => 'Every hour';
+
+ @override
+ String notifIntervalHours(int n) {
+ return 'Every $n hours';
+ }
+
+ @override
+ String get settingsBatteryUnrestricted => 'Allow unrestricted battery use';
+
+ @override
+ String get settingsBatteryUnrestrictedDesc =>
+ 'Keeps the system from pausing background checks on some phones';
+
@override
String get appShellPressBackToExit => 'Press back again to exit';
diff --git a/lib/l10n/app_localizations_ro.dart b/lib/l10n/app_localizations_ro.dart
index c6cde879..3a09fbe1 100644
--- a/lib/l10n/app_localizations_ro.dart
+++ b/lib/l10n/app_localizations_ro.dart
@@ -907,6 +907,65 @@ class AppLocalizationsRo extends AppLocalizations {
@override
String get appShellShowsTab => 'Shows';
+ @override
+ String get appShellPodcastsTab => 'Podcasts';
+
+ @override
+ String get libraryTabEpisodes => 'Episodes';
+
+ @override
+ String get filterAllEpisodes => 'All';
+
+ @override
+ String get filterUnplayed => 'Unplayed';
+
+ @override
+ String get episodeFeedEmpty => 'No episodes match this filter';
+
+ @override
+ String get settingsPodcastTab => 'Podcasts tab';
+
+ @override
+ String get settingsPodcastTabDesc =>
+ 'Give one podcast library its own tab in the bottom bar';
+
+ @override
+ String get settingsPodcastTabLibrary => 'Podcasts tab library';
+
+ @override
+ String get settingsMergeImpliedByPodcastTab =>
+ 'Always on while the Podcasts tab is enabled';
+
+ @override
+ String get settingsEpisodeNotifs => 'New episode notifications';
+
+ @override
+ String get settingsEpisodeNotifsDesc =>
+ 'Check subscribed shows in the background';
+
+ @override
+ String get notifIntervalOff => 'Off';
+
+ @override
+ String notifIntervalMinutes(int n) {
+ return 'Every $n minutes';
+ }
+
+ @override
+ String get notifIntervalHour => 'Every hour';
+
+ @override
+ String notifIntervalHours(int n) {
+ return 'Every $n hours';
+ }
+
+ @override
+ String get settingsBatteryUnrestricted => 'Allow unrestricted battery use';
+
+ @override
+ String get settingsBatteryUnrestrictedDesc =>
+ 'Keeps the system from pausing background checks on some phones';
+
@override
String get appShellPressBackToExit => 'Press back again to exit';
diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart
index dccd2e96..fcdeb73c 100644
--- a/lib/l10n/app_localizations_ru.dart
+++ b/lib/l10n/app_localizations_ru.dart
@@ -908,6 +908,65 @@ class AppLocalizationsRu extends AppLocalizations {
@override
String get appShellShowsTab => 'Shows';
+ @override
+ String get appShellPodcastsTab => 'Podcasts';
+
+ @override
+ String get libraryTabEpisodes => 'Episodes';
+
+ @override
+ String get filterAllEpisodes => 'All';
+
+ @override
+ String get filterUnplayed => 'Unplayed';
+
+ @override
+ String get episodeFeedEmpty => 'No episodes match this filter';
+
+ @override
+ String get settingsPodcastTab => 'Podcasts tab';
+
+ @override
+ String get settingsPodcastTabDesc =>
+ 'Give one podcast library its own tab in the bottom bar';
+
+ @override
+ String get settingsPodcastTabLibrary => 'Podcasts tab library';
+
+ @override
+ String get settingsMergeImpliedByPodcastTab =>
+ 'Always on while the Podcasts tab is enabled';
+
+ @override
+ String get settingsEpisodeNotifs => 'New episode notifications';
+
+ @override
+ String get settingsEpisodeNotifsDesc =>
+ 'Check subscribed shows in the background';
+
+ @override
+ String get notifIntervalOff => 'Off';
+
+ @override
+ String notifIntervalMinutes(int n) {
+ return 'Every $n minutes';
+ }
+
+ @override
+ String get notifIntervalHour => 'Every hour';
+
+ @override
+ String notifIntervalHours(int n) {
+ return 'Every $n hours';
+ }
+
+ @override
+ String get settingsBatteryUnrestricted => 'Allow unrestricted battery use';
+
+ @override
+ String get settingsBatteryUnrestrictedDesc =>
+ 'Keeps the system from pausing background checks on some phones';
+
@override
String get appShellPressBackToExit => 'Нажмите «Назад» ещё раз, чтобы выйти';
diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart
index d8fb8ec0..265303c6 100644
--- a/lib/l10n/app_localizations_zh.dart
+++ b/lib/l10n/app_localizations_zh.dart
@@ -896,6 +896,65 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get appShellShowsTab => '节目';
+ @override
+ String get appShellPodcastsTab => 'Podcasts';
+
+ @override
+ String get libraryTabEpisodes => 'Episodes';
+
+ @override
+ String get filterAllEpisodes => 'All';
+
+ @override
+ String get filterUnplayed => 'Unplayed';
+
+ @override
+ String get episodeFeedEmpty => 'No episodes match this filter';
+
+ @override
+ String get settingsPodcastTab => 'Podcasts tab';
+
+ @override
+ String get settingsPodcastTabDesc =>
+ 'Give one podcast library its own tab in the bottom bar';
+
+ @override
+ String get settingsPodcastTabLibrary => 'Podcasts tab library';
+
+ @override
+ String get settingsMergeImpliedByPodcastTab =>
+ 'Always on while the Podcasts tab is enabled';
+
+ @override
+ String get settingsEpisodeNotifs => 'New episode notifications';
+
+ @override
+ String get settingsEpisodeNotifsDesc =>
+ 'Check subscribed shows in the background';
+
+ @override
+ String get notifIntervalOff => 'Off';
+
+ @override
+ String notifIntervalMinutes(int n) {
+ return 'Every $n minutes';
+ }
+
+ @override
+ String get notifIntervalHour => 'Every hour';
+
+ @override
+ String notifIntervalHours(int n) {
+ return 'Every $n hours';
+ }
+
+ @override
+ String get settingsBatteryUnrestricted => 'Allow unrestricted battery use';
+
+ @override
+ String get settingsBatteryUnrestrictedDesc =>
+ 'Keeps the system from pausing background checks on some phones';
+
@override
String get appShellPressBackToExit => '再按一次返回键退出';
diff --git a/lib/main.dart b/lib/main.dart
index 7d0324a2..220e4f62 100644
--- a/lib/main.dart
+++ b/lib/main.dart
@@ -29,6 +29,7 @@ import 'services/user_account_service.dart';
import 'services/android_auto_service.dart';
import 'services/carplay_service.dart';
import 'services/chromecast_service.dart';
+import 'services/episode_notification_service.dart';
import 'services/home_widget_service.dart';
import 'services/log_service.dart';
import 'services/quick_actions_service.dart';
@@ -560,6 +561,10 @@ class _AuthGateState extends State<AuthGate> {
try {
await applyOrientationLock();
} catch (_) {}
+ // Background new-episode notifications: re-register the periodic job
+ // (self-healing after OEM kills) and wire up notification taps.
+ EpisodeNotificationService.syncRegistration();
+ EpisodeNotificationService.initTapHandling();
// Restore cover seed color
{
final seedInt = await PlayerSettings.getCoverSeedColor();
diff --git a/lib/providers/_lp_core.dart b/lib/providers/_lp_core.dart
index 2040e417..6fbc7939 100644
--- a/lib/providers/_lp_core.dart
+++ b/lib/providers/_lp_core.dart
@@ -654,20 +654,48 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
void _buildProgressMap(AuthProvider auth) {
_progressMap = {};
- final userJson = auth.userJson;
- if (userJson == null) return;
- final progressList = userJson['mediaProgress'] as List<dynamic>?;
- if (progressList == null) return;
- for (final mp in progressList) {
- if (mp is Map<String, dynamic>) {
- final itemId = mp['libraryItemId'] as String?;
- final episodeId = mp['episodeId'] as String?;
- if (itemId != null) {
- final key = episodeId != null ? '$itemId-$episodeId' : itemId;
- _progressMap[key] = mp;
+ final progressList = auth.userJson?['mediaProgress'] as List<dynamic>?;
+ if (progressList != null) {
+ for (final mp in progressList) {
+ if (mp is Map<String, dynamic>) {
+ final itemId = mp['libraryItemId'] as String?;
+ final episodeId = mp['episodeId'] as String?;
+ if (itemId != null) {
+ final key = episodeId != null ? '$itemId-$episodeId' : itemId;
+ _progressMap[key] = mp;
+ }
}
}
}
+ // Overlay queued-offline ebook positions (their PATCH never landed), so a
+ // cold start can't resume the reader behind the last page read offline.
+ _overlayPendingEbookProgress();
+ }
+
+ // Once overlaid here, the position lives in _progressMap like any local
+ // write, so _refreshProgress's furthest-wins snapshot carries it forward.
+ Future<void> _overlayPendingEbookProgress() async {
+ final pending = await ProgressSyncService().getPendingEbookProgress();
+ if (pending.isEmpty) return;
+ var changed = false;
+ for (final entry in pending.entries) {
+ final loc = entry.value['loc'] as String?;
+ final prog = (entry.value['prog'] as num?)?.toDouble() ?? 0;
+ if (loc == null) continue;
+ // Furthest wins, same rule as _refreshProgress: a fresher server
+ // position (read on another device) stays.
+ final serverProg =
+ (_progressMap[entry.key]?['ebookProgress'] as num?)?.toDouble() ?? -1;
+ if (prog >= serverProg) {
+ _progressMap[entry.key] = {
+ ...?_progressMap[entry.key],
+ 'ebookLocation': loc,
+ 'ebookProgress': prog.clamp(0.0, 1.0),
+ };
+ changed = true;
+ }
+ }
+ if (changed) notifyListeners();
}
Future<void> _refreshProgress() async {
@@ -1278,12 +1306,15 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
return;
}
- if (!force &&
- _lastPersonalizedFetchAt != null &&
- _lastPersonalizedFetchLibraryId == _selectedLibraryId &&
- DateTime.now().difference(_lastPersonalizedFetchAt!) <
- _StateMixin._personalizedFetchCooldown) {
- return;
+ // Per-library cooldown, so a book <-> podcast tab flip that returns
+ // within the window reuses the cached sections instead of refetching.
+ if (!force) {
+ final fetchedAt = _sectionsFetchedAt[_selectedLibraryId];
+ if (fetchedAt != null &&
+ DateTime.now().difference(fetchedAt) <
+ _StateMixin._personalizedFetchCooldown) {
+ return;
+ }
}
final inFlight = _doLoadPersonalizedView();
@@ -1336,6 +1367,10 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
_injectDownloadedSection();
+ // Snapshot after injection so a tab flip restores the full shelf set.
+ _sectionsByLibrary[_selectedLibraryId!] = _personalizedSections;
+ _sectionsFetchedAt[_selectedLibraryId!] = DateTime.now();
+
if (isPodcastLibrary) {
_hydrateRssFeedFieldsDeferred();
}
diff --git a/lib/providers/_lp_state.dart b/lib/providers/_lp_state.dart
index 4ff6dff5..eb5459e3 100644
--- a/lib/providers/_lp_state.dart
+++ b/lib/providers/_lp_state.dart
@@ -24,6 +24,13 @@ mixin _StateMixin on ChangeNotifier {
final Map<String, int> _pendingUnfinishedDeltas = {};
final Map<String, (int, int)> _unfinishedCountAdjustments = {};
+ /// Personalized sections cached per library, so tab-driven flips between
+ /// the book library and the dedicated Podcasts tab restore instantly
+ /// instead of blanking and refetching. Refreshed through the normal
+ /// loadPersonalizedView path.
+ final Map<String, List<dynamic>> _sectionsByLibrary = {};
+ final Map<String, DateTime> _sectionsFetchedAt = {};
+
Future<void>? _personalizedInFlight;
Future<void>? _progressShelvesInFlight;
DateTime? _lastPersonalizedFetchAt;
diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dart
index 6ebc0338..8d1a778e 100644
--- a/lib/providers/library_provider.dart
+++ b/lib/providers/library_provider.dart
@@ -318,6 +318,7 @@ class LibraryProvider extends ChangeNotifier
_playlists = [];
_collections = [];
await ScopedPrefs.setString('last_selected_library', libraryId);
+ await _rememberBookLibrary(libraryId);
await _loadSectionPrefs();
notifyListeners();
await loadPersonalizedView(force: true);
@@ -325,6 +326,56 @@ class LibraryProvider extends ChangeNotifier
CarPlayService().refreshTemplates();
}
+ /// Library switch for the dedicated Podcasts tab flips. Never stops
+ /// playback, restores cached sections instantly and only refetches once
+ /// the per-library cooldown expires - picker-driven switches keep using
+ /// [selectLibrary] (full refresh).
+ Future<void> selectLibraryLight(String libraryId) async {
+ if (libraryId == _selectedLibraryId) return;
+ _selectedLibraryId = libraryId;
+ _series = [];
+ _playlists = [];
+ _collections = [];
+ _personalizedSections = _sectionsByLibrary[libraryId] ?? [];
+ await ScopedPrefs.setString('last_selected_library', libraryId);
+ await _rememberBookLibrary(libraryId);
+ await _loadSectionPrefs();
+ notifyListeners();
+ await loadPersonalizedView();
+ AndroidAutoService().refresh(force: true);
+ CarPlayService().refreshTemplates();
+ }
+
+ bool isPodcastLibraryId(String libraryId) {
+ final library = _libraries.firstWhere(
+ (l) => l['id'] == libraryId,
+ orElse: () => null,
+ );
+ if (library is! Map<String, dynamic>) return false;
+ return (library['mediaType'] as String? ?? 'book') == 'podcast';
+ }
+
+ /// Track the last non-podcast library so the Home/Library tabs know where
+ /// to return when leaving the dedicated Podcasts tab.
+ Future<void> _rememberBookLibrary(String libraryId) async {
+ if (!isPodcastLibraryId(libraryId)) {
+ await ScopedPrefs.setString('last_book_library', libraryId);
+ }
+ }
+
+ /// The library the Home/Library tabs should show: the last-used book
+ /// library, or the first non-podcast library as a fallback.
+ Future<String?> lastBookLibraryId() async {
+ final saved = await ScopedPrefs.getString('last_book_library');
+ if (saved != null && _libraries.any((l) => l['id'] == saved)) return saved;
+ for (final l in _libraries) {
+ if ((l['mediaType'] as String? ?? 'book') != 'podcast') {
+ return l['id'] as String?;
+ }
+ }
+ return null;
+ }
+
Future<void> refresh() async {
if (isOffline) {
diff --git a/lib/screens/app_shell.dart b/lib/screens/app_shell.dart
index b1085ec2..bbdad814 100644
--- a/lib/screens/app_shell.dart
+++ b/lib/screens/app_shell.dart
@@ -25,6 +25,7 @@ import 'home_screen.dart';
import 'library_screen.dart';
import 'stats_screen.dart';
import 'settings_screen.dart';
+import '../widgets/library_picker_sheet.dart';
import '../widgets/welcome_sheet.dart';
import '../services/review_service.dart';
import '../services/update_checker_service.dart';
@@ -72,7 +73,8 @@ class AppShell extends StatefulWidget {
_applyLibraryFilterGlobal((s) => s.applyGenreFilter(genre));
static bool _applyLibraryFilterGlobal(
- void Function(LibraryScreenState) apply) {
+ void Function(LibraryScreenState) apply,
+ ) {
final inst = _AppShellState._instance;
if (inst == null) return false;
// If the full-screen expanded player is on top of the shell, pop it
@@ -102,6 +104,7 @@ class AppShell extends StatefulWidget {
WidgetsBinding.instance.addPostFrameCallback((_) => tryApply());
}
}
+
WidgetsBinding.instance.addPostFrameCallback((_) => tryApply());
return true;
}
@@ -120,11 +123,19 @@ class AppShell extends StatefulWidget {
State<AppShell> createState() => _AppShellState();
}
-class _AppShellState extends State<AppShell> with WidgetsBindingObserver, TickerProviderStateMixin {
+class _AppShellState extends State<AppShell>
+ with WidgetsBindingObserver, TickerProviderStateMixin {
static _AppShellState? _instance;
// Tabs: 0=Home, 1=Library, 2=Absorbing (default), 3=Stats, 4=Settings
int _currentIndex = 2; // overridden by user preference in initState
+
+ // Dedicated Podcasts tab (optional 6th destination, display order Home,
+ // Library, Podcasts, Absorbing, Stats, Settings). Stack pages keep their
+ // historic 0-4 indexes: the Podcasts and Library destinations share page 1,
+ // and which one is highlighted is derived from the selected library.
+ bool _podcastTabEnabled = false;
+ String _podcastTabLibraryId = '';
final _homeKey = GlobalKey<HomeScreenState>();
final _libraryKey = GlobalKey<LibraryScreenState>();
final _player = AudioPlayerService();
@@ -136,7 +147,8 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver, Ticker
bool _expandedIsOpen = false;
bool _wasCasting = false;
DateTime? _lastBackPress;
- String? _lastCoverItemId; // tracks which item's cover we derived the scheme from
+ // Tracks which item's cover we derived the scheme from.
+ String? _lastCoverItemId;
// ── Scroll-to-hide bottom nav (driven by Library screen) ──
late final AnimationController _navBarAnimController = AnimationController(
@@ -174,6 +186,7 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver, Ticker
WidgetsBinding.instance.addPostFrameCallback((_) => tryFocus());
}
}
+
WidgetsBinding.instance.addPostFrameCallback((_) => tryFocus());
}
@@ -312,7 +325,9 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver, Ticker
_wasPlaying = _player.isPlaying;
_lastItemId = _player.currentItemId;
WidgetsBinding.instance.addObserver(this);
- AudioPlayerService.setOnEpisodePlayStartedCallback(AppShell.goToAbsorbingGlobal);
+ AudioPlayerService.setOnEpisodePlayStartedCallback(
+ AppShell.goToAbsorbingGlobal,
+ );
_player.addListener(_onPlayerChanged);
_wasCasting = _cast.isCasting;
_cast.addListener(_onCastChanged);
@@ -323,16 +338,76 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver, Ticker
if (mounted) _deriveCoverScheme();
});
context.read<LibraryProvider>().addListener(_onLibraryChanged);
+ _loadPodcastTabPrefs();
+ PlayerSettings.settingsChanged.addListener(_loadPodcastTabPrefs);
WelcomeSheet.showIfNeeded(context);
_checkForUpdate();
}
+ Future<void> _loadPodcastTabPrefs() async {
+ final enabled = await PlayerSettings.getPodcastTabEnabled();
+ final libId = await PlayerSettings.getPodcastTabLibraryId();
+ if (!mounted) return;
+ if (enabled != _podcastTabEnabled || libId != _podcastTabLibraryId) {
+ setState(() {
+ _podcastTabEnabled = enabled;
+ _podcastTabLibraryId = libId;
+ });
+ }
+ }
+
+ bool _podcastsShown(LibraryProvider lib) =>
+ _podcastTabEnabled &&
+ _podcastTabLibraryId.isNotEmpty &&
+ lib.libraries.any((l) => l['id'] == _podcastTabLibraryId);
+
+ // Display-destination index <-> stack page mapping when the Podcasts tab
+ // is shown (it sits at display slot 2 and shares stack page 1).
+ int _pageForDest(int dest, bool podcastsShown) {
+ if (!podcastsShown) return dest;
+ if (dest <= 1) return dest;
+ if (dest == 2) return 1;
+ return dest - 1;
+ }
+
+ int _selectedDest(LibraryProvider lib, bool podcastsShown) {
+ if (!podcastsShown) return _currentIndex;
+ if (_currentIndex == 0) return 0;
+ if (_currentIndex == 1) {
+ return lib.selectedLibraryId == _podcastTabLibraryId ? 2 : 1;
+ }
+ return _currentIndex + 1;
+ }
+
+ /// Keep the selected library in step with the destination being entered:
+ /// Podcasts pins its library; Home/Library return to the remembered book
+ /// library. Uses the light switch so playback and cached shelves survive.
+ void _syncTabLibrary(int dest, bool podcastsShown) {
+ if (!podcastsShown) return;
+ final lib = context.read<LibraryProvider>();
+ if (dest == 2) {
+ if (lib.selectedLibraryId != _podcastTabLibraryId) {
+ lib.selectLibraryLight(_podcastTabLibraryId);
+ }
+ } else if (dest == 0 || dest == 1) {
+ if (lib.selectedLibraryId == _podcastTabLibraryId) {
+ lib.lastBookLibraryId().then((bookLib) {
+ if (mounted && bookLib != null && bookLib != _podcastTabLibraryId) {
+ lib.selectLibraryLight(bookLib);
+ }
+ });
+ }
+ }
+ }
+
static const _isGithubBuild = bool.fromEnvironment('GITHUB_BUILD');
void _checkForUpdate() async {
if (!_isGithubBuild) return;
final includePreReleases = await PlayerSettings.getIncludePreReleases();
- final info = await UpdateCheckerService.check(includePreReleases: includePreReleases);
+ final info = await UpdateCheckerService.check(
+ includePreReleases: includePreReleases,
+ );
if (info == null || !mounted) return;
await UpdateDialog.show(context, info);
}
@@ -344,7 +419,10 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver, Ticker
_navBarAnimController.dispose();
_player.removeListener(_onPlayerChanged);
_cast.removeListener(_onCastChanged);
- try { context.read<LibraryProvider>().removeListener(_onLibraryChanged); } catch (_) {}
+ PlayerSettings.settingsChanged.removeListener(_loadPodcastTabPrefs);
+ try {
+ context.read<LibraryProvider>().removeListener(_onLibraryChanged);
+ } catch (_) {}
if (_instance == this) _instance = null;
WidgetsBinding.instance.removeObserver(this);
super.dispose();
@@ -355,6 +433,14 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver, Ticker
// Re-derive cover scheme whenever absorbing list changes so the app
// theme always reflects the current [0] book.
_deriveCoverScheme();
+ // With the dedicated Podcasts tab, Home never shows the podcast library.
+ // Covers the cold start restoring last_selected_library onto page 0.
+ final lib = context.read<LibraryProvider>();
+ if (_currentIndex == 0 &&
+ _podcastsShown(lib) &&
+ lib.selectedLibraryId == _podcastTabLibraryId) {
+ _syncTabLibrary(0, true);
+ }
}
/// Attempt to derive cover scheme. Returns true if successful.
@@ -387,23 +473,30 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver, Ticker
if (coverUrl.startsWith('/')) {
provider = FileImage(File(coverUrl));
} else {
- provider = CachedNetworkImageProvider(coverUrl, headers: lib.mediaHeaders);
+ provider = CachedNetworkImageProvider(
+ coverUrl,
+ headers: lib.mediaHeaders,
+ );
}
final brightness = Theme.of(context).brightness;
PaletteGenerator.fromImageProvider(provider, maximumColorCount: 16)
.then((palette) {
- final seedColor = accentFromCoverPalette(palette);
- if (seedColor == null) {
- _lastCoverItemId = null;
- return;
- }
- final scheme = ColorScheme.fromSeed(seedColor: seedColor, brightness: brightness);
- coverSchemeNotifier.value = scheme;
- PlayerSettings.setCoverSeedColor(seedColor.toARGB32());
- }).catchError((_) {
- _lastCoverItemId = null;
- });
+ final seedColor = accentFromCoverPalette(palette);
+ if (seedColor == null) {
+ _lastCoverItemId = null;
+ return;
+ }
+ final scheme = ColorScheme.fromSeed(
+ seedColor: seedColor,
+ brightness: brightness,
+ );
+ coverSchemeNotifier.value = scheme;
+ PlayerSettings.setCoverSeedColor(seedColor.toARGB32());
+ })
+ .catchError((_) {
+ _lastCoverItemId = null;
+ });
return true; // cover URL found, image load in progress
}
@@ -437,6 +530,10 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver, Ticker
}
Future<void> _maybeAutoExpand() async {
+ // Only auto-open the full-screen player from the Absorbing tab - starting
+ // playback from elsewhere (another tab, the nav long-press) shouldn't
+ // yank the user into the player.
+ if (_currentIndex != 2) return;
final enabled = await PlayerSettings.getFullScreenPlayer();
if (!enabled || !mounted || !_player.hasBook) return;
@@ -479,12 +576,11 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver, Ticker
_expandedIsOpen = true;
final nav = Navigator.of(context, rootNavigator: true);
- await nav.push(ExpandedCardRoute(
- child: ExpandedCard(
- item: item,
- player: _player,
+ await nav.push(
+ ExpandedCardRoute(
+ child: ExpandedCard(item: item, player: _player),
),
- ));
+ );
// Route was popped — expanded view closed
_expandedIsOpen = false;
}
@@ -568,7 +664,8 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver, Ticker
}
// Only do a full server refresh if enough time has passed
- if (_lastRefresh == null || now.difference(_lastRefresh!) > _refreshCooldown) {
+ if (_lastRefresh == null ||
+ now.difference(_lastRefresh!) > _refreshCooldown) {
_lastRefresh = now;
lib.refresh();
// Keep Android Auto / CarPlay browse tree in sync
@@ -594,18 +691,25 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver, Ticker
// If already on Absorbing tab, require double-back to exit
if (_currentIndex == 2) {
final now = DateTime.now();
- if (_lastBackPress != null && now.difference(_lastBackPress!) < const Duration(seconds: 2)) {
+ if (_lastBackPress != null &&
+ now.difference(_lastBackPress!) < const Duration(seconds: 2)) {
SystemChannels.platform.invokeMethod('SystemNavigator.pop', true);
return;
}
_lastBackPress = now;
ScaffoldMessenger.of(context).clearSnackBars();
- ScaffoldMessenger.of(context).showSnackBar(SnackBar(
- content: Text(AppLocalizations.of(context)!.appShellPressBackToExit),
- duration: const Duration(seconds: 2),
- behavior: SnackBarBehavior.floating,
- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
- ));
+ ScaffoldMessenger.of(context).showSnackBar(
+ SnackBar(
+ content: Text(
+ AppLocalizations.of(context)!.appShellPressBackToExit,
+ ),
+ duration: const Duration(seconds: 2),
+ behavior: SnackBarBehavior.floating,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(12),
+ ),
+ ),
+ );
return;
}
@@ -613,18 +717,18 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver, Ticker
_switchToAbsorbing();
},
child: Scaffold(
- body: FadeTransition(
- opacity: _fadeController,
- child: IndexedStack(
- index: _currentIndex,
- children: List<Widget>.generate(
- _pages.length,
- (i) => _pages[i] ?? const SizedBox.shrink(),
+ body: FadeTransition(
+ opacity: _fadeController,
+ child: IndexedStack(
+ index: _currentIndex,
+ children: List<Widget>.generate(
+ _pages.length,
+ (i) => _pages[i] ?? const SizedBox.shrink(),
+ ),
),
),
+ bottomNavigationBar: _buildBottomNav(context),
),
- bottomNavigationBar: _buildBottomNav(context),
- ),
);
}
@@ -640,7 +744,8 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver, Ticker
} else if (_currentIndex == 1) {
correctNotifier = _libraryKey.currentState?.barsRevealNotifier;
}
- final wrongAttachment = isHomeOrLibrary &&
+ final wrongAttachment =
+ isHomeOrLibrary &&
_navBarListener != null &&
correctNotifier != null &&
!identical(_activeBarNotifier, correctNotifier);
@@ -664,7 +769,9 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver, Ticker
// nav bar visible so it doesn't get hidden by the previous tab's notifier.
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
- if (_currentIndex != 0 && _currentIndex != 1 && _navBarListener != null) {
+ if (_currentIndex != 0 &&
+ _currentIndex != 1 &&
+ _navBarListener != null) {
_detachNavBarListener();
_navBarAnimController.value = 1.0;
}
@@ -674,64 +781,133 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver, Ticker
// shorter screen height. Tablets keep the full-size bar in any orientation.
final mq = MediaQuery.of(context);
final isTablet = mq.size.shortestSide >= 600;
- final isPhoneLandscape = !isTablet && mq.orientation == Orientation.landscape;
+ final isPhoneLandscape =
+ !isTablet && mq.orientation == Orientation.landscape;
+ final lib = context.watch<LibraryProvider>();
+ final podcastsShown = _podcastsShown(lib);
+ final destinations = _buildDestinations(context, podcastsShown);
return SizeTransition(
sizeFactor: _navBarAnimController,
axisAlignment: 1.0,
- child: NavigationBar(
- selectedIndex: _currentIndex,
- height: isPhoneLandscape ? 56 : null,
- labelBehavior: isPhoneLandscape
- ? NavigationDestinationLabelBehavior.alwaysHide
- : NavigationDestinationLabelBehavior.alwaysShow,
- onDestinationSelected: (i) {
- // If tapping Library while already on Library, clear search
- if (i == 1 && _currentIndex == 1 &&
- _libraryKey.currentState?.isSearchActive == true) {
- _libraryKey.currentState?.clearSearch();
- return;
- }
- _navigateTo(i);
- // Refresh data on switching to Library, Home, Absorbing, or Stats
- if (i == 0 || i == 1 || i == 2 || i == 3) {
- _refreshDataForTab(i);
- }
- },
- destinations: _buildDestinations(context),
+ // NavigationBar has no per-destination long-press, so map the press x
+ // to a destination slot. Plain taps pass through untouched.
+ child: GestureDetector(
+ onLongPressStart: (details) =>
+ _onNavLongPress(details.localPosition.dx, destinations.length),
+ child: NavigationBar(
+ selectedIndex: _selectedDest(lib, podcastsShown),
+ height: isPhoneLandscape ? 56 : null,
+ labelBehavior: isPhoneLandscape
+ ? NavigationDestinationLabelBehavior.alwaysHide
+ : NavigationDestinationLabelBehavior.alwaysShow,
+ onDestinationSelected: (dest) {
+ final page = _pageForDest(dest, podcastsShown);
+ // Re-tapping the active library-ish destination clears search
+ if (page == 1 &&
+ _currentIndex == 1 &&
+ dest == _selectedDest(lib, podcastsShown) &&
+ _libraryKey.currentState?.isSearchActive == true) {
+ _libraryKey.currentState?.clearSearch();
+ return;
+ }
+ _syncTabLibrary(dest, podcastsShown);
+ _navigateTo(page);
+ // Refresh data on switching to Library, Home, Absorbing, or Stats
+ if (page == 0 || page == 1 || page == 2 || page == 3) {
+ _refreshDataForTab(page);
+ }
+ },
+ destinations: destinations,
+ ),
),
);
}
- List<NavigationDestination> _buildDestinations(BuildContext context) {
+ void _onNavLongPress(double dx, int destCount) {
+ final width = MediaQuery.sizeOf(context).width;
+ if (width <= 0 || destCount <= 0) return;
+ final slot = (dx / (width / destCount)).floor().clamp(0, destCount - 1);
+ final absorbingSlot = destCount >= 6 ? 3 : 2;
+ if (slot == 0) {
+ // Home: quick library switcher.
+ final lib = context.read<LibraryProvider>();
+ if (lib.libraries.length < 2) return;
+ HapticFeedback.mediumImpact();
+ showLibraryPickerSheet(context, lib);
+ } else if (slot == 1) {
+ // Library: focus search.
+ HapticFeedback.mediumImpact();
+ final lib = context.read<LibraryProvider>();
+ if (_podcastsShown(lib)) _syncTabLibrary(1, true);
+ _openSearch();
+ } else if (slot == absorbingSlot) {
+ // Absorbing: toggle playback without leaving the current tab.
+ if (!_player.hasBook) return;
+ HapticFeedback.mediumImpact();
+ if (_player.isPlaying) {
+ _player.pause();
+ } else {
+ _player.play();
+ }
+ }
+ }
+
+ List<NavigationDestination> _buildDestinations(
+ BuildContext context,
+ bool podcastsShown,
+ ) {
final l = AppLocalizations.of(context)!;
final lib = context.watch<LibraryProvider>();
- final isPodcast = lib.isPodcastLibrary;
+ // With the dedicated Podcasts tab, Home/Library always wear their book
+ // labels - the podcast library being selected must not morph them.
+ final isPodcast = !podcastsShown && lib.isPodcastLibrary;
+ // tooltip: '' everywhere: the default label Tooltip registers its own
+ // long-press recognizer, which silently wins the gesture arena over the
+ // bar-level long-press handler (quick actions per slot).
return [
NavigationDestination(
icon: Icon(isPodcast ? Icons.explore_outlined : Icons.home_outlined),
- selectedIcon: Icon(isPodcast ? Icons.explore_rounded : Icons.home_rounded),
+ selectedIcon: Icon(
+ isPodcast ? Icons.explore_rounded : Icons.home_rounded,
+ ),
label: isPodcast ? l.appShellDiscoverTab : l.appShellHomeTab,
+ tooltip: '',
),
NavigationDestination(
- icon: Icon(isPodcast ? Icons.podcasts_outlined : Icons.library_books_outlined),
- selectedIcon: Icon(isPodcast ? Icons.podcasts_rounded : Icons.library_books_rounded),
+ icon: Icon(
+ isPodcast ? Icons.podcasts_outlined : Icons.library_books_outlined,
+ ),
+ selectedIcon: Icon(
+ isPodcast ? Icons.podcasts_rounded : Icons.library_books_rounded,
+ ),
label: isPodcast ? l.appShellShowsTab : l.appShellLibraryTab,
+ tooltip: '',
),
+ if (podcastsShown)
+ NavigationDestination(
+ icon: const Icon(Icons.podcasts_outlined),
+ selectedIcon: const Icon(Icons.podcasts_rounded),
+ label: l.appShellPodcastsTab,
+ tooltip: '',
+ ),
NavigationDestination(
icon: const _AnimatedWaveIcon(size: 24, active: false),
selectedIcon: const _AnimatedWaveIcon(size: 24, active: true),
label: Wording.of(context).appShellAbsorbingTab,
+ tooltip: '',
),
NavigationDestination(
icon: const Icon(Icons.bar_chart_rounded),
selectedIcon: const Icon(Icons.bar_chart_rounded),
label: l.appShellStatsTab,
+ tooltip: '',
),
NavigationDestination(
icon: const Icon(Icons.settings_outlined),
selectedIcon: const Icon(Icons.settings_rounded),
label: l.appShellSettingsTab,
+ tooltip: '',
),
];
}
@@ -808,7 +984,11 @@ class _NavWavePainter extends CustomPainter {
final Color color;
final bool playing;
- _NavWavePainter({required this.phase, required this.color, required this.playing});
+ _NavWavePainter({
+ required this.phase,
+ required this.color,
+ required this.playing,
+ });
static const _barHeights = [0.35, 0.6, 1.0, 0.6, 0.35];
static const _barCount = 5;
@@ -832,7 +1012,10 @@ class _NavWavePainter extends CustomPainter {
if (playing) {
final barPhase = phase * 2 * math.pi + i * 1.2;
- final ratio = (baseRatio * (0.5 + 0.5 * math.sin(barPhase))).clamp(0.2, 1.0);
+ final ratio = (baseRatio * (0.5 + 0.5 * math.sin(barPhase))).clamp(
+ 0.2,
+ 1.0,
+ );
final half = maxHalf * ratio;
canvas.drawLine(Offset(x, midY - half), Offset(x, midY + half), paint);
} else {
diff --git a/lib/screens/home_screen.dart b/lib/screens/home_screen.dart
index 6bf00624..c87b60b3 100644
--- a/lib/screens/home_screen.dart
+++ b/lib/screens/home_screen.dart
@@ -12,6 +12,7 @@ import '../services/audio_player_service.dart';
import '../services/download_service.dart';
import '../widgets/home_section.dart';
import '../widgets/absorb_page_header.dart';
+import '../widgets/library_picker_sheet.dart';
import '../widgets/shimmer.dart';
import '../widgets/book_detail_sheet.dart';
import '../widgets/card_buttons.dart';
@@ -205,79 +206,6 @@ class HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateMi
}
}
- void _showLibraryPicker(BuildContext context, ColorScheme cs, TextTheme tt,
- List<dynamic> allLibraries, LibraryProvider lib) {
- final l = AppLocalizations.of(context)!;
- showModalBottomSheet(
- context: context,
- isScrollControlled: true,
- useSafeArea: true,
- backgroundColor: Colors.transparent,
- builder: (ctx) {
- final bottomPad = MediaQuery.of(ctx).viewPadding.bottom;
- return Container(
- constraints:
- BoxConstraints(maxHeight: MediaQuery.of(ctx).size.height * 0.6),
- decoration: BoxDecoration(
- color: cs.surface,
- borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
- ),
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- const SizedBox(height: 12),
- Center(
- child: Container(
- width: 40,
- height: 4,
- decoration: BoxDecoration(
- color: cs.onSurfaceVariant.withValues(alpha: 0.3),
- borderRadius: BorderRadius.circular(2)))),
- const SizedBox(height: 16),
- Padding(
- padding: const EdgeInsets.symmetric(horizontal: 24),
- child: Text(l.selectLibrary,
- style:
- tt.titleLarge?.copyWith(fontWeight: FontWeight.w600)),
- ),
- const SizedBox(height: 12),
- Flexible(
- child: ListView.builder(
- shrinkWrap: true,
- padding: EdgeInsets.only(bottom: bottomPad + 16),
- itemCount: allLibraries.length,
- itemBuilder: (_, i) {
- final library = allLibraries[i] as Map<String, dynamic>;
- final id = library['id'] as String;
- final name = library['name'] as String? ?? l.libraryFallback;
- final mediaType = library['mediaType'] as String? ?? 'book';
- final isSelected = id == lib.selectedLibraryId;
- return ListTile(
- leading: Icon(
- mediaType == 'podcast'
- ? Icons.podcasts_rounded
- : Icons.auto_stories_rounded,
- color: isSelected ? cs.primary : cs.onSurfaceVariant),
- title: Text(name),
- trailing: isSelected
- ? Icon(Icons.check_circle_rounded, color: cs.primary)
- : null,
- selected: isSelected,
- onTap: () {
- Navigator.pop(ctx);
- if (!isSelected) lib.selectLibrary(id);
- },
- );
- },
- ),
- ),
- ],
- ),
- );
- },
- );
- }
-
static const _sectionIcons = {
'continue-listening': Icons.play_circle_outline_rounded,
'continue-series': Icons.auto_stories_rounded,
@@ -370,8 +298,7 @@ class HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateMi
borderRadius: BorderRadius.circular(20),
clipBehavior: Clip.antiAlias,
child: InkWell(
- onTap: () => _showLibraryPicker(
- context, cs, tt, allLibraries, lib),
+ onTap: () => showLibraryPickerSheet(context, lib),
borderRadius: BorderRadius.circular(20),
child: Container(
padding: const EdgeInsets.symmetric(
diff --git a/lib/screens/library_screen.dart b/lib/screens/library_screen.dart
index 6bc13648..dc4b0f62 100644
--- a/lib/screens/library_screen.dart
+++ b/lib/screens/library_screen.dart
@@ -14,7 +14,9 @@ import '../services/socket_service.dart';
import '../services/download_service.dart';
import '../services/audio_player_service.dart';
import '../widgets/absorb_page_header.dart';
+import '../widgets/library_picker_sheet.dart';
import '../widgets/library_search_results.dart';
+import '../widgets/podcast_episode_feed.dart';
import '../main.dart' show flatNotifier, gradientIntensityNotifier;
import '../widgets/library_sort_filter_sheet.dart';
import '../widgets/library_books_tab.dart';
@@ -29,7 +31,8 @@ import 'app_shell.dart';
import 'upcoming_releases_screen.dart';
import '../widgets/audible_series_sheet.dart' show showAudibleRegionPicker;
import '../widgets/offline_status_icon.dart';
-import '../widgets/rmab_config_sheet.dart' show kRmabBaseUrlKey, kRmabApiTokenKey;
+import '../widgets/rmab_config_sheet.dart'
+ show kRmabBaseUrlKey, kRmabApiTokenKey;
import '../widgets/rmab_search_results_sheet.dart';
import '../widgets/scroll_reveal.dart';
import '../services/scoped_prefs.dart';
@@ -52,10 +55,28 @@ int responsiveGridCount(BuildContext context) {
const double libraryGridBottomPadding = 180;
// ─── Sort modes ──────────────────────────────────────────────
-enum LibrarySort { recentlyAdded, alphabetical, authorName, publishedYear, duration, random, totalDuration }
+enum LibrarySort {
+ recentlyAdded,
+ alphabetical,
+ authorName,
+ publishedYear,
+ duration,
+ random,
+ totalDuration,
+}
// ─── Filter modes ────────────────────────────────────────────
-enum LibraryFilter { none, inProgress, finished, notStarted, downloaded, inASeries, hasEbook, genre, tag }
+enum LibraryFilter {
+ none,
+ inProgress,
+ finished,
+ notStarted,
+ downloaded,
+ inASeries,
+ hasEbook,
+ genre,
+ tag,
+}
/// Series-tab progress filter. Computed client-side from per-book progress
/// because the ABS server's `?filter=` param doesn't support series-level
@@ -70,11 +91,13 @@ class LibraryScreen extends StatefulWidget {
State<LibraryScreen> createState() => LibraryScreenState();
}
-class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMixin {
+class LibraryScreenState extends State<LibraryScreen>
+ with TickerProviderStateMixin {
// ── Search state ──
final _searchController = TextEditingController();
final _focusNode = FocusNode();
bool _rmabConfigured = false;
+
/// GlobalKey on the SearchBar so its Element (and the TextField + focus
/// inside) survives the tree swap when `_isInSearchMode` flips. Without
/// this, typing the first character unmounts the tabbed tree, the
@@ -110,6 +133,7 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
SystemChannels.textInput.invokeMethod<void>('TextInput.show');
});
}
+
List<dynamic> _searchBookResults = [];
List<dynamic> _searchSeriesResults = [];
List<dynamic> _searchAuthorResults = [];
@@ -126,6 +150,8 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
// ── Tab state ──
TabController? _tabController;
int _currentTab = 0;
+ // Podcast libraries: 0 = Shows grid, 1 = Episodes feed.
+ int _podcastView = 0;
// ── Browse state (Library tab) ──
bool _collapseSeries = false;
@@ -281,8 +307,7 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
final base = await ScopedPrefs.getString(kRmabBaseUrlKey);
final token = await ScopedPrefs.getString(kRmabApiTokenKey);
if (!mounted) return;
- final next =
- (base ?? '').isNotEmpty && (token ?? '').isNotEmpty;
+ final next = (base ?? '').isNotEmpty && (token ?? '').isNotEmpty;
debugPrint('[RMAB] library: _rmabConfigured=$next');
if (next != _rmabConfigured) {
setState(() => _rmabConfigured = next);
@@ -327,12 +352,14 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
// on account scope + libraryId inside _loadLists, so this is a no-op when
// nothing relevant changed.
_loadLists();
- if (lib.selectedLibraryId != _lastLibraryId && lib.selectedLibraryId != null) {
+ if (lib.selectedLibraryId != _lastLibraryId &&
+ lib.selectedLibraryId != null) {
_lastLibraryId = lib.selectedLibraryId;
_loadGeneration++;
// Cover shape can differ per library.
PlayerSettings.getRectangleCoversFor(lib.selectedLibraryId).then((v) {
- if (mounted && v != _rectangleCovers) setState(() => _rectangleCovers = v);
+ if (mounted && v != _rectangleCovers)
+ setState(() => _rectangleCovers = v);
});
// Rebuild tab controller if library type changed
@@ -351,6 +378,7 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
}
setState(() {
+ _podcastView = 0;
_items.clear();
_page = 0;
_hasMore = true;
@@ -532,11 +560,20 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
}
});
// Lazy load data for the restored tab
- if (!isPodcast && savedTab == 1 && _seriesItems.isEmpty && !_isLoadingSeriesPage) {
+ if (!isPodcast &&
+ savedTab == 1 &&
+ _seriesItems.isEmpty &&
+ !_isLoadingSeriesPage) {
_loadSeriesPage();
- } else if (!isPodcast && savedTab == 2 && !_authorsLoaded && !_isLoadingAuthors) {
+ } else if (!isPodcast &&
+ savedTab == 2 &&
+ !_authorsLoaded &&
+ !_isLoadingAuthors) {
_loadAuthors();
- } else if (!isPodcast && savedTab == 3 && !_narratorsLoaded && !_isLoadingNarrators) {
+ } else if (!isPodcast &&
+ savedTab == 3 &&
+ !_narratorsLoaded &&
+ !_isLoadingNarrators) {
_loadNarrators();
}
}
@@ -546,7 +583,8 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
PlayerSettings.getHideEbookOnly(),
PlayerSettings.getCollapseSeries(),
PlayerSettings.getRectangleCoversFor(
- context.read<LibraryProvider>().selectedLibraryId),
+ context.read<LibraryProvider>().selectedLibraryId,
+ ),
]).then((values) {
final newHideEbook = values[0];
final newCollapse = values[1];
@@ -594,15 +632,10 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
String unwrap(dynamic v) =>
v is Map ? (v['name'] as String? ?? '') : v.toString();
setState(() {
- _availableGenres = genres
- .map(unwrap)
- .where((g) => g.isNotEmpty)
- .toList()
- ..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
- _availableTags = tags
- .map(unwrap)
- .where((t) => t.isNotEmpty)
- .toList()
+ _availableGenres =
+ genres.map(unwrap).where((g) => g.isNotEmpty).toList()
+ ..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
+ _availableTags = tags.map(unwrap).where((t) => t.isNotEmpty).toList()
..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
});
}
@@ -667,18 +700,30 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
int desc;
switch (_sort) {
case LibrarySort.recentlyAdded:
- sort = 'addedAt'; desc = _sortAsc ? 0 : 1; break;
+ sort = 'addedAt';
+ desc = _sortAsc ? 0 : 1;
+ break;
case LibrarySort.alphabetical:
- sort = 'media.metadata.title'; desc = _sortAsc ? 0 : 1; break;
+ sort = 'media.metadata.title';
+ desc = _sortAsc ? 0 : 1;
+ break;
case LibrarySort.authorName:
- sort = 'media.metadata.authorNameLF'; desc = _sortAsc ? 0 : 1; break;
+ sort = 'media.metadata.authorNameLF';
+ desc = _sortAsc ? 0 : 1;
+ break;
case LibrarySort.publishedYear:
- sort = 'media.metadata.publishedYear'; desc = _sortAsc ? 0 : 1; break;
+ sort = 'media.metadata.publishedYear';
+ desc = _sortAsc ? 0 : 1;
+ break;
case LibrarySort.duration:
case LibrarySort.totalDuration:
- sort = 'media.duration'; desc = _sortAsc ? 0 : 1; break;
+ sort = 'media.duration';
+ desc = _sortAsc ? 0 : 1;
+ break;
case LibrarySort.random:
- sort = 'addedAt'; desc = 1; break;
+ sort = 'addedAt';
+ desc = 1;
+ break;
}
String? filter;
@@ -713,7 +758,8 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
sort: sort,
desc: desc,
filter: filter,
- collapseSeries: _collapseSeries && !useClientFilter && !lib.isPodcastLibrary,
+ collapseSeries:
+ _collapseSeries && !useClientFilter && !lib.isPodcastLibrary,
);
if (result == null || !mounted || gen != _loadGeneration) break;
final results = (result['results'] as List<dynamic>?) ?? [];
@@ -724,10 +770,16 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
final ts = r['updatedAt'] as num?;
if (id != null && ts != null) lib.registerUpdatedAt(id, ts.toInt());
if (id != null) {
- final coverPath = (r['media'] as Map<String, dynamic>?)?['coverPath'] as String?;
- lib.registerHasCover(id, coverPath != null && coverPath.isNotEmpty);
+ final coverPath =
+ (r['media'] as Map<String, dynamic>?)?['coverPath']
+ as String?;
+ lib.registerHasCover(
+ id,
+ coverPath != null && coverPath.isNotEmpty,
+ );
}
- if (useClientFilter && !DownloadService().isDownloaded(id ?? '')) continue;
+ if (useClientFilter && !DownloadService().isDownloaded(id ?? ''))
+ continue;
if (_hideEbookOnly && PlayerSettings.isEbookOnly(r)) continue;
_items.add(r);
}
@@ -763,10 +815,16 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
if (r is Map<String, dynamic>) {
final id = r['id'] as String?;
final ts = r['updatedAt'] as num?;
- if (id != null && ts != null) lib.registerUpdatedAt(id, ts.toInt());
+ if (id != null && ts != null)
+ lib.registerUpdatedAt(id, ts.toInt());
if (id != null) {
- final coverPath = (r['media'] as Map<String, dynamic>?)?['coverPath'] as String?;
- lib.registerHasCover(id, coverPath != null && coverPath.isNotEmpty);
+ final coverPath =
+ (r['media'] as Map<String, dynamic>?)?['coverPath']
+ as String?;
+ lib.registerHasCover(
+ id,
+ coverPath != null && coverPath.isNotEmpty,
+ );
}
if (_hideEbookOnly && PlayerSettings.isEbookOnly(r)) continue;
_items.add(r);
@@ -777,7 +835,9 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
// Client-side filters (e.g. hide-ebook-only) reduce _items below total,
// which would leave _hasMore permanently true and the loader spinning.
_hasMore = results.length >= _pageSize;
- debugPrint('[LibPage] page=${_page - 1} results=${results.length} pageSize=$_pageSize filtered=${_items.length} total=$total hideEbook=$_hideEbookOnly hasMore=$_hasMore');
+ debugPrint(
+ '[LibPage] page=${_page - 1} results=${results.length} pageSize=$_pageSize filtered=${_items.length} total=$total hideEbook=$_hideEbookOnly hasMore=$_hasMore',
+ );
_isLoadingPage = false;
});
} else if (mounted && gen == _loadGeneration) {
@@ -841,7 +901,10 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
/// from [LibraryProvider]. Used by the series tab's client-side filter
/// (the ABS server doesn't support series-level progress filters).
bool _seriesMatchesFilter(
- Map<String, dynamic> series, SeriesFilter filter, LibraryProvider lib) {
+ Map<String, dynamic> series,
+ SeriesFilter filter,
+ LibraryProvider lib,
+ ) {
if (filter == SeriesFilter.none) return true;
final books = series['books'] as List<dynamic>? ?? const [];
if (books.isEmpty) return false;
@@ -888,13 +951,17 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
String sort;
switch (_seriesSort) {
case LibrarySort.alphabetical:
- sort = 'name'; break;
+ sort = 'name';
+ break;
case LibrarySort.recentlyAdded:
- sort = 'addedAt'; break;
+ sort = 'addedAt';
+ break;
case LibrarySort.totalDuration:
- sort = 'numBooks'; break;
+ sort = 'numBooks';
+ break;
default:
- sort = 'name'; break;
+ sort = 'name';
+ break;
}
// ── Filtered mode: paginate the same way as the unfiltered path, but
@@ -928,7 +995,8 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
_seriesPage++;
// hasMore = there's still source data left, regardless of how many
// pages matched.
- _hasMoreSeries = (_seriesPage * filteredPageSize) < unfilteredTotal &&
+ _hasMoreSeries =
+ (_seriesPage * filteredPageSize) < unfilteredTotal &&
results.isNotEmpty;
// The visible count is what the user sees; track it for the InfoRow.
_totalSeries = _seriesItems.length;
@@ -991,14 +1059,23 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
});
// Update cache
if (total >= 250) {
- lib.setSeriesTabCache(cacheKey, List<Map<String, dynamic>>.from(_seriesItems), total);
+ lib.setSeriesTabCache(
+ cacheKey,
+ List<Map<String, dynamic>>.from(_seriesItems),
+ total,
+ );
}
} else if (mounted) {
setState(() => _isLoadingSeriesPage = false);
}
}
- Future<void> _refreshSeriesInBackground(ApiService api, LibraryProvider lib, String sort, String cacheKey) async {
+ Future<void> _refreshSeriesInBackground(
+ ApiService api,
+ LibraryProvider lib,
+ String sort,
+ String cacheKey,
+ ) async {
final allItems = <Map<String, dynamic>>[];
int page = 0;
int total = 0;
@@ -1042,7 +1119,10 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
final lib = context.read<LibraryProvider>();
final api = auth.apiService;
if (api == null || lib.selectedLibraryId == null) {
- setState(() { _isLoadingAuthors = false; _authorsLoaded = true; });
+ setState(() {
+ _isLoadingAuthors = false;
+ _authorsLoaded = true;
+ });
return;
}
@@ -1062,7 +1142,9 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
if (_authorSort == LibrarySort.totalDuration) {
final aCount = a['numBooks'] as int? ?? 0;
final bCount = b['numBooks'] as int? ?? 0;
- return _authorSortAsc ? aCount.compareTo(bCount) : bCount.compareTo(aCount);
+ return _authorSortAsc
+ ? aCount.compareTo(bCount)
+ : bCount.compareTo(aCount);
}
final aName = (a['name'] as String? ?? '').toLowerCase();
final bName = (b['name'] as String? ?? '').toLowerCase();
@@ -1078,7 +1160,10 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
final lib = context.read<LibraryProvider>();
final api = auth.apiService;
if (api == null || lib.selectedLibraryId == null) {
- setState(() { _isLoadingNarrators = false; _narratorsLoaded = true; });
+ setState(() {
+ _isLoadingNarrators = false;
+ _narratorsLoaded = true;
+ });
return;
}
@@ -1097,16 +1182,30 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
_narrators.sort((a, b) {
final aLower = a.toLowerCase();
final bLower = b.toLowerCase();
- return _narratorSortAsc ? aLower.compareTo(bLower) : bLower.compareTo(aLower);
+ return _narratorSortAsc
+ ? aLower.compareTo(bLower)
+ : bLower.compareTo(aLower);
});
}
// ── Change sort and reload ──
void _changeSort(LibrarySort newSort) {
- if (_currentTab == 1) { _changeSeriesSort(newSort); return; }
- if (_currentTab == 2) { _changeAuthorSort(newSort); return; }
- if (_currentTab == 3) { _changeNarratorSort(newSort); return; }
- if (_currentTab == 4) { _changeListsSort(newSort); return; }
+ if (_currentTab == 1) {
+ _changeSeriesSort(newSort);
+ return;
+ }
+ if (_currentTab == 2) {
+ _changeAuthorSort(newSort);
+ return;
+ }
+ if (_currentTab == 3) {
+ _changeNarratorSort(newSort);
+ return;
+ }
+ if (_currentTab == 4) {
+ _changeListsSort(newSort);
+ return;
+ }
final isPodcast = context.read<LibraryProvider>().isPodcastLibrary;
if (newSort == _sort) {
@@ -1132,7 +1231,10 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
setState(() {
_sort = newSort;
// Smart defaults: A-Z and Length start ascending, others start descending
- _sortAsc = newSort == LibrarySort.alphabetical || newSort == LibrarySort.authorName || newSort == LibrarySort.duration;
+ _sortAsc =
+ newSort == LibrarySort.alphabetical ||
+ newSort == LibrarySort.authorName ||
+ newSort == LibrarySort.duration;
_items.clear();
_page = 0;
_hasMore = true;
@@ -1156,7 +1258,9 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
void _changeSeriesSort(LibrarySort newSort) {
if (newSort == _seriesSort) {
- setState(() { _seriesSortAsc = !_seriesSortAsc; });
+ setState(() {
+ _seriesSortAsc = !_seriesSortAsc;
+ });
} else {
setState(() {
_seriesSort = newSort;
@@ -1177,7 +1281,9 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
void _changeAuthorSort(LibrarySort newSort) {
if (newSort == _authorSort) {
- setState(() { _authorSortAsc = !_authorSortAsc; });
+ setState(() {
+ _authorSortAsc = !_authorSortAsc;
+ });
} else {
setState(() {
_authorSort = newSort;
@@ -1192,7 +1298,9 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
void _changeNarratorSort(LibrarySort newSort) {
if (newSort == _narratorSort) {
- setState(() { _narratorSortAsc = !_narratorSortAsc; });
+ setState(() {
+ _narratorSortAsc = !_narratorSortAsc;
+ });
} else {
setState(() {
_narratorSort = newSort;
@@ -1202,7 +1310,8 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
PlayerSettings.setNarratorSort(_narratorSort.name);
PlayerSettings.setNarratorSortAsc(_narratorSortAsc);
setState(() => _sortNarrators());
- if (_narratorsScrollController.hasClients) _narratorsScrollController.jumpTo(0);
+ if (_narratorsScrollController.hasClients)
+ _narratorsScrollController.jumpTo(0);
}
void _changeListsSort(LibrarySort newSort) {
@@ -1239,11 +1348,12 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
case LibrarySort.totalDuration:
return countOf(a).compareTo(countOf(b));
default:
- return (a['name'] as String? ?? '')
- .toLowerCase()
- .compareTo((b['name'] as String? ?? '').toLowerCase());
+ return (a['name'] as String? ?? '').toLowerCase().compareTo(
+ (b['name'] as String? ?? '').toLowerCase(),
+ );
}
}
+
entries.sort((a, b) => _listsSortAsc ? asc(a, b) : asc(b, a));
return entries;
}
@@ -1269,8 +1379,9 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
/// Change the Series tab's client-side progress filter and reload.
void _changeSeriesFilter(SeriesFilter newFilter) {
- final effective =
- newFilter == _seriesFilter ? SeriesFilter.none : newFilter;
+ final effective = newFilter == _seriesFilter
+ ? SeriesFilter.none
+ : newFilter;
if (effective == _seriesFilter) return;
setState(() {
_seriesFilter = effective;
@@ -1286,11 +1397,11 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
// ── Change filter and reload ──
void _changeFilter(LibraryFilter newFilter, {String? genre, String? tag}) {
- final sameAsCurrent = newFilter == _filter &&
- genre == _genreFilter &&
- tag == _tagFilter;
+ final sameAsCurrent =
+ newFilter == _filter && genre == _genreFilter && tag == _tagFilter;
final effective = sameAsCurrent ? LibraryFilter.none : newFilter;
- if (effective == _filter && genre == _genreFilter && tag == _tagFilter) return;
+ if (effective == _filter && genre == _genreFilter && tag == _tagFilter)
+ return;
final isPodcast = context.read<LibraryProvider>().isPodcastLibrary;
_loadGeneration++;
setState(() {
@@ -1335,7 +1446,8 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
final libId = lib.selectedLibraryId;
if (api == null || libId == null) return Future.value();
final key = '${UserAccountService().activeScopeKey}|$libId';
- if (_listsLoadingKey == key && _listsLoadFuture != null) return _listsLoadFuture!;
+ if (_listsLoadingKey == key && _listsLoadFuture != null)
+ return _listsLoadFuture!;
if (_listsLoadedKey == key) return Future.value();
_listsLoadingKey = key;
final f = _fetchLists(key, api, libId);
@@ -1346,7 +1458,8 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
Future<void> _fetchLists(String key, ApiService api, String libId) async {
// Seed the Lists pill from the remembered flag so it shows right away (and
// doesn't blink out while reloading) before the network confirms.
- final remembered = await ScopedPrefs.getBool(_listsPresentKey(libId)) ?? false;
+ final remembered =
+ await ScopedPrefs.getBool(_listsPresentKey(libId)) ?? false;
if (!mounted || _listsLoadingKey != key) return;
// New key (library/account changed) or first load: drop the previous lists
// before fetching the new ones.
@@ -1430,7 +1543,9 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
_searchBookResults = (result['book'] as List<dynamic>?) ?? [];
if (_hideEbookOnly) {
_searchBookResults = _searchBookResults.where((r) {
- final item = r['libraryItem'] as Map<String, dynamic>? ?? r as Map<String, dynamic>;
+ final item =
+ r['libraryItem'] as Map<String, dynamic>? ??
+ r as Map<String, dynamic>;
return !PlayerSettings.isEbookOnly(item);
}).toList();
}
@@ -1482,15 +1597,20 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
_searchController.text.trim() == query) {
var books = BookSearchIndex()
.search(libId, query)
- .map((h) => <String, dynamic>{
- 'libraryItem': h.item,
- '_titleMatch': h.titleMatch,
- })
+ .map(
+ (h) => <String, dynamic>{
+ 'libraryItem': h.item,
+ '_titleMatch': h.titleMatch,
+ },
+ )
.toList();
if (_hideEbookOnly) {
books = books
- .where((r) =>
- !PlayerSettings.isEbookOnly(r['libraryItem'] as Map<String, dynamic>))
+ .where(
+ (r) => !PlayerSettings.isEbookOnly(
+ r['libraryItem'] as Map<String, dynamic>,
+ ),
+ )
.toList();
}
setState(() => _searchBookResults = books);
@@ -1498,9 +1618,14 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
}
}
- Future<void> _searchNarrators(String query, String libraryId, dynamic api) async {
+ Future<void> _searchNarrators(
+ String query,
+ String libraryId,
+ dynamic api,
+ ) async {
final lowerQuery = query.toLowerCase();
- if (_allNarratorsCache == null || _allNarratorsCacheLibraryId != libraryId) {
+ if (_allNarratorsCache == null ||
+ _allNarratorsCacheLibraryId != libraryId) {
final all = await api.getLibraryNarrators(libraryId);
_allNarratorsCache = (all as List).cast<String>();
_allNarratorsCacheLibraryId = libraryId;
@@ -1516,11 +1641,16 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
List<Map<String, dynamic>>? _cachedShowsWithEpisodes;
String? _cachedShowsLibraryId;
- Future<void> _searchEpisodes(String query, String libraryId, dynamic api) async {
+ Future<void> _searchEpisodes(
+ String query,
+ String libraryId,
+ dynamic api,
+ ) async {
final lowerQuery = query.toLowerCase();
// Cache all shows with episodes so subsequent searches are instant
- if (_cachedShowsWithEpisodes == null || _cachedShowsLibraryId != libraryId) {
+ if (_cachedShowsWithEpisodes == null ||
+ _cachedShowsLibraryId != libraryId) {
final items = await api.getLibraryItems(libraryId, limit: 100);
if (items == null || !mounted) return;
final results = items['results'] as List<dynamic>? ?? [];
@@ -1531,9 +1661,11 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
final show = (r['libraryItem'] ?? r) as Map<String, dynamic>;
final showId = show['id'] as String?;
if (showId == null) continue;
- futures.add(api.getLibraryItem(showId).then((fullItem) {
- if (fullItem != null) shows.add(fullItem);
- }));
+ futures.add(
+ api.getLibraryItem(showId).then((fullItem) {
+ if (fullItem != null) shows.add(fullItem);
+ }),
+ );
}
await Future.wait(futures);
_cachedShowsWithEpisodes = shows;
@@ -1556,67 +1688,6 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
}
}
- void _showLibraryPicker(BuildContext context, ColorScheme cs, TextTheme tt, List<dynamic> allLibraries, LibraryProvider lib) {
- final l = AppLocalizations.of(context)!;
- showModalBottomSheet(
- context: context,
- isScrollControlled: true,
- useSafeArea: true,
- backgroundColor: Colors.transparent,
- builder: (ctx) {
- final bottomPad = MediaQuery.of(ctx).viewPadding.bottom;
- return Container(
- constraints: BoxConstraints(maxHeight: MediaQuery.of(ctx).size.height * 0.6),
- decoration: BoxDecoration(
- color: cs.surface,
- borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
- ),
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- const SizedBox(height: 12),
- Center(child: Container(width: 40, height: 4,
- decoration: BoxDecoration(color: cs.onSurfaceVariant.withValues(alpha: 0.3), borderRadius: BorderRadius.circular(2)))),
- const SizedBox(height: 16),
- Padding(
- padding: const EdgeInsets.symmetric(horizontal: 24),
- child: Text(l.selectLibrary, style: tt.titleLarge?.copyWith(fontWeight: FontWeight.w600)),
- ),
- const SizedBox(height: 12),
- Flexible(
- child: ListView.builder(
- shrinkWrap: true,
- padding: EdgeInsets.only(bottom: bottomPad + 16),
- itemCount: allLibraries.length,
- itemBuilder: (_, i) {
- final library = allLibraries[i] as Map<String, dynamic>;
- final id = library['id'] as String;
- final name = library['name'] as String? ?? l.libraryFallback;
- final mediaType = library['mediaType'] as String? ?? 'book';
- final isSelected = id == lib.selectedLibraryId;
- return ListTile(
- leading: Icon(mediaType == 'podcast' ? Icons.podcasts_rounded : Icons.auto_stories_rounded,
- color: isSelected ? cs.primary : cs.onSurfaceVariant),
- title: Text(name),
- trailing: isSelected
- ? Icon(Icons.check_circle_rounded, color: cs.primary)
- : null,
- selected: isSelected,
- onTap: () {
- Navigator.pop(ctx);
- if (!isSelected) lib.selectLibrary(id);
- },
- );
- },
- ),
- ),
- ],
- ),
- );
- },
- );
- }
-
String _seriesFilterLabelOf(AppLocalizations l) => switch (_seriesFilter) {
SeriesFilter.inProgress => l.inProgress,
SeriesFilter.finished => l.filterFinished,
@@ -1636,7 +1707,12 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
LibraryFilter.none => '',
};
- Future<void> _showSortFilterSheet(BuildContext context, ColorScheme cs, TextTheme tt, {int initialTab = 0}) async {
+ Future<void> _showSortFilterSheet(
+ BuildContext context,
+ ColorScheme cs,
+ TextTheme tt, {
+ int initialTab = 0,
+ }) async {
final LibraryTab tab;
final LibrarySort currentSort;
final bool currentSortAsc;
@@ -1681,29 +1757,55 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
availableGenres: _availableGenres,
availableTags: _availableTags,
initialTab: initialTab,
- cs: cs, tt: tt,
+ cs: cs,
+ tt: tt,
libraryTab: tab,
- onSortChanged: (sort) { Navigator.pop(ctx); _changeSort(sort); },
+ onSortChanged: (sort) {
+ Navigator.pop(ctx);
+ _changeSort(sort);
+ },
onSortDirectionToggled: () {
if (_currentTab == 1) {
- setState(() { _seriesSortAsc = !_seriesSortAsc; _seriesItems.clear(); _seriesPage = 0; _hasMoreSeries = true; _isLoadingSeriesPage = false; });
+ setState(() {
+ _seriesSortAsc = !_seriesSortAsc;
+ _seriesItems.clear();
+ _seriesPage = 0;
+ _hasMoreSeries = true;
+ _isLoadingSeriesPage = false;
+ });
PlayerSettings.setSeriesSortAsc(_seriesSortAsc);
- if (_seriesScrollController.hasClients) _seriesScrollController.jumpTo(0);
+ if (_seriesScrollController.hasClients)
+ _seriesScrollController.jumpTo(0);
_loadSeriesPage();
} else if (_currentTab == 2) {
- setState(() { _authorSortAsc = !_authorSortAsc; _sortAuthors(); });
+ setState(() {
+ _authorSortAsc = !_authorSortAsc;
+ _sortAuthors();
+ });
PlayerSettings.setAuthorSortAsc(_authorSortAsc);
- if (_authorsScrollController.hasClients) _authorsScrollController.jumpTo(0);
+ if (_authorsScrollController.hasClients)
+ _authorsScrollController.jumpTo(0);
} else if (_currentTab == 3) {
- setState(() { _narratorSortAsc = !_narratorSortAsc; _sortNarrators(); });
+ setState(() {
+ _narratorSortAsc = !_narratorSortAsc;
+ _sortNarrators();
+ });
PlayerSettings.setNarratorSortAsc(_narratorSortAsc);
- if (_narratorsScrollController.hasClients) _narratorsScrollController.jumpTo(0);
+ if (_narratorsScrollController.hasClients)
+ _narratorsScrollController.jumpTo(0);
} else if (_currentTab == 4) {
setState(() => _listsSortAsc = !_listsSortAsc);
PlayerSettings.setListsSortAsc(_listsSortAsc);
- if (_listsScrollController.hasClients) _listsScrollController.jumpTo(0);
+ if (_listsScrollController.hasClients)
+ _listsScrollController.jumpTo(0);
} else {
- setState(() { _sortAsc = !_sortAsc; _items.clear(); _page = 0; _hasMore = true; _isLoadingPage = false; });
+ setState(() {
+ _sortAsc = !_sortAsc;
+ _items.clear();
+ _page = 0;
+ _hasMore = true;
+ _isLoadingPage = false;
+ });
final isPodcast = context.read<LibraryProvider>().isPodcastLibrary;
if (isPodcast) {
_podcastSortAsc = _sortAsc;
@@ -1720,7 +1822,10 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
Navigator.pop(ctx);
_changeFilter(filter, genre: genre, tag: tag);
},
- onClearFilter: () { Navigator.pop(ctx); _changeFilter(LibraryFilter.none); },
+ onClearFilter: () {
+ Navigator.pop(ctx);
+ _changeFilter(LibraryFilter.none);
+ },
collapseSeries: _collapseSeries,
onCollapseSeriesChanged: (value) {
_loadGeneration++;
@@ -1736,10 +1841,12 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
_loadPage();
},
isPodcastLibrary: context.read<LibraryProvider>().isPodcastLibrary,
- onUpcomingReleases: tab == LibraryTab.series ? () {
- Navigator.pop(ctx);
- _openUpcomingReleases();
- } : null,
+ onUpcomingReleases: tab == LibraryTab.series
+ ? () {
+ Navigator.pop(ctx);
+ _openUpcomingReleases();
+ }
+ : null,
currentSeriesFilter: _seriesFilter,
onSeriesFilterChanged: tab == LibraryTab.series
? (sf) {
@@ -1768,7 +1875,12 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
_wasOffline = libWatch.isOffline;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
- setState(() { _items.clear(); _page = 0; _hasMore = true; _isLoadingPage = false; });
+ setState(() {
+ _items.clear();
+ _page = 0;
+ _hasMore = true;
+ _isLoadingPage = false;
+ });
_loadPage();
});
}
@@ -1792,7 +1904,9 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
end: Alignment.bottomCenter,
stops: const [0.0, 0.22, 0.72, 1.0],
colors: [
- cs.primary.withValues(alpha: gradientIntensityNotifier.value),
+ cs.primary.withValues(
+ alpha: gradientIntensityNotifier.value,
+ ),
cs.surface,
lowerFade,
scaffoldBg,
@@ -1814,7 +1928,9 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
onNotification: (n) {
if (n is ScrollUpdateNotification) {
_revealDriver.noteScroll(
- n.scrollDelta ?? 0, n.metrics.pixels);
+ n.scrollDelta ?? 0,
+ n.metrics.pixels,
+ );
} else if (n is ScrollEndNotification) {
_revealDriver.settle();
}
@@ -1823,12 +1939,28 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
child: Builder(
builder: (ctx) {
return _isInSearchMode
- ? _buildSearchResults(cs, tt, l,
- _buildHeaderSliver(context, useSharedFocus: true))
+ ? _buildSearchResults(
+ cs,
+ tt,
+ l,
+ _buildHeaderSliver(context, useSharedFocus: true),
+ )
: hasTabs
- ? _buildTabbedContent(cs, tt)
- : _buildGrid(_buildHeaderSliver(context,
- useSharedFocus: true));
+ ? _buildTabbedContent(cs, tt)
+ : _podcastView == 1
+ ? PodcastEpisodeFeed(
+ key: ValueKey(
+ 'epfeed-${libWatch.selectedLibraryId}',
+ ),
+ libraryId: libWatch.selectedLibraryId ?? '',
+ headerSliver: _buildHeaderSliver(
+ context,
+ useSharedFocus: true,
+ ),
+ )
+ : _buildGrid(
+ _buildHeaderSliver(context, useSharedFocus: true),
+ );
},
),
),
@@ -1877,7 +2009,7 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
- _buildFloatingSortButton(cs, tt),
+ _buildPodcastViewPill(cs),
if (context.read<AuthProvider>().isAdmin) ...[
const SizedBox(width: 8),
_buildFloatingManageButton(cs),
@@ -1903,8 +2035,10 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
/// receives focus from taps and the Search app shortcut). Inactive tabs
/// get a fresh internal FocusNode per SearchBar so they don't fight over
/// the shared one.
- Widget _buildHeaderSliver(BuildContext context,
- {required bool useSharedFocus}) {
+ Widget _buildHeaderSliver(
+ BuildContext context, {
+ required bool useSharedFocus,
+ }) {
final cs = Theme.of(context).colorScheme;
final tt = Theme.of(context).textTheme;
final l = AppLocalizations.of(context)!;
@@ -1937,7 +2071,9 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
end: Alignment.bottomCenter,
stops: const [0.0, 0.22, 0.72, 1.0],
colors: [
- cs.primary.withValues(alpha: gradientIntensityNotifier.value),
+ cs.primary.withValues(
+ alpha: gradientIntensityNotifier.value,
+ ),
cs.surface,
lowerFade,
scaffoldBg,
@@ -1950,29 +2086,31 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
),
);
return SliverAppBar(
- floating: true,
- snap: true,
- // primary: false disables Material's automatic status
- // bar padding so the header doesn't get inset twice
- // (we already wrap the whole NestedScrollView in
- // SafeArea above).
- primary: false,
- toolbarHeight: _isInSearchMode
- ? 156
- : ((_filter != LibraryFilter.none ||
- _seriesFilter != SeriesFilter.none)
- ? 196
- : 184),
- backgroundColor: scaffoldBg,
- surfaceTintColor: Colors.transparent,
- elevation: 0,
- scrolledUnderElevation: 0,
- automaticallyImplyLeading: false,
- flexibleSpace: ClipRect(
- child: Stack(
- children: [
- Positioned.fill(child: headerBackground),
- Column(mainAxisSize: MainAxisSize.min, children: [
+ floating: true,
+ snap: true,
+ // primary: false disables Material's automatic status
+ // bar padding so the header doesn't get inset twice
+ // (we already wrap the whole NestedScrollView in
+ // SafeArea above).
+ primary: false,
+ toolbarHeight: _isInSearchMode
+ ? 156
+ : ((_filter != LibraryFilter.none ||
+ _seriesFilter != SeriesFilter.none)
+ ? 196
+ : 184),
+ backgroundColor: scaffoldBg,
+ surfaceTintColor: Colors.transparent,
+ elevation: 0,
+ scrolledUnderElevation: 0,
+ automaticallyImplyLeading: false,
+ flexibleSpace: ClipRect(
+ child: Stack(
+ children: [
+ Positioned.fill(child: headerBackground),
+ Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
AbsorbPageHeader(
title: l.libraryTitle,
trailing: OfflineStatusIcon(
@@ -1990,36 +2128,63 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
}
},
),
- actions: hasMultipleLibraries ? [
- GestureDetector(
- onTap: () => _showLibraryPicker(context, cs, tt, allLibraries, lib),
- child: Container(
- padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
- decoration: BoxDecoration(
- color: cs.onSurface.withValues(alpha: 0.06),
- borderRadius: BorderRadius.circular(20),
- border: Border.all(color: cs.onSurface.withValues(alpha: 0.08)),
- ),
- child: SizedBox(
- height: 20,
- child: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- Icon(lib.isPodcastLibrary ? Icons.podcasts_rounded : Icons.auto_stories_rounded, size: 18, color: cs.onSurfaceVariant),
- const SizedBox(width: 6),
- ConstrainedBox(
- constraints: const BoxConstraints(maxWidth: 140),
- child: Text(libraryName, style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600, color: cs.onSurfaceVariant),
- overflow: TextOverflow.ellipsis, maxLines: 1),
+ actions: hasMultipleLibraries
+ ? [
+ GestureDetector(
+ onTap: () => showLibraryPickerSheet(context, lib),
+ child: Container(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 10,
+ vertical: 5,
),
- const SizedBox(width: 4),
- Icon(Icons.unfold_more_rounded, size: 18, color: cs.onSurfaceVariant),
- ],
+ decoration: BoxDecoration(
+ color: cs.onSurface.withValues(alpha: 0.06),
+ borderRadius: BorderRadius.circular(20),
+ border: Border.all(
+ color: cs.onSurface.withValues(alpha: 0.08),
+ ),
+ ),
+ child: SizedBox(
+ height: 20,
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(
+ lib.isPodcastLibrary
+ ? Icons.podcasts_rounded
+ : Icons.auto_stories_rounded,
+ size: 18,
+ color: cs.onSurfaceVariant,
+ ),
+ const SizedBox(width: 6),
+ ConstrainedBox(
+ constraints: const BoxConstraints(
+ maxWidth: 140,
+ ),
+ child: Text(
+ libraryName,
+ style: TextStyle(
+ fontSize: 13,
+ fontWeight: FontWeight.w600,
+ color: cs.onSurfaceVariant,
+ ),
+ overflow: TextOverflow.ellipsis,
+ maxLines: 1,
+ ),
+ ),
+ const SizedBox(width: 4),
+ Icon(
+ Icons.unfold_more_rounded,
+ size: 18,
+ color: cs.onSurfaceVariant,
+ ),
+ ],
+ ),
+ ),
+ ),
),
- ),
- ),
- ),
- ] : null,
+ ]
+ : null,
),
Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),
@@ -2057,19 +2222,98 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
),
],
onChanged: _onSearchChanged,
- padding: const WidgetStatePropertyAll(EdgeInsets.symmetric(horizontal: 8)),
+ padding: const WidgetStatePropertyAll(
+ EdgeInsets.symmetric(horizontal: 8),
+ ),
side: WidgetStatePropertyAll(
BorderSide(color: cs.onSurface.withValues(alpha: 0.08)),
),
),
),
// Item count + filter badge row
- if (!_isInSearchMode)
- _buildInfoRow(cs, tt, l),
- ]),
- ],
+ if (!_isInSearchMode) _buildInfoRow(cs, tt, l),
+ ],
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+
+ // Shows | Episodes switcher for podcast libraries, styled like the book
+ // libraries' floating tab pills.
+ Widget _buildPodcastViewPill(ColorScheme cs) {
+ final l = AppLocalizations.of(context)!;
+ final labels = [l.appShellShowsTab, l.libraryTabEpisodes];
+ return ClipRRect(
+ borderRadius: BorderRadius.circular(24),
+ child: BackdropFilter(
+ filter: ui.ImageFilter.blur(sigmaX: 20, sigmaY: 20),
+ child: Container(
+ padding: const EdgeInsets.all(4),
+ decoration: BoxDecoration(
+ color: cs.surface.withValues(alpha: 0.6),
+ borderRadius: BorderRadius.circular(24),
+ border: Border.all(color: cs.primary.withValues(alpha: 0.25)),
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: List.generate(labels.length, (i) {
+ final active = _podcastView == i;
+ return GestureDetector(
+ onTap: () {
+ if (!active) {
+ setState(() => _podcastView = i);
+ } else if (i == 0) {
+ // Re-tap on the active Shows pill opens the sort sheet,
+ // same as the book libraries' pills.
+ _showSortFilterSheet(
+ context,
+ cs,
+ Theme.of(context).textTheme,
+ );
+ }
+ },
+ child: AnimatedContainer(
+ duration: const Duration(milliseconds: 200),
+ curve: Curves.easeInOut,
+ padding: EdgeInsets.symmetric(
+ horizontal: active ? 14 : 12,
+ vertical: 8,
+ ),
+ decoration: BoxDecoration(
+ color: active
+ ? cs.primary.withValues(alpha: 0.15)
+ : Colors.transparent,
+ borderRadius: BorderRadius.circular(20),
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(
+ labels[i],
+ maxLines: 1,
+ softWrap: false,
+ style: TextStyle(
+ fontSize: 13,
+ fontWeight: active
+ ? FontWeight.w700
+ : FontWeight.w500,
+ color: active ? cs.primary : cs.onSurfaceVariant,
+ ),
+ ),
+ if (active && i == 0) ...[
+ const SizedBox(width: 4),
+ Icon(Icons.sort_rounded, size: 14, color: cs.primary),
+ ],
+ ],
+ ),
+ ),
+ );
+ }),
),
),
+ ),
);
}
@@ -2109,7 +2353,10 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
onTap: () {
if (active) {
_showSortFilterSheet(
- context, cs, Theme.of(context).textTheme);
+ context,
+ cs,
+ Theme.of(context).textTheme,
+ );
} else {
_tabController?.animateTo(i);
}
@@ -2118,7 +2365,9 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
duration: const Duration(milliseconds: 200),
curve: Curves.easeInOut,
padding: EdgeInsets.symmetric(
- horizontal: active ? 14 : 12, vertical: 8),
+ horizontal: active ? 14 : 12,
+ vertical: 8,
+ ),
decoration: BoxDecoration(
color: active
? cs.primary.withValues(alpha: 0.15)
@@ -2134,15 +2383,21 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
softWrap: false,
style: TextStyle(
fontSize: 13,
- fontWeight:
- active ? FontWeight.w700 : FontWeight.w500,
- color:
- active ? cs.primary : cs.onSurfaceVariant,
+ fontWeight: active
+ ? FontWeight.w700
+ : FontWeight.w500,
+ color: active
+ ? cs.primary
+ : cs.onSurfaceVariant,
),
),
if (active) ...[
const SizedBox(width: 4),
- Icon(Icons.sort_rounded, size: 14, color: cs.primary),
+ Icon(
+ Icons.sort_rounded,
+ size: 14,
+ color: cs.primary,
+ ),
],
],
),
@@ -2158,7 +2413,6 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
);
}
-
Future<void> _openUpcomingReleases() async {
final saved = await PlayerSettings.getAudibleRegion();
if (saved.isEmpty) {
@@ -2168,43 +2422,9 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
await PlayerSettings.setAudibleRegion(chosen);
}
if (!mounted) return;
- Navigator.push(context, MaterialPageRoute(
- builder: (_) => const UpcomingReleasesScreen(),
- ));
- }
-
- Widget _buildFloatingSortButton(ColorScheme cs, TextTheme tt) {
- return GestureDetector(
- onTap: () => _showSortFilterSheet(context, cs, tt),
- child: ClipRRect(
- borderRadius: BorderRadius.circular(24),
- child: BackdropFilter(
- filter: ui.ImageFilter.blur(sigmaX: 20, sigmaY: 20),
- child: Container(
- padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 8),
- decoration: BoxDecoration(
- color: cs.surface.withValues(alpha: 0.6),
- borderRadius: BorderRadius.circular(24),
- border: Border.all(color: cs.primary.withValues(alpha: 0.25)),
- ),
- child: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- Text(
- AppLocalizations.of(context)!.sort,
- style: TextStyle(
- fontSize: 13,
- fontWeight: FontWeight.w700,
- color: cs.primary,
- ),
- ),
- const SizedBox(width: 4),
- Icon(Icons.sort_rounded, size: 14, color: cs.primary),
- ],
- ),
- ),
- ),
- ),
+ Navigator.push(
+ context,
+ MaterialPageRoute(builder: (_) => const UpcomingReleasesScreen()),
);
}
@@ -2213,8 +2433,12 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
onTap: () {
final lib = context.read<LibraryProvider>().selectedLibrary;
if (lib != null) {
- Navigator.push(context, MaterialPageRoute(
- builder: (_) => AdminPodcastsScreen(library: lib)));
+ Navigator.push(
+ context,
+ MaterialPageRoute(
+ builder: (_) => AdminPodcastsScreen(library: lib),
+ ),
+ );
}
},
child: ClipRRect(
@@ -2266,7 +2490,10 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
GestureDetector(
onTap: () => _changeFilter(LibraryFilter.none),
child: Container(
- padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
+ padding: const EdgeInsets.symmetric(
+ horizontal: 10,
+ vertical: 4,
+ ),
decoration: BoxDecoration(
color: cs.tertiary.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(20),
@@ -2274,10 +2501,22 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
- Icon(Icons.filter_list_rounded, size: 14, color: cs.tertiary),
+ Icon(
+ Icons.filter_list_rounded,
+ size: 14,
+ color: cs.tertiary,
+ ),
const SizedBox(width: 4),
- Text(_filterLabelOf(l), style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: cs.tertiary),
- overflow: TextOverflow.ellipsis, maxLines: 1),
+ Text(
+ _filterLabelOf(l),
+ style: TextStyle(
+ fontSize: 12,
+ fontWeight: FontWeight.w600,
+ color: cs.tertiary,
+ ),
+ overflow: TextOverflow.ellipsis,
+ maxLines: 1,
+ ),
const SizedBox(width: 4),
Icon(Icons.close_rounded, size: 14, color: cs.tertiary),
],
@@ -2289,7 +2528,10 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
GestureDetector(
onTap: () => _changeSeriesFilter(SeriesFilter.none),
child: Container(
- padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
+ padding: const EdgeInsets.symmetric(
+ horizontal: 10,
+ vertical: 4,
+ ),
decoration: BoxDecoration(
color: cs.tertiary.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(20),
@@ -2297,10 +2539,22 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
- Icon(Icons.filter_list_rounded, size: 14, color: cs.tertiary),
+ Icon(
+ Icons.filter_list_rounded,
+ size: 14,
+ color: cs.tertiary,
+ ),
const SizedBox(width: 4),
- Text(_seriesFilterLabelOf(l), style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: cs.tertiary),
- overflow: TextOverflow.ellipsis, maxLines: 1),
+ Text(
+ _seriesFilterLabelOf(l),
+ style: TextStyle(
+ fontSize: 12,
+ fontWeight: FontWeight.w600,
+ color: cs.tertiary,
+ ),
+ overflow: TextOverflow.ellipsis,
+ maxLines: 1,
+ ),
const SizedBox(width: 4),
Icon(Icons.close_rounded, size: 14, color: cs.tertiary),
],
@@ -2309,8 +2563,12 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
),
],
const Spacer(),
- Text(countText,
- style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant.withValues(alpha: 0.6))),
+ Text(
+ countText,
+ style: tt.labelSmall?.copyWith(
+ color: cs.onSurfaceVariant.withValues(alpha: 0.6),
+ ),
+ ),
],
),
);
@@ -2349,7 +2607,8 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
coverAspectRatio: _coverAspectRatio,
onOpenCollection: (c) {
final id = c['id'] as String?;
- if (id != null && id.isNotEmpty) CollectionDetailSheet.show(context, id);
+ if (id != null && id.isNotEmpty)
+ CollectionDetailSheet.show(context, id);
},
onOpenPlaylist: (p) {
final id = p['id'] as String?;
@@ -2474,7 +2733,11 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
// SEARCH RESULTS
// ═══════════════════════════════════════════════════════════════
Widget _buildSearchResults(
- ColorScheme cs, TextTheme tt, AppLocalizations l, Widget headerSliver) {
+ ColorScheme cs,
+ TextTheme tt,
+ AppLocalizations l,
+ Widget headerSliver,
+ ) {
final injector = headerSliver;
if (_isSearching) {
return CustomScrollView(
@@ -2491,10 +2754,19 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
if (!_hasSearched) {
return CustomScrollView(
physics: const AlwaysScrollableScrollPhysics(),
- slivers: [injector, const SliverToBoxAdapter(child: SizedBox.shrink())],
+ slivers: [
+ injector,
+ const SliverToBoxAdapter(child: SizedBox.shrink()),
+ ],
);
}
- if (_searchBookResults.isEmpty && _searchSeriesResults.isEmpty && _searchAuthorResults.isEmpty && _searchNarratorResults.isEmpty && _searchEpisodeResults.isEmpty && _searchTagResults.isEmpty && _searchGenreResults.isEmpty) {
+ if (_searchBookResults.isEmpty &&
+ _searchSeriesResults.isEmpty &&
+ _searchAuthorResults.isEmpty &&
+ _searchNarratorResults.isEmpty &&
+ _searchEpisodeResults.isEmpty &&
+ _searchTagResults.isEmpty &&
+ _searchGenreResults.isEmpty) {
final libProv = context.read<LibraryProvider>();
final showRmabCta = _rmabConfigured && !libProv.isPodcastLibrary;
return CustomScrollView(
@@ -2507,10 +2779,16 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
- Icon(Icons.search_off_rounded, size: 48, color: cs.onSurfaceVariant),
+ Icon(
+ Icons.search_off_rounded,
+ size: 48,
+ color: cs.onSurfaceVariant,
+ ),
const SizedBox(height: 12),
- Text(l.libraryNoResults,
- style: tt.bodyLarge?.copyWith(color: cs.onSurfaceVariant)),
+ Text(
+ l.libraryNoResults,
+ style: tt.bodyLarge?.copyWith(color: cs.onSurfaceVariant),
+ ),
if (showRmabCta) ...[
const SizedBox(height: 20),
OutlinedButton.icon(
@@ -2518,12 +2796,8 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
label: Text(l.rmabRequestCta),
onPressed: () {
final q = _searchController.text.trim();
- debugPrint(
- '[RMAB] library CTA tapped (query="$q")');
- showRmabSearchResultsSheet(
- context,
- initialQuery: q,
- );
+ debugPrint('[RMAB] library CTA tapped (query="$q")');
+ showRmabSearchResultsSheet(context, initialQuery: q);
},
),
],
@@ -2539,210 +2813,260 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
final isPodcast = context.read<LibraryProvider>().isPodcastLibrary;
final children = <Widget>[
- // ─── BOOKS / SHOWS (only title matches) ───
- if (_searchBookResults.isNotEmpty) ...[
- ...() {
- final query = _searchController.text.trim().toLowerCase();
- final titleMatches = _searchBookResults.where((result) {
- // Fuzzy index results carry their own title-match flag; fall back
- // to a substring check for server/podcast results.
- final tm = result['_titleMatch'];
- if (tm is bool) return tm;
- final item = result['libraryItem'] as Map<String, dynamic>? ?? {};
- final media = item['media'] as Map<String, dynamic>? ?? {};
- final metadata = media['metadata'] as Map<String, dynamic>? ?? {};
- final title = (metadata['title'] as String? ?? '').toLowerCase();
- return title.contains(query);
- }).toList();
- if (titleMatches.isEmpty) return <Widget>[];
- return <Widget>[
- Padding(
- padding: const EdgeInsets.fromLTRB(4, 8, 4, 8),
- child: Text(isPodcast ? l.librarySearchShows : l.librarySearchBooks,
- style: tt.titleMedium?.copyWith(
- fontWeight: FontWeight.w600, color: cs.primary)),
+ // ─── BOOKS / SHOWS (only title matches) ───
+ if (_searchBookResults.isNotEmpty) ...[
+ ...() {
+ final query = _searchController.text.trim().toLowerCase();
+ final titleMatches = _searchBookResults.where((result) {
+ // Fuzzy index results carry their own title-match flag; fall back
+ // to a substring check for server/podcast results.
+ final tm = result['_titleMatch'];
+ if (tm is bool) return tm;
+ final item = result['libraryItem'] as Map<String, dynamic>? ?? {};
+ final media = item['media'] as Map<String, dynamic>? ?? {};
+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};
+ final title = (metadata['title'] as String? ?? '').toLowerCase();
+ return title.contains(query);
+ }).toList();
+ if (titleMatches.isEmpty) return <Widget>[];
+ return <Widget>[
+ Padding(
+ padding: const EdgeInsets.fromLTRB(4, 8, 4, 8),
+ child: Text(
+ isPodcast ? l.librarySearchShows : l.librarySearchBooks,
+ style: tt.titleMedium?.copyWith(
+ fontWeight: FontWeight.w600,
+ color: cs.primary,
+ ),
),
- ...titleMatches.map((result) {
- final item =
- result['libraryItem'] as Map<String, dynamic>? ?? {};
- return BookResultTile(
- item: item,
- serverUrl: auth.serverUrl,
- token: auth.token,
- );
- }),
- ];
- }(),
- ],
+ ),
+ ...titleMatches.map((result) {
+ final item = result['libraryItem'] as Map<String, dynamic>? ?? {};
+ return BookResultTile(
+ item: item,
+ serverUrl: auth.serverUrl,
+ token: auth.token,
+ );
+ }),
+ ];
+ }(),
+ ],
- // ─── EPISODES ───
- if (_searchEpisodeResults.isNotEmpty) ...[
- Padding(
- padding: EdgeInsets.fromLTRB(
- 4, _searchBookResults.isNotEmpty ? 20 : 8, 4, 8),
- child: Text(l.librarySearchEpisodes,
- style: tt.titleMedium?.copyWith(
- fontWeight: FontWeight.w600, color: cs.primary)),
+ // ─── EPISODES ───
+ if (_searchEpisodeResults.isNotEmpty) ...[
+ Padding(
+ padding: EdgeInsets.fromLTRB(
+ 4,
+ _searchBookResults.isNotEmpty ? 20 : 8,
+ 4,
+ 8,
),
- ..._searchEpisodeResults.map((result) {
- return EpisodeResultTile(
- show: result['show']!,
- episode: result['episode']!,
- serverUrl: auth.serverUrl,
- token: auth.token,
- );
- }),
- ],
-
- // ─── SERIES ───
- if (_searchSeriesResults.isNotEmpty) ...[
- Padding(
- padding: EdgeInsets.fromLTRB(
- 4, _searchBookResults.isNotEmpty ? 20 : 8, 4, 8),
- child: Text(l.librarySearchSeries,
- style: tt.titleMedium?.copyWith(
- fontWeight: FontWeight.w600, color: cs.primary)),
+ child: Text(
+ l.librarySearchEpisodes,
+ style: tt.titleMedium?.copyWith(
+ fontWeight: FontWeight.w600,
+ color: cs.primary,
+ ),
),
- ..._searchSeriesResults.map((result) {
- final seriesData =
- result['series'] as Map<String, dynamic>? ?? {};
- final books = result['books'] as List<dynamic>? ?? [];
- return SeriesResultCard(
- series: seriesData,
- books: books,
- serverUrl: auth.serverUrl,
- token: auth.token,
- );
- }),
- ],
+ ),
+ ..._searchEpisodeResults.map((result) {
+ return EpisodeResultTile(
+ show: result['show']!,
+ episode: result['episode']!,
+ serverUrl: auth.serverUrl,
+ token: auth.token,
+ );
+ }),
+ ],
- // ─── AUTHORS ───
- if (_searchAuthorResults.isNotEmpty) ...[
- Padding(
- padding: EdgeInsets.fromLTRB(
- 4, (_searchBookResults.isNotEmpty || _searchSeriesResults.isNotEmpty) ? 20 : 8, 4, 8),
- child: Text(l.librarySearchAuthors,
- style: tt.titleMedium?.copyWith(
- fontWeight: FontWeight.w600, color: cs.primary)),
+ // ─── SERIES ───
+ if (_searchSeriesResults.isNotEmpty) ...[
+ Padding(
+ padding: EdgeInsets.fromLTRB(
+ 4,
+ _searchBookResults.isNotEmpty ? 20 : 8,
+ 4,
+ 8,
),
- ..._searchAuthorResults.map((result) {
- final authorData =
- result['author'] as Map<String, dynamic>? ?? result as Map<String, dynamic>;
- return AuthorResultTile(
- author: authorData,
- serverUrl: auth.serverUrl,
- token: auth.token,
- );
- }),
- ],
+ child: Text(
+ l.librarySearchSeries,
+ style: tt.titleMedium?.copyWith(
+ fontWeight: FontWeight.w600,
+ color: cs.primary,
+ ),
+ ),
+ ),
+ ..._searchSeriesResults.map((result) {
+ final seriesData = result['series'] as Map<String, dynamic>? ?? {};
+ final books = result['books'] as List<dynamic>? ?? [];
+ return SeriesResultCard(
+ series: seriesData,
+ books: books,
+ serverUrl: auth.serverUrl,
+ token: auth.token,
+ );
+ }),
+ ],
- // ─── NARRATORS ───
- if (_searchNarratorResults.isNotEmpty) ...[
- Padding(
- padding: EdgeInsets.fromLTRB(
- 4, (_searchBookResults.isNotEmpty || _searchSeriesResults.isNotEmpty || _searchAuthorResults.isNotEmpty) ? 20 : 8, 4, 8),
- child: Text(l.libraryTabNarrators,
- style: tt.titleMedium?.copyWith(
- fontWeight: FontWeight.w600, color: cs.primary)),
+ // ─── AUTHORS ───
+ if (_searchAuthorResults.isNotEmpty) ...[
+ Padding(
+ padding: EdgeInsets.fromLTRB(
+ 4,
+ (_searchBookResults.isNotEmpty || _searchSeriesResults.isNotEmpty)
+ ? 20
+ : 8,
+ 4,
+ 8,
),
- ..._searchNarratorResults.map((name) => NarratorResultTile(name: name)),
- ],
+ child: Text(
+ l.librarySearchAuthors,
+ style: tt.titleMedium?.copyWith(
+ fontWeight: FontWeight.w600,
+ color: cs.primary,
+ ),
+ ),
+ ),
+ ..._searchAuthorResults.map((result) {
+ final authorData =
+ result['author'] as Map<String, dynamic>? ??
+ result as Map<String, dynamic>;
+ return AuthorResultTile(
+ author: authorData,
+ serverUrl: auth.serverUrl,
+ token: auth.token,
+ );
+ }),
+ ],
- // ─── GENRES ───
- if (_searchGenreResults.isNotEmpty) ...[
- Padding(
- padding: EdgeInsets.fromLTRB(
- 4,
- (_searchBookResults.isNotEmpty ||
- _searchSeriesResults.isNotEmpty ||
- _searchAuthorResults.isNotEmpty ||
- _searchNarratorResults.isNotEmpty)
- ? 20
- : 8,
- 4,
- 8),
- child: Text(l.librarySearchGenres,
- style: tt.titleMedium?.copyWith(
- fontWeight: FontWeight.w600, color: cs.primary)),
+ // ─── NARRATORS ───
+ if (_searchNarratorResults.isNotEmpty) ...[
+ Padding(
+ padding: EdgeInsets.fromLTRB(
+ 4,
+ (_searchBookResults.isNotEmpty ||
+ _searchSeriesResults.isNotEmpty ||
+ _searchAuthorResults.isNotEmpty)
+ ? 20
+ : 8,
+ 4,
+ 8,
),
- ..._searchGenreResults.map((name) => GenreResultTile(
- name: name,
- onTap: () => _applyGenreFilter(name),
- )),
- ],
+ child: Text(
+ l.libraryTabNarrators,
+ style: tt.titleMedium?.copyWith(
+ fontWeight: FontWeight.w600,
+ color: cs.primary,
+ ),
+ ),
+ ),
+ ..._searchNarratorResults.map((name) => NarratorResultTile(name: name)),
+ ],
- // ─── TAGS ───
- if (_searchTagResults.isNotEmpty) ...[
- Padding(
- padding: EdgeInsets.fromLTRB(
- 4,
- (_searchBookResults.isNotEmpty ||
- _searchSeriesResults.isNotEmpty ||
- _searchAuthorResults.isNotEmpty ||
- _searchNarratorResults.isNotEmpty ||
- _searchGenreResults.isNotEmpty)
- ? 20
- : 8,
- 4,
- 8),
- child: Text(l.librarySearchTags,
- style: tt.titleMedium?.copyWith(
- fontWeight: FontWeight.w600, color: cs.primary)),
+ // ─── GENRES ───
+ if (_searchGenreResults.isNotEmpty) ...[
+ Padding(
+ padding: EdgeInsets.fromLTRB(
+ 4,
+ (_searchBookResults.isNotEmpty ||
+ _searchSeriesResults.isNotEmpty ||
+ _searchAuthorResults.isNotEmpty ||
+ _searchNarratorResults.isNotEmpty)
+ ? 20
+ : 8,
+ 4,
+ 8,
),
- ..._searchTagResults.map((name) => TagResultTile(
- name: name,
- onTap: () => _applyTagFilter(name),
- )),
- ],
- // ─── RMAB FOOTER (when results exist + RMAB configured) ───
- if (_rmabConfigured && !isPodcast) ...[
- Padding(
- padding: const EdgeInsets.only(top: 28),
- child: Divider(color: cs.outlineVariant.withValues(alpha: 0.4)),
+ child: Text(
+ l.librarySearchGenres,
+ style: tt.titleMedium?.copyWith(
+ fontWeight: FontWeight.w600,
+ color: cs.primary,
+ ),
+ ),
+ ),
+ ..._searchGenreResults.map(
+ (name) =>
+ GenreResultTile(name: name, onTap: () => _applyGenreFilter(name)),
+ ),
+ ],
+
+ // ─── TAGS ───
+ if (_searchTagResults.isNotEmpty) ...[
+ Padding(
+ padding: EdgeInsets.fromLTRB(
+ 4,
+ (_searchBookResults.isNotEmpty ||
+ _searchSeriesResults.isNotEmpty ||
+ _searchAuthorResults.isNotEmpty ||
+ _searchNarratorResults.isNotEmpty ||
+ _searchGenreResults.isNotEmpty)
+ ? 20
+ : 8,
+ 4,
+ 8,
),
- Padding(
- padding: const EdgeInsets.fromLTRB(4, 12, 4, 4),
- child: Text(
- l.rmabSearchFooterPrompt,
- style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant),
+ child: Text(
+ l.librarySearchTags,
+ style: tt.titleMedium?.copyWith(
+ fontWeight: FontWeight.w600,
+ color: cs.primary,
),
),
- Material(
- color: Colors.transparent,
- child: InkWell(
- borderRadius: BorderRadius.circular(10),
- onTap: () {
- final q = _searchController.text.trim();
- debugPrint(
- '[RMAB] library footer CTA tapped (query="$q")');
- showRmabSearchResultsSheet(
- context,
- initialQuery: q,
- );
- },
- child: Padding(
- padding: const EdgeInsets.symmetric(
- horizontal: 4, vertical: 12),
- child: Row(children: [
- Icon(Icons.menu_book_rounded,
- size: 20, color: cs.primary),
+ ),
+ ..._searchTagResults.map(
+ (name) =>
+ TagResultTile(name: name, onTap: () => _applyTagFilter(name)),
+ ),
+ ],
+ // ─── RMAB FOOTER (when results exist + RMAB configured) ───
+ if (_rmabConfigured && !isPodcast) ...[
+ Padding(
+ padding: const EdgeInsets.only(top: 28),
+ child: Divider(color: cs.outlineVariant.withValues(alpha: 0.4)),
+ ),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(4, 12, 4, 4),
+ child: Text(
+ l.rmabSearchFooterPrompt,
+ style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant),
+ ),
+ ),
+ Material(
+ color: Colors.transparent,
+ child: InkWell(
+ borderRadius: BorderRadius.circular(10),
+ onTap: () {
+ final q = _searchController.text.trim();
+ debugPrint('[RMAB] library footer CTA tapped (query="$q")');
+ showRmabSearchResultsSheet(context, initialQuery: q);
+ },
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 12),
+ child: Row(
+ children: [
+ Icon(Icons.menu_book_rounded, size: 20, color: cs.primary),
const SizedBox(width: 12),
Expanded(
child: Text(
- l.rmabSearchFooterCta(
- _searchController.text.trim()),
+ l.rmabSearchFooterCta(_searchController.text.trim()),
style: tt.bodyMedium?.copyWith(
- color: cs.primary,
- fontWeight: FontWeight.w600),
+ color: cs.primary,
+ fontWeight: FontWeight.w600,
+ ),
),
),
- Icon(Icons.arrow_forward_rounded,
- size: 18, color: cs.primary),
- ]),
+ Icon(
+ Icons.arrow_forward_rounded,
+ size: 18,
+ color: cs.primary,
+ ),
+ ],
),
),
),
- ],
+ ),
+ ],
];
return CustomScrollView(
@@ -2751,12 +3075,9 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
injector,
SliverPadding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 100),
- sliver: SliverList(
- delegate: SliverChildListDelegate(children),
- ),
+ sliver: SliverList(delegate: SliverChildListDelegate(children)),
),
],
);
}
}
-
diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart
index 5af51680..12c71b03 100644
--- a/lib/screens/settings_screen.dart
+++ b/lib/screens/settings_screen.dart
@@ -14,6 +14,7 @@ import '../providers/auth_provider.dart';
import '../providers/library_provider.dart';
import '../services/audio_player_service.dart';
import '../services/download_service.dart';
+import '../services/episode_notification_service.dart';
import '../services/sleep_timer_service.dart';
import '../services/user_account_service.dart';
import '../services/backup_service.dart';
@@ -107,6 +108,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
}
bool _queueAutoDownload = false;
bool _mergeAbsorbingLibraries = false;
+ bool _podcastTabEnabled = false;
+ String _podcastTabLibraryId = '';
+ int _episodeNotifMinutes = 0;
int _maxConcurrentDownloads = 1;
bool _hideEbookOnly = false;
bool _showGoodreadsButton = false;
@@ -633,6 +637,63 @@ class _SettingsScreenState extends State<SettingsScreen> {
);
}
+ String _episodeNotifIntervalLabel(AppLocalizations l, int minutes) {
+ if (minutes <= 0) return l.notifIntervalOff;
+ if (minutes < 60) return l.notifIntervalMinutes(minutes);
+ if (minutes == 60) return l.notifIntervalHour;
+ return l.notifIntervalHours(minutes ~/ 60);
+ }
+
+ String _episodeNotifLabel(AppLocalizations l) =>
+ _episodeNotifIntervalLabel(l, _episodeNotifMinutes);
+
+ Future<void> _pickEpisodeNotifInterval() async {
+ final l = AppLocalizations.of(context)!;
+ final picked = await showDialog<int>(
+ context: context,
+ builder: (ctx) => SimpleDialog(
+ title: Text(l.settingsEpisodeNotifs),
+ children: [
+ for (final m in [0, 15, 30, 60, 180, 360, 720, 1440])
+ RadioListTile<int>(
+ value: m,
+ groupValue: _episodeNotifMinutes,
+ title: Text(_episodeNotifIntervalLabel(l, m)),
+ onChanged: (v) => Navigator.pop(ctx, v),
+ ),
+ ],
+ ),
+ );
+ if (picked == null || picked == _episodeNotifMinutes) return;
+ setState(() => _episodeNotifMinutes = picked);
+ await PlayerSettings.setEpisodeNotifIntervalMinutes(picked);
+ await EpisodeNotificationService.syncRegistration();
+ // Make sure notifications are allowed when turning the feature on.
+ if (picked > 0) await Permission.notification.request();
+ }
+
+ Future<void> _pickPodcastTabLibrary(List<Map<String, dynamic>> podcastLibs) async {
+ final l = AppLocalizations.of(context)!;
+ final picked = await showDialog<String>(
+ context: context,
+ builder: (ctx) => SimpleDialog(
+ title: Text(l.settingsPodcastTabLibrary),
+ children: [
+ for (final p in podcastLibs)
+ RadioListTile<String>(
+ value: p['id'] as String,
+ groupValue: _podcastTabLibraryId,
+ title: Text(p['name'] as String? ?? ''),
+ onChanged: (v) => Navigator.pop(ctx, v),
+ ),
+ ],
+ ),
+ );
+ if (picked == null || picked == _podcastTabLibraryId) return;
+ setState(() => _podcastTabLibraryId = picked);
+ await PlayerSettings.setPodcastTabLibraryId(picked);
+ }
+
Future<void> _loadSettings() async {
final results = await Future.wait([
AutoRewindSettings.load(), // 0
@@ -651,7 +712,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
PlayerSettings.getShakeAddMinutes(), // 13
PlayerSettings.getBookQueueMode(), // 14
PlayerSettings.getQueueAutoDownload(), // 15
- PlayerSettings.getMergeAbsorbingLibraries(), // 16
+ PlayerSettings.getMergeAbsorbingLibrariesRaw(), // 16
PlayerSettings.getMaxConcurrentDownloads(), // 17
PlayerSettings.getHideEbookOnly(), // 18
PlayerSettings.getShowGoodreadsButton(), // 19
@@ -762,7 +823,13 @@ class _SettingsScreenState extends State<SettingsScreen> {
final longSkipButtons = await PlayerSettings.getLongSkipButtons();
final longFwd = await PlayerSettings.getLongForwardSkip();
final longBack = await PlayerSettings.getLongBackSkip();
+ final podcastTabEnabled = await PlayerSettings.getPodcastTabEnabled();
+ final podcastTabLibraryId = await PlayerSettings.getPodcastTabLibraryId();
+ final episodeNotifMinutes = await PlayerSettings.getEpisodeNotifIntervalMinutes();
if (mounted) setState(() {
+ _podcastTabEnabled = podcastTabEnabled;
+ _podcastTabLibraryId = podcastTabLibraryId;
+ _episodeNotifMinutes = episodeNotifMinutes;
_sleepRewindSeconds = sleepRewind;
_lockPortrait = lockPortrait;
_autoSeriesDownloadDefault = autoSeriesDownload;
@@ -1773,18 +1840,24 @@ class _SettingsScreenState extends State<SettingsScreen> {
valueListenable: classicWordingNotifier,
builder: (context, _, __) {
final w = Wording.of(context);
+ // The dedicated Podcasts tab implies merged libraries;
+ // show it locked on rather than a toggle that snaps back.
+ final effectiveMerge =
+ _mergeAbsorbingLibraries || _podcastTabEnabled;
return SwitchListTile(
title: Row(children: [
Flexible(child: Text(w.mergeLibraries)),
_infoIcon(w.mergeLibrariesInfoTitle, w.mergeLibrariesInfoContent),
]),
subtitle: Text(
- _mergeAbsorbingLibraries
- ? w.mergeLibrariesOnSubtitle
- : w.mergeLibrariesOffSubtitle,
+ _podcastTabEnabled
+ ? l.settingsMergeImpliedByPodcastTab
+ : effectiveMerge
+ ? w.mergeLibrariesOnSubtitle
+ : w.mergeLibrariesOffSubtitle,
style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
- value: _mergeAbsorbingLibraries,
- onChanged: _loaded ? (v) {
+ value: effectiveMerge,
+ onChanged: (_loaded && !_podcastTabEnabled) ? (v) {
setState(() => _mergeAbsorbingLibraries = v);
PlayerSettings.setMergeAbsorbingLibraries(v);
} : null,
@@ -1832,7 +1905,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
]),
const SizedBox(height: 8),
// When libraries are merged, show a single unified control
- if (_mergeAbsorbingLibraries) ...[
+ if (_mergeAbsorbingLibraries || _podcastTabEnabled) ...[
Text(l.queueModeMergedSubtitle,
style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
const SizedBox(height: 8),
@@ -2928,6 +3001,65 @@ class _SettingsScreenState extends State<SettingsScreen> {
isExpanded: _expandedSection == 'Library',
onExpansionChanged: (v) => _onSectionExpanded('Library', v),
children: [
+ Consumer<LibraryProvider>(builder: (context, lib, _) {
+ final podcastLibs = lib.libraries
+ .whereType<Map<String, dynamic>>()
+ .where((l) => (l['mediaType'] as String? ?? 'book') == 'podcast')
+ .toList();
+ if (podcastLibs.isEmpty) return const SizedBox.shrink();
+ final currentName = podcastLibs.firstWhere(
+ (p) => p['id'] == _podcastTabLibraryId,
+ orElse: () => podcastLibs.first,
+ )['name'] as String? ?? '';
+ return Column(children: [
+ SwitchListTile(
+ title: Text(l.settingsPodcastTab),
+ subtitle: Text(l.settingsPodcastTabDesc,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _podcastTabEnabled,
+ onChanged: _loaded ? (v) async {
+ var libId = _podcastTabLibraryId;
+ if (v && !podcastLibs.any((p) => p['id'] == libId)) {
+ libId = podcastLibs.first['id'] as String;
+ await PlayerSettings.setPodcastTabLibraryId(libId);
+ }
+ setState(() {
+ _podcastTabEnabled = v;
+ _podcastTabLibraryId = libId;
+ });
+ await PlayerSettings.setPodcastTabEnabled(v);
+ } : null,
+ ),
+ if (_podcastTabEnabled && podcastLibs.length > 1)
+ ListTile(
+ title: Text(l.settingsPodcastTabLibrary),
+ subtitle: Text(currentName,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ trailing: Icon(Icons.chevron_right_rounded, color: cs.onSurfaceVariant),
+ onTap: () => _pickPodcastTabLibrary(podcastLibs),
+ ),
+ if (Platform.isAndroid) ...[
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ ListTile(
+ title: Text(l.settingsEpisodeNotifs),
+ subtitle: Text(
+ '${l.settingsEpisodeNotifsDesc} - ${_episodeNotifLabel(l)}',
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ trailing: Icon(Icons.chevron_right_rounded, color: cs.onSurfaceVariant),
+ onTap: _loaded ? _pickEpisodeNotifInterval : null,
+ ),
+ if (_episodeNotifMinutes > 0)
+ ListTile(
+ title: Text(l.settingsBatteryUnrestricted),
+ subtitle: Text(l.settingsBatteryUnrestrictedDesc,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ trailing: Icon(Icons.battery_saver_rounded, color: cs.onSurfaceVariant),
+ onTap: () => Permission.ignoreBatteryOptimizations.request(),
+ ),
+ ],
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ ]);
+ }),
SwitchListTile(
title: Text(l.hideEbookOnlyTitles),
subtitle: Text(
@@ -4002,6 +4134,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
if (settings?['manualSeedColor'] is int) applyManualSeed(settings!['manualSeedColor'] as int);
if (settings?['gradientIntensity'] is num) applyGradientIntensity((settings!['gradientIntensity'] as num).toDouble());
if (settings?['useColorEverywhere'] is bool) applyUseColorEverywhere(settings!['useColorEverywhere'] as bool);
+ await applyOrientationLock();
// Refresh UI
await _loadSettings();
diff --git a/lib/services/api_service.dart b/lib/services/api_service.dart
index c3f65440..3a723c6f 100644
--- a/lib/services/api_service.dart
+++ b/lib/services/api_service.dart
@@ -119,6 +119,9 @@ class ApiService {
_refreshCompleter = Completer<bool>();
try {
+ // Timeout is load-bearing: this is awaited from tryRestoreSession via
+ // the 401-retry path, and a stalled response here would otherwise hold
+ // the splash screen forever.
final response = await http.post(
Uri.parse('$_cleanBaseUrl/api/authorize'),
headers: {
@@ -126,7 +129,7 @@ class ApiService {
'Authorization': 'Bearer $_refreshToken',
'x-return-tokens': 'true',
},
- );
+ ).timeout(const Duration(seconds: 15));
if (response.statusCode == 200) {
final data = jsonDecode(response.body) as Map<String, dynamic>;
@@ -1328,10 +1331,10 @@ class ApiService {
/// Get recent podcast episodes for a library.
/// GET /api/libraries/:id/recent-episodes
- Future<List<dynamic>> getRecentEpisodes(String libraryId, {int limit = 25}) async {
+ Future<List<dynamic>> getRecentEpisodes(String libraryId, {int limit = 25, int page = 0}) async {
try {
final resp = await _authGet(
- Uri.parse('$_cleanBaseUrl/api/libraries/$libraryId/recent-episodes?limit=$limit'),
+ Uri.parse('$_cleanBaseUrl/api/libraries/$libraryId/recent-episodes?limit=$limit&page=$page'),
);
if (resp.statusCode == 200) {
final data = jsonDecode(resp.body);
diff --git a/lib/services/backup_service.dart b/lib/services/backup_service.dart
index 84afcc81..bc88c21f 100644
--- a/lib/services/backup_service.dart
+++ b/lib/services/backup_service.dart
@@ -55,7 +55,10 @@ class BackupService {
'rollingDownloadCount': await PlayerSettings.getRollingDownloadCount(),
'rollingDownloadDeleteFinished': await PlayerSettings.getRollingDownloadDeleteFinished(),
'queueAutoDownload': await PlayerSettings.getQueueAutoDownload(),
- 'mergeAbsorbingLibraries': await PlayerSettings.getMergeAbsorbingLibraries(),
+ 'mergeAbsorbingLibraries': await PlayerSettings.getMergeAbsorbingLibrariesRaw(),
+ 'podcastTabEnabled': await PlayerSettings.getPodcastTabEnabled(),
+ 'podcastTabLibraryId': await PlayerSettings.getPodcastTabLibraryId(),
+ 'episodeNotifIntervalMinutes': await PlayerSettings.getEpisodeNotifIntervalMinutes(),
'maxConcurrentDownloads': await PlayerSettings.getMaxConcurrentDownloads(),
'colorSource': await PlayerSettings.getColorSource(),
'flatBackground': await PlayerSettings.getFlatBackground(),
@@ -441,6 +444,9 @@ class BackupService {
if (s['rollingDownloadDeleteFinished'] != null) PlayerSettings.setRollingDownloadDeleteFinished(s['rollingDownloadDeleteFinished'] as bool);
if (s['queueAutoDownload'] != null) PlayerSettings.setQueueAutoDownload(s['queueAutoDownload'] as bool);
if (s['mergeAbsorbingLibraries'] != null) PlayerSettings.setMergeAbsorbingLibraries(s['mergeAbsorbingLibraries'] as bool);
+ if (s['podcastTabEnabled'] != null) PlayerSettings.setPodcastTabEnabled(s['podcastTabEnabled'] as bool);
+ if (s['podcastTabLibraryId'] != null) PlayerSettings.setPodcastTabLibraryId(s['podcastTabLibraryId'] as String);
+ if (s['episodeNotifIntervalMinutes'] != null) PlayerSettings.setEpisodeNotifIntervalMinutes(s['episodeNotifIntervalMinutes'] as int);
if (s['maxConcurrentDownloads'] != null) PlayerSettings.setMaxConcurrentDownloads(s['maxConcurrentDownloads'] as int);
if (s['colorSource'] != null) PlayerSettings.setColorSource(s['colorSource'] as String);
if (s['flatBackground'] != null) PlayerSettings.setFlatBackground(s['flatBackground'] as bool);
diff --git a/lib/services/download_service.dart b/lib/services/download_service.dart
index 84cffecd..6d0abb43 100644
--- a/lib/services/download_service.dart
+++ b/lib/services/download_service.dart
@@ -283,6 +283,13 @@ class DownloadService extends ChangeNotifier {
factory DownloadService() => _instance;
DownloadService._();
+ /// Set to true (before init) by short-lived background isolates like the
+ /// episode-notification job. Downloads then run as plain background tasks
+ /// instead of in the foreground service: Android 15+ kills a dataSync
+ /// foreground service started while the app is in the background almost
+ /// immediately ("FGS (dataSync) timed out"), leaving the task stuck at 0%.
+ static bool backgroundIsolateMode = false;
+
final Map<String, DownloadInfo> _downloads = {};
final Set<String> _activeDownloadIds = {};
final Set<String> _cancelledIds = {};
@@ -695,13 +702,19 @@ class DownloadService extends ChangeNotifier {
/// continue when backgrounded, locked, or killed.
Future<void> _configureDownloader() async {
if (_downloaderConfigured) return;
- // Always run downloads in the Android foreground service. Without this,
- // smaller books can run as background WorkManager jobs that some OEM ROMs
- // throttle or kill, leaving downloads stuck.
+ // Run downloads in the Android foreground service. Without this, smaller
+ // books can run as background WorkManager jobs that some OEM ROMs throttle
+ // or kill, leaving downloads stuck. Exception: background isolates must NOT
+ // use the foreground service (see backgroundIsolateMode) - the app's next
+ // real start reconfigures back to always.
if (Platform.isAndroid) {
try {
- await FileDownloader()
- .configure(androidConfig: [(Config.runInForeground, Config.always)]);
+ await FileDownloader().configure(androidConfig: [
+ (
+ Config.runInForeground,
+ backgroundIsolateMode ? Config.never : Config.always,
+ ),
+ ]);
} catch (e) {
debugPrint('[Download] androidConfig failed: $e');
}
@@ -1247,6 +1260,42 @@ class DownloadService extends ChangeNotifier {
return null;
}
+ /// Download entry point for short-lived background isolates (the episode
+ /// notification job). Same guards as [downloadItem], but awaits the enqueue
+ /// (the isolate dies as soon as the task returns, which would cut off a
+ /// fire-and-forget mid-flight) and skips the in-memory concurrency queue
+ /// (queued entries would die with the isolate; background_downloader
+ /// schedules the handed-over tasks natively either way).
+ Future<void> enqueueBackgroundDownload({
+ required ApiService api,
+ required String itemId,
+ required String title,
+ String? author,
+ String? coverUrl,
+ String? episodeId,
+ String? libraryId,
+ }) async {
+ if (_activeDownloadIds.contains(itemId)) return;
+ if (isDownloaded(itemId)) return;
+ if (_queue.any((q) => q.itemId == itemId)) return;
+ final wifiOnly = await PlayerSettings.getWifiOnlyDownloads();
+ if (wifiOnly) {
+ final connectivity = await Connectivity().checkConnectivity();
+ // Not on WiFi: skip silently - the in-app catch-up still sees the
+ // episode as new and downloads it on the next open.
+ if (!connectivity.contains(ConnectivityResult.wifi)) return;
+ }
+ await _executeDownload(
+ api: api,
+ itemId: itemId,
+ title: title,
+ author: author,
+ coverUrl: coverUrl,
+ episodeId: episodeId,
+ libraryId: libraryId,
+ );
+ }
+
/// Fill free download slots from the queue.
Future<void> _processQueue() async {
final maxConcurrent = await PlayerSettings.getMaxConcurrentDownloads();
diff --git a/lib/services/episode_notification_service.dart b/lib/services/episode_notification_service.dart
new file mode 100644
index 00000000..5aac4076
--- /dev/null
+++ b/lib/services/episode_notification_service.dart
@@ -0,0 +1,256 @@
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:flutter/foundation.dart';
+import 'package:flutter_local_notifications/flutter_local_notifications.dart';
+import 'package:shared_preferences/shared_preferences.dart';
+import 'package:workmanager/workmanager.dart';
+
+import '../main.dart' show rootNavigatorKey;
+import '../providers/auth_provider.dart';
+import '../providers/library_provider.dart';
+import '../widgets/episode_list_sheet.dart';
+import 'api_service.dart';
+import 'download_service.dart';
+import 'player_settings.dart';
+import 'scoped_prefs.dart';
+import 'user_account_service.dart';
+import 'package:provider/provider.dart';
+
+/// Background new-episode notifications (Android). A WorkManager periodic job
+/// polls the subscribed shows and notifies about episodes it hasn't notified
+/// about before. The job keeps its own last-seen state (notified_episodes_*),
+/// separate from known_episodes_* - that one drives the in-app absorbing-queue
+/// insertion and auto-download and must keep seeing "new" episodes when the
+/// app next opens.
+class EpisodeNotificationService {
+ static const _uniqueName = 'com.barnabas.absorb.episodeNotifCheck';
+ static const channelId = 'new_episodes';
+
+ /// Register/cancel the periodic job to match the setting. Called on app
+ /// start (self-healing after OEM kills) and when the setting changes.
+ static Future<void> syncRegistration() async {
+ if (!Platform.isAndroid) return;
+ try {
+ final minutes = await PlayerSettings.getEpisodeNotifIntervalMinutes();
+ if (minutes <= 0) {
+ await Workmanager().cancelByUniqueName(_uniqueName);
+ return;
+ }
+ await Workmanager().initialize(episodeNotifDispatcher);
+ await Workmanager().registerPeriodicTask(
+ _uniqueName,
+ _uniqueName,
+ frequency: Duration(minutes: minutes),
+ existingWorkPolicy: ExistingPeriodicWorkPolicy.update,
+ constraints: Constraints(networkType: NetworkType.connected),
+ backoffPolicy: BackoffPolicy.linear,
+ );
+ debugPrint('[EpisodeNotif] periodic task registered every ${minutes}m');
+ } catch (e) {
+ debugPrint('[EpisodeNotif] syncRegistration failed: $e');
+ }
+ }
+
+ /// Foreground notification-tap wiring. Safe to call once at startup; also
+ /// resolves a cold start launched from a notification.
+ static Future<void> initTapHandling() async {
+ if (!Platform.isAndroid) return;
+ final plugin = FlutterLocalNotificationsPlugin();
+ await plugin.initialize(
+ const InitializationSettings(
+ android: AndroidInitializationSettings('drawable/ic_notification'),
+ ),
+ onDidReceiveNotificationResponse: (resp) => _handleTap(resp.payload),
+ );
+ final launch = await plugin.getNotificationAppLaunchDetails();
+ if (launch?.didNotificationLaunchApp == true) {
+ _handleTap(launch!.notificationResponse?.payload);
+ }
+ }
+
+ /// Open the show's episode list once the app (navigator + session) is up.
+ static Future<void> _handleTap(String? payload) async {
+ if (payload == null || !payload.startsWith('show:')) return;
+ final showId = payload.substring(5);
+ for (var i = 0; i < 60; i++) {
+ final ctx = rootNavigatorKey.currentContext;
+ if (ctx != null && ctx.mounted) {
+ try {
+ final api = ctx.read<AuthProvider>().apiService;
+ if (api != null) {
+ // Warm the provider so progress/covers resolve in the sheet.
+ ctx.read<LibraryProvider>();
+ final item = await api.getLibraryItem(showId);
+ final ctx2 = rootNavigatorKey.currentContext;
+ if (item != null && ctx2 != null && ctx2.mounted) {
+ EpisodeListSheet.show(ctx2, item);
+ }
+ return;
+ }
+ } catch (_) {}
+ }
+ await Future.delayed(const Duration(milliseconds: 500));
+ }
+ }
+}
+
+/// WorkManager entry point - runs in a fresh background isolate.
+@pragma('vm:entry-point')
+void episodeNotifDispatcher() {
+ Workmanager().executeTask((task, inputData) async {
+ try {
+ await _checkAndNotify();
+ } catch (e) {
+ debugPrint('[EpisodeNotif] background check failed: $e');
+ }
+ // Never ask WorkManager to retry: the next periodic run covers it.
+ return true;
+ });
+}
+
+Future<void> _checkAndNotify() async {
+ // Resolve the active account scope so ScopedPrefs reads hit the right user.
+ await UserAccountService().init();
+
+ final subscribed = await ScopedPrefs.getStringList('subscribed_podcasts');
+ if (subscribed.isEmpty) return;
+
+ final api = await _buildApiService();
+ if (api == null) return;
+
+ final plugin = FlutterLocalNotificationsPlugin();
+ const channel = AndroidNotificationChannel(
+ EpisodeNotificationService.channelId,
+ 'New episodes',
+ description: 'New episodes from subscribed podcasts',
+ importance: Importance.defaultImportance,
+ );
+ await plugin
+ .resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()
+ ?.createNotificationChannel(channel);
+
+ DownloadService? dl;
+ for (final showId in subscribed) {
+ try {
+ final item = await api.getLibraryItem(showId);
+ if (item == null) continue;
+ final media = item['media'] as Map<String, dynamic>? ?? {};
+ final episodes = (media['episodes'] as List<dynamic>? ?? [])
+ .whereType<Map<String, dynamic>>()
+ .toList();
+ if (episodes.isEmpty) continue;
+
+ final key = 'notified_episodes_$showId';
+ final seen = (await ScopedPrefs.getStringList(key)).toSet();
+ final currentIds =
+ episodes.map((e) => e['id'] as String? ?? '').where((id) => id.isNotEmpty).toList();
+
+ // First sight of this show (fresh subscribe or feature just enabled):
+ // seed silently so we don't blast the whole back catalog.
+ if (seen.isEmpty) {
+ await ScopedPrefs.setStringList(key, currentIds);
+ continue;
+ }
+
+ final fresh = episodes
+ .where((e) => !seen.contains(e['id'] as String? ?? ''))
+ .toList();
+ if (fresh.isEmpty) continue;
+
+ final showTitle =
+ ((media['metadata'] as Map<String, dynamic>?)?['title'] as String?) ??
+ 'Podcast';
+ final body = fresh.length == 1
+ ? (fresh.first['title'] as String? ?? 'New episode')
+ : '${fresh.length} new episodes';
+ await plugin.show(
+ // Stable per-show id so repeat checks update rather than stack.
+ 0x45500000 | (showId.hashCode & 0xFFFFF),
+ showTitle,
+ body,
+ const NotificationDetails(
+ android: AndroidNotificationDetails(
+ EpisodeNotificationService.channelId,
+ 'New episodes',
+ channelDescription: 'New episodes from subscribed podcasts',
+ icon: 'drawable/ic_notification',
+ importance: Importance.defaultImportance,
+ priority: Priority.defaultPriority,
+ ),
+ ),
+ payload: 'show:$showId',
+ );
+
+ await ScopedPrefs.setStringList(key, [...seen, ...fresh.map((e) => e['id'] as String)]);
+
+ // Start the downloads now so the episodes are ready when the app next
+ // opens - same auto-download behavior as the in-app catch-up (WiFi-only
+ // setting respected inside enqueueBackgroundDownload). If anything here
+ // fails, the in-app catch-up still downloads them: known_episodes_*
+ // hasn't seen these episodes yet.
+ try {
+ if (dl == null) {
+ DownloadService.backgroundIsolateMode = true;
+ dl = DownloadService();
+ await dl.init();
+ }
+ for (final ep in fresh) {
+ final epId = ep['id'] as String;
+ await dl.enqueueBackgroundDownload(
+ api: api,
+ itemId: '$showId-$epId',
+ title: ep['title'] as String? ?? 'Episode',
+ author: showTitle,
+ coverUrl: api.getCoverUrl(showId),
+ episodeId: epId,
+ libraryId: item['libraryId'] as String?,
+ );
+ }
+ } catch (e) {
+ debugPrint('[EpisodeNotif] download enqueue failed for $showId: $e');
+ }
+ } catch (e) {
+ debugPrint('[EpisodeNotif] check failed for $showId: $e');
+ }
+ }
+}
+
+/// ApiService from raw prefs - same pattern as the home-widget cold path
+/// (server_url/token/refresh_token/custom_headers, prefer a reachable local
+/// server so home-WiFi setups work).
+Future<ApiService?> _buildApiService() async {
+ final prefs = await SharedPreferences.getInstance();
+ final remoteUrl = prefs.getString('server_url');
+ final token = prefs.getString('token');
+ if (remoteUrl == null || token == null) return null;
+ final refreshToken = prefs.getString('refresh_token');
+
+ Map<String, String>? customHeaders;
+ final headersJson = prefs.getString('custom_headers');
+ if (headersJson != null) {
+ try {
+ customHeaders = Map<String, String>.from(jsonDecode(headersJson) as Map);
+ } catch (_) {}
+ }
+ final headers = customHeaders ?? const <String, String>{};
+
+ String baseUrl = remoteUrl;
+ final localEnabled = await PlayerSettings.getLocalServerEnabled();
+ final localUrl = await PlayerSettings.getLocalServerUrl();
+ if (localEnabled && localUrl.isNotEmpty) {
+ final localReachable = await ApiService.pingServer(localUrl, customHeaders: headers)
+ .timeout(const Duration(seconds: 3), onTimeout: () => false);
+ if (localReachable) baseUrl = localUrl;
+ }
+
+ return ApiService(
+ baseUrl: baseUrl,
+ token: token,
+ refreshToken: refreshToken,
+ isLegacyToken: refreshToken == null,
+ customHeaders: headers,
+ onTokensRefreshed: (access, refresh) =>
+ UserAccountService().persistRefreshedTokens(access, refresh),
+ );
+}
diff --git a/lib/services/player_settings.dart b/lib/services/player_settings.dart
index 328d4367..5815f71e 100644
--- a/lib/services/player_settings.dart
+++ b/lib/services/player_settings.dart
@@ -153,9 +153,28 @@ class PlayerSettings {
static Future<String> getBookmarkSort() => _get('bookmarkSort', 'newest');
static Future<void> setBookmarkSort(String value) => _set('bookmarkSort', value);
- static Future<bool> getMergeAbsorbingLibraries() => _get('mergeAbsorbingLibraries', false);
+ // The dedicated Podcasts tab implies merged behavior: playback must survive
+ // the tab-driven library flips and the Absorbing tab must keep showing the
+ // playing item from either tab.
+ static Future<bool> getMergeAbsorbingLibraries() async =>
+ await _get('mergeAbsorbingLibraries', false) || await getPodcastTabEnabled();
+ /// The stored toggle value, without the Podcasts-tab implication. For the
+ /// settings UI and backups - exporting the effective value would bake
+ /// merge=true into a restore permanently.
+ static Future<bool> getMergeAbsorbingLibrariesRaw() => _get('mergeAbsorbingLibraries', false);
static Future<void> setMergeAbsorbingLibraries(bool value) => _set('mergeAbsorbingLibraries', value);
+ // Dedicated bottom-nav Podcasts tab (pinned to one podcast library).
+ static Future<bool> getPodcastTabEnabled() => _get('podcastTabEnabled', false);
+ static Future<void> setPodcastTabEnabled(bool value) => _set('podcastTabEnabled', value, notify: true);
+ static Future<String> getPodcastTabLibraryId() => _get('podcastTabLibraryId', '');
+ static Future<void> setPodcastTabLibraryId(String value) => _set('podcastTabLibraryId', value, notify: true);
+
+ // Background new-episode notification checks, in minutes (0 = off).
+ // WorkManager's floor for periodic jobs is 15 minutes.
+ static Future<int> getEpisodeNotifIntervalMinutes() => _get('episodeNotifIntervalMinutes', 0);
+ static Future<void> setEpisodeNotifIntervalMinutes(int value) => _set('episodeNotifIntervalMinutes', value, notify: true);
+
static Future<int> getMaxConcurrentDownloads() => _get('maxConcurrentDownloads', 1);
static Future<void> setMaxConcurrentDownloads(int value) => _set('maxConcurrentDownloads', value);
diff --git a/lib/widgets/library_picker_sheet.dart b/lib/widgets/library_picker_sheet.dart
new file mode 100644
index 00000000..a63bf8c7
--- /dev/null
+++ b/lib/widgets/library_picker_sheet.dart
@@ -0,0 +1,102 @@
+import 'package:flutter/material.dart';
+import '../l10n/app_localizations.dart';
+import '../providers/library_provider.dart';
+import '../services/player_settings.dart';
+
+/// Bottom-sheet library switcher shared by the Home/Library headers and the
+/// bottom-nav long-press. When the dedicated Podcasts tab is enabled, its
+/// library is hidden here - the tab is its only surface.
+Future<void> showLibraryPickerSheet(
+ BuildContext context,
+ LibraryProvider lib,
+) async {
+ String? excludeLibraryId;
+ if (await PlayerSettings.getPodcastTabEnabled()) {
+ final id = await PlayerSettings.getPodcastTabLibraryId();
+ if (id.isNotEmpty) excludeLibraryId = id;
+ }
+ if (!context.mounted) return;
+
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ final l = AppLocalizations.of(context)!;
+ final allLibraries = lib.libraries
+ .whereType<Map<String, dynamic>>()
+ .where((library) => library['id'] != excludeLibraryId)
+ .toList();
+
+ showModalBottomSheet(
+ context: context,
+ isScrollControlled: true,
+ useSafeArea: true,
+ backgroundColor: Colors.transparent,
+ builder: (ctx) {
+ final bottomPad = MediaQuery.of(ctx).viewPadding.bottom;
+ return Container(
+ constraints: BoxConstraints(
+ maxHeight: MediaQuery.of(ctx).size.height * 0.6,
+ ),
+ decoration: BoxDecoration(
+ color: cs.surface,
+ borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
+ ),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ const SizedBox(height: 12),
+ Center(
+ child: Container(
+ width: 40,
+ height: 4,
+ decoration: BoxDecoration(
+ color: cs.onSurfaceVariant.withValues(alpha: 0.3),
+ borderRadius: BorderRadius.circular(2),
+ ),
+ ),
+ ),
+ const SizedBox(height: 16),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 24),
+ child: Text(
+ l.selectLibrary,
+ style: tt.titleLarge?.copyWith(fontWeight: FontWeight.w600),
+ ),
+ ),
+ const SizedBox(height: 12),
+ Flexible(
+ child: ListView.builder(
+ shrinkWrap: true,
+ padding: EdgeInsets.only(bottom: bottomPad + 16),
+ itemCount: allLibraries.length,
+ itemBuilder: (_, i) {
+ final library = allLibraries[i];
+ final id = library['id'] as String;
+ final name = library['name'] as String? ?? l.libraryFallback;
+ final mediaType = library['mediaType'] as String? ?? 'book';
+ final isSelected = id == lib.selectedLibraryId;
+ return ListTile(
+ leading: Icon(
+ mediaType == 'podcast'
+ ? Icons.podcasts_rounded
+ : Icons.auto_stories_rounded,
+ color: isSelected ? cs.primary : cs.onSurfaceVariant,
+ ),
+ title: Text(name),
+ trailing: isSelected
+ ? Icon(Icons.check_circle_rounded, color: cs.primary)
+ : null,
+ selected: isSelected,
+ onTap: () {
+ Navigator.pop(ctx);
+ if (!isSelected) lib.selectLibrary(id);
+ },
+ );
+ },
+ ),
+ ),
+ ],
+ ),
+ );
+ },
+ );
+}
diff --git a/lib/widgets/overlay_toast.dart b/lib/widgets/overlay_toast.dart
index 3680962e..8d67eb12 100644
--- a/lib/widgets/overlay_toast.dart
+++ b/lib/widgets/overlay_toast.dart
@@ -10,7 +10,10 @@ void showOverlayToast(BuildContext context, String message, {IconData? icon}) {
_currentToast?.remove();
_currentToast = null;
- final overlay = Overlay.of(context);
+ // No overlay (startup, account switch, background-triggered callers): drop
+ // the toast instead of throwing into whatever async flow asked for it.
+ final overlay = Overlay.maybeOf(context);
+ if (overlay == null) return;
late OverlayEntry entry;
entry = OverlayEntry(
builder: (_) => _AnimatedToast(
diff --git a/lib/widgets/podcast_episode_feed.dart b/lib/widgets/podcast_episode_feed.dart
new file mode 100644
index 00000000..bfd59bf0
--- /dev/null
+++ b/lib/widgets/podcast_episode_feed.dart
@@ -0,0 +1,460 @@
+import 'dart:io';
+
+import 'package:cached_network_image/cached_network_image.dart';
+import 'package:flutter/material.dart';
+import 'package:provider/provider.dart';
+import '../l10n/app_localizations.dart';
+import '../providers/auth_provider.dart';
+import '../providers/library_provider.dart';
+import '../services/audio_player_service.dart';
+import '../services/chromecast_service.dart';
+import '../services/download_service.dart';
+import '../services/scoped_prefs.dart';
+import 'card_buttons.dart' show showErrorSnackBar;
+import 'episode_list_sheet.dart';
+import 'episode_row.dart';
+import 'overlay_toast.dart';
+
+/// Recent-episodes feed for podcast libraries (the "Episodes" pill): the
+/// library's newest episodes across all shows, with quick filters and swipe
+/// actions (mark played / download).
+class PodcastEpisodeFeed extends StatefulWidget {
+ final String libraryId;
+
+ /// The library page header (title, search, library chip), passed in so the
+ /// feed keeps the same chrome as the Shows grid.
+ final Widget? headerSliver;
+ const PodcastEpisodeFeed({
+ super.key,
+ required this.libraryId,
+ this.headerSliver,
+ });
+
+ @override
+ State<PodcastEpisodeFeed> createState() => _PodcastEpisodeFeedState();
+}
+
+class _PodcastEpisodeFeedState extends State<PodcastEpisodeFeed> {
+ static const _pageSize = 50;
+
+ final _episodes = <Map<String, dynamic>>[];
+ bool _loading = true;
+ bool _loadingMore = false;
+ bool _hasMore = true;
+ int _page = 0;
+ String? _error;
+ String _filter = 'all';
+ final _scroll = ScrollController();
+
+ @override
+ void initState() {
+ super.initState();
+ ScopedPrefs.getString('episode_feed_filter_${widget.libraryId}').then((v) {
+ if (mounted && v != null && v.isNotEmpty) setState(() => _filter = v);
+ });
+ _scroll.addListener(_onScroll);
+ _loadPage();
+ }
+
+ @override
+ void dispose() {
+ _scroll.dispose();
+ super.dispose();
+ }
+
+ void _onScroll() {
+ if (!_hasMore || _loadingMore || _loading) return;
+ if (_scroll.position.pixels > _scroll.position.maxScrollExtent - 600) {
+ _loadPage();
+ }
+ }
+
+ Future<void> _loadPage() async {
+ final api = context.read<AuthProvider>().apiService;
+ if (api == null) {
+ setState(() {
+ _error = 'Not connected to server';
+ _loading = false;
+ });
+ return;
+ }
+ setState(() => _loadingMore = _page > 0);
+ final batch = await api.getRecentEpisodes(
+ widget.libraryId,
+ limit: _pageSize,
+ page: _page,
+ );
+ if (!mounted) return;
+ setState(() {
+ _episodes.addAll(batch.whereType<Map<String, dynamic>>());
+ _hasMore = batch.length >= _pageSize;
+ _page++;
+ _loading = false;
+ _loadingMore = false;
+ });
+ }
+
+ Future<void> _refresh() async {
+ _episodes.clear();
+ _page = 0;
+ _hasMore = true;
+ await _loadPage();
+ }
+
+ void _setFilter(String f) {
+ if (f == _filter) return;
+ setState(() => _filter = f);
+ ScopedPrefs.setString('episode_feed_filter_${widget.libraryId}', f);
+ }
+
+ String _showIdOf(Map<String, dynamic> ep) =>
+ ep['libraryItemId'] as String? ??
+ ep['podcastId'] as String? ??
+ (ep['podcast'] as Map<String, dynamic>?)?['id'] as String? ??
+ '';
+
+ /// The recent-episodes payload carries the parent show as `podcast` (a
+ /// library item without its episode list). Fall back to a minimal synthetic
+ /// item so the detail sheets can still resolve title/cover by id.
+ Map<String, dynamic> _podcastItemOf(Map<String, dynamic> ep) {
+ final podcast = ep['podcast'];
+ if (podcast is Map<String, dynamic> && podcast['id'] != null) {
+ return {
+ ...podcast,
+ 'libraryId': podcast['libraryId'] ?? widget.libraryId,
+ };
+ }
+ return {
+ 'id': _showIdOf(ep),
+ 'libraryId': widget.libraryId,
+ 'mediaType': 'podcast',
+ 'media': {
+ 'metadata': {'title': ep['podcastTitle'] as String? ?? ''},
+ },
+ };
+ }
+
+ String _showTitleOf(Map<String, dynamic> ep) {
+ final podcast = ep['podcast'] as Map<String, dynamic>?;
+ final meta =
+ (podcast?['media'] as Map<String, dynamic>?)?['metadata']
+ as Map<String, dynamic>?;
+ return meta?['title'] as String? ?? ep['podcastTitle'] as String? ?? '';
+ }
+
+ Widget _showCover(LibraryProvider lib, String showId, ColorScheme cs) {
+ final url = lib.getCoverUrl(showId, width: 96);
+ final placeholder = Container(
+ width: 48,
+ height: 48,
+ color: cs.surfaceContainer,
+ child: Icon(Icons.podcasts_rounded, size: 22, color: cs.onSurfaceVariant),
+ );
+ return ClipRRect(
+ borderRadius: BorderRadius.circular(8),
+ child: url == null
+ ? placeholder
+ // Downloaded shows resolve to a local file path.
+ : url.startsWith('/')
+ ? Image.file(
+ File(url),
+ width: 48,
+ height: 48,
+ fit: BoxFit.cover,
+ errorBuilder: (_, __, ___) => placeholder,
+ )
+ : CachedNetworkImage(
+ imageUrl: url,
+ httpHeaders: lib.mediaHeaders,
+ width: 48,
+ height: 48,
+ fit: BoxFit.cover,
+ errorWidget: (_, __, ___) => placeholder,
+ ),
+ );
+ }
+
+ bool _matchesFilter(LibraryProvider lib, Map<String, dynamic> ep) {
+ if (_filter == 'all') return true;
+ final showId = _showIdOf(ep);
+ final epId = ep['id'] as String? ?? '';
+ if (_filter == 'downloaded') {
+ return DownloadService().isDownloaded('$showId-$epId');
+ }
+ final progress = lib.getEpisodeProgress(showId, epId);
+ final finished =
+ lib.getEpisodeProgressData(showId, epId)?['isFinished'] == true;
+ if (_filter == 'unplayed') return progress <= 0 && !finished;
+ if (_filter == 'inprogress') return progress > 0 && !finished;
+ return true;
+ }
+
+ Future<void> _playEpisode(Map<String, dynamic> ep) async {
+ final api = context.read<AuthProvider>().apiService;
+ if (api == null) return;
+ final showId = _showIdOf(ep);
+ final episodeId = ep['id'] as String? ?? '';
+ final title = ep['title'] as String? ?? '';
+ final duration = (ep['duration'] as num?)?.toDouble() ?? 0;
+ final coverUrl = api.getCoverUrl(showId);
+ final chapters = ep['chapters'] as List<dynamic>? ?? [];
+ final showTitle = _showTitleOf(ep);
+
+ final cast = ChromecastService();
+ if (cast.isConnected) {
+ await cast.castItem(
+ api: api,
+ itemId: showId,
+ title: title,
+ author: showTitle,
+ coverUrl: coverUrl,
+ totalDuration: duration,
+ chapters: chapters,
+ episodeId: episodeId,
+ );
+ return;
+ }
+ final error = await AudioPlayerService().playItem(
+ api: api,
+ itemId: showId,
+ title: title,
+ author: showTitle,
+ coverUrl: coverUrl,
+ totalDuration: duration,
+ chapters: chapters,
+ episodeId: episodeId,
+ episodeTitle: title,
+ libraryId: widget.libraryId,
+ );
+ if (error != null && mounted) showErrorSnackBar(context, error);
+ }
+
+ Future<void> _downloadEpisode(Map<String, dynamic> ep) async {
+ final api = context.read<AuthProvider>().apiService;
+ if (api == null) return;
+ final showId = _showIdOf(ep);
+ final episodeId = ep['id'] as String? ?? '';
+ final error = await DownloadService().downloadItem(
+ api: api,
+ itemId: '$showId-$episodeId',
+ title: ep['title'] as String? ?? '',
+ author: _showTitleOf(ep),
+ coverUrl: api.getCoverUrl(showId),
+ episodeId: episodeId,
+ libraryId: widget.libraryId,
+ );
+ if (error != null && mounted) {
+ showOverlayToast(context, error, icon: Icons.error_outline_rounded);
+ }
+ }
+
+ Future<void> _toggleFinished(Map<String, dynamic> ep) async {
+ final api = context.read<AuthProvider>().apiService;
+ if (api == null) return;
+ final lib = context.read<LibraryProvider>();
+ final showId = _showIdOf(ep);
+ final epId = ep['id'] as String? ?? '';
+ final duration = (ep['duration'] as num?)?.toDouble() ?? 0;
+ final finished =
+ lib.getEpisodeProgressData(showId, epId)?['isFinished'] == true;
+
+ if (finished) {
+ await api.updateEpisodeProgress(
+ showId,
+ epId,
+ currentTime: 0,
+ duration: duration,
+ isFinished: false,
+ );
+ await lib.refreshProgressOnly();
+ } else {
+ await api.updateEpisodeProgress(
+ showId,
+ epId,
+ currentTime: duration,
+ duration: duration,
+ isFinished: true,
+ );
+ lib.markFinishedLocally('$showId-$epId', skipAutoAdvance: true);
+ }
+ if (mounted) setState(() {});
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final l = AppLocalizations.of(context)!;
+ final lib = context.watch<LibraryProvider>();
+
+ if (_loading) {
+ return const Center(child: CircularProgressIndicator());
+ }
+ if (_error != null && _episodes.isEmpty) {
+ return Center(
+ child: Padding(
+ padding: const EdgeInsets.all(24),
+ child: Text(
+ _error!,
+ textAlign: TextAlign.center,
+ style: TextStyle(color: cs.onSurfaceVariant),
+ ),
+ ),
+ );
+ }
+
+ final filtered = _episodes.where((ep) => _matchesFilter(lib, ep)).toList();
+
+ return RefreshIndicator(
+ onRefresh: _refresh,
+ child: CustomScrollView(
+ controller: _scroll,
+ physics: const AlwaysScrollableScrollPhysics(),
+ slivers: [
+ if (widget.headerSliver != null) widget.headerSliver!,
+ SliverToBoxAdapter(
+ child: SafeArea(
+ bottom: false,
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(16, 8, 16, 4),
+ child: SingleChildScrollView(
+ scrollDirection: Axis.horizontal,
+ child: Row(
+ children: [
+ for (final (key, label) in [
+ ('all', l.filterAllEpisodes),
+ ('unplayed', l.filterUnplayed),
+ ('inprogress', l.inProgress),
+ ('downloaded', l.downloaded),
+ ]) ...[
+ ChoiceChip(
+ label: Text(label),
+ selected: _filter == key,
+ onSelected: (_) => _setFilter(key),
+ visualDensity: VisualDensity.compact,
+ ),
+ const SizedBox(width: 8),
+ ],
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ if (filtered.isEmpty)
+ SliverFillRemaining(
+ hasScrollBody: false,
+ child: Center(
+ child: Text(
+ l.episodeFeedEmpty,
+ style: TextStyle(color: cs.onSurfaceVariant),
+ ),
+ ),
+ )
+ else
+ SliverList.builder(
+ itemCount: filtered.length + (_loadingMore ? 1 : 0),
+ itemBuilder: (context, i) {
+ if (i >= filtered.length) {
+ return const Padding(
+ padding: EdgeInsets.all(16),
+ child: Center(
+ child: SizedBox(
+ width: 22,
+ height: 22,
+ child: CircularProgressIndicator(strokeWidth: 2),
+ ),
+ ),
+ );
+ }
+ final ep = filtered[i];
+ final showId = _showIdOf(ep);
+ final epId = ep['id'] as String? ?? '';
+ final finished =
+ lib.getEpisodeProgressData(showId, epId)?['isFinished'] ==
+ true;
+ return Dismissible(
+ key: ValueKey('feed-$showId-$epId'),
+ // Swipes act without dismissing the row.
+ confirmDismiss: (direction) async {
+ if (direction == DismissDirection.startToEnd) {
+ _toggleFinished(ep);
+ } else {
+ _downloadEpisode(ep);
+ }
+ return false;
+ },
+ background: Container(
+ color: cs.primaryContainer,
+ alignment: Alignment.centerLeft,
+ padding: const EdgeInsets.only(left: 24),
+ child: Icon(
+ finished
+ ? Icons.radio_button_unchecked_rounded
+ : Icons.check_circle_rounded,
+ color: cs.onPrimaryContainer,
+ ),
+ ),
+ secondaryBackground: Container(
+ color: cs.secondaryContainer,
+ alignment: Alignment.centerRight,
+ padding: const EdgeInsets.only(right: 24),
+ child: Icon(
+ Icons.download_rounded,
+ color: cs.onSecondaryContainer,
+ ),
+ ),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.center,
+ children: [
+ // Show cover so the feed reads at a glance; tapping it
+ // opens the show's episode list.
+ Padding(
+ padding: const EdgeInsets.only(left: 16),
+ child: GestureDetector(
+ onTap: () => EpisodeListSheet.show(
+ context,
+ _podcastItemOf(ep),
+ ),
+ child: _showCover(lib, showId, cs),
+ ),
+ ),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Padding(
+ padding: const EdgeInsets.only(left: 20, top: 2),
+ child: Text(
+ _showTitleOf(ep),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: TextStyle(
+ fontSize: 11,
+ fontWeight: FontWeight.w600,
+ color: cs.primary,
+ ),
+ ),
+ ),
+ EpisodeRow(
+ episode: ep,
+ podcastItem: _podcastItemOf(ep),
+ itemId: showId,
+ podcastTitle: _showTitleOf(ep),
+ onPlay: () => _playEpisode(ep),
+ onDownload: () => _downloadEpisode(ep),
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ );
+ },
+ ),
+ // Room for the floating pill bar.
+ const SliverToBoxAdapter(child: SizedBox(height: 96)),
+ ],
+ ),
+ );
+ }
+}
diff --git a/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/AudioServicePlugin.java b/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/AudioServicePlugin.java
index b776a840..c38ee2e3 100644
--- a/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/AudioServicePlugin.java
+++ b/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/AudioServicePlugin.java
@@ -266,6 +266,7 @@ public class AudioServicePlugin implements FlutterPlugin, ActivityAware {
public void onAttachedToEngine(FlutterPluginBinding binding) {
flutterPluginBinding = binding;
clientInterface = new ClientInterface(flutterPluginBinding.getBinaryMessenger());
+ clientInterface.plugin = this;
clientInterface.setContext(flutterPluginBinding.getApplicationContext());
clientInterfaces.add(clientInterface);
if (applicationContext == null) {
@@ -278,9 +279,13 @@ public class AudioServicePlugin implements FlutterPlugin, ActivityAware {
audioHandlerInterface = new AudioHandlerInterface(flutterPluginBinding.getBinaryMessenger());
AudioService.init(audioHandlerInterface);
}
- if (mediaBrowser == null) {
- connect();
- }
+ // Absorb patch: do NOT connect() here. Auxiliary engines (WorkManager's
+ // background job) also attach this plugin, and connecting from them
+ // starts AudioService, which caches a FlutterEngine running the full
+ // app main() headless in a frozen background process - the activity
+ // then attaches to that stuck engine and sits on the splash screen.
+ // Engines that actually host audio connect via onAttachedToActivity or
+ // the "configure" call below.
}
@Override
@@ -413,6 +418,10 @@ public class AudioServicePlugin implements FlutterPlugin, ActivityAware {
private final MethodChannel channel;
private boolean wrongEngineDetected;
private boolean serviceConnectionFailed;
+ // Absorb patch: back-reference to the owning plugin instance so the
+ // "configure" handler can call the (instance) connect() - see the
+ // connect() relocation comments in onAttachedToEngine.
+ private AudioServicePlugin plugin;
// This is implemented in Dart already.
// But we may need to bring this back if we want to connect to another process's media session.
@@ -500,6 +509,14 @@ public class AudioServicePlugin implements FlutterPlugin, ActivityAware {
}
audioHandlerInterface.invokePendingMethods();
}
+ // Absorb patch: connect() moved here from onAttachedToEngine
+ // (see the comment there). This runs for every engine that
+ // hosts an AudioHandler - the activity's engine and the
+ // service-spawned headless engine - but never for auxiliary
+ // engines that don't call AudioService.init.
+ if (mediaBrowser == null && plugin != null) {
+ plugin.connect();
+ }
if (mediaController != null) {
result.success(mapOf());
} else {
diff --git a/pubspec.lock b/pubspec.lock
index 4a9e7cad..6a2d6d0c 100644
--- a/pubspec.lock
+++ b/pubspec.lock
@@ -1383,6 +1383,38 @@ packages:
url: "https://pub.dev"
source: hosted
version: "0.0.3"
+ workmanager:
+ dependency: "direct main"
+ description:
+ name: workmanager
+ sha256: "065673b2a465865183093806925419d311a9a5e0995aa74ccf8920fd695e2d10"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.9.0+3"
+ workmanager_android:
+ dependency: transitive
+ description:
+ name: workmanager_android
+ sha256: "9ae744db4ef891f5fcd2fb8671fccc712f4f96489a487a1411e0c8675e5e8cb7"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.9.0+2"
+ workmanager_apple:
+ dependency: transitive
+ description:
+ name: workmanager_apple
+ sha256: "1cc12ae3cbf5535e72f7ba4fde0c12dd11b757caf493a28e22d684052701f2ca"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.9.1+2"
+ workmanager_platform_interface:
+ dependency: transitive
+ description:
+ name: workmanager_platform_interface
+ sha256: f40422f10b970c67abb84230b44da22b075147637532ac501729256fcea10a47
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.9.1+1"
xdg_directories:
dependency: transitive
description:
diff --git a/pubspec.yaml b/pubspec.yaml
index 7f8b26e4..8f520b79 100644
--- a/pubspec.yaml
+++ b/pubspec.yaml
@@ -56,6 +56,9 @@ dependencies:
# Download notifications
flutter_local_notifications: ^17.2.1
+ # Background new-episode checks (Android)
+ workmanager: ^0.9.0
+
device_info_plus: ^11.0.0
# choose file location