Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Add manual queue mode, concurrent downloads

Nathan Poulson53f48ccde34b
diff --git a/lib/main.dart b/lib/main.dart
index 8f8d8ef5..1be0711e 100644
--- a/lib/main.dart
+++ b/lib/main.dart
@@ -68,6 +68,9 @@ void main() async {
final savedTheme = await PlayerSettings.getThemeMode();
themeNotifier.value = parseThemeMode(savedTheme);
+ // Migrate old auto-play booleans → unified queueMode (one-time, no-op after first run)
+ await PlayerSettings.migrateQueueMode();
+
// Load device info for server identification
await ApiService.initDeviceId();
await ApiService.initVersion();
diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dart
index 66739507..f8a7ccbb 100644
--- a/lib/providers/library_provider.dart
+++ b/lib/providers/library_provider.dart
@@ -423,7 +423,10 @@ class LibraryProvider extends ChangeNotifier {
// Restore manual offline preference and start connectivity monitoring
// Must complete before loading libraries so offline state is correct
AudioPlayerService.setOnBookFinishedCallback(markFinishedLocally);
- AudioPlayerService.setOnPlayStartedCallback(_checkRollingDownloads);
+ AudioPlayerService.setOnPlayStartedCallback((key) {
+ _checkRollingDownloads(key);
+ _checkQueueAutoDownloads(key);
+ });
ChromecastService.setOnBookFinishedCallback(markFinishedLocally);
restoreOfflineMode().then((_) async {
@@ -505,8 +508,9 @@ class LibraryProvider extends ChangeNotifier {
// down the API call will fail and _goOfflineWithPing() will be called.
setNetworkOffline(false);
// WiFi restored — catch up on any pending rolling downloads
- if (result.contains(ConnectivityResult.wifi) && _rollingDownloadSeries.isNotEmpty) {
- _catchUpRollingDownloads();
+ if (result.contains(ConnectivityResult.wifi)) {
+ if (_rollingDownloadSeries.isNotEmpty) _catchUpRollingDownloads();
+ _catchUpQueueAutoDownloads();
}
}
});
@@ -630,6 +634,7 @@ class LibraryProvider extends ChangeNotifier {
// Catch up on any rolling downloads that were missed (e.g. app was closed,
// or WiFi wasn't available when the download should have triggered)
_catchUpRollingDownloads();
+ _catchUpQueueAutoDownloads();
}
/// Change the selected library and reload data.
@@ -1064,10 +1069,10 @@ class LibraryProvider extends ChangeNotifier {
}
}
- // Auto-play the next book in series if the setting is enabled.
+ // Auto-play the next book in series if auto_next mode is enabled.
if (newContinueSeriesKey != null && _api != null) {
- PlayerSettings.getAutoPlayNextBook().then((autoPlay) {
- if (!autoPlay) return;
+ PlayerSettings.getQueueMode().then((mode) {
+ if (mode != 'auto_next') return;
// Don't auto-play if BT/headphones just disconnected — the server
// refresh is async and may return after the user left the car.
if (AudioPlayerService.wasNoisyPause) return;
@@ -1240,7 +1245,7 @@ class LibraryProvider extends ChangeNotifier {
}
}
- /// Add a book to the absorbing list manually.
+ /// Add a book to the absorbing list manually (at the front — used by playback).
Future<void> addToAbsorbing(String itemId) async {
_manualAbsorbAdds.add(itemId);
_manualAbsorbRemoves.remove(itemId);
@@ -1249,6 +1254,24 @@ class LibraryProvider extends ChangeNotifier {
notifyListeners();
}
+ /// Add an item to the END of the absorbing list (queue behavior).
+ /// Used by the "Add to Absorbing" button — no playback started.
+ Future<void> addToAbsorbingQueue(String itemId) async {
+ _manualAbsorbAdds.add(itemId);
+ _manualAbsorbRemoves.remove(itemId);
+ _absorbingIdsAdd(itemId, atFront: false);
+ await _saveManualAbsorbing();
+ notifyListeners();
+ }
+
+ /// Replace the absorbing card order with a new order and persist.
+ Future<void> reorderAbsorbing(List<String> newOrder) async {
+ _absorbingBookIds = newOrder;
+ await _saveManualAbsorbing();
+ notifyListeners();
+ _catchUpQueueAutoDownloads();
+ }
+
/// Re-allow an item that was previously removed, so it can reappear in Absorbing.
/// Called when the user explicitly plays an item that they had removed.
/// [key] can be a plain itemId (books) or compound "itemId-episodeId" (podcasts).
@@ -1350,7 +1373,17 @@ class LibraryProvider extends ChangeNotifier {
// Instant local auto-advance — uses cached metadata + download info,
// no server call needed. Fires first so playback starts immediately,
// then the server refresh still runs in the background when online.
- _autoAdvanceOffline(itemId);
+ PlayerSettings.getQueueMode().then((mode) {
+ if (mode == 'manual') {
+ _manualQueueAdvance(itemId);
+ } else if (mode == 'auto_next') {
+ _autoAdvanceOffline(itemId);
+ }
+ // mode == 'off': do nothing, playback stops
+ });
+
+ // Slide the rolling download window forward for the finished item's series
+ _checkRollingDownloads(itemId);
// Auto-delete finished download if this item's series/show is opted in
if (_rollingDownloadSeries.isNotEmpty && DownloadService().isDownloaded(itemId)) {
@@ -1373,20 +1406,63 @@ class LibraryProvider extends ChangeNotifier {
});
}
- // For podcast episodes, fetch the next episode and THEN refresh.
- // This avoids a race where the refresh prunes the newly added episode.
+ // Auto-delete for queue-based downloads (manual queue + queueAutoDownload)
+ if (DownloadService().isDownloaded(itemId)) {
+ Future.wait([
+ PlayerSettings.getQueueMode(),
+ PlayerSettings.getQueueAutoDownload(),
+ PlayerSettings.getRollingDownloadDeleteFinished(),
+ ]).then((results) {
+ final qMode = results[0] as String;
+ final qAutoDl = results[1] as bool;
+ final deleteFin = results[2] as bool;
+ if (qMode != 'manual' || !qAutoDl || !deleteFin) return;
+ // Skip if already handled by series-based block above
+ bool handledBySeries = false;
+ if (_rollingDownloadSeries.isNotEmpty) {
+ if (itemId.length > 36) {
+ handledBySeries = _rollingDownloadSeries.contains(itemId.substring(0, 36));
+ } else {
+ final data = _itemDataWithSeries(itemId);
+ if (data != null) {
+ final (seriesId, _) = _extractSeries(data);
+ handledBySeries = seriesId != null && _rollingDownloadSeries.contains(seriesId);
+ }
+ }
+ }
+ if (!handledBySeries) {
+ DownloadService().deleteDownload(itemId, skipStopCheck: true);
+ _showRollingSnackBar('Deleted finished download');
+ }
+ });
+ }
+
+ // For podcast episodes, fetch the next episode (only in auto_next mode)
+ // and THEN refresh. This avoids a race where the refresh prunes the
+ // newly added episode.
final isCompound = itemId.length > 36;
if (isCompound && !skipRefresh && _api != null && !isOffline) {
- // UUIDs are always 36 chars; compound key = "showUUID-episodeId"
final showId = itemId.substring(0, 36);
final episodeId = itemId.substring(37);
- _addNextPodcastEpisode(showId, episodeId, itemId).then((_) {
- if (_selectedLibraryId != null && !isOffline) {
- loadPersonalizedView(force: true);
+ PlayerSettings.getQueueMode().then((queueMode) {
+ if (queueMode == 'auto_next') {
+ _addNextPodcastEpisode(showId, episodeId, itemId).then((_) {
+ if (_selectedLibraryId != null && !isOffline) {
+ loadPersonalizedView(force: true);
+ }
+ PlayerSettings.getWhenFinished().then((mode) {
+ if (mode == 'auto_remove') removeFromAbsorbing(itemId);
+ });
+ });
+ } else {
+ // manual or off — still refresh and handle auto-remove, just don't add next episode
+ if (_selectedLibraryId != null && !isOffline) {
+ loadPersonalizedView(force: true);
+ }
+ PlayerSettings.getWhenFinished().then((mode) {
+ if (mode == 'auto_remove') removeFromAbsorbing(itemId);
+ });
}
- PlayerSettings.getWhenFinished().then((mode) {
- if (mode == 'auto_remove') removeFromAbsorbing(itemId);
- });
});
return; // skip the default refresh below — handled above
}
@@ -1458,9 +1534,9 @@ class LibraryProvider extends ChangeNotifier {
await _saveManualAbsorbing();
notifyListeners();
- // Auto-play the next episode if the setting is enabled.
+ // Auto-play the next episode if auto_next mode is enabled.
// Skip if local auto-advance already started playback.
- if (await PlayerSettings.getAutoPlayNextPodcast() && _api != null &&
+ if ((await PlayerSettings.getQueueMode()) == 'auto_next' && _api != null &&
!AudioPlayerService().isPlaying) {
final metadata = media['metadata'] as Map<String, dynamic>? ?? {};
final title = metadata['title'] as String? ?? '';
@@ -1482,6 +1558,73 @@ class LibraryProvider extends ChangeNotifier {
} catch (_) {}
}
+ /// Manual queue auto-advance: scan absorbing list from after the finished
+ /// item, find the first non-finished card, and play it.
+ void _manualQueueAdvance(String finishedKey) async {
+ if (AudioPlayerService.wasNoisyPause) return;
+
+ final merged = await PlayerSettings.getMergeAbsorbingLibraries();
+
+ // Determine the finished item's library so we only advance within the same library
+ final finishedCached = _absorbingItemCache[finishedKey];
+ final finishedLibId = finishedCached?['libraryId'] as String?;
+
+ final finishedIdx = _absorbingBookIds.indexOf(finishedKey);
+ final startIdx = finishedIdx >= 0 ? finishedIdx + 1 : 0;
+
+ for (int i = startIdx; i < _absorbingBookIds.length; i++) {
+ final key = _absorbingBookIds[i];
+ if (isItemFinishedByKey(key)) continue;
+
+ final cached = _absorbingItemCache[key];
+ if (cached == null) continue;
+
+ // Stay within the same library unless merge mode is on
+ if (!merged && finishedLibId != null) {
+ final candidateLibId = cached['libraryId'] as String?;
+ if (candidateLibId != null && candidateLibId != finishedLibId) continue;
+ }
+
+ final media = cached['media'] as Map<String, dynamic>? ?? {};
+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};
+ final title = metadata['title'] as String? ?? '';
+ final author = metadata['authorName'] as String? ?? '';
+
+ if (key.length > 36) {
+ final showId = key.substring(0, 36);
+ final epId = key.substring(37);
+ final ep = cached['recentEpisode'] as Map<String, dynamic>?;
+ final epDuration = (ep?['duration'] as num?)?.toDouble()
+ ?? (media['duration'] as num?)?.toDouble() ?? 0;
+ AudioPlayerService().playItem(
+ api: _api ?? ApiService(baseUrl: '', token: ''),
+ itemId: showId,
+ title: title,
+ author: author,
+ coverUrl: getCoverUrl(showId),
+ totalDuration: epDuration,
+ chapters: [],
+ episodeId: epId,
+ episodeTitle: ep?['title'] as String?,
+ );
+ } else {
+ final duration = (media['duration'] as num?)?.toDouble() ?? 0;
+ final chapters = media['chapters'] as List<dynamic>? ?? [];
+ AudioPlayerService().playItem(
+ api: _api ?? ApiService(baseUrl: '', token: ''),
+ itemId: key,
+ title: title,
+ author: author,
+ coverUrl: getCoverUrl(key),
+ totalDuration: duration,
+ chapters: chapters,
+ );
+ }
+ return; // started the next item
+ }
+ // All remaining cards are finished — playback stops naturally.
+ }
+
/// Offline auto-advance: find the next downloaded book in series or next
/// downloaded podcast episode and auto-play it without any server calls.
void _autoAdvanceOffline(String finishedKey) {
@@ -1541,8 +1684,8 @@ class LibraryProvider extends ChangeNotifier {
}
void _autoAdvanceOfflineBook(String finishedBookId) {
- PlayerSettings.getAutoPlayNextBook().then((autoPlay) {
- if (!autoPlay) return;
+ PlayerSettings.getQueueMode().then((mode) {
+ if (mode != 'auto_next') return;
if (AudioPlayerService.wasNoisyPause) return;
final finished = _itemDataWithSeries(finishedBookId);
@@ -1594,8 +1737,8 @@ class LibraryProvider extends ChangeNotifier {
}
void _autoAdvanceOfflinePodcast(String finishedKey) {
- PlayerSettings.getAutoPlayNextPodcast().then((autoPlay) {
- if (!autoPlay) return;
+ PlayerSettings.getQueueMode().then((mode) {
+ if (mode != 'auto_next') return;
if (AudioPlayerService.wasNoisyPause) return;
final showId = finishedKey.substring(0, 36);
@@ -1743,6 +1886,96 @@ class LibraryProvider extends ChangeNotifier {
}
}
+ /// Auto-download the next N items from the absorbing queue when manual
+ /// queue mode is active and queueAutoDownload is enabled.
+ void _checkQueueAutoDownloads(String playingKey) async {
+ if (_api == null || isOffline) return;
+ final queueMode = await PlayerSettings.getQueueMode();
+ if (queueMode != 'manual') return;
+ final enabled = await PlayerSettings.getQueueAutoDownload();
+ if (!enabled) return;
+ final merged = await PlayerSettings.getMergeAbsorbingLibraries();
+
+ final wifiOnly = await PlayerSettings.getWifiOnlyDownloads();
+ if (wifiOnly) {
+ final connectivity = await Connectivity().checkConnectivity();
+ if (!connectivity.contains(ConnectivityResult.wifi)) return;
+ }
+
+ final count = await PlayerSettings.getRollingDownloadCount();
+ final dl = DownloadService();
+ int queued = 0;
+ int newDownloads = 0;
+
+ final playingIdx = _absorbingBookIds.indexOf(playingKey);
+ final startIdx = playingIdx >= 0 ? playingIdx : 0;
+
+ final playingCached = _absorbingItemCache[playingKey];
+ final playingLibId = playingCached?['libraryId'] as String?;
+
+ for (int i = startIdx; i < _absorbingBookIds.length && queued < count; i++) {
+ final key = _absorbingBookIds[i];
+ if (isItemFinishedByKey(key)) continue;
+
+ final cached = _absorbingItemCache[key];
+ if (cached == null) continue;
+
+ // Stay within the same library unless merge mode is on
+ if (!merged && playingLibId != null) {
+ final candidateLibId = cached['libraryId'] as String?;
+ if (candidateLibId != null && candidateLibId != playingLibId) continue;
+ }
+
+ if (dl.isDownloaded(key) || dl.isDownloading(key)) {
+ queued++;
+ continue;
+ }
+
+ final media = cached['media'] as Map<String, dynamic>? ?? {};
+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};
+ final title = metadata['title'] as String? ?? '';
+ final author = metadata['authorName'] as String? ?? '';
+
+ if (key.length > 36) {
+ final showId = key.substring(0, 36);
+ final epId = key.substring(37);
+ final ep = cached['recentEpisode'] as Map<String, dynamic>?;
+ dl.downloadItem(
+ api: _api!,
+ itemId: key,
+ title: ep?['title'] as String? ?? 'Episode',
+ author: title,
+ coverUrl: getCoverUrl(showId),
+ episodeId: epId,
+ );
+ } else {
+ dl.downloadItem(
+ api: _api!,
+ itemId: key,
+ title: title,
+ author: author,
+ coverUrl: getCoverUrl(key),
+ );
+ }
+ queued++;
+ newDownloads++;
+ }
+
+ if (newDownloads > 0) {
+ _showRollingSnackBar('Queue: downloading $newDownloads item${newDownloads == 1 ? '' : 's'}');
+ }
+ }
+
+ /// On WiFi restore or library load, trigger queue auto-downloads for
+ /// whatever is currently playing.
+ void _catchUpQueueAutoDownloads() {
+ final itemId = AudioPlayerService().currentItemId;
+ if (itemId == null) return;
+ final epId = AudioPlayerService().currentEpisodeId;
+ final key = epId != null ? '$itemId-$epId' : itemId;
+ _checkQueueAutoDownloads(key);
+ }
+
/// Download the next [count]-1 books in the same series as [bookId].
Future<void> _rollingDownloadBook(String bookId, int count) async {
// Try local cache first, then fetch from server if series info is missing
@@ -1766,7 +1999,8 @@ class LibraryProvider extends ChangeNotifier {
int newDownloads = 0;
// Download the currently-playing book too if not already downloaded
- if (!dl.isDownloaded(bookId) && !dl.isDownloading(bookId)) {
+ final anchorFinished = _progressMap[bookId]?['isFinished'] == true;
+ if (!anchorFinished && !dl.isDownloaded(bookId) && !dl.isDownloading(bookId)) {
final media = data!['media'] as Map<String, dynamic>? ?? {};
final md = media['metadata'] as Map<String, dynamic>? ?? {};
dl.downloadItem(
@@ -1778,7 +2012,8 @@ class LibraryProvider extends ChangeNotifier {
);
newDownloads++;
}
- queued++; // Count current book toward the window
+ // Don't count finished anchor toward the window so it slides forward
+ if (!anchorFinished) queued++;
for (final book in books) {
if (queued >= count) break;
@@ -1855,7 +2090,8 @@ class LibraryProvider extends ChangeNotifier {
int newDownloads = 0;
// Download the currently-playing episode too if not already downloaded
- if (!dl.isDownloaded(compoundKey) && !dl.isDownloading(compoundKey)) {
+ final anchorFinished = _progressMap[compoundKey]?['isFinished'] == true;
+ if (!anchorFinished && !dl.isDownloaded(compoundKey) && !dl.isDownloading(compoundKey)) {
final curEp = episodes[currentIdx] as Map<String, dynamic>;
dl.downloadItem(
api: _api!,
@@ -1867,7 +2103,8 @@ class LibraryProvider extends ChangeNotifier {
);
newDownloads++;
}
- queued++; // Count current episode toward the window
+ // Don't count finished anchor toward the window so it slides forward
+ if (!anchorFinished) queued++;
for (int i = currentIdx + 1; i < episodes.length && queued < count; i++) {
final ep = episodes[i] as Map<String, dynamic>;
@@ -1913,4 +2150,15 @@ class LibraryProvider extends ChangeNotifier {
if (_manualAbsorbRemoves.contains(key)) return false;
return _absorbingBookIds.contains(key);
}
+
+ /// Check if an absorbing item (by its key) is finished.
+ bool isItemFinishedByKey(String key) {
+ if (_locallyFinishedItems.contains(key)) return true;
+ if (key.length > 36) {
+ final showId = key.substring(0, 36);
+ final epId = key.substring(37);
+ return getEpisodeProgressData(showId, epId)?['isFinished'] == true;
+ }
+ return getProgressData(key)?['isFinished'] == true;
+ }
}
diff --git a/lib/screens/absorbing_screen.dart b/lib/screens/absorbing_screen.dart
index 2b55b2c6..c0c21efe 100644
--- a/lib/screens/absorbing_screen.dart
+++ b/lib/screens/absorbing_screen.dart
@@ -46,6 +46,7 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {
_player.addListener(_rebuild);
_cast.addListener(_rebuild);
_restoreLastFinished();
+ _loadMergeLibraries();
}
Future<void> _restoreLastFinished() async {
@@ -55,6 +56,11 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {
}
}
+ Future<void> _loadMergeLibraries() async {
+ final v = await PlayerSettings.getMergeAbsorbingLibraries();
+ if (mounted && v != _mergeLibraries) setState(() => _mergeLibraries = v);
+ }
+
@override
void dispose() {
_player.removeListener(_rebuild);
@@ -74,9 +80,11 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {
// Used during the slide-to-front animation so the user sees their book smoothly
// slide to the beginning rather than the list instantly reordering underneath them.
bool _suppressReorder = false;
+ bool _mergeLibraries = false;
void _rebuild() {
if (!mounted) return;
+ _loadMergeLibraries(); // refresh in case setting changed
// Detect item or episode change (same show, different episode counts as a change)
final itemChanged = _player.currentItemId != _lastPlayingId;
final episodeChanged = _player.currentEpisodeId != _lastPlayingEpisodeId;
@@ -303,11 +311,11 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {
items.add(fromSection);
continue;
}
- // Cache fallback — only include if it matches the current library
+ // Cache fallback — include if it matches the current library (or merge is on)
final cached = cache[key];
if (cached != null) {
final itemLibId = cached['libraryId'] as String?;
- if (selectedLibraryId == null || itemLibId == null || itemLibId == selectedLibraryId) {
+ if (_mergeLibraries || selectedLibraryId == null || itemLibId == null || itemLibId == selectedLibraryId) {
items.add(cached);
} else {
skippedKeys[key] = 'wrong library (item=$itemLibId, selected=$selectedLibraryId)';
@@ -348,8 +356,8 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {
if (activeId != null) {
final activeIsPodcast = activeEpId != null;
- // Only show if the active item matches the current library type
- if (activeIsPodcast == isPod) {
+ // Only show if the active item matches the current library type (or merge is on)
+ if (_mergeLibraries || activeIsPodcast == isPod) {
final activeKey = activeEpId != null ? '$activeId-$activeEpId' : activeId;
final existingIdx = items.indexWhere((b) => _absorbingKey(b) == activeKey);
@@ -387,7 +395,7 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {
if (!_player.hasBook && _lastFinishedId != null && !removes.contains(_lastFinishedId)) {
// Compound podcast keys are "uuid-uuid" (>36 chars); plain book UUIDs are 36.
final finishedIsPodcast = _lastFinishedId!.length > 36;
- if (finishedIsPodcast == isPod) {
+ if (_mergeLibraries || finishedIsPodcast == isPod) {
final finishedIdx = items.indexWhere((b) => _absorbingKey(b) == _lastFinishedId);
if (finishedIdx > 0) {
final item = items.removeAt(finishedIdx);
@@ -401,6 +409,7 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {
@override
Widget build(BuildContext context) {
+ _loadMergeLibraries(); // refresh in case setting changed
final cs = Theme.of(context).colorScheme;
final tt = Theme.of(context).textTheme;
final lib = context.watch<LibraryProvider>();
@@ -565,6 +574,21 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {
),
),
),
+ if (books.length > 1) ...[
+ const SizedBox(width: 8),
+ GestureDetector(
+ onTap: () => _showReorderSheet(context, lib, books),
+ child: Container(
+ padding: const EdgeInsets.all(6),
+ decoration: BoxDecoration(
+ color: subtleBg,
+ shape: BoxShape.circle,
+ border: Border.all(color: subtleBorder),
+ ),
+ child: Icon(Icons.reorder_rounded, size: 14, color: muted),
+ ),
+ ),
+ ],
],
),
// ── Page Dots ──
@@ -671,6 +695,28 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {
),
);
}
+
+ void _showReorderSheet(BuildContext context, LibraryProvider lib, List<Map<String, dynamic>> books) {
+ final keys = books.map((b) => _absorbingKey(b)).toList();
+ showModalBottomSheet(
+ context: context,
+ isScrollControlled: true,
+ useSafeArea: true,
+ backgroundColor: Colors.transparent,
+ builder: (_) => DraggableScrollableSheet(
+ expand: false,
+ initialChildSize: 0.6,
+ minChildSize: 0.3,
+ maxChildSize: 0.9,
+ builder: (_, __) => _ReorderAbsorbingSheet(
+ keys: keys,
+ books: books,
+ lib: lib,
+ absorbingKeyFn: _absorbingKey,
+ ),
+ ),
+ );
+ }
}
// ─── PAGE DOTS ──────────────────────────────────────────────
@@ -708,3 +754,163 @@ class _PageDots extends StatelessWidget {
);
}
}
+
+// ─── REORDER ABSORBING SHEET ──────────────────────────────────
+
+class _ReorderAbsorbingSheet extends StatefulWidget {
+ final List<String> keys;
+ final List<Map<String, dynamic>> books;
+ final LibraryProvider lib;
+ final String Function(Map<String, dynamic>) absorbingKeyFn;
+
+ const _ReorderAbsorbingSheet({
+ required this.keys,
+ required this.books,
+ required this.lib,
+ required this.absorbingKeyFn,
+ });
+
+ @override
+ State<_ReorderAbsorbingSheet> createState() => _ReorderAbsorbingSheetState();
+}
+
+class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {
+ late List<String> _order;
+ late Map<String, Map<String, dynamic>> _booksByKey;
+
+ @override
+ void initState() {
+ super.initState();
+ _order = List.from(widget.keys);
+ _booksByKey = {
+ for (final b in widget.books) widget.absorbingKeyFn(b): b,
+ };
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+
+ return Container(
+ decoration: BoxDecoration(
+ color: cs.surface,
+ borderRadius: const BorderRadius.vertical(top: Radius.circular(20)),
+ ),
+ child: Column(children: [
+ // Handle
+ Center(child: Container(
+ margin: const EdgeInsets.only(top: 10),
+ width: 32, height: 4,
+ decoration: BoxDecoration(
+ color: cs.onSurface.withValues(alpha: 0.2),
+ borderRadius: BorderRadius.circular(2),
+ ),
+ )),
+ // Header
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 12, 8, 8),
+ child: Row(children: [
+ Expanded(child: Text('Reorder Queue',
+ style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600))),
+ TextButton(
+ onPressed: () {
+ widget.lib.reorderAbsorbing(_order);
+ Navigator.pop(context);
+ },
+ child: const Text('Done'),
+ ),
+ ]),
+ ),
+ Expanded(
+ child: ReorderableListView.builder(
+ buildDefaultDragHandles: false,
+ proxyDecorator: (child, index, animation) {
+ return AnimatedBuilder(
+ animation: animation,
+ builder: (context, child) => Material(
+ elevation: 4,
+ borderRadius: BorderRadius.circular(12),
+ color: cs.surfaceContainer,
+ child: child,
+ ),
+ child: child,
+ );
+ },
+ itemCount: _order.length,
+ onReorder: (oldIdx, newIdx) {
+ setState(() {
+ if (newIdx > oldIdx) newIdx--;
+ final item = _order.removeAt(oldIdx);
+ _order.insert(newIdx, item);
+ });
+ },
+ itemBuilder: (context, i) {
+ final key = _order[i];
+ final book = _booksByKey[key];
+ if (book == null) return SizedBox.shrink(key: ValueKey(key));
+
+ final media = book['media'] as Map<String, dynamic>? ?? {};
+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};
+ final title = metadata['title'] as String? ?? 'Unknown';
+ final author = metadata['authorName'] as String? ?? '';
+ final re = book['recentEpisode'] as Map<String, dynamic>?;
+ final epTitle = re?['title'] as String?;
+ final isFinished = widget.lib.isItemFinishedByKey(key);
+
+ return Padding(
+ key: ValueKey(key),
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 2),
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
+ decoration: BoxDecoration(
+ color: isFinished ? cs.onSurface.withValues(alpha: 0.03) : Colors.transparent,
+ borderRadius: BorderRadius.circular(12),
+ ),
+ child: Row(children: [
+ // Queue position number
+ SizedBox(width: 24, child: Text('${i + 1}',
+ style: tt.labelMedium?.copyWith(
+ color: isFinished ? cs.onSurface.withValues(alpha: 0.3) : cs.primary,
+ fontWeight: FontWeight.w700,
+ ))),
+ // Finished indicator
+ if (isFinished)
+ Icon(Icons.check_circle_rounded, size: 16, color: Colors.green.withValues(alpha: 0.5))
+ else
+ Icon(Icons.circle_outlined, size: 16, color: cs.onSurface.withValues(alpha: 0.2)),
+ const SizedBox(width: 8),
+ // Title + subtitle
+ Expanded(child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(epTitle ?? title,
+ maxLines: 1, overflow: TextOverflow.ellipsis,
+ style: tt.bodyMedium?.copyWith(
+ color: isFinished ? cs.onSurface.withValues(alpha: 0.4) : null,
+ )),
+ if (epTitle != null)
+ Text(title, maxLines: 1, overflow: TextOverflow.ellipsis,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ if (author.isNotEmpty && epTitle == null)
+ Text(author, maxLines: 1, overflow: TextOverflow.ellipsis,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ ],
+ )),
+ // Drag handle
+ ReorderableDragStartListener(
+ index: i,
+ child: Icon(Icons.drag_handle_rounded, size: 20,
+ color: cs.onSurface.withValues(alpha: 0.3)),
+ ),
+ ]),
+ ),
+ );
+ },
+ ),
+ ),
+ ]),
+ );
+ }
+}
diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart
index 51df1ab3..a4dea751 100644
--- a/lib/screens/settings_screen.dart
+++ b/lib/screens/settings_screen.dart
@@ -45,8 +45,10 @@ class _SettingsScreenState extends State<SettingsScreen> {
bool _resetSleepOnPause = false;
bool _sleepFadeOut = true;
int _shakeAddMinutes = 5;
- bool _autoPlayNextBook = false;
- bool _autoPlayNextPodcast = false;
+ String _queueMode = 'off';
+ bool _queueAutoDownload = false;
+ bool _mergeAbsorbingLibraries = false;
+ int _maxConcurrentDownloads = 1;
String _whenFinished = 'overlay';
bool _hideEbookOnly = false;
bool _showGoodreadsButton = false;
@@ -81,8 +83,10 @@ class _SettingsScreenState extends State<SettingsScreen> {
final resetOnPause = await PlayerSettings.getResetSleepOnPause();
final sleepFade = await PlayerSettings.getSleepFadeOut();
final shakeMins = await PlayerSettings.getShakeAddMinutes();
- final autoPlayBook = await PlayerSettings.getAutoPlayNextBook();
- final autoPlayPod = await PlayerSettings.getAutoPlayNextPodcast();
+ final queueMode = await PlayerSettings.getQueueMode();
+ final queueAutoDl = await PlayerSettings.getQueueAutoDownload();
+ final mergeLibs = await PlayerSettings.getMergeAbsorbingLibraries();
+ final maxConc = await PlayerSettings.getMaxConcurrentDownloads();
final whenFinished = await PlayerSettings.getWhenFinished();
final hideEbook = await PlayerSettings.getHideEbookOnly();
final showGoodreads = await PlayerSettings.getShowGoodreadsButton();
@@ -109,8 +113,10 @@ class _SettingsScreenState extends State<SettingsScreen> {
_resetSleepOnPause = resetOnPause;
_sleepFadeOut = sleepFade;
_shakeAddMinutes = shakeMins;
- _autoPlayNextBook = autoPlayBook;
- _autoPlayNextPodcast = autoPlayPod;
+ _queueMode = queueMode;
+ _queueAutoDownload = queueAutoDl;
+ _mergeAbsorbingLibraries = mergeLibs;
+ _maxConcurrentDownloads = maxConc;
_whenFinished = whenFinished;
_hideEbookOnly = hideEbook;
_showGoodreadsButton = showGoodreads;
@@ -514,7 +520,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 8),
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
- Text('When finished', style: tt.bodyMedium?.copyWith(color: cs.onSurface)),
+ Text('When absorbed', style: tt.bodyMedium?.copyWith(color: cs.onSurface)),
const SizedBox(height: 4),
Text('What happens to the absorbing card when a book or episode finishes',
style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
@@ -522,7 +528,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
SizedBox(width: double.infinity, child: SegmentedButton<String>(
segments: const [
ButtonSegment(value: 'overlay', icon: Icon(Icons.layers_rounded), label: Text('Show Overlay')),
- ButtonSegment(value: 'auto_remove', icon: Icon(Icons.auto_delete_rounded), label: Text('Auto-remove')),
+ ButtonSegment(value: 'auto_remove', icon: Icon(Icons.auto_delete_rounded), label: Text('Auto-release')),
],
selected: {_whenFinished},
onSelectionChanged: _loaded ? (s) {
@@ -533,29 +539,94 @@ class _SettingsScreenState extends State<SettingsScreen> {
)),
]),
),
- const Divider(height: 1, indent: 16, endIndent: 16),
SwitchListTile(
- title: const Text('Auto-play next book in series'),
+ title: const Text('Merge libraries'),
subtitle: Text(
- _autoPlayNextBook ? 'On — next book plays automatically' : 'Off',
+ _mergeAbsorbingLibraries
+ ? 'Absorbing page shows items from all libraries'
+ : 'Absorbing page shows current library only',
style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
- value: _autoPlayNextBook,
+ value: _mergeAbsorbingLibraries,
onChanged: _loaded ? (v) {
- setState(() => _autoPlayNextBook = v);
- PlayerSettings.setAutoPlayNextBook(v);
+ setState(() => _mergeAbsorbingLibraries = v);
+ PlayerSettings.setMergeAbsorbingLibraries(v);
} : null,
),
const Divider(height: 1, indent: 16, endIndent: 16),
- SwitchListTile(
- title: const Text('Auto-play next podcast episode'),
- subtitle: Text(
- _autoPlayNextPodcast ? 'On — next episode plays automatically' : 'Off',
- style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
- value: _autoPlayNextPodcast,
- onChanged: _loaded ? (v) {
- setState(() => _autoPlayNextPodcast = v);
- PlayerSettings.setAutoPlayNextPodcast(v);
- } : null,
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 8),
+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Row(children: [
+ Text('Queue mode', style: tt.bodyMedium?.copyWith(color: cs.onSurface)),
+ const SizedBox(width: 4),
+ GestureDetector(
+ onTap: () => showDialog(
+ context: context,
+ builder: (ctx) => AlertDialog(
+ title: const Text('Queue Mode'),
+ content: const Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text('Off', style: TextStyle(fontWeight: FontWeight.w600)),
+ SizedBox(height: 4),
+ Text('Playback stops when the current book or episode finishes.'),
+ SizedBox(height: 12),
+ Text('Manual Queue', style: TextStyle(fontWeight: FontWeight.w600)),
+ SizedBox(height: 4),
+ Text('Your absorbing cards act as a playlist. When one finishes, the next non-finished card auto-plays. Add items with the "Add to Absorbing" button on a book or episode and reorder from the absorbing screen.'),
+ SizedBox(height: 12),
+ Text('Auto Absorb', style: TextStyle(fontWeight: FontWeight.w600)),
+ SizedBox(height: 4),
+ Text('Automatically absorbs the next book in a series or the next episode in a podcast show.'),
+ ],
+ ),
+ actions: [TextButton(onPressed: () => Navigator.pop(ctx), child: Text('Got it'))],
+ ),
+ ),
+ child: Icon(Icons.info_outline_rounded, size: 16, color: cs.onSurfaceVariant),
+ ),
+ ]),
+ const SizedBox(height: 4),
+ Text(
+ _queueMode == 'off' ? 'Playback stops when current item finishes'
+ : _queueMode == 'manual' ? 'Auto-plays next non-finished card in order'
+ : 'Auto-absorbs next book in series or podcast episode',
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant),
+ ),
+ const SizedBox(height: 8),
+ SizedBox(width: double.infinity, child: SegmentedButton<String>(
+ segments: const [
+ ButtonSegment(value: 'off', icon: Icon(Icons.stop_rounded), label: Text('Off')),
+ ButtonSegment(value: 'manual', icon: Icon(Icons.queue_music_rounded), label: Text('Manual')),
+ ButtonSegment(value: 'auto_next', icon: Icon(Icons.skip_next_rounded), label: Text('Auto')),
+ ],
+ selected: {_queueMode},
+ onSelectionChanged: _loaded ? (s) {
+ setState(() => _queueMode = s.first);
+ PlayerSettings.setQueueMode(s.first);
+ } : null,
+ style: const ButtonStyle(visualDensity: VisualDensity.compact),
+ )),
+ if (_queueMode == 'manual') ...[
+ const SizedBox(height: 4),
+ SwitchListTile(
+ title: const Text('Auto-download queue'),
+ subtitle: Text(
+ _queueAutoDownload
+ ? 'Keep next $_rollingDownloadCount items downloaded'
+ : 'Off — manual downloads only',
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _queueAutoDownload,
+ onChanged: _loaded ? (v) {
+ setState(() => _queueAutoDownload = v);
+ PlayerSettings.setQueueAutoDownload(v);
+ } : null,
+ dense: true,
+ contentPadding: EdgeInsets.zero,
+ ),
+ ],
+ ]),
),
],
),
@@ -970,6 +1041,33 @@ class _SettingsScreenState extends State<SettingsScreen> {
} : null,
),
const Divider(height: 1, indent: 16, endIndent: 16),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ const SizedBox(height: 12),
+ Text('Concurrent downloads', style: tt.bodyMedium?.copyWith(color: cs.onSurface)),
+ const SizedBox(height: 8),
+ SizedBox(width: double.infinity, child: SegmentedButton<int>(
+ segments: const [
+ ButtonSegment(value: 1, label: Text('1')),
+ 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: {_maxConcurrentDownloads},
+ onSelectionChanged: (v) {
+ setState(() => _maxConcurrentDownloads = v.first);
+ PlayerSettings.setMaxConcurrentDownloads(v.first);
+ },
+ )),
+ const SizedBox(height: 8),
+ ],
+ ),
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
ListTile(
title: const Text('Auto-download'),
subtitle: Text(
@@ -1002,7 +1100,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
),
),
SwitchListTile(
- title: const Text('Delete finished downloads'),
+ title: const Text('Delete absorbed downloads'),
subtitle: Text(
_rollingDownloadDeleteFinished
? 'Finished items are removed to save space'
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index 2c5f014e..3dd0037d 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -96,6 +96,30 @@ class PlayerSettings {
static Future<bool> getRollingDownloadDeleteFinished() => _get('rollingDownloadDeleteFinished', false);
static Future<void> setRollingDownloadDeleteFinished(bool value) => _set('rollingDownloadDeleteFinished', value);
+ static Future<bool> getQueueAutoDownload() => _get('queueAutoDownload', false);
+ static Future<void> setQueueAutoDownload(bool value) => _set('queueAutoDownload', value);
+
+ static Future<bool> getMergeAbsorbingLibraries() => _get('mergeAbsorbingLibraries', false);
+ static Future<void> setMergeAbsorbingLibraries(bool value) => _set('mergeAbsorbingLibraries', value);
+
+ static Future<int> getMaxConcurrentDownloads() => _get('maxConcurrentDownloads', 1);
+ static Future<void> setMaxConcurrentDownloads(int value) => _set('maxConcurrentDownloads', value);
+
+ // ── Queue mode (replaces autoPlayNextBook + autoPlayNextPodcast) ──
+ // Values: 'off', 'manual', 'auto_next'
+ static Future<String> getQueueMode() => _get('queueMode', 'off');
+ static Future<void> setQueueMode(String value) => _set('queueMode', value);
+
+ /// One-time migration from the old boolean auto-play settings to queueMode.
+ static Future<void> migrateQueueMode() async {
+ final prefs = await SharedPreferences.getInstance();
+ if (prefs.containsKey('queueMode')) return;
+ final autoBook = prefs.getBool('autoPlayNextBook') ?? false;
+ final autoPod = prefs.getBool('autoPlayNextPodcast') ?? false;
+ await prefs.setString('queueMode', (autoBook || autoPod) ? 'auto_next' : 'off');
+ }
+
+ // Legacy getters kept for backup service compatibility
static Future<bool> getAutoPlayNextBook() => _get('autoPlayNextBook', false);
static Future<void> setAutoPlayNextBook(bool value) => _set('autoPlayNextBook', value);
diff --git a/lib/services/backup_service.dart b/lib/services/backup_service.dart
index 8efe7d36..fcf7053c 100644
--- a/lib/services/backup_service.dart
+++ b/lib/services/backup_service.dart
@@ -17,8 +17,10 @@ class BackupService {
final settings = <String, dynamic>{
'defaultSpeed': await PlayerSettings.getDefaultSpeed(),
'wifiOnlyDownloads': await PlayerSettings.getWifiOnlyDownloads(),
- 'autoPlayNextBook': await PlayerSettings.getAutoPlayNextBook(),
- 'autoPlayNextPodcast': await PlayerSettings.getAutoPlayNextPodcast(),
+ 'queueMode': await PlayerSettings.getQueueMode(),
+ // Legacy keys for backward compat with older app versions
+ 'autoPlayNextBook': (await PlayerSettings.getQueueMode()) == 'auto_next',
+ 'autoPlayNextPodcast': (await PlayerSettings.getQueueMode()) == 'auto_next',
'whenFinished': await PlayerSettings.getWhenFinished(),
'showBookSlider': await PlayerSettings.getShowBookSlider(),
'speedAdjustedTime': await PlayerSettings.getSpeedAdjustedTime(),
@@ -41,6 +43,9 @@ class BackupService {
'cardButtonOrder': await PlayerSettings.getCardButtonOrder(),
'rollingDownloadCount': await PlayerSettings.getRollingDownloadCount(),
'rollingDownloadDeleteFinished': await PlayerSettings.getRollingDownloadDeleteFinished(),
+ 'queueAutoDownload': await PlayerSettings.getQueueAutoDownload(),
+ 'mergeAbsorbingLibraries': await PlayerSettings.getMergeAbsorbingLibraries(),
+ 'maxConcurrentDownloads': await PlayerSettings.getMaxConcurrentDownloads(),
};
// AutoRewind
@@ -141,8 +146,14 @@ class BackupService {
final s = data['settings'] as Map<String, dynamic>? ?? {};
if (s['defaultSpeed'] != null) PlayerSettings.setDefaultSpeed((s['defaultSpeed'] as num).toDouble());
if (s['wifiOnlyDownloads'] != null) PlayerSettings.setWifiOnlyDownloads(s['wifiOnlyDownloads'] as bool);
- if (s['autoPlayNextBook'] != null) PlayerSettings.setAutoPlayNextBook(s['autoPlayNextBook'] as bool);
- if (s['autoPlayNextPodcast'] != null) PlayerSettings.setAutoPlayNextPodcast(s['autoPlayNextPodcast'] as bool);
+ if (s['queueMode'] != null) {
+ PlayerSettings.setQueueMode(s['queueMode'] as String);
+ } else {
+ // Legacy backup — migrate the old booleans
+ final autoBook = s['autoPlayNextBook'] as bool? ?? false;
+ final autoPod = s['autoPlayNextPodcast'] as bool? ?? false;
+ PlayerSettings.setQueueMode((autoBook || autoPod) ? 'auto_next' : 'off');
+ }
if (s['whenFinished'] != null) PlayerSettings.setWhenFinished(s['whenFinished'] as String);
if (s['showBookSlider'] != null) PlayerSettings.setShowBookSlider(s['showBookSlider'] as bool);
if (s['speedAdjustedTime'] != null) PlayerSettings.setSpeedAdjustedTime(s['speedAdjustedTime'] as bool);
@@ -169,6 +180,9 @@ class BackupService {
}
if (s['rollingDownloadCount'] != null) PlayerSettings.setRollingDownloadCount(s['rollingDownloadCount'] as int);
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['maxConcurrentDownloads'] != null) PlayerSettings.setMaxConcurrentDownloads(s['maxConcurrentDownloads'] as int);
// AutoRewind
final r = data['autoRewind'] as Map<String, dynamic>?;
diff --git a/lib/services/download_notification_service.dart b/lib/services/download_notification_service.dart
index ba487d8a..ac84be4f 100644
--- a/lib/services/download_notification_service.dart
+++ b/lib/services/download_notification_service.dart
@@ -2,8 +2,9 @@ import 'package:flutter/foundation.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
/// Manages notifications for audiobook downloads.
-/// Uses an Android **foreground service** for progress so the OS won't kill
-/// the download when the app is backgrounded or the screen is locked.
+/// Uses an Android **foreground service** for a summary notification so the OS
+/// won't kill the download when the app is backgrounded or the screen is locked.
+/// Each concurrent download gets its own progress notification.
/// A separate high-importance channel handles completion/error alerts.
class DownloadNotificationService {
// Singleton
@@ -19,13 +20,20 @@ class DownloadNotificationService {
static const _progressChannelId = 'absorb_downloads';
static const _progressChannelName = 'Download Progress';
static const _progressChannelDesc = 'Shows progress during audiobook downloads';
- static const _progressNotifId = 9001;
// Alert channel for completion / error (heads-up + sound)
static const _alertChannelId = 'absorb_download_alerts';
static const _alertChannelName = 'Download Alerts';
static const _alertChannelDesc = 'Notifications when downloads finish or fail';
- static const _alertNotifId = 9002;
+
+ // Notification IDs
+ static const _foregroundNotifId = 9000; // summary foreground service
+ // Per-download progress: 9001 + slot (slots 0–4)
+ static int _progressNotifId(int slot) => 9001 + slot;
+ // Alerts use incrementing IDs so they stack
+ int _nextAlertId = 9010;
+
+ int _activeCount = 0;
Future<void> init() async {
if (_initialized) return;
@@ -68,27 +76,128 @@ class DownloadNotificationService {
_initialized = true;
}
- /// Start the foreground service and show initial progress notification.
- /// Call once at the start of a download.
- Future<void> startForeground({
+ /// Start tracking a new download. Starts the foreground service if this is
+ /// the first active download. Shows an individual progress notification.
+ Future<void> startDownload({
+ required int slot,
required String title,
String? author,
}) async {
if (!_initialized) await init();
+ _activeCount++;
- final subtitle = author != null && author.isNotEmpty
- ? '$author • Starting…'
- : 'Starting…';
+ // Start foreground service if this is the first download
+ if (_activeCount == 1) {
+ await _startForeground();
+ } else {
+ await _updateForegroundSummary();
+ }
- final androidDetails = AndroidNotificationDetails(
+ // Show individual progress notification
+ await _showSlotProgress(
+ slot: slot,
+ title: title,
+ author: author,
+ percent: 0,
+ starting: true,
+ );
+ }
+
+ /// Update progress for an individual download.
+ Future<void> updateProgress({
+ required int slot,
+ required String title,
+ required double progress,
+ String? author,
+ }) async {
+ if (!_initialized) await init();
+ final percent = (progress * 100).round().clamp(0, 100);
+ await _showSlotProgress(
+ slot: slot,
+ title: title,
+ author: author,
+ percent: percent,
+ );
+ }
+
+ /// Mark a download as finished (success or error). Cancels its progress
+ /// notification, shows an alert, and stops the foreground service if no
+ /// downloads remain.
+ Future<void> finishDownload({
+ required int slot,
+ required String title,
+ bool success = true,
+ String? errorMessage,
+ }) async {
+ if (!_initialized) await init();
+
+ // Cancel individual progress notification
+ try {
+ await _plugin.cancel(_progressNotifId(slot));
+ } catch (e) {
+ debugPrint('[DownloadNotif] Cancel slot $slot failed: $e');
+ }
+
+ _activeCount = (_activeCount - 1).clamp(0, 99);
+
+ if (_activeCount == 0) {
+ await _stopForeground();
+ } else {
+ await _updateForegroundSummary();
+ }
+
+ // Show alert
+ if (success) {
+ await _showAlert(
+ title: 'Download Complete',
+ body: '$title is ready to listen offline',
+ );
+ } else {
+ await _showAlert(
+ title: 'Download Failed',
+ body: errorMessage ?? title,
+ );
+ }
+ }
+
+ /// Cancel a download's notification without showing an alert.
+ Future<void> cancelDownload(int slot) async {
+ try {
+ await _plugin.cancel(_progressNotifId(slot));
+ } catch (e) {
+ debugPrint('[DownloadNotif] Cancel slot $slot failed: $e');
+ }
+
+ _activeCount = (_activeCount - 1).clamp(0, 99);
+
+ if (_activeCount == 0) {
+ await _stopForeground();
+ } else {
+ await _updateForegroundSummary();
+ }
+ }
+
+ /// Dismiss all download notifications and stop the foreground service.
+ Future<void> dismiss() async {
+ await _stopForeground();
+ _activeCount = 0;
+ // Cancel all possible slot notifications
+ for (int i = 0; i < 5; i++) {
+ try {
+ await _plugin.cancel(_progressNotifId(i));
+ } catch (_) {}
+ }
+ }
+
+ // ── Private helpers ──
+
+ Future<void> _startForeground() async {
+ const androidDetails = AndroidNotificationDetails(
_progressChannelId,
_progressChannelName,
channelDescription: _progressChannelDesc,
importance: Importance.defaultImportance,
priority: Priority.defaultPriority,
- showProgress: true,
- maxProgress: 100,
- progress: 0,
ongoing: true,
autoCancel: false,
onlyAlertOnce: true,
@@ -96,16 +205,14 @@ class DownloadNotificationService {
icon: 'drawable/ic_notification',
);
- // Start as a foreground service — this prevents Android from killing
- // the process while the download is active.
final androidPlugin = _plugin.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>();
if (androidPlugin != null) {
try {
await androidPlugin.startForegroundService(
- _progressNotifId,
- 'Downloading: $title',
- subtitle,
+ _foregroundNotifId,
+ 'Downloading...',
+ '1 download active',
notificationDetails: androidDetails,
payload: 'download',
);
@@ -113,30 +220,20 @@ class DownloadNotificationService {
debugPrint('[DownloadNotif] Foreground service started');
} catch (e) {
debugPrint('[DownloadNotif] Foreground service failed, falling back: $e');
- // Fall back to a regular notification
await _plugin.show(
- _progressNotifId,
- 'Downloading: $title',
- subtitle,
- NotificationDetails(android: androidDetails),
+ _foregroundNotifId,
+ 'Downloading...',
+ '1 download active',
+ const NotificationDetails(android: androidDetails),
);
_foregroundActive = false;
}
}
}
- /// Show or update the download progress notification.
- Future<void> showProgress({
- required String title,
- required double progress,
- String? author,
- }) async {
- if (!_initialized) await init();
-
- final percent = (progress * 100).round().clamp(0, 100);
- final subtitle = author != null && author.isNotEmpty
- ? '$author • $percent%'
- : '$percent%';
+ Future<void> _updateForegroundSummary() async {
+ if (_activeCount <= 0) return;
+ final subtitle = '$_activeCount download${_activeCount == 1 ? '' : 's'} active';
final androidDetails = AndroidNotificationDetails(
_progressChannelId,
@@ -144,9 +241,6 @@ class DownloadNotificationService {
channelDescription: _progressChannelDesc,
importance: Importance.defaultImportance,
priority: Priority.defaultPriority,
- showProgress: true,
- maxProgress: 100,
- progress: percent,
ongoing: true,
autoCancel: false,
onlyAlertOnce: true,
@@ -155,15 +249,14 @@ class DownloadNotificationService {
);
await _plugin.show(
- _progressNotifId,
- 'Downloading: $title',
+ _foregroundNotifId,
+ 'Downloading...',
subtitle,
NotificationDetails(android: androidDetails),
);
}
- /// Stop the foreground service and clear the progress notification.
- Future<void> stopForeground() async {
+ Future<void> _stopForeground() async {
if (_foregroundActive) {
final androidPlugin = _plugin.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>();
@@ -178,50 +271,51 @@ class DownloadNotificationService {
_foregroundActive = false;
}
try {
- await _plugin.cancel(_progressNotifId);
+ await _plugin.cancel(_foregroundNotifId);
} catch (e) {
- debugPrint('[DownloadNotif] Cancel progress failed: $e');
+ debugPrint('[DownloadNotif] Cancel foreground failed: $e');
}
}
- /// Show a heads-up completion notification with sound.
- /// Stops the foreground service and dismisses the progress notification first.
- Future<void> showComplete({required String title}) async {
- if (!_initialized) await init();
-
- // Stop the foreground service + clear progress
- await stopForeground();
+ Future<void> _showSlotProgress({
+ required int slot,
+ required String title,
+ String? author,
+ required int percent,
+ bool starting = false,
+ }) async {
+ final subtitle = starting
+ ? (author != null && author.isNotEmpty ? '$author • Starting…' : 'Starting…')
+ : (author != null && author.isNotEmpty ? '$author • $percent%' : '$percent%');
- const androidDetails = AndroidNotificationDetails(
- _alertChannelId,
- _alertChannelName,
- channelDescription: _alertChannelDesc,
- importance: Importance.high,
- priority: Priority.high,
- ongoing: false,
- autoCancel: true,
+ final androidDetails = AndroidNotificationDetails(
+ _progressChannelId,
+ _progressChannelName,
+ channelDescription: _progressChannelDesc,
+ importance: Importance.defaultImportance,
+ priority: Priority.defaultPriority,
+ showProgress: true,
+ maxProgress: 100,
+ progress: percent,
+ ongoing: true,
+ autoCancel: false,
+ onlyAlertOnce: true,
+ category: AndroidNotificationCategory.progress,
icon: 'drawable/ic_notification',
- ticker: 'Download complete',
- category: AndroidNotificationCategory.status,
- visibility: NotificationVisibility.public,
);
await _plugin.show(
- _alertNotifId,
- 'Download Complete',
- '$title is ready to listen offline',
- const NotificationDetails(android: androidDetails),
+ _progressNotifId(slot),
+ 'Downloading: $title',
+ subtitle,
+ NotificationDetails(android: androidDetails),
);
}
- /// Show a heads-up error notification with sound.
- /// Stops the foreground service and dismisses the progress notification first.
- Future<void> showError({required String title, String? message}) async {
- if (!_initialized) await init();
-
- // Stop the foreground service + clear progress
- await stopForeground();
-
+ Future<void> _showAlert({
+ required String title,
+ required String body,
+ }) async {
const androidDetails = AndroidNotificationDetails(
_alertChannelId,
_alertChannelName,
@@ -231,26 +325,19 @@ class DownloadNotificationService {
ongoing: false,
autoCancel: true,
icon: 'drawable/ic_notification',
- ticker: 'Download failed',
category: AndroidNotificationCategory.status,
visibility: NotificationVisibility.public,
);
+ final alertId = _nextAlertId++;
+ // Wrap around to avoid unbounded growth
+ if (_nextAlertId > 9099) _nextAlertId = 9010;
+
await _plugin.show(
- _alertNotifId,
- 'Download Failed',
- message ?? title,
+ alertId,
+ title,
+ body,
const NotificationDetails(android: androidDetails),
);
}
-
- /// Dismiss all download notifications and stop the foreground service.
- Future<void> dismiss() async {
- await stopForeground();
- try {
- await _plugin.cancel(_alertNotifId);
- } catch (e) {
- debugPrint('[DownloadNotif] Cancel alert failed: $e');
- }
- }
}
diff --git a/lib/services/download_service.dart b/lib/services/download_service.dart
index d54530a4..d44c84b0 100644
--- a/lib/services/download_service.dart
+++ b/lib/services/download_service.dart
@@ -116,14 +116,14 @@ class DownloadService extends ChangeNotifier {
DownloadService._();
final Map<String, DownloadInfo> _downloads = {};
- String? _activeDownloadId;
- http.Client? _httpClient;
- bool _cancelled = false;
+ final Set<String> _activeDownloadIds = {};
+ final Map<String, http.Client> _httpClients = {};
+ final Set<String> _cancelledIds = {};
+ final Map<String, int> _downloadSlots = {};
String? _customDownloadPath;
/// Queue of pending download requests.
final List<_QueuedDownload> _queue = [];
- bool _processingQueue = false;
/// The current download directory path, or null if using default.
String? get customDownloadPath => _customDownloadPath;
@@ -425,7 +425,7 @@ class DownloadService extends ChangeNotifier {
String? coverUrl,
String? episodeId,
}) async {
- if (_activeDownloadId == itemId) return null;
+ if (_activeDownloadIds.contains(itemId)) return null;
if (isDownloaded(itemId)) return null;
// Already queued — don't duplicate
if (_queue.any((q) => q.itemId == itemId)) return null;
@@ -439,8 +439,10 @@ class DownloadService extends ChangeNotifier {
}
}
- // If another download is active, queue this one
- if (_activeDownloadId != null) {
+ final maxConcurrent = await PlayerSettings.getMaxConcurrentDownloads();
+
+ // If at capacity, queue this one
+ if (_activeDownloadIds.length >= maxConcurrent) {
_queue.add(_QueuedDownload(
api: api,
itemId: itemId,
@@ -458,41 +460,47 @@ class DownloadService extends ChangeNotifier {
coverUrl: coverUrl,
);
notifyListeners();
- // Ensure queue processor is running
- if (!_processingQueue) unawaited(_processQueue());
return null;
}
- await _executeDownload(
+ // Launch immediately (fire-and-forget so caller doesn't block)
+ unawaited(_executeDownload(
api: api,
itemId: itemId,
title: title,
author: author,
coverUrl: coverUrl,
episodeId: episodeId,
- );
- // Process any queued downloads
- if (_queue.isNotEmpty && !_processingQueue) {
- unawaited(_processQueue());
- }
+ ));
return null;
}
+ /// Fill free download slots from the queue.
Future<void> _processQueue() async {
- _processingQueue = true;
- while (_activeDownloadId != null) {
- await Future<void>.delayed(const Duration(milliseconds: 100));
- }
- while (_queue.isNotEmpty) {
+ final maxConcurrent = await PlayerSettings.getMaxConcurrentDownloads();
+ while (_queue.isNotEmpty && _activeDownloadIds.length < maxConcurrent) {
final next = _queue.removeAt(0);
// Skip if cancelled/removed while waiting
if (isDownloaded(next.itemId)) continue;
- await _executeDownload(
+ if (_activeDownloadIds.contains(next.itemId)) continue;
+ unawaited(_executeDownload(
api: next.api, itemId: next.itemId, title: next.title,
author: next.author, coverUrl: next.coverUrl, episodeId: next.episodeId,
- );
+ ));
+ }
+ }
+
+ /// Assign the lowest free notification slot (0–4).
+ int _assignSlot(String itemId) {
+ for (int i = 0; i < 5; i++) {
+ if (!_downloadSlots.containsValue(i)) {
+ _downloadSlots[itemId] = i;
+ return i;
+ }
}
- _processingQueue = false;
+ // Fallback (shouldn't happen with max 5 concurrent)
+ _downloadSlots[itemId] = 0;
+ return 0;
}
Future<void> _executeDownload({
@@ -503,8 +511,12 @@ class DownloadService extends ChangeNotifier {
String? coverUrl,
String? episodeId,
}) async {
- _activeDownloadId = itemId;
- _cancelled = false;
+ _activeDownloadIds.add(itemId);
+ _cancelledIds.remove(itemId);
+ final slot = _assignSlot(itemId);
+ final client = http.Client();
+ _httpClients[itemId] = client;
+
_downloads[itemId] = DownloadInfo(
itemId: itemId,
status: DownloadStatus.downloading,
@@ -515,12 +527,12 @@ class DownloadService extends ChangeNotifier {
);
notifyListeners();
- // Show persistent download notification via foreground service
+ // Show per-download notification + foreground service
final notif = DownloadNotificationService();
try {
- await notif.startForeground(title: title, author: author);
+ await notif.startDownload(slot: slot, title: title, author: author);
} catch (e) {
- debugPrint('[Download] startForeground non-fatal error: $e');
+ debugPrint('[Download] startDownload non-fatal error: $e');
}
try {
@@ -567,36 +579,31 @@ class DownloadService extends ChangeNotifier {
}
final localPaths = List<String?>.filled(audioTracks.length, null);
- _httpClient = http.Client();
// Track progress per-track for overall calculation
final trackProgress = List<double>.filled(audioTracks.length, 0.0);
- int _lastNotifPercent = -1;
- DateTime _lastUIUpdate = DateTime.now();
-
- Future<void> _showProgressSafe(
- DownloadNotificationService notif,
- String title,
- String? author,
- double progress,
- ) async {
+ int lastNotifPercent = -1;
+ DateTime lastUIUpdate = DateTime.now();
+
+ Future<void> showProgressSafe(double progress) async {
try {
- await notif.showProgress(
+ await notif.updateProgress(
+ slot: slot,
title: title,
author: author,
progress: progress,
);
} catch (e) {
- debugPrint('[Download] showProgress non-fatal error: $e');
+ debugPrint('[Download] updateProgress non-fatal error: $e');
}
}
- void _updateProgress() {
+ void updateProgress() {
final overall = trackProgress.reduce((a, b) => a + b) / audioTracks.length;
final now = DateTime.now();
// Throttle UI updates to max ~4/sec
- if (now.difference(_lastUIUpdate).inMilliseconds > 250) {
- _lastUIUpdate = now;
+ if (now.difference(lastUIUpdate).inMilliseconds > 250) {
+ lastUIUpdate = now;
_downloads[itemId] = DownloadInfo(
itemId: itemId,
status: DownloadStatus.downloading,
@@ -609,13 +616,13 @@ class DownloadService extends ChangeNotifier {
}
// Throttle notification to every 2%
final pct = (overall * 50).round();
- if (pct != _lastNotifPercent) {
- _lastNotifPercent = pct;
- unawaited(_showProgressSafe(notif, title, author, overall));
+ if (pct != lastNotifPercent) {
+ lastNotifPercent = pct;
+ unawaited(showProgressSafe(overall));
}
}
- Future<void> _downloadTrack(int i) async {
+ Future<void> downloadTrack(int i) async {
final track = audioTracks[i] as Map<String, dynamic>;
final contentUrl = track['contentUrl'] as String? ?? '';
final fullUrl = api.buildTrackUrl(contentUrl);
@@ -637,7 +644,7 @@ class DownloadService extends ChangeNotifier {
final request = http.Request('GET', Uri.parse(fullUrl));
api.mediaHeaders.forEach((key, value) => request.headers[key] = value);
- final response = await _httpClient!.send(request)
+ final response = await client.send(request)
.timeout(const Duration(seconds: 30));
if (response.statusCode != 200) {
@@ -652,7 +659,7 @@ class DownloadService extends ChangeNotifier {
sink.add(chunk);
receivedBytes += chunk.length;
trackProgress[i] = totalBytes > 0 ? receivedBytes / totalBytes : 0.5;
- _updateProgress();
+ updateProgress();
}
} finally {
await sink.close();
@@ -661,11 +668,12 @@ class DownloadService extends ChangeNotifier {
}
// Download tracks in parallel batches of 3
- const concurrency = 3;
- for (int batch = 0; batch < audioTracks.length; batch += concurrency) {
- final end = (batch + concurrency).clamp(0, audioTracks.length);
+ const trackConcurrency = 3;
+ for (int batch = 0; batch < audioTracks.length; batch += trackConcurrency) {
+ if (_cancelledIds.contains(itemId)) break;
+ final end = (batch + trackConcurrency).clamp(0, audioTracks.length);
await Future.wait([
- for (int i = batch; i < end; i++) _downloadTrack(i),
+ for (int i = batch; i < end; i++) downloadTrack(i),
]);
}
@@ -704,7 +712,7 @@ class DownloadService extends ChangeNotifier {
// Show completion notification
try {
- await notif.showComplete(title: title);
+ await notif.finishDownload(slot: slot, title: title);
} catch (_) {}
// If this book is currently streaming, hot-swap to local files
@@ -724,9 +732,12 @@ class DownloadService extends ChangeNotifier {
if (bookDir.existsSync()) bookDir.deleteSync(recursive: true);
} catch (_) {}
- if (_cancelled) {
+ if (_cancelledIds.contains(itemId)) {
debugPrint('[Download] Cancelled: $title');
_downloads.remove(itemId);
+ try {
+ await notif.cancelDownload(slot);
+ } catch (_) {}
} else {
final isStorageFull = e.toString().contains('No space left') ||
e.toString().contains('ENOSPC');
@@ -743,17 +754,27 @@ class DownloadService extends ChangeNotifier {
);
// Show error notification
try {
- await notif.showError(title: title, message: '$errorMsg: $title');
+ await notif.finishDownload(
+ slot: slot,
+ title: title,
+ success: false,
+ errorMessage: '$errorMsg: $title',
+ );
} catch (notifErr) {
- debugPrint('[Download] showError non-fatal error: $notifErr');
+ debugPrint('[Download] finishDownload non-fatal error: $notifErr');
}
}
}
- _activeDownloadId = null;
- _httpClient = null;
+ _activeDownloadIds.remove(itemId);
+ _downloadSlots.remove(itemId);
+ _httpClients.remove(itemId);
+ _cancelledIds.remove(itemId);
notifyListeners();
+
+ // Fill freed slot from queue
+ unawaited(_processQueue());
}
Future<void> deleteDownload(String itemId, {bool skipStopCheck = false}) async {
@@ -795,16 +816,11 @@ class DownloadService extends ChangeNotifier {
}
void cancelDownload(String itemId) {
- if (_activeDownloadId == itemId) {
- _cancelled = true;
- _httpClient?.close();
- _httpClient = null;
- _activeDownloadId = null;
- unawaited(
- DownloadNotificationService().dismiss().catchError((Object e) {
- debugPrint('[Download] dismiss non-fatal error: $e');
- }),
- );
+ if (_activeDownloadIds.contains(itemId)) {
+ _cancelledIds.add(itemId);
+ _httpClients[itemId]?.close();
+ _httpClients.remove(itemId);
+ // Notification cleanup happens in _executeDownload's catch block
}
// Remove from queue if it was waiting
_queue.removeWhere((q) => q.itemId == itemId);
diff --git a/lib/widgets/book_detail_sheet.dart b/lib/widgets/book_detail_sheet.dart
index 97d1c662..1b6f272a 100644
--- a/lib/widgets/book_detail_sheet.dart
+++ b/lib/widgets/book_detail_sheet.dart
@@ -355,10 +355,16 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
_sheetBtn(icon: Icons.restart_alt_rounded,
label: 'Reset Progress', onTap: () => _resetProgress(context, auth, duration)),
],
- if (lib.isOnAbsorbingList(widget.itemId)) ...[
- const SizedBox(height: 8),
- _sheetBtn(icon: Icons.remove_circle_outline_rounded,
- label: 'Remove from Absorbing', onTap: () async {
+ const SizedBox(height: 8),
+ _sheetBtn(
+ icon: lib.isOnAbsorbingList(widget.itemId)
+ ? Icons.remove_circle_outline_rounded
+ : Icons.add_circle_outline_rounded,
+ label: lib.isOnAbsorbingList(widget.itemId)
+ ? 'Remove from Absorbing'
+ : 'Add to Absorbing',
+ onTap: () async {
+ if (lib.isOnAbsorbingList(widget.itemId)) {
await lib.removeFromAbsorbing(widget.itemId);
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
@@ -367,8 +373,24 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
behavior: SnackBarBehavior.floating,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))));
}
- }),
- ],
+ } else {
+ await lib.addToAbsorbingQueue(widget.itemId);
+ // Populate cache so the absorbing card can render immediately
+ if (_item != null) {
+ final cached = Map<String, dynamic>.from(_item!);
+ cached['_absorbingKey'] = widget.itemId;
+ lib.absorbingItemCache[widget.itemId] = cached;
+ }
+ if (context.mounted) {
+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(
+ duration: const Duration(seconds: 3),
+ content: const Text('Added to Absorbing'),
+ behavior: SnackBarBehavior.floating,
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))));
+ }
+ }
+ },
+ ),
const SizedBox(height: 16),
Wrap(spacing: 8, runSpacing: 8, children: [
if (year.isNotEmpty) _chip(Icons.calendar_today_rounded, year),
diff --git a/lib/widgets/episode_list_sheet.dart b/lib/widgets/episode_list_sheet.dart
index 9a54a141..d14cc949 100644
--- a/lib/widgets/episode_list_sheet.dart
+++ b/lib/widgets/episode_list_sheet.dart
@@ -886,11 +886,17 @@ class _EpisodeDetailSheetState extends State<EpisodeDetailSheet> {
_sheetBtn(icon: Icons.restart_alt_rounded,
label: 'Reset Progress', onTap: () => _resetProgress(context)),
],
- // Remove from Absorbing
- if (lib.isOnAbsorbingList(dlKey)) ...[
- const SizedBox(height: 8),
- _sheetBtn(icon: Icons.remove_circle_outline_rounded,
- label: 'Remove from Absorbing', onTap: () async {
+ // Add / Remove from Absorbing
+ const SizedBox(height: 8),
+ _sheetBtn(
+ icon: lib.isOnAbsorbingList(dlKey)
+ ? Icons.remove_circle_outline_rounded
+ : Icons.add_circle_outline_rounded,
+ label: lib.isOnAbsorbingList(dlKey)
+ ? 'Remove from Absorbing'
+ : 'Add to Absorbing',
+ onTap: () async {
+ if (lib.isOnAbsorbingList(dlKey)) {
await lib.removeFromAbsorbing(dlKey);
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
@@ -899,8 +905,23 @@ class _EpisodeDetailSheetState extends State<EpisodeDetailSheet> {
behavior: SnackBarBehavior.floating,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))));
}
- }),
- ],
+ } else {
+ await lib.addToAbsorbingQueue(dlKey);
+ // Populate cache so the absorbing card can render this episode
+ final cached = Map<String, dynamic>.from(widget.podcastItem);
+ cached['recentEpisode'] = Map<String, dynamic>.from(widget.episode);
+ cached['_absorbingKey'] = dlKey;
+ lib.absorbingItemCache[dlKey] = cached;
+ if (context.mounted) {
+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(
+ duration: const Duration(seconds: 3),
+ content: const Text('Added to Absorbing'),
+ behavior: SnackBarBehavior.floating,
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))));
+ }
+ }
+ },
+ ),
// Metadata chips
const SizedBox(height: 16),