Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Rework rolling downloads to per-series/show opt-in

Nathan Poulsondfc849327c5d
diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dart
index e967c040..375190e3 100644
--- a/lib/providers/library_provider.dart
+++ b/lib/providers/library_provider.dart
@@ -41,6 +41,47 @@ class LibraryProvider extends ChangeNotifier {
static const _personalizedFetchCooldown = Duration(seconds: 5);
static const _rssHydrationCooldown = Duration(minutes: 10);
+ // Per-series/show rolling download opt-in
+ Set<String> _rollingDownloadSeries = {};
+
+ bool isRollingDownloadEnabled(String seriesOrShowId) =>
+ _rollingDownloadSeries.contains(seriesOrShowId);
+
+ Future<void> enableRollingDownload(String seriesOrShowId) async {
+ _rollingDownloadSeries.add(seriesOrShowId);
+ await _saveRollingDownloadSeries();
+ notifyListeners();
+ }
+
+ Future<void> disableRollingDownload(String seriesOrShowId) async {
+ _rollingDownloadSeries.remove(seriesOrShowId);
+ await _saveRollingDownloadSeries();
+ notifyListeners();
+ }
+
+ Future<void> toggleRollingDownload(String seriesOrShowId) async {
+ if (_rollingDownloadSeries.contains(seriesOrShowId)) {
+ await disableRollingDownload(seriesOrShowId);
+ } else {
+ await enableRollingDownload(seriesOrShowId);
+ }
+ }
+
+ Future<void> _loadRollingDownloadSeries() async {
+ _rollingDownloadSeries =
+ (await ScopedPrefs.getStringList('rolling_download_series')).toSet();
+ // Clean up old global key if it exists
+ final prefs = await SharedPreferences.getInstance();
+ if (prefs.containsKey('rollingDownload')) {
+ await prefs.remove('rollingDownload');
+ }
+ }
+
+ Future<void> _saveRollingDownloadSeries() async {
+ await ScopedPrefs.setStringList(
+ 'rolling_download_series', _rollingDownloadSeries.toList());
+ }
+
// Offline mode
bool _manualOffline = false;
bool _networkOffline = false;
@@ -361,6 +402,7 @@ class LibraryProvider extends ChangeNotifier {
_manualAbsorbRemoves.clear();
_absorbingBookIds.clear();
_absorbingItemCache.clear();
+ _rollingDownloadSeries.clear();
_itemUpdatedAt.clear();
_personalizedInFlight = null;
_lastPersonalizedFetchAt = null;
@@ -385,6 +427,7 @@ class LibraryProvider extends ChangeNotifier {
debugPrint('[Library] restoreOfflineMode done, serverReachable=${auth.serverReachable} api=${_api != null} offline=$isOffline');
_startConnectivityMonitoring();
_loadManualAbsorbing();
+ _loadRollingDownloadSeries();
// If server was unreachable on startup, force offline mode and ping
if (!auth.serverReachable) {
@@ -1278,8 +1321,10 @@ class LibraryProvider extends ChangeNotifier {
_lastFinishedItemId = itemId;
_locallyFinishedItems.add(itemId);
// Move finished item to front so the next-in-series/episode lands at index 1
- _absorbingBookIds.remove(itemId);
- _absorbingBookIds.insert(0, itemId);
+ // (only if it was already in the absorbing list — don't add books that weren't there)
+ if (_absorbingBookIds.remove(itemId)) {
+ _absorbingBookIds.insert(0, itemId);
+ }
// Ensure cache entry has _absorbingKey so the card can extract the episode ID
if (itemId.length > 36) {
final cached = _absorbingItemCache[itemId];
@@ -1294,16 +1339,26 @@ class LibraryProvider extends ChangeNotifier {
// then the server refresh still runs in the background when online.
_autoAdvanceOffline(itemId);
- // Auto-delete finished download when rolling delete is enabled
- PlayerSettings.getRollingDownload().then((rolling) {
- if (!rolling) return;
+ // Auto-delete finished download if this item's series/show is opted in
+ if (_rollingDownloadSeries.isNotEmpty && DownloadService().isDownloaded(itemId)) {
PlayerSettings.getRollingDownloadDeleteFinished().then((delete) {
- if (delete && DownloadService().isDownloaded(itemId)) {
- DownloadService().deleteDownload(itemId);
+ if (!delete) return;
+ bool optedIn = false;
+ if (itemId.length > 36) {
+ optedIn = _rollingDownloadSeries.contains(itemId.substring(0, 36));
+ } else {
+ final data = _itemDataWithSeries(itemId);
+ if (data != null) {
+ final (seriesId, _) = _extractSeries(data);
+ optedIn = seriesId != null && _rollingDownloadSeries.contains(seriesId);
+ }
+ }
+ if (optedIn) {
+ DownloadService().deleteDownload(itemId, skipStopCheck: true);
_showRollingSnackBar('Deleted finished download');
}
});
- });
+ }
// For podcast episodes, fetch the next episode and THEN refresh.
// This avoids a race where the refresh prunes the newly added episode.
@@ -1591,18 +1646,32 @@ class LibraryProvider extends ChangeNotifier {
// ── Rolling auto-download ──────────────────────────────────────────────
- /// Called when a new item starts playing. If rolling downloads are enabled,
- /// ensures the next N-1 items in the same series/podcast are downloaded.
- void _checkRollingDownloads(String playingKey) {
- PlayerSettings.getRollingDownload().then((enabled) async {
- if (!enabled || _api == null || isOffline) return;
- final count = await PlayerSettings.getRollingDownloadCount();
- if (playingKey.length > 36) {
+ /// Called when a new item starts playing. If the item's series/show is
+ /// opted in for rolling downloads, ensures the next N items are downloaded.
+ void _checkRollingDownloads(String playingKey) async {
+ if (_api == null || isOffline || _rollingDownloadSeries.isEmpty) return;
+ final count = await PlayerSettings.getRollingDownloadCount();
+
+ if (playingKey.length > 36) {
+ // Podcast: show ID is first 36 chars
+ final showId = playingKey.substring(0, 36);
+ if (_rollingDownloadSeries.contains(showId)) {
_rollingDownloadPodcast(playingKey, count);
- } else {
+ }
+ } else {
+ // Book: extract series ID from metadata
+ var data = _itemDataWithSeries(playingKey);
+ var (seriesId, _) = data != null ? _extractSeries(data) : (null, null);
+ if (seriesId == null) {
+ final fullItem = await _api!.getLibraryItem(playingKey);
+ if (fullItem != null) {
+ (seriesId, _) = _extractSeries(fullItem);
+ }
+ }
+ if (seriesId != null && _rollingDownloadSeries.contains(seriesId)) {
_rollingDownloadBook(playingKey, count);
}
- });
+ }
}
/// Download the next [count]-1 books in the same series as [bookId].
diff --git a/lib/screens/absorbing_screen.dart b/lib/screens/absorbing_screen.dart
index 3c6755c8..2b55b2c6 100644
--- a/lib/screens/absorbing_screen.dart
+++ b/lib/screens/absorbing_screen.dart
@@ -579,7 +579,17 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {
? Center(child: CircularProgressIndicator(strokeWidth: 2, color: cs.onSurface.withValues(alpha: 0.24)))
: books.isEmpty
? _emptyState(cs, tt, effectiveOffline)
- : PageView.builder(
+ : books.length == 1
+ ? LayoutBuilder(
+ builder: (context, constraints) {
+ final vPad = (constraints.maxHeight * 0.04).clamp(12.0, 40.0);
+ return Padding(
+ padding: EdgeInsets.symmetric(horizontal: 4, vertical: vPad),
+ child: RepaintBoundary(child: AbsorbingCard(key: ValueKey(_absorbingKey(books[0])), item: books[0], player: _player)),
+ );
+ },
+ )
+ : PageView.builder(
controller: _pageController,
scrollDirection: Axis.horizontal,
clipBehavior: Clip.none,
diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart
index ba7a6cb0..8fdc2039 100644
--- a/lib/screens/settings_screen.dart
+++ b/lib/screens/settings_screen.dart
@@ -34,7 +34,6 @@ class _SettingsScreenState extends State<SettingsScreen> {
AutoRewindSettings _rewindSettings = const AutoRewindSettings();
double _defaultSpeed = 1.0;
bool _wifiOnlyDownloads = false;
- bool _rollingDownload = false;
int _rollingDownloadCount = 3;
bool _rollingDownloadDeleteFinished = false;
bool _showBookSlider = false;
@@ -70,7 +69,6 @@ class _SettingsScreenState extends State<SettingsScreen> {
final s = await AutoRewindSettings.load();
final speed = await PlayerSettings.getDefaultSpeed();
final wifiOnly = await PlayerSettings.getWifiOnlyDownloads();
- final rolling = await PlayerSettings.getRollingDownload();
final rollingCount = await PlayerSettings.getRollingDownloadCount();
final rollingDelete = await PlayerSettings.getRollingDownloadDeleteFinished();
final bookSlider = await PlayerSettings.getShowBookSlider();
@@ -98,7 +96,6 @@ class _SettingsScreenState extends State<SettingsScreen> {
_rewindSettings = s;
_defaultSpeed = speed;
_wifiOnlyDownloads = wifiOnly;
- _rollingDownload = rolling;
_rollingDownloadCount = rollingCount;
_rollingDownloadDeleteFinished = rollingDelete;
_showBookSlider = bookSlider;
@@ -958,58 +955,50 @@ class _SettingsScreenState extends State<SettingsScreen> {
} : null,
),
const Divider(height: 1, indent: 16, endIndent: 16),
+ ListTile(
+ title: const Text('Auto-download'),
+ subtitle: Text(
+ 'Enable per series or podcast from their detail pages',
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ leading: Icon(Icons.downloading_rounded, color: cs.primary),
+ ),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text('Keep next', style: tt.bodyMedium?.copyWith(color: cs.onSurface)),
+ const SizedBox(height: 8),
+ SizedBox(width: double.infinity, child: SegmentedButton<int>(
+ segments: const [
+ ButtonSegment(value: 2, label: Text('2')),
+ ButtonSegment(value: 3, label: Text('3')),
+ ButtonSegment(value: 4, label: Text('4')),
+ ButtonSegment(value: 5, label: Text('5')),
+ ],
+ selected: {_rollingDownloadCount},
+ onSelectionChanged: (v) {
+ setState(() => _rollingDownloadCount = v.first);
+ PlayerSettings.setRollingDownloadCount(v.first);
+ },
+ )),
+ const SizedBox(height: 8),
+ ],
+ ),
+ ),
SwitchListTile(
- title: const Text('Rolling downloads'),
+ title: const Text('Delete finished downloads'),
subtitle: Text(
- _rollingDownload
- ? 'Auto-download next items in a series or podcast'
- : 'Off — manual downloads only',
+ _rollingDownloadDeleteFinished
+ ? 'Finished items are removed to save space'
+ : 'Off — finished downloads kept',
style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
- value: _rollingDownload,
+ value: _rollingDownloadDeleteFinished,
onChanged: _loaded ? (v) {
- setState(() => _rollingDownload = v);
- PlayerSettings.setRollingDownload(v);
+ setState(() => _rollingDownloadDeleteFinished = v);
+ PlayerSettings.setRollingDownloadDeleteFinished(v);
} : null,
),
- if (_rollingDownload) ...[
- Padding(
- padding: const EdgeInsets.symmetric(horizontal: 16),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text('Keep next', style: tt.bodyMedium?.copyWith(color: cs.onSurface)),
- const SizedBox(height: 8),
- SizedBox(width: double.infinity, child: SegmentedButton<int>(
- segments: const [
- ButtonSegment(value: 2, label: Text('2')),
- ButtonSegment(value: 3, label: Text('3')),
- ButtonSegment(value: 4, label: Text('4')),
- ButtonSegment(value: 5, label: Text('5')),
- ],
- selected: {_rollingDownloadCount},
- onSelectionChanged: (v) {
- setState(() => _rollingDownloadCount = v.first);
- PlayerSettings.setRollingDownloadCount(v.first);
- },
- )),
- const SizedBox(height: 8),
- ],
- ),
- ),
- SwitchListTile(
- title: const Text('Delete finished downloads'),
- subtitle: Text(
- _rollingDownloadDeleteFinished
- ? 'Finished items are removed to save space'
- : 'Off — finished downloads kept',
- style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
- value: _rollingDownloadDeleteFinished,
- onChanged: _loaded ? (v) {
- setState(() => _rollingDownloadDeleteFinished = v);
- PlayerSettings.setRollingDownloadDeleteFinished(v);
- } : null,
- ),
- ],
const Divider(height: 1, indent: 16, endIndent: 16),
ListTile(
leading: Icon(Icons.folder_outlined, color: cs.primary),
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index 03d73fc6..fad1af13 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -89,9 +89,6 @@ class PlayerSettings {
static Future<bool> getWifiOnlyDownloads() => _get('wifiOnlyDownloads', false);
static Future<void> setWifiOnlyDownloads(bool value) => _set('wifiOnlyDownloads', value);
- static Future<bool> getRollingDownload() => _get('rollingDownload', false);
- static Future<void> setRollingDownload(bool value) => _set('rollingDownload', value);
-
static Future<int> getRollingDownloadCount() => _get('rollingDownloadCount', 3);
static Future<void> setRollingDownloadCount(int value) => _set('rollingDownloadCount', value);
diff --git a/lib/services/download_service.dart b/lib/services/download_service.dart
index 81393f4a..d54530a4 100644
--- a/lib/services/download_service.dart
+++ b/lib/services/download_service.dart
@@ -756,15 +756,17 @@ class DownloadService extends ChangeNotifier {
notifyListeners();
}
- Future<void> deleteDownload(String itemId) async {
+ Future<void> deleteDownload(String itemId, {bool skipStopCheck = false}) async {
final info = _downloads[itemId];
if (info == null) return;
// Stop playback if this item is currently playing to avoid crashes
- final player = AudioPlayerService();
- if (player.currentItemId == itemId ||
- (itemId.length > 36 && player.currentItemId == itemId.substring(0, 36))) {
- await player.stop();
+ if (!skipStopCheck) {
+ final player = AudioPlayerService();
+ if (player.currentItemId == itemId ||
+ (itemId.length > 36 && player.currentItemId == itemId.substring(0, 36))) {
+ await player.stop();
+ }
}
for (final path in info.localPaths) {
diff --git a/lib/widgets/episode_list_sheet.dart b/lib/widgets/episode_list_sheet.dart
index beb48bfc..9a54a141 100644
--- a/lib/widgets/episode_list_sheet.dart
+++ b/lib/widgets/episode_list_sheet.dart
@@ -52,6 +52,7 @@ class _EpisodeListSheetState extends State<EpisodeListSheet> {
List<dynamic> _episodes = [];
bool _isLoading = true;
bool _isDownloadingAll = false;
+ bool _autoDownloadEnabled = false;
String get _itemId => widget.podcastItem['id'] as String? ?? '';
@@ -69,6 +70,15 @@ class _EpisodeListSheetState extends State<EpisodeListSheet> {
void initState() {
super.initState();
_loadEpisodes();
+ _loadAutoDownloadState();
+ }
+
+ void _loadAutoDownloadState() {
+ if (_itemId.isEmpty) return;
+ final lib = context.read<LibraryProvider>();
+ setState(() {
+ _autoDownloadEnabled = lib.isRollingDownloadEnabled(_itemId);
+ });
}
Future<void> _loadEpisodes() async {
@@ -186,6 +196,26 @@ class _EpisodeListSheetState extends State<EpisodeListSheet> {
final api = auth.apiService;
if (api == null) return;
+ // Offer to enable auto-download if not already on
+ if (_itemId.isNotEmpty && !_autoDownloadEnabled) {
+ final enable = await showDialog<bool>(
+ context: context,
+ builder: (ctx) => AlertDialog(
+ title: const Text('Auto-Download This Podcast?'),
+ content: const Text('Automatically download the next episodes as you listen.'),
+ actions: [
+ TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('No Thanks')),
+ FilledButton(onPressed: () => Navigator.pop(ctx, true), child: const Text('Enable')),
+ ],
+ ),
+ );
+ if (enable == true && mounted) {
+ final lib = context.read<LibraryProvider>();
+ await lib.enableRollingDownload(_itemId);
+ setState(() => _autoDownloadEnabled = true);
+ }
+ }
+
setState(() => _isDownloadingAll = true);
for (final ep in _episodes) {
@@ -376,6 +406,47 @@ class _EpisodeListSheetState extends State<EpisodeListSheet> {
),
],
+ // Auto-download toggle
+ if (_itemId.isNotEmpty) ...[
+ const SizedBox(height: 8),
+ GestureDetector(
+ onTap: () async {
+ final lib = context.read<LibraryProvider>();
+ await lib.toggleRollingDownload(_itemId);
+ setState(() => _autoDownloadEnabled = lib.isRollingDownloadEnabled(_itemId));
+ },
+ child: Container(
+ height: 36,
+ decoration: BoxDecoration(
+ color: _autoDownloadEnabled
+ ? cs.primary.withValues(alpha: 0.08)
+ : cs.onSurface.withValues(alpha: 0.04),
+ borderRadius: BorderRadius.circular(14),
+ border: Border.all(
+ color: _autoDownloadEnabled
+ ? cs.primary.withValues(alpha: 0.2)
+ : cs.onSurface.withValues(alpha: 0.08),
+ ),
+ ),
+ child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
+ Icon(
+ _autoDownloadEnabled ? Icons.downloading_rounded : Icons.download_outlined,
+ size: 16,
+ color: _autoDownloadEnabled ? cs.primary : cs.onSurfaceVariant,
+ ),
+ const SizedBox(width: 6),
+ Text(
+ _autoDownloadEnabled ? 'Auto-Download On' : 'Auto-Download Off',
+ style: TextStyle(
+ color: _autoDownloadEnabled ? cs.primary : cs.onSurfaceVariant,
+ fontSize: 12, fontWeight: FontWeight.w500,
+ ),
+ ),
+ ]),
+ ),
+ ),
+ ],
+
// Episodes section header
const SizedBox(height: 16),
Align(
diff --git a/lib/widgets/series_books_sheet.dart b/lib/widgets/series_books_sheet.dart
index 79f78068..c9687f58 100644
--- a/lib/widgets/series_books_sheet.dart
+++ b/lib/widgets/series_books_sheet.dart
@@ -65,6 +65,7 @@ class _SeriesBooksSheetState extends State<SeriesBooksSheet> {
bool _isLoading = true;
bool _isDownloadingAll = false;
bool _isMarkingAll = false;
+ bool _autoDownloadEnabled = false;
@override
void initState() {
@@ -75,6 +76,16 @@ class _SeriesBooksSheetState extends State<SeriesBooksSheet> {
if (_books.isNotEmpty) _isLoading = false;
// Fetch full data from API for proper sequence info
_fetchFromApi();
+ _loadAutoDownloadState();
+ }
+
+ void _loadAutoDownloadState() {
+ final seriesId = widget.seriesId;
+ if (seriesId == null || seriesId.isEmpty) return;
+ final lib = context.read<LibraryProvider>();
+ setState(() {
+ _autoDownloadEnabled = lib.isRollingDownloadEnabled(seriesId);
+ });
}
/// Unwrap ABS format: { libraryItem: {...}, sequence: "1" }
@@ -296,6 +307,27 @@ class _SeriesBooksSheetState extends State<SeriesBooksSheet> {
final api = auth.apiService;
if (api == null) return;
+ // Offer to enable auto-download if not already on
+ final seriesId = widget.seriesId;
+ if (seriesId != null && seriesId.isNotEmpty && !_autoDownloadEnabled) {
+ final enable = await showDialog<bool>(
+ context: context,
+ builder: (ctx) => AlertDialog(
+ title: const Text('Auto-Download This Series?'),
+ content: const Text('Automatically download the next books as you listen.'),
+ actions: [
+ TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('No Thanks')),
+ FilledButton(onPressed: () => Navigator.pop(ctx, true), child: const Text('Enable')),
+ ],
+ ),
+ );
+ if (enable == true && mounted) {
+ final lib = context.read<LibraryProvider>();
+ await lib.enableRollingDownload(seriesId);
+ setState(() => _autoDownloadEnabled = true);
+ }
+ }
+
setState(() => _isDownloadingAll = true);
for (final book in _books) {
@@ -482,6 +514,47 @@ class _SeriesBooksSheetState extends State<SeriesBooksSheet> {
},
),
),
+ // Auto-download toggle
+ if (widget.seriesId != null && widget.seriesId!.isNotEmpty)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(24, 0, 24, 12),
+ child: GestureDetector(
+ onTap: () async {
+ final lib = context.read<LibraryProvider>();
+ await lib.toggleRollingDownload(widget.seriesId!);
+ setState(() => _autoDownloadEnabled = lib.isRollingDownloadEnabled(widget.seriesId!));
+ },
+ child: Container(
+ height: 36,
+ decoration: BoxDecoration(
+ color: _autoDownloadEnabled
+ ? cs.primary.withValues(alpha: 0.08)
+ : cs.onSurface.withValues(alpha: 0.04),
+ borderRadius: BorderRadius.circular(14),
+ border: Border.all(
+ color: _autoDownloadEnabled
+ ? cs.primary.withValues(alpha: 0.2)
+ : cs.onSurface.withValues(alpha: 0.08),
+ ),
+ ),
+ child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
+ Icon(
+ _autoDownloadEnabled ? Icons.downloading_rounded : Icons.download_outlined,
+ size: 16,
+ color: _autoDownloadEnabled ? cs.primary : cs.onSurfaceVariant,
+ ),
+ const SizedBox(width: 6),
+ Text(
+ _autoDownloadEnabled ? 'Auto-Download On' : 'Auto-Download Off',
+ style: TextStyle(
+ color: _autoDownloadEnabled ? cs.primary : cs.onSurfaceVariant,
+ fontSize: 12, fontWeight: FontWeight.w500,
+ ),
+ ),
+ ]),
+ ),
+ ),
+ ),
],
if (_isLoading && _books.isEmpty)
const Expanded(