Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Keep playback smooth and make Absorbing stay in sync

Barnabas816adfb952fa
diff --git a/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt b/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt
index 9b7951ca..88ea2cc9 100644
--- a/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt
+++ b/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt
@@ -121,6 +121,14 @@ class MainActivity : AudioServiceActivity() {
}
Log.d(TAG, "EQ method channel registered")
+ MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "com.absorb.audio_diag")
+ .setMethodCallHandler { call, result ->
+ when (call.method) {
+ "snapshot" -> result.success(AudioService.getDiagnosticSnapshot())
+ else -> result.notImplemented()
+ }
+ }
+
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "com.absorb.storage")
.setMethodCallHandler { call, result ->
when (call.method) {
@@ -289,8 +297,14 @@ class MainActivity : AudioServiceActivity() {
))
} catch (e: Exception) {
effectsAvailable = false
- Log.e(TAG, "init failed: ${e.message}")
- result.error("EQ_INIT_ERROR", e.message, null)
+ Log.d(TAG, "EQ probe deferred until playback: ${e.message}")
+ result.success(mapOf(
+ "bands" to 5,
+ "frequencies" to listOf(60, 230, 910, 3600, 14000),
+ "minLevel" to -15.0,
+ "maxLevel" to 15.0,
+ "deferred" to true
+ ))
}
}
diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb
index 60ebb9b4..86802155 100644
--- a/lib/l10n/app_de.arb
+++ b/lib/l10n/app_de.arb
@@ -921,7 +921,7 @@
"keepNextInfoContent": "Die Anzahl der Elemente, die heruntergeladen bleiben sollen, einschließlich des Elements, das du gerade hörst. Beispiel: \"Nächste 3 behalten\" bedeutet, das aktuelle Buch plus die nächsten 2 in der Serie oder im Podcast bleiben heruntergeladen.",
"deleteAbsorbedDownloads": "Absorbed Downloads löschen",
"deleteAbsorbedDownloadsInfoTitle": "Absorbed Downloads löschen",
- "deleteAbsorbedDownloadsInfoContent": "Wenn aktiviert, werden heruntergeladene Bücher oder Episoden automatisch von deinem Gerät gelöscht, nachdem du sie zu Ende gehört hast. Das hilft, Speicherplatz freizugeben, während du dich durch deine Bibliothek arbeitest.",
+ "deleteAbsorbedDownloadsInfoContent": "Wenn aktiviert, werden heruntergeladene Bücher oder Episoden automatisch von diesem Gerät gelöscht, nachdem du sie in Absorb zu Ende gehört hast. Wenn du einen Titel im Web oder auf einem anderen Gerät beendest, bleibt der Download hier erhalten.",
"deleteAbsorbedOnSubtitle": "Beendete Elemente werden entfernt, um Platz zu sparen",
"deleteAbsorbedOffSubtitle": "Aus - beendete Downloads werden behalten",
"downloadLocation": "Download-Speicherort",
diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb
index 05aa7c66..41961be3 100644
--- a/lib/l10n/app_en.arb
+++ b/lib/l10n/app_en.arb
@@ -856,7 +856,7 @@
"keepNextInfoContent": "The number of items to keep downloaded, including the one you're currently listening to. For example, \"Keep next 3\" means the current book plus the next 2 in the series or podcast will stay downloaded.",
"deleteAbsorbedDownloads": "Delete absorbed downloads",
"deleteAbsorbedDownloadsInfoTitle": "Delete Absorbed Downloads",
- "deleteAbsorbedDownloadsInfoContent": "When enabled, downloaded books or episodes are automatically deleted from your device after you finish listening to them. This helps free up storage space as you work through your library.",
+ "deleteAbsorbedDownloadsInfoContent": "When enabled, downloaded books or episodes are automatically deleted from this device after you finish them in Absorb. Finishing an item on the web or another device won’t delete its download here.",
"deleteAbsorbedOnSubtitle": "Finished items are removed to save space",
"deleteAbsorbedOffSubtitle": "Off - finished downloads kept",
"downloadLocation": "Download location",
diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb
index 568499ce..4f82db2d 100644
--- a/lib/l10n/app_fr.arb
+++ b/lib/l10n/app_fr.arb
@@ -654,7 +654,7 @@
"keepNextInfoContent": "Le nombre d’éléments à conserver téléchargés, y compris celui que vous écoutez actuellement. Par exemple, « Garder les 3 suivants » signifie que le livre en cours plus les 2 suivants dans la série ou le podcast resteront téléchargés.",
"deleteAbsorbedDownloads": "Supprimer les téléchargements absorbés",
"deleteAbsorbedDownloadsInfoTitle": "Supprimer les téléchargements absorbés",
- "deleteAbsorbedDownloadsInfoContent": "Lorsque cette option est activée, les livres ou épisodes téléchargés sont automatiquement supprimés de votre appareil après que vous avez fini de les écouter. Cela permet de libérer de l’espace de stockage au fur et à mesure que vous avancez dans votre bibliothèque.",
+ "deleteAbsorbedDownloadsInfoContent": "Lorsque cette option est activée, les livres ou épisodes téléchargés sont automatiquement supprimés de cet appareil lorsque vous les terminez dans Absorb. Si vous terminez un livre ou un épisode sur le Web ou un autre appareil, son téléchargement reste sur cet appareil.",
"deleteAbsorbedOnSubtitle": "Les éléments achevés sont supprimés pour libérer de l'espace",
"deleteAbsorbedOffSubtitle": "Désactivé - les téléchargements terminés sont conservés",
"downloadLocation": "Emplacement de téléchargement",
@@ -1392,4 +1392,4 @@
},
"readerAnnotations": "Notes",
"readerSearchEmpty": "Entrez un mot ou une phrase puis recherchez."
-}
\ No newline at end of file
+}
diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart
index 58449b80..d8fca852 100644
--- a/lib/l10n/app_localizations.dart
+++ b/lib/l10n/app_localizations.dart
@@ -3319,7 +3319,7 @@ abstract class AppLocalizations {
/// No description provided for @deleteAbsorbedDownloadsInfoContent.
///
/// In en, this message translates to:
- /// **'When enabled, downloaded books or episodes are automatically deleted from your device after you finish listening to them. This helps free up storage space as you work through your library.'**
+ /// **'When enabled, downloaded books or episodes are automatically deleted from this device after you finish them in Absorb. Finishing an item on the web or another device won’t delete its download here.'**
String get deleteAbsorbedDownloadsInfoContent;
/// No description provided for @deleteAbsorbedOnSubtitle.
diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart
index 569b7f4f..627f8f37 100644
--- a/lib/l10n/app_localizations_de.dart
+++ b/lib/l10n/app_localizations_de.dart
@@ -1797,7 +1797,7 @@ class AppLocalizationsDe extends AppLocalizations {
@override
String get deleteAbsorbedDownloadsInfoContent =>
- 'Wenn aktiviert, werden heruntergeladene Bücher oder Episoden automatisch von deinem Gerät gelöscht, nachdem du sie zu Ende gehört hast. Das hilft, Speicherplatz freizugeben, während du dich durch deine Bibliothek arbeitest.';
+ 'Wenn aktiviert, werden heruntergeladene Bücher oder Episoden automatisch von diesem Gerät gelöscht, nachdem du sie in Absorb zu Ende gehört hast. Wenn du einen Titel im Web oder auf einem anderen Gerät beendest, bleibt der Download hier erhalten.';
@override
String get deleteAbsorbedOnSubtitle =>
diff --git a/lib/l10n/app_localizations_el.dart b/lib/l10n/app_localizations_el.dart
index 718c4058..d5491894 100644
--- a/lib/l10n/app_localizations_el.dart
+++ b/lib/l10n/app_localizations_el.dart
@@ -1781,7 +1781,7 @@ class AppLocalizationsEl extends AppLocalizations {
@override
String get deleteAbsorbedDownloadsInfoContent =>
- 'When enabled, downloaded books or episodes are automatically deleted from your device after you finish listening to them. This helps free up storage space as you work through your library.';
+ 'When enabled, downloaded books or episodes are automatically deleted from this device after you finish them in Absorb. Finishing an item on the web or another device won’t delete its download here.';
@override
String get deleteAbsorbedOnSubtitle =>
diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart
index 006f437d..5db0d290 100644
--- a/lib/l10n/app_localizations_en.dart
+++ b/lib/l10n/app_localizations_en.dart
@@ -1781,7 +1781,7 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get deleteAbsorbedDownloadsInfoContent =>
- 'When enabled, downloaded books or episodes are automatically deleted from your device after you finish listening to them. This helps free up storage space as you work through your library.';
+ 'When enabled, downloaded books or episodes are automatically deleted from this device after you finish them in Absorb. Finishing an item on the web or another device won’t delete its download here.';
@override
String get deleteAbsorbedOnSubtitle =>
diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart
index 4f6c8b36..7cdd38e9 100644
--- a/lib/l10n/app_localizations_es.dart
+++ b/lib/l10n/app_localizations_es.dart
@@ -1783,7 +1783,7 @@ class AppLocalizationsEs extends AppLocalizations {
@override
String get deleteAbsorbedDownloadsInfoContent =>
- 'When enabled, downloaded books or episodes are automatically deleted from your device after you finish listening to them. This helps free up storage space as you work through your library.';
+ 'When enabled, downloaded books or episodes are automatically deleted from this device after you finish them in Absorb. Finishing an item on the web or another device won’t delete its download here.';
@override
String get deleteAbsorbedOnSubtitle =>
diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart
index 522c71bf..d9ac2240 100644
--- a/lib/l10n/app_localizations_fr.dart
+++ b/lib/l10n/app_localizations_fr.dart
@@ -1795,7 +1795,7 @@ class AppLocalizationsFr extends AppLocalizations {
@override
String get deleteAbsorbedDownloadsInfoContent =>
- 'Lorsque cette option est activée, les livres ou épisodes téléchargés sont automatiquement supprimés de votre appareil après que vous avez fini de les écouter. Cela permet de libérer de l’espace de stockage au fur et à mesure que vous avancez dans votre bibliothèque.';
+ 'Lorsque cette option est activée, les livres ou épisodes téléchargés sont automatiquement supprimés de cet appareil lorsque vous les terminez dans Absorb. Si vous terminez un livre ou un épisode sur le Web ou un autre appareil, son téléchargement reste sur cet appareil.';
@override
String get deleteAbsorbedOnSubtitle =>
diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart
index f8170cd1..733ed2a2 100644
--- a/lib/l10n/app_localizations_it.dart
+++ b/lib/l10n/app_localizations_it.dart
@@ -1781,7 +1781,7 @@ class AppLocalizationsIt extends AppLocalizations {
@override
String get deleteAbsorbedDownloadsInfoContent =>
- 'When enabled, downloaded books or episodes are automatically deleted from your device after you finish listening to them. This helps free up storage space as you work through your library.';
+ 'When enabled, downloaded books or episodes are automatically deleted from this device after you finish them in Absorb. Finishing an item on the web or another device won’t delete its download here.';
@override
String get deleteAbsorbedOnSubtitle =>
diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart
index 7e86c536..19d69e20 100644
--- a/lib/l10n/app_localizations_ja.dart
+++ b/lib/l10n/app_localizations_ja.dart
@@ -1781,7 +1781,7 @@ class AppLocalizationsJa extends AppLocalizations {
@override
String get deleteAbsorbedDownloadsInfoContent =>
- 'When enabled, downloaded books or episodes are automatically deleted from your device after you finish listening to them. This helps free up storage space as you work through your library.';
+ 'When enabled, downloaded books or episodes are automatically deleted from this device after you finish them in Absorb. Finishing an item on the web or another device won’t delete its download here.';
@override
String get deleteAbsorbedOnSubtitle =>
diff --git a/lib/l10n/app_localizations_no.dart b/lib/l10n/app_localizations_no.dart
index 1f7fdc8f..09e8db55 100644
--- a/lib/l10n/app_localizations_no.dart
+++ b/lib/l10n/app_localizations_no.dart
@@ -1781,7 +1781,7 @@ class AppLocalizationsNo extends AppLocalizations {
@override
String get deleteAbsorbedDownloadsInfoContent =>
- 'When enabled, downloaded books or episodes are automatically deleted from your device after you finish listening to them. This helps free up storage space as you work through your library.';
+ 'When enabled, downloaded books or episodes are automatically deleted from this device after you finish them in Absorb. Finishing an item on the web or another device won’t delete its download here.';
@override
String get deleteAbsorbedOnSubtitle =>
diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart
index 06474ad0..51d3278c 100644
--- a/lib/l10n/app_localizations_pt.dart
+++ b/lib/l10n/app_localizations_pt.dart
@@ -1781,7 +1781,7 @@ class AppLocalizationsPt extends AppLocalizations {
@override
String get deleteAbsorbedDownloadsInfoContent =>
- 'When enabled, downloaded books or episodes are automatically deleted from your device after you finish listening to them. This helps free up storage space as you work through your library.';
+ 'When enabled, downloaded books or episodes are automatically deleted from this device after you finish them in Absorb. Finishing an item on the web or another device won’t delete its download here.';
@override
String get deleteAbsorbedOnSubtitle =>
diff --git a/lib/l10n/app_localizations_ro.dart b/lib/l10n/app_localizations_ro.dart
index 4ab961d8..63ee7609 100644
--- a/lib/l10n/app_localizations_ro.dart
+++ b/lib/l10n/app_localizations_ro.dart
@@ -1781,7 +1781,7 @@ class AppLocalizationsRo extends AppLocalizations {
@override
String get deleteAbsorbedDownloadsInfoContent =>
- 'When enabled, downloaded books or episodes are automatically deleted from your device after you finish listening to them. This helps free up storage space as you work through your library.';
+ 'When enabled, downloaded books or episodes are automatically deleted from this device after you finish them in Absorb. Finishing an item on the web or another device won’t delete its download here.';
@override
String get deleteAbsorbedOnSubtitle =>
diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart
index 6e01cee5..4b0b98cc 100644
--- a/lib/l10n/app_localizations_ru.dart
+++ b/lib/l10n/app_localizations_ru.dart
@@ -1785,7 +1785,7 @@ class AppLocalizationsRu extends AppLocalizations {
@override
String get deleteAbsorbedDownloadsInfoContent =>
- 'When enabled, downloaded books or episodes are automatically deleted from your device after you finish listening to them. This helps free up storage space as you work through your library.';
+ 'When enabled, downloaded books or episodes are automatically deleted from this device after you finish them in Absorb. Finishing an item on the web or another device won’t delete its download here.';
@override
String get deleteAbsorbedOnSubtitle =>
diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart
index cec78051..461313a1 100644
--- a/lib/l10n/app_localizations_zh.dart
+++ b/lib/l10n/app_localizations_zh.dart
@@ -1745,7 +1745,7 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get deleteAbsorbedDownloadsInfoContent =>
- '启用后,听完的书籍或剧集将自动从设备中删除。这有助于在你浏览媒体库时释放存储空间。';
+ '启用后,在 Absorb 中听完的已下载书籍或剧集会自动从此设备删除。如果你在网页端或其他设备上听完,保存在此设备上的下载不会被删除。';
@override
String get deleteAbsorbedOnSubtitle => '已完成项目将被移除以节省空间';
diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb
index 1793687d..3cb5960b 100644
--- a/lib/l10n/app_zh.arb
+++ b/lib/l10n/app_zh.arb
@@ -564,7 +564,7 @@
"keepNextInfoContent": "要保留下载的项目数量,包括你当前正在收听的项目。例如,\"保留接下来3个\"意味着当前书籍加上系列或播客中的下2本将保持下载状态。",
"deleteAbsorbedDownloads": "删除已完成的下载",
"deleteAbsorbedDownloadsInfoTitle": "删除已完成的下载",
- "deleteAbsorbedDownloadsInfoContent": "启用后,听完的书籍或剧集将自动从设备中删除。这有助于在你浏览媒体库时释放存储空间。",
+ "deleteAbsorbedDownloadsInfoContent": "启用后,在 Absorb 中听完的已下载书籍或剧集会自动从此设备删除。如果你在网页端或其他设备上听完,保存在此设备上的下载不会被删除。",
"deleteAbsorbedOnSubtitle": "已完成项目将被移除以节省空间",
"deleteAbsorbedOffSubtitle": "关闭 - 保留已完成的下载",
"downloadLocation": "下载位置",
@@ -1459,4 +1459,4 @@
"autoDownloadOnWifiInfoTitle": "Wi-Fi 下自动下载",
"autoDownloadOnWifiOnSubtitle": "在 Wi-Fi 下开始流式播放时,书籍将在后台下载",
"saved": "已保存"
-}
\ No newline at end of file
+}
diff --git a/lib/providers/_lp_absorbing.dart b/lib/providers/_lp_absorbing.dart
index ef68b832..ceefe9f1 100644
--- a/lib/providers/_lp_absorbing.dart
+++ b/lib/providers/_lp_absorbing.dart
@@ -38,6 +38,11 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {
Future<void> _loadManualAbsorbing() async {
_manualAbsorbAdds =
(await ScopedPrefs.getStringList('absorbing_manual_adds')).toSet();
+ _finishedManualAbsorbAdds = (await ScopedPrefs.getStringList(
+ 'absorbing_finished_manual_adds',
+ ))
+ .toSet()
+ ..retainAll(_manualAbsorbAdds);
_manualAbsorbRemoves =
(await ScopedPrefs.getStringList('absorbing_manual_removes')).toSet();
_absorbingBookIds =
@@ -63,6 +68,10 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {
_dedupeAbsorbingIds();
await ScopedPrefs.setStringList(
'absorbing_manual_adds', _manualAbsorbAdds.toList());
+ await ScopedPrefs.setStringList(
+ 'absorbing_finished_manual_adds',
+ _finishedManualAbsorbAdds.toList(),
+ );
await ScopedPrefs.setStringList(
'absorbing_manual_removes', _manualAbsorbRemoves.toList());
await ScopedPrefs.setStringList(
@@ -73,16 +82,23 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {
void _pruneRemotelyFinishedBooks(Iterable<String> keys) {
var changed = false;
+ final player = AudioPlayerService();
+ final activeKey = player.currentEpisodeId != null
+ ? '${player.currentItemId}-${player.currentEpisodeId}'
+ : player.currentItemId;
for (final key in keys) {
if (key.length > 36 ||
shouldIncludeBookInAbsorbing(
isFinished: (this as LibraryProvider).isItemFinishedByKey(key),
- manuallyAdded: _manualAbsorbAdds.contains(key),
+ addedAfterFinish: _finishedManualAbsorbAdds.contains(key),
+ isActive: player.hasBook && key == activeKey,
)) {
continue;
}
changed = _absorbingBookIds.remove(key) || changed;
changed = _absorbingItemCache.remove(key) != null || changed;
+ changed = _manualAbsorbAdds.remove(key) || changed;
+ changed = _finishedManualAbsorbAdds.remove(key) || changed;
}
if (changed) unawaited(_saveManualAbsorbing());
}
@@ -94,9 +110,14 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {
final continueSeriesKeys = <String>[];
final existingIds = Set<String>.from(_absorbingBookIds);
+ final player = AudioPlayerService();
+ final activeKey = player.currentEpisodeId != null
+ ? '${player.currentItemId}-${player.currentEpisodeId}'
+ : player.currentItemId;
bool shouldIncludeBook(String key) => shouldIncludeBookInAbsorbing(
isFinished: (this as LibraryProvider).isItemFinishedByKey(key),
- manuallyAdded: _manualAbsorbAdds.contains(key),
+ addedAfterFinish: _finishedManualAbsorbAdds.contains(key),
+ isActive: player.hasBook && key == activeKey,
);
for (final section in _personalizedSections) {
@@ -276,6 +297,11 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {
for (final id in toRemove) {
_absorbingBookIds.remove(id);
_absorbingItemCache.remove(id);
+ if (id.length <= 36 &&
+ (this as LibraryProvider).isItemFinishedByKey(id) &&
+ !_finishedManualAbsorbAdds.contains(id)) {
+ _manualAbsorbAdds.remove(id);
+ }
}
final migrateRemove = <String>[];
@@ -355,18 +381,30 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {
Future<void> addToAbsorbing(String itemId) async {
_manualAbsorbAdds.add(itemId);
+ if ((this as LibraryProvider).isItemFinishedByKey(itemId)) {
+ _finishedManualAbsorbAdds.add(itemId);
+ } else {
+ _finishedManualAbsorbAdds.remove(itemId);
+ }
_manualAbsorbRemoves.remove(itemId);
_absorbingIdsAdd(itemId);
await _saveManualAbsorbing();
notifyListeners();
+ unawaited(_catchUpQueueAutoDownloads());
}
Future<void> addToAbsorbingQueue(String itemId) async {
_manualAbsorbAdds.add(itemId);
+ if ((this as LibraryProvider).isItemFinishedByKey(itemId)) {
+ _finishedManualAbsorbAdds.add(itemId);
+ } else {
+ _finishedManualAbsorbAdds.remove(itemId);
+ }
_manualAbsorbRemoves.remove(itemId);
_absorbingIdsAdd(itemId, atFront: false);
await _saveManualAbsorbing();
notifyListeners();
+ unawaited(_catchUpQueueAutoDownloads());
}
Future<void> reorderAbsorbing(List<String> newOrder) async {
@@ -374,7 +412,44 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {
setFreshQueuedFront(null);
await _saveManualAbsorbing();
notifyListeners();
- _catchUpQueueAutoDownloads();
+ unawaited(_catchUpQueueAutoDownloads());
+ }
+
+ Future<void> _prepareAbsorbingForPlayback(
+ String key,
+ double duration,
+ ) async {
+ final self = this as LibraryProvider;
+ final wasFinished = self.isItemFinishedByKey(key);
+
+ if (wasFinished) {
+ _finishedManualAbsorbAdds.remove(key);
+ _manualAbsorbAdds.remove(key);
+ self.resetProgressFor(key);
+ }
+
+ unblockFromAbsorbing(key);
+ if (!wasFinished) return;
+
+ try {
+ await _saveManualAbsorbing();
+ final sync = ProgressSyncService();
+ final saved = await sync.getLocal(key);
+ final savedDuration = (saved?['duration'] as num?)?.toDouble() ?? 0;
+ final savedSpeed = (saved?['speed'] as num?)?.toDouble() ?? 1;
+ await sync.saveLocal(
+ itemId: key,
+ currentTime: 0,
+ duration: duration > 0 ? duration : savedDuration,
+ speed: savedSpeed,
+ isFinished: false,
+ );
+ if (_api != null && !isOffline) {
+ unawaited(sync.syncToServer(api: _api!, itemId: key));
+ }
+ } catch (e) {
+ debugPrint('[Absorbing] Failed to prepare finished item replay: $e');
+ }
}
void unblockFromAbsorbing(String key,
@@ -441,10 +516,12 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {
Future<void> removeFromAbsorbing(String key) async {
_manualAbsorbRemoves.add(key);
_manualAbsorbAdds.remove(key);
+ _finishedManualAbsorbAdds.remove(key);
_absorbingBookIds.remove(key);
_absorbingItemCache.remove(key);
await _saveManualAbsorbing();
notifyListeners();
+ unawaited(_catchUpQueueAutoDownloads());
}
void markFinishedLocally(String itemId,
@@ -496,7 +573,7 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {
}
_checkRollingDownloads(itemId);
- _checkQueueAutoDownloads(itemId);
+ unawaited(_catchUpQueueAutoDownloads());
if (DownloadService().isDownloaded(itemId)) {
PlayerSettings.getRollingDownloadDeleteFinished().then((delete) {
@@ -906,6 +983,7 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {
final id = dlInfo.itemId;
if (id == finishedBookId) continue;
if (id.length > 36) continue;
+ if (_manualAbsorbRemoves.contains(id)) continue;
if (_progressMap[id]?['isFinished'] == true) continue;
final data = _itemDataWithSeries(id);
@@ -1062,6 +1140,7 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {
playlistItem['libraryItem'] as Map<String, dynamic>? ?? const {};
final media = libraryItem['media'] as Map<String, dynamic>? ?? const {};
final metadata = media['metadata'] as Map<String, dynamic>? ?? const {};
+ String? playbackError;
if (episodeId != null) {
Map<String, dynamic>? episode =
@@ -1075,7 +1154,7 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {
as num?)
?.toDouble() ??
0.0;
- await AudioPlayerService().playItem(
+ playbackError = await AudioPlayerService().playItem(
api: api,
itemId: libraryItemId,
title: metadata['title'] as String? ?? '',
@@ -1092,7 +1171,7 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {
} else {
final duration = (media['duration'] as num?)?.toDouble() ?? 0;
final chapters = media['chapters'] as List<dynamic>? ?? const [];
- await AudioPlayerService().playItem(
+ playbackError = await AudioPlayerService().playItem(
api: api,
itemId: libraryItemId,
title: metadata['title'] as String? ?? '',
@@ -1103,7 +1182,7 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {
libraryId: libraryItem['libraryId'] as String?,
);
}
- return true;
+ return playbackError == null;
}
/// Start playing the first unfinished item in [playlistId]. Returns true if
@@ -1207,6 +1286,241 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {
.toList();
}
+ Map<String, dynamic> _queueDownloadItem(
+ String key,
+ Map<String, dynamic> libraryItem, {
+ Map<String, dynamic>? episode,
+ }) {
+ final isPodcast = key.length > 36;
+ return {
+ 'libraryItemId': isPodcast ? key.substring(0, 36) : key,
+ if (isPodcast) 'episodeId': key.substring(37),
+ 'libraryItem': libraryItem,
+ if (episode != null) 'episode': episode,
+ };
+ }
+
+ /// Returns the current item and the items after it in the active queue's
+ /// actual playback order. Every entry uses the same shape as a playlist item.
+ Future<List<Map<String, dynamic>>> _queueItemsForDownload(
+ String currentKey,
+ String mode,
+ ApiService api, {
+ required int limit,
+ required String bookMode,
+ required String podcastMode,
+ required bool merged,
+ required String? queueSourceId,
+ required String? podcastAdvanceDir,
+ required bool Function() isStale,
+ }) async {
+ final self = this as LibraryProvider;
+
+ if (mode == 'manual') {
+ final currentIsPodcast = currentKey.length > 36;
+
+ Future<Map<String, dynamic>?> resolveItem(String key) async {
+ final cached = _absorbingItemCache[key];
+ if (cached != null) return cached;
+ final isPodcast = key.length > 36;
+ final libraryItemId = isPodcast ? key.substring(0, 36) : key;
+ final fetched = await api.getLibraryItem(libraryItemId);
+ if (fetched == null || isStale()) return null;
+ final resolved = Map<String, dynamic>.from(fetched);
+ resolved['_absorbingKey'] = key;
+ if (isPodcast) {
+ final episodeId = key.substring(37);
+ final media = resolved['media'] as Map<String, dynamic>? ?? const {};
+ for (final episode
+ in (media['episodes'] as List<dynamic>? ?? const [])) {
+ if (episode is Map<String, dynamic> &&
+ episode['id'] == episodeId) {
+ resolved['recentEpisode'] = episode;
+ break;
+ }
+ }
+ }
+ return resolved;
+ }
+
+ Map<String, dynamic>? currentItem = _absorbingItemCache[currentKey];
+ if (!merged && currentItem == null) {
+ currentItem = await resolveItem(currentKey);
+ if (isStale()) return const [];
+ }
+ final currentLibraryId = currentItem?['libraryId'] as String?;
+ final keys = manualQueueTail(
+ items: _absorbingBookIds,
+ currentKey: currentKey,
+ keyOf: (key) => key,
+ isFinished: self.isItemFinishedByKey,
+ isPodcast: (key) => key.length > 36,
+ queueMode: (key) => key.length > 36 ? podcastMode : bookMode,
+ libraryId: (key) =>
+ _absorbingItemCache[key]?['libraryId'] as String?,
+ merged: merged,
+ currentIsPodcast: currentIsPodcast,
+ currentLibraryId: currentLibraryId,
+ );
+ final result = <Map<String, dynamic>>[];
+ final seen = <String>{};
+
+ for (final key in keys) {
+ if (result.length >= limit || isStale()) break;
+ if (!seen.add(key) || self.isItemFinishedByKey(key)) continue;
+ final cached = key == currentKey && currentItem != null
+ ? currentItem
+ : await resolveItem(key);
+ if (cached == null || isStale()) continue;
+ if (!merged && currentLibraryId != null) {
+ final candidateLibraryId = cached['libraryId'] as String?;
+ if (candidateLibraryId != null &&
+ candidateLibraryId != currentLibraryId) {
+ continue;
+ }
+ }
+ result.add(_queueDownloadItem(
+ key,
+ cached,
+ episode: cached['recentEpisode'] as Map<String, dynamic>?,
+ ));
+ }
+ return result;
+ }
+
+ if (mode == 'playlist') {
+ final playlistId = queueSourceId;
+ if (playlistId == null) return const [];
+ Map<String, dynamic>? playlist = _playlists
+ .whereType<Map<String, dynamic>>()
+ .where((item) => item['id'] == playlistId)
+ .firstOrNull;
+ playlist ??= await api.getPlaylist(playlistId);
+ if (playlist == null || isStale()) return const [];
+ final items = (playlist['items'] as List<dynamic>? ?? const [])
+ .whereType<Map<String, dynamic>>()
+ .toList();
+ return queueTailFrom(
+ items: items,
+ currentKey: currentKey,
+ keyOf: _playlistItemKey,
+ );
+ }
+
+ if (mode == 'collection') {
+ final collectionId = queueSourceId;
+ if (collectionId == null) return const [];
+ Map<String, dynamic>? collection = _collections
+ .whereType<Map<String, dynamic>>()
+ .where((item) => item['id'] == collectionId)
+ .firstOrNull;
+ collection ??= await api.getCollection(collectionId);
+ if (collection == null || isStale()) return const [];
+ final items = _collectionItems(collection);
+ return queueTailFrom(
+ items: items,
+ currentKey: currentKey,
+ keyOf: _playlistItemKey,
+ );
+ }
+
+ if (mode != 'auto_next') return const [];
+
+ if (currentKey.length > 36) {
+ final showId = currentKey.substring(0, 36);
+ final currentEpisodeId = currentKey.substring(37);
+ Map<String, dynamic>? show;
+ for (final cached in _absorbingItemCache.values) {
+ if (cached['id'] != showId) continue;
+ final episodes = (cached['media'] as Map<String, dynamic>?)?['episodes']
+ as List<dynamic>?;
+ if (episodes != null && episodes.isNotEmpty) {
+ show = cached;
+ break;
+ }
+ }
+ show ??= await api.getLibraryItem(showId);
+ if (show == null || isStale()) return const [];
+
+ final media = show['media'] as Map<String, dynamic>? ?? const {};
+ final episodes = (media['episodes'] as List<dynamic>? ?? const [])
+ .whereType<Map<String, dynamic>>()
+ .where((episode) =>
+ (episode['id'] as String? ?? '').isNotEmpty)
+ .toList();
+ final tail = podcastQueueTail(
+ episodes: episodes,
+ currentEpisodeId: currentEpisodeId,
+ idOf: (episode) => episode['id'] as String? ?? '',
+ publishedAt: (episode) =>
+ (episode['publishedAt'] as num?)?.toInt() ?? 0,
+ newestFirst: podcastAdvanceDir == 'newest_first',
+ );
+ return tail.map((episode) {
+ return _queueDownloadItem(
+ '$showId-${episode['id']}',
+ show!,
+ episode: episode,
+ );
+ }).toList();
+ }
+
+ var current = _itemDataWithSeries(currentKey);
+ var (seriesId, currentSequence) = current != null
+ ? _StateMixin._extractSeries(current)
+ : (null, null);
+ if (seriesId == null || currentSequence == null) {
+ current = await api.getLibraryItem(currentKey);
+ if (current != null) {
+ (seriesId, currentSequence) = _StateMixin._extractSeries(current);
+ }
+ }
+ if (isStale() ||
+ current == null ||
+ seriesId == null ||
+ currentSequence == null) {
+ return const [];
+ }
+
+ final libraryId = current['libraryId'] as String? ?? _selectedLibraryId;
+ if (libraryId == null) {
+ return [_queueDownloadItem(currentKey, current)];
+ }
+
+ List<dynamic> books;
+ try {
+ books = await api.getBooksBySeries(
+ libraryId,
+ seriesId,
+ limit: 100,
+ );
+ } catch (error) {
+ debugPrint('[QueueDownload] Series fetch failed: $error');
+ return [_queueDownloadItem(currentKey, current)];
+ }
+ if (isStale()) return const [];
+
+ final candidates = seriesQueueTail(
+ current: current,
+ books: books.whereType<Map<String, dynamic>>().where((book) {
+ final id = book['id'] as String?;
+ return id != null && !_manualAbsorbRemoves.contains(id);
+ }),
+ currentKey: currentKey,
+ currentSeriesId: seriesId,
+ currentSequence: currentSequence,
+ keyOf: (book) => book['id'] as String? ?? '',
+ seriesId: (book) => _StateMixin._extractSeries(book).$1,
+ sequence: (book) => _StateMixin._extractSeries(book).$2,
+ );
+ return candidates.map((book) {
+ return _queueDownloadItem(
+ book['id'] as String? ?? currentKey,
+ book,
+ );
+ }).toList();
+ }
+
/// Start playing the first unfinished book in [collectionId].
Future<bool> playCollectionFromStart(String collectionId) async {
final c = await _getCollectionById(collectionId);
@@ -1374,7 +1688,7 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {
final contentUrl = track['contentUrl'] as String? ?? '';
return {'url': api.buildTrackUrl(contentUrl)};
}).toList();
- audioHeaders = api.mediaHeaders;
+ audioHeaders = api.playbackSessionHeaders;
} else if (localPaths.length != 1) {
debugPrint('[PreBuffer] Next item $key is multi-track, skip (MVP)');
return null;
@@ -1550,6 +1864,7 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {
final candidates = <double, Map<String, dynamic>>{};
void consider(String id, Map<String, dynamic> d) {
if (id == currentBookId) return;
+ if (_manualAbsorbRemoves.contains(id)) return;
if (self.isItemFinishedByKey(id)) return;
final (sid, seq) = _StateMixin._extractSeries(d);
if (sid != seriesId || seq == null || seq <= currentSeq!) return;
@@ -1571,10 +1886,11 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {
// Server fallback when next book isn't loaded locally. Mirrors what
// _addNextSeriesBookToAbsorbing does so the peek matches the eventual
// advance behaviour.
- if (candidates.isEmpty && _api != null && _selectedLibraryId != null) {
+ final libraryId = data?['libraryId'] as String? ?? _selectedLibraryId;
+ if (candidates.isEmpty && _api != null && libraryId != null) {
try {
final books = await _api!.getBooksBySeries(
- _selectedLibraryId!,
+ libraryId,
seriesId,
limit: 100,
);
diff --git a/lib/providers/_lp_core.dart b/lib/providers/_lp_core.dart
index 4012b471..428a30a3 100644
--- a/lib/providers/_lp_core.dart
+++ b/lib/providers/_lp_core.dart
@@ -815,6 +815,8 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
if (cleared > 0) {
debugPrint('[Progress] Cleared $cleared overrides');
}
+ (this as _AbsorbingMixin)
+ ._pruneRemotelyFinishedBooks(_progressMap.keys);
}
} catch (_) {}
}
@@ -871,7 +873,7 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
if (reachable) {
setNetworkOffline(false);
if (_rollingDownloadSeries.isNotEmpty) _catchUpRollingDownloads();
- _catchUpQueueAutoDownloads();
+ unawaited(_catchUpQueueAutoDownloads());
(this as LibraryProvider).catchUpSubscribedPodcasts();
} else {
debugPrint('[Library] Connectivity changed but server unreachable — starting ping timer');
@@ -1216,9 +1218,14 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
final playingKey = player.currentEpisodeId != null
? '${player.currentItemId}-${player.currentEpisodeId}'
: player.currentItemId;
- if (key == playingKey && player.hasBook && player.isPlaying) {
- if (mp['isFinished'] == true) {
+ if (key == playingKey && player.hasBook) {
+ if (mp['isFinished'] == true && !_resetItems.contains(key)) {
(this as _AbsorbingMixin).markFinishedLocally(key, skipAutoAdvance: true);
+ } else if (mp['isFinished'] != true) {
+ _progressMap[key] = mp;
+ _localProgressOverrides.remove(key);
+ _resetItems.remove(key);
+ notifyListeners();
}
return;
}
@@ -1590,6 +1597,7 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
} catch (_) {}
_isLoadingPlaylists = false;
notifyListeners();
+ unawaited(_catchUpQueueAutoDownloads());
}
Future<Map<String, dynamic>?> createPlaylist(String name) async {
@@ -1695,6 +1703,7 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
} catch (_) {}
_isLoadingCollections = false;
notifyListeners();
+ unawaited(_catchUpQueueAutoDownloads());
}
Future<Map<String, dynamic>?> createCollection(String name, {List<String> books = const []}) async {
@@ -2180,8 +2189,6 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
if (!connectivity.contains(ConnectivityResult.wifi)) return;
}
- final count = await PlayerSettings.getRollingDownloadCount();
-
for (final seriesOrShowId in _rollingDownloadSeries.toList()) {
String? latestPodcastKey;
num latestPodcastUpdate = 0;
@@ -2212,33 +2219,55 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
}
if (latestPodcastKey != null) {
- _rollingDownloadPodcast(latestPodcastKey, count);
+ _checkRollingDownloads(latestPodcastKey);
} else if (latestBookKey != null) {
- _rollingDownloadBook(latestBookKey, count);
+ _checkRollingDownloads(latestBookKey);
}
}
}
void _checkRollingDownloads(String playingKey) async {
- if (_api == null || isOffline) return;
+ final api = _api;
+ if (api == null || isOffline) return;
// With the "auto series download" default on, a book in a series enables
// rolling download for that series on first play (books only).
final autoSeriesDefault =
await PlayerSettings.getAutoSeriesDownloadDefault();
+ final player = AudioPlayerService();
+ final activeKey = player.currentEpisodeId == null
+ ? player.currentItemId
+ : '${player.currentItemId}-${player.currentEpisodeId}';
+ final activeQueueMode = activeKey == null
+ ? 'off'
+ : activeKey.length > 36
+ ? await PlayerSettings.getPodcastQueueMode()
+ : await PlayerSettings.getBookQueueMode();
+ final activeQueueOwnsWindow = activeQueueMode != 'off' &&
+ await PlayerSettings.getQueueAutoDownload();
if (_rollingDownloadSeries.isEmpty && !autoSeriesDefault) return;
final count = await PlayerSettings.getRollingDownloadCount();
if (playingKey.length > 36) {
final showId = playingKey.substring(0, 36);
+ final activeShowId = activeKey != null && activeKey.length > 36
+ ? activeKey.substring(0, 36)
+ : null;
+ if (activeQueueOwnsWindow && activeShowId == showId) return;
if (_rollingDownloadSeries.contains(showId)) {
_rollingDownloadPodcast(playingKey, count);
}
} else {
+ if (activeQueueOwnsWindow &&
+ activeKey == playingKey &&
+ !autoSeriesDefault) {
+ return;
+ }
var data = _itemDataWithSeries(playingKey);
var (seriesId, _) = data != null ? _StateMixin._extractSeries(data) : (null, null);
if (seriesId == null) {
- final fullItem = await _api!.getLibraryItem(playingKey);
+ final fullItem = await api.getLibraryItem(playingKey);
if (fullItem != null) {
+ data = fullItem;
(seriesId, _) = _StateMixin._extractSeries(fullItem);
}
}
@@ -2248,112 +2277,243 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
await _saveRollingDownloadSeries();
notifyListeners();
}
+ if (activeQueueOwnsWindow && activeKey != null && activeKey.length <= 36) {
+ if (activeKey == playingKey) return;
+ var activeData = _itemDataWithSeries(activeKey);
+ var (activeSeriesId, _) = activeData != null
+ ? _StateMixin._extractSeries(activeData)
+ : (null, null);
+ if (activeSeriesId == null) {
+ activeData = await api.getLibraryItem(activeKey);
+ if (activeData != null) {
+ (activeSeriesId, _) = _StateMixin._extractSeries(activeData);
+ }
+ }
+ if (activeSeriesId == seriesId) return;
+ }
if (_rollingDownloadSeries.contains(seriesId)) {
_rollingDownloadBook(playingKey, count);
}
}
}
- void _checkQueueAutoDownloads(String playingKey) async {
- if (_api == null || isOffline) {
- return;
- }
- final isPodcastKey = playingKey.length > 36;
- final queueMode = isPodcastKey
- ? await PlayerSettings.getPodcastQueueMode()
- : await PlayerSettings.getBookQueueMode();
- 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 ((this as LibraryProvider).isItemFinishedByKey(key)) continue;
+ Future<void> _checkQueueAutoDownloads(String playingKey) async {
+ try {
+ final self = this as LibraryProvider;
+ final planGeneration = ++_queueDownloadPlanGeneration;
+ final api = _api;
+ if (api == null || isOffline) return;
+ final accountGeneration = self._accountLoadGeneration;
+
+ String? activePlayerKey() {
+ final player = AudioPlayerService();
+ final itemId = player.currentItemId;
+ if (itemId == null) return null;
+ final episodeId = player.currentEpisodeId;
+ return episodeId == null ? itemId : '$itemId-$episodeId';
+ }
+
+ bool isStale() {
+ return planGeneration != _queueDownloadPlanGeneration ||
+ accountGeneration != self._accountLoadGeneration ||
+ !identical(api, _api) ||
+ isOffline ||
+ activePlayerKey() != playingKey;
+ }
+
+ if (isStale()) return;
+ final isPodcastKey = playingKey.length > 36;
+ final bookMode = await PlayerSettings.getBookQueueMode();
+ if (isStale()) return;
+ final podcastMode = await PlayerSettings.getPodcastQueueMode();
+ if (isStale()) return;
+ final merged = await PlayerSettings.getMergeAbsorbingLibraries();
+ if (isStale()) return;
+ final queueMode = isPodcastKey ? podcastMode : bookMode;
+ if (queueMode == 'off') return;
+ final queueSourceId = queueMode == 'playlist'
+ ? await PlayerSettings.getQueuePlaylistId()
+ : queueMode == 'collection'
+ ? await PlayerSettings.getQueueCollectionId()
+ : null;
+ if (isStale()) return;
+
+ final enabled = await PlayerSettings.getQueueAutoDownload();
+ if (!enabled || isStale()) return;
+ final count = await PlayerSettings.getRollingDownloadCount();
+ if (count <= 0 || isStale()) return;
+ final podcastAdvanceDir = isPodcastKey && queueMode == 'auto_next'
+ ? await PlayerSettings.getPodcastAdvanceDir(
+ playingKey.substring(0, 36))
+ : null;
+ if (isStale()) return;
+
+ final wifiOnly = await PlayerSettings.getWifiOnlyDownloads();
+ if (isStale()) return;
+ if (wifiOnly) {
+ final connectivity = await Connectivity().checkConnectivity();
+ if (isStale() ||
+ !connectivity.contains(ConnectivityResult.wifi)) {
+ return;
+ }
+ }
- final cached = _absorbingItemCache[key];
- if (cached == null) continue;
+ Future<bool> settingsStillMatch() async {
+ if (isStale()) return false;
+ if (await PlayerSettings.getBookQueueMode() != bookMode || isStale()) {
+ return false;
+ }
+ if (await PlayerSettings.getPodcastQueueMode() != podcastMode ||
+ isStale()) {
+ return false;
+ }
+ if (await PlayerSettings.getMergeAbsorbingLibraries() != merged ||
+ isStale()) {
+ return false;
+ }
+ if (!await PlayerSettings.getQueueAutoDownload() || isStale()) {
+ return false;
+ }
+ if (await PlayerSettings.getRollingDownloadCount() != count ||
+ isStale()) {
+ return false;
+ }
+ if (queueMode == 'playlist' &&
+ await PlayerSettings.getQueuePlaylistId() != queueSourceId) {
+ return false;
+ }
+ if (queueMode == 'collection' &&
+ await PlayerSettings.getQueueCollectionId() != queueSourceId) {
+ return false;
+ }
+ if (podcastAdvanceDir != null &&
+ await PlayerSettings.getPodcastAdvanceDir(
+ playingKey.substring(0, 36)) !=
+ podcastAdvanceDir) {
+ return false;
+ }
+ return !isStale();
+ }
+
+ final items = await self._queueItemsForDownload(
+ playingKey,
+ queueMode,
+ api,
+ limit: count,
+ bookMode: bookMode,
+ podcastMode: podcastMode,
+ merged: merged,
+ queueSourceId: queueSourceId,
+ podcastAdvanceDir: podcastAdvanceDir,
+ isStale: isStale,
+ );
+ if (items.isEmpty || !await settingsStillMatch()) return;
+
+ final downloads = DownloadService();
+ var newDownloads = 0;
+ String keyOf(Map<String, dynamic> item) {
+ final libraryItemId = item['libraryItemId'] as String? ?? '';
+ final episodeId = item['episodeId'] as String?;
+ return episodeId == null
+ ? libraryItemId
+ : '$libraryItemId-$episodeId';
+ }
+ final pendingItems = queueItemsNeedingDownload(
+ items: items.where((item) => keyOf(item).isNotEmpty),
+ count: count,
+ keyOf: keyOf,
+ isFinished: (item) => self.isItemFinishedByKey(keyOf(item)),
+ isAvailable: (item) {
+ final key = keyOf(item);
+ return downloads.isDownloaded(key) || downloads.isDownloading(key);
+ },
+ );
- if (!merged && playingLibId != null) {
- final candidateLibId = cached['libraryId'] as String?;
- if (candidateLibId != null && candidateLibId != playingLibId) continue;
- }
+ for (final item in pendingItems) {
+ if (isStale()) return;
+ final libraryItemId = item['libraryItemId'] as String? ?? '';
+ if (libraryItemId.isEmpty) continue;
+ final episodeId = item['episodeId'] as String?;
+ final key = keyOf(item);
+ if (downloads.isDownloaded(key) || downloads.isDownloading(key)) {
+ continue;
+ }
- if (dl.isDownloaded(key) || dl.isDownloading(key)) {
- queued++;
- continue;
- }
+ var libraryItem =
+ item['libraryItem'] as Map<String, dynamic>? ?? const {};
+ if (libraryItem['media'] == null) {
+ final fetched = await api.getLibraryItem(libraryItemId);
+ if (fetched != null) libraryItem = fetched;
+ }
+ if (!await settingsStillMatch()) return;
+ final media =
+ libraryItem['media'] as Map<String, dynamic>? ?? const {};
+ final metadata =
+ media['metadata'] as Map<String, dynamic>? ?? const {};
+ var episode = item['episode'] as Map<String, dynamic>?;
+ if (episode == null && episodeId != null) {
+ for (final candidate
+ in (media['episodes'] as List<dynamic>? ?? const [])) {
+ if (candidate is Map<String, dynamic> &&
+ candidate['id'] == episodeId) {
+ episode = candidate;
+ break;
+ }
+ }
+ }
- 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,
- libraryId: _selectedLibraryId,
- );
- } else {
- dl.downloadItem(
- api: _api!,
+ final title = episodeId == null
+ ? metadata['title'] as String? ?? ''
+ : episode?['title'] as String? ?? 'Episode';
+ final author = episodeId == null
+ ? metadata['authorName'] as String? ?? ''
+ : metadata['title'] as String? ?? '';
+ if (downloads.isDownloaded(key) || downloads.isDownloading(key)) {
+ continue;
+ }
+ final error = await downloads.downloadItem(
+ api: api,
itemId: key,
title: title,
author: author,
- coverUrl: getCoverUrl(key),
- libraryId: _selectedLibraryId,
+ coverUrl: getCoverUrl(libraryItemId),
+ episodeId: episodeId,
+ libraryId:
+ libraryItem['libraryId'] as String? ?? _selectedLibraryId,
+ shouldStart: () => !isStale(),
);
+ if (isStale()) return;
+ if (error == null &&
+ (downloads.isDownloaded(key) || downloads.isDownloading(key))) {
+ newDownloads++;
+ }
}
- queued++;
- newDownloads++;
- }
- if (newDownloads > 0) {
- final l = _l();
- _showRollingToast(
- l?.lpQueueDownloadingItems(newDownloads)
- ?? 'Queue: downloading $newDownloads item${newDownloads == 1 ? '' : 's'}',
- icon: Icons.download_rounded);
+ if (newDownloads > 0) {
+ final l = _l();
+ _showRollingToast(
+ l?.lpQueueDownloadingItems(newDownloads) ??
+ 'Queue: downloading $newDownloads item${newDownloads == 1 ? '' : 's'}',
+ icon: Icons.download_rounded);
+ }
+ } catch (error, stackTrace) {
+ debugPrint('[QueueDownload] Check failed: $error\n$stackTrace');
}
}
- void _catchUpQueueAutoDownloads() {
+ Future<void> _catchUpQueueAutoDownloads() async {
final itemId = AudioPlayerService().currentItemId;
- if (itemId == null) return;
+ if (itemId == null) {
+ _queueDownloadPlanGeneration++;
+ return;
+ }
final epId = AudioPlayerService().currentEpisodeId;
final key = epId != null ? '$itemId-$epId' : itemId;
- _checkQueueAutoDownloads(key);
+ await _checkQueueAutoDownloads(key);
}
+ Future<void> syncQueueAutoDownloads() => _catchUpQueueAutoDownloads();
+
void _checkAutoDownloadOnStream(String playingKey) async {
if (_api == null || isOffline) {
return;
@@ -2398,9 +2558,10 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
(seriesId, currentSeq) = _StateMixin._extractSeries(fullItem);
}
if (seriesId == null || currentSeq == null) return;
+ final libraryId = data?['libraryId'] as String? ?? _selectedLibraryId;
final books = await _api!.getBooksBySeries(
- _selectedLibraryId ?? '',
+ libraryId ?? '',
seriesId,
limit: 100,
);
@@ -2422,7 +2583,7 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
title: md['title'] as String? ?? '',
author: md['authorName'] as String? ?? '',
coverUrl: getCoverUrl(bookId),
- libraryId: _selectedLibraryId,
+ libraryId: libraryId,
);
newDownloads++;
}
@@ -2462,7 +2623,7 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
title: metadata['title'] as String? ?? '',
author: metadata['authorName'] as String? ?? '',
coverUrl: getCoverUrl(id),
- libraryId: _selectedLibraryId,
+ libraryId: bookMap['libraryId'] as String? ?? libraryId,
);
queued++;
newDownloads++;
@@ -2484,14 +2645,17 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
final fullItem = await _api!.getLibraryItem(showId);
if (fullItem == null) return;
final media = fullItem['media'] as Map<String, dynamic>? ?? {};
+ final libraryId = fullItem['libraryId'] as String? ?? _selectedLibraryId;
final episodes =
List<dynamic>.from(media['episodes'] as List<dynamic>? ?? []);
if (episodes.isEmpty) return;
+ final newestFirst =
+ await PlayerSettings.getPodcastAdvanceDir(showId) == 'newest_first';
episodes.sort((a, b) {
final aTime = (a['publishedAt'] as num?)?.toInt() ?? 0;
final bTime = (b['publishedAt'] as num?)?.toInt() ?? 0;
- return aTime.compareTo(bTime);
+ return newestFirst ? bTime.compareTo(aTime) : aTime.compareTo(bTime);
});
final currentIdx = episodes.indexWhere(
@@ -2516,7 +2680,7 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
author: metadata['title'] as String? ?? '',
coverUrl: getCoverUrl(showId),
episodeId: episodeId,
- libraryId: _selectedLibraryId,
+ libraryId: libraryId,
);
newDownloads++;
}
@@ -2541,7 +2705,7 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
author: metadata['title'] as String? ?? '',
coverUrl: getCoverUrl(showId),
episodeId: epId,
- libraryId: _selectedLibraryId,
+ libraryId: libraryId,
);
queued++;
newDownloads++;
diff --git a/lib/providers/_lp_state.dart b/lib/providers/_lp_state.dart
index 3c82dac5..2dac94a2 100644
--- a/lib/providers/_lp_state.dart
+++ b/lib/providers/_lp_state.dart
@@ -94,9 +94,11 @@ mixin _StateMixin on ChangeNotifier {
final Set<String> _resetItems = {};
Set<String> _manualAbsorbAdds = {};
+ Set<String> _finishedManualAbsorbAdds = {};
Set<String> _manualAbsorbRemoves = {};
List<String> _absorbingBookIds = [];
Map<String, Map<String, dynamic>> _absorbingItemCache = {};
+ int _queueDownloadPlanGeneration = 0;
String? _lastFinishedItemId;
// A just-arrived subscribed-podcast episode the user asked to land at the top
// of the queue. The absorbing screen's "keep last-finished/playing on top"
diff --git a/lib/providers/auth_provider.dart b/lib/providers/auth_provider.dart
index ae3dc40e..38a36fe8 100644
--- a/lib/providers/auth_provider.dart
+++ b/lib/providers/auth_provider.dart
@@ -51,6 +51,7 @@ class AuthProvider extends ChangeNotifier {
// Now that the server is back, pull the user info we missed.
if (value) unawaited(_ensureUserInfo());
}
+
Map<String, String> _customHeaders = {};
// Local server auto-switch
@@ -69,10 +70,13 @@ class AuthProvider extends ChangeNotifier {
bool get startOnAbsorbingAfterAccountChange =>
_startOnAbsorbingAfterAccountChange;
bool get serverReachable => _serverReachable;
+
/// Current access token (or legacy token for old servers).
String? get token => _accessToken;
String? get serverUrl => _serverUrl;
- String? get activeServerUrl => (_useLocalServer && _localServerUrl.isNotEmpty) ? _localServerUrl : _serverUrl;
+ String? get activeServerUrl => (_useLocalServer && _localServerUrl.isNotEmpty)
+ ? _localServerUrl
+ : _serverUrl;
bool get useLocalServer => _useLocalServer;
bool get localServerEnabled => _localServerEnabled;
String get localServerUrl => _localServerUrl;
@@ -183,7 +187,8 @@ class AuthProvider extends ChangeNotifier {
/// admin updates the full device list to figure out what THIS user can
/// still see.
List<Map<String, dynamic>> filterDevicesForCurrentUser(
- List<Map<String, dynamic>> all) {
+ List<Map<String, dynamic>> all,
+ ) {
final id = _userId;
final type = _userJson?['type'] as String? ?? 'user';
final isAdminLike = type == 'admin' || type == 'root';
@@ -232,14 +237,12 @@ class AuthProvider extends ChangeNotifier {
refreshToken: refreshToken,
isLegacyToken: isLegacyToken,
customHeaders: _customHeaders,
- loadPersistedTokens: () => UserAccountService()
- .loadPersistedTokens(sessionServer, sessionUsername),
- onTokensRefreshed: (access, refresh) => _onTokensRefreshed(
+ loadPersistedTokens: () => UserAccountService().loadPersistedTokens(
sessionServer,
sessionUsername,
- access,
- refresh,
),
+ onTokensRefreshed: (access, refresh) =>
+ _onTokensRefreshed(sessionServer, sessionUsername, access, refresh),
onAuthExpired: () => _onAuthExpired(sessionServer, sessionUsername),
);
}
@@ -261,6 +264,9 @@ class AuthProvider extends ChangeNotifier {
_accessToken == null) {
return;
}
+ final refreshUnchanged =
+ newRefreshToken == null || newRefreshToken == _refreshToken;
+ if (_accessToken == newAccessToken && refreshUnchanged) return;
_accessToken = newAccessToken;
if (newRefreshToken != null) _refreshToken = newRefreshToken;
try {
@@ -304,8 +310,12 @@ class AuthProvider extends ChangeNotifier {
final server = _serverUrl;
final username = _username;
if (server == null || _accessToken == null) return;
- final tokens = await UserAccountService().loadPersistedTokens(server, username);
- if (tokens?.accessToken == null || tokens!.accessToken == _accessToken) return;
+ final tokens = await UserAccountService().loadPersistedTokens(
+ server,
+ username,
+ );
+ if (tokens?.accessToken == null || tokens!.accessToken == _accessToken)
+ return;
await _onTokensRefreshed(
server,
username,
@@ -327,11 +337,15 @@ class AuthProvider extends ChangeNotifier {
// Show a message to the user
final ctx = rootNavigatorKey.currentContext;
final l = ctx != null ? AppLocalizations.of(ctx) : null;
- final msg = l?.authSessionExpired ?? 'Session expired. Please log in again.';
- if (ctx != null) showOverlayToast(ctx, msg, icon: Icons.error_outline_rounded);
- unawaited(logout(forgetAccount: false).whenComplete(() {
- _authExpiryInProgress = false;
- }));
+ final msg =
+ l?.authSessionExpired ?? 'Session expired. Please log in again.';
+ if (ctx != null)
+ showOverlayToast(ctx, msg, icon: Icons.error_outline_rounded);
+ unawaited(
+ logout(forgetAccount: false).whenComplete(() {
+ _authExpiryInProgress = false;
+ }),
+ );
}
/// Try to restore a saved session from SharedPreferences.
@@ -347,7 +361,9 @@ class AuthProvider extends ChangeNotifier {
try {
debugPrint('[Auth] getting SharedPreferences...');
final prefs = await SharedPreferences.getInstance();
- debugPrint('[Auth] SharedPreferences loaded (${sw.elapsedMilliseconds}ms)');
+ debugPrint(
+ '[Auth] SharedPreferences loaded (${sw.elapsedMilliseconds}ms)',
+ );
final savedUrl = prefs.getString('server_url');
final savedToken = prefs.getString('token');
final savedRefreshToken = prefs.getString('refresh_token');
@@ -357,7 +373,9 @@ class AuthProvider extends ChangeNotifier {
// return them, so without this they'd stay empty until next login.
await _restoreEreaderDevices();
- debugPrint('[Auth] saved credentials: url=${savedUrl != null}, token=${savedToken != null}, refreshToken=${savedRefreshToken != null}');
+ debugPrint(
+ '[Auth] saved credentials: url=${savedUrl != null}, token=${savedToken != null}, refreshToken=${savedRefreshToken != null}',
+ );
if (savedUrl != null && savedToken != null) {
// Always restore credentials so we can at least go offline
@@ -365,15 +383,20 @@ class AuthProvider extends ChangeNotifier {
if (restoredUrl != savedUrl) {
await prefs.setString('server_url', restoredUrl);
if (savedUsername != null) {
- await UserAccountService()
- .updateAccountUrl(savedUrl, savedUsername, restoredUrl);
+ await UserAccountService().updateAccountUrl(
+ savedUrl,
+ savedUsername,
+ restoredUrl,
+ );
}
}
_serverUrl = restoredUrl;
_accessToken = savedToken;
_refreshToken = savedRefreshToken;
_isLegacyToken = savedRefreshToken == null;
- debugPrint('[Auth] Restored token: ${savedToken.substring(0, savedToken.length.clamp(0, 20))}... (${savedToken.length} chars, isLegacy=$_isLegacyToken)');
+ debugPrint(
+ '[Auth] Restored token: ${savedToken.substring(0, savedToken.length.clamp(0, 20))}... (${savedToken.length} chars, isLegacy=$_isLegacyToken)',
+ );
_username = savedUsername;
_userId = prefs.getString('user_id');
_defaultLibraryId = savedLibraryId;
@@ -384,8 +407,9 @@ class AuthProvider extends ChangeNotifier {
var legacyCustomHeaders = <String, String>{};
if (headersJson != null) {
try {
- legacyCustomHeaders =
- Map<String, String>.from(jsonDecode(headersJson) as Map);
+ legacyCustomHeaders = Map<String, String>.from(
+ jsonDecode(headersJson) as Map,
+ );
} catch (_) {}
}
SavedAccount? restoredAccount;
@@ -396,8 +420,7 @@ class AuthProvider extends ChangeNotifier {
break;
}
}
- _customHeaders =
- restoredAccount?.customHeaders ?? legacyCustomHeaders;
+ _customHeaders = restoredAccount?.customHeaders ?? legacyCustomHeaders;
// Load local server config
await _loadLocalServerSettings();
@@ -409,25 +432,37 @@ class AuthProvider extends ChangeNotifier {
if (_localServerEnabled && _localServerUrl.isNotEmpty) {
final connectivity = await Connectivity().checkConnectivity();
if (connectivity.contains(ConnectivityResult.wifi)) {
- debugPrint('[Auth] On WiFi with local server enabled, trying local first... (${sw.elapsedMilliseconds}ms)');
- final localReachable = await ApiService.pingServer(_localServerUrl, customHeaders: _customHeaders)
- .timeout(const Duration(seconds: 2), onTimeout: () => false);
+ debugPrint(
+ '[Auth] On WiFi with local server enabled, trying local first... (${sw.elapsedMilliseconds}ms)',
+ );
+ final localReachable = await ApiService.pingServer(
+ _localServerUrl,
+ customHeaders: _customHeaders,
+ ).timeout(const Duration(seconds: 2), onTimeout: () => false);
if (localReachable) {
- debugPrint('[Auth] Local server reachable - using local (${sw.elapsedMilliseconds}ms)');
+ debugPrint(
+ '[Auth] Local server reachable - using local (${sw.elapsedMilliseconds}ms)',
+ );
_useLocalServer = true;
reachable = true;
}
}
}
if (!reachable) {
- debugPrint('[Auth] pinging remote server... (${sw.elapsedMilliseconds}ms)');
+ debugPrint(
+ '[Auth] pinging remote server... (${sw.elapsedMilliseconds}ms)',
+ );
// Cap at 5s so a silently-dropping reverse proxy or dead network
// path doesn't hold up app launch. The health-check timer will
// re-probe every 60s once we're past startup, so a transient
// false-offline self-corrects quickly.
- reachable = await ApiService.pingServer(restoredUrl, customHeaders: _customHeaders)
- .timeout(const Duration(seconds: 5), onTimeout: () => false);
- debugPrint('[Auth] remote ping result: reachable=$reachable (${sw.elapsedMilliseconds}ms)');
+ reachable = await ApiService.pingServer(
+ restoredUrl,
+ customHeaders: _customHeaders,
+ ).timeout(const Duration(seconds: 5), onTimeout: () => false);
+ debugPrint(
+ '[Auth] remote ping result: reachable=$reachable (${sw.elapsedMilliseconds}ms)',
+ );
}
_serverReachable = reachable;
@@ -470,7 +505,9 @@ class AuthProvider extends ChangeNotifier {
debugPrint('[Auth] /me returned null (token may be invalid)');
}
}
- debugPrint('[Auth] authorize/me done (${sw.elapsedMilliseconds}ms)');
+ debugPrint(
+ '[Auth] authorize/me done (${sw.elapsedMilliseconds}ms)',
+ );
} catch (_) {}
_fetchServerVersion(activeServerUrl!);
}
@@ -482,11 +519,15 @@ class AuthProvider extends ChangeNotifier {
}
} catch (e) {
// Restore failed — but if we already set credentials, keep them
- debugPrint('[Auth] tryRestoreSession error: $e (${sw.elapsedMilliseconds}ms)');
+ debugPrint(
+ '[Auth] tryRestoreSession error: $e (${sw.elapsedMilliseconds}ms)',
+ );
_serverReachable = false;
}
- debugPrint('[Auth] tryRestoreSession done, isAuthenticated=$isAuthenticated (${sw.elapsedMilliseconds}ms)');
+ debugPrint(
+ '[Auth] tryRestoreSession done, isAuthenticated=$isAuthenticated (${sw.elapsedMilliseconds}ms)',
+ );
if (isAuthenticated) _pushSessionToWear();
_isLoading = false;
notifyListeners();
@@ -507,7 +548,8 @@ class AuthProvider extends ChangeNotifier {
/// already have the user.
Future<void> _ensureUserInfo() async {
if (_userJson != null || _ensuringUserInfo) return;
- if (!isAuthenticated || _accessToken == null || activeServerUrl == null) return;
+ if (!isAuthenticated || _accessToken == null || activeServerUrl == null)
+ return;
_ensuringUserInfo = true;
try {
final api = _createSessionApi(
@@ -540,7 +582,9 @@ class AuthProvider extends ChangeNotifier {
}
}
if (_userJson != null) {
- debugPrint('[Auth] Loaded user info on reconnect (type=${_userJson?['type']})');
+ debugPrint(
+ '[Auth] Loaded user info on reconnect (type=${_userJson?['type']})',
+ );
notifyListeners();
}
} catch (e) {
@@ -566,9 +610,13 @@ class AuthProvider extends ChangeNotifier {
final url = normalizeServerUrl(serverUrl);
// Check server reachability
- final reachable = await ApiService.pingServer(url, customHeaders: customHeaders);
+ final reachable = await ApiService.pingServer(
+ url,
+ customHeaders: customHeaders,
+ );
if (!reachable) {
- _errorMessage = l?.authCannotReachServer(url) ?? 'Cannot reach server at $url';
+ _errorMessage =
+ l?.authCannotReachServer(url) ?? 'Cannot reach server at $url';
return false;
}
@@ -583,14 +631,16 @@ class AuthProvider extends ChangeNotifier {
if (result == null) {
_errorMessage = statusCode == 401
? (l?.authInvalidUsernameOrPassword ?? 'Invalid username or password')
- : (l?.authLoginFailedDetail ?? 'Login failed - check your server address and credentials');
+ : (l?.authLoginFailedDetail ??
+ 'Login failed - check your server address and credentials');
return false;
}
// Extract user info
final user = result['user'] as Map<String, dynamic>?;
if (user == null) {
- _errorMessage = l?.authUnexpectedServerResponse ?? 'Unexpected server response';
+ _errorMessage =
+ l?.authUnexpectedServerResponse ?? 'Unexpected server response';
return false;
}
@@ -599,7 +649,8 @@ class AuthProvider extends ChangeNotifier {
// the top-level shape and legacy token used by older servers.
final tokens = AuthTokens.fromResponse(result);
if (tokens.token == null) {
- _errorMessage = l?.authUnexpectedServerResponse ?? 'Unexpected server response';
+ _errorMessage =
+ l?.authUnexpectedServerResponse ?? 'Unexpected server response';
return false;
}
_isLegacyToken = tokens.isLegacy;
@@ -607,8 +658,12 @@ class AuthProvider extends ChangeNotifier {
_refreshToken = tokens.refreshToken;
debugPrint('[Auth] Login response keys: ${result.keys.toList()}');
debugPrint('[Auth] Login user keys: ${user.keys.toList()}');
- debugPrint('[Auth] accessToken=${tokens.accessToken != null}, refreshToken=${tokens.refreshToken != null}, legacyToken=${tokens.legacyToken != null}, isLegacy=$_isLegacyToken');
- debugPrint('[Auth] Token being used: ${_accessToken != null ? '${_accessToken!.substring(0, _accessToken!.length.clamp(0, 20))}... (${_accessToken!.length} chars)' : 'null'}');
+ debugPrint(
+ '[Auth] accessToken=${tokens.accessToken != null}, refreshToken=${tokens.refreshToken != null}, legacyToken=${tokens.legacyToken != null}, isLegacy=$_isLegacyToken',
+ );
+ debugPrint(
+ '[Auth] Token being used: ${_accessToken != null ? '${_accessToken!.substring(0, _accessToken!.length.clamp(0, 20))}... (${_accessToken!.length} chars)' : 'null'}',
+ );
_username = user['username'] as String?;
_userId = user['id'] as String?;
_defaultLibraryId = result['userDefaultLibraryId'] as String?;
@@ -621,8 +676,9 @@ class AuthProvider extends ChangeNotifier {
await _persistEreaderDevices();
// Try to get version from login response first, fall back to /status
- final loginVersion = result['serverVersion'] as String?
- ?? (_serverSettings?['version'] as String?);
+ final loginVersion =
+ result['serverVersion'] as String? ??
+ (_serverSettings?['version'] as String?);
if (loginVersion != null && loginVersion.isNotEmpty) {
_serverVersion = loginVersion;
} else {
@@ -634,7 +690,8 @@ class AuthProvider extends ChangeNotifier {
final prefs = await SharedPreferences.getInstance();
await prefs.setString('server_url', _serverUrl!);
if (_accessToken != null) await prefs.setString('token', _accessToken!);
- if (_refreshToken != null) await prefs.setString('refresh_token', _refreshToken!);
+ if (_refreshToken != null)
+ await prefs.setString('refresh_token', _refreshToken!);
if (_username != null) await prefs.setString('username', _username!);
if (_userId != null) await prefs.setString('user_id', _userId!);
if (_defaultLibraryId != null) {
@@ -649,15 +706,17 @@ class AuthProvider extends ChangeNotifier {
// Save to multi-account service
try {
- await UserAccountService().saveAccount(SavedAccount(
- serverUrl: _serverUrl!,
- username: _username ?? '',
- token: _accessToken ?? '',
- refreshToken: _refreshToken,
- userId: _userId,
- isLegacyToken: _isLegacyToken,
- customHeaders: customHeaders,
- ));
+ await UserAccountService().saveAccount(
+ SavedAccount(
+ serverUrl: _serverUrl!,
+ username: _username ?? '',
+ token: _accessToken ?? '',
+ refreshToken: _refreshToken,
+ userId: _userId,
+ isLegacyToken: _isLegacyToken,
+ customHeaders: customHeaders,
+ ),
+ );
} catch (_) {}
await _onAccountActivated();
@@ -686,9 +745,13 @@ class AuthProvider extends ChangeNotifier {
final url = normalizeServerUrl(serverUrl);
- final reachable = await ApiService.pingServer(url, customHeaders: customHeaders);
+ final reachable = await ApiService.pingServer(
+ url,
+ customHeaders: customHeaders,
+ );
if (!reachable) {
- _errorMessage = l?.authCannotReachServer(url) ?? 'Cannot reach server at $url';
+ _errorMessage =
+ l?.authCannotReachServer(url) ?? 'Cannot reach server at $url';
return false;
}
@@ -701,7 +764,8 @@ class AuthProvider extends ChangeNotifier {
if (user == null) {
_errorMessage = statusCode == 401
? (l?.authInvalidApiKey ?? 'Invalid API key')
- : (l?.authLoginFailedDetail ?? 'Login failed - check your server address and API key');
+ : (l?.authLoginFailedDetail ??
+ 'Login failed - check your server address and API key');
return false;
}
@@ -733,15 +797,17 @@ class AuthProvider extends ChangeNotifier {
} catch (_) {}
try {
- await UserAccountService().saveAccount(SavedAccount(
- serverUrl: _serverUrl!,
- username: _username ?? '',
- token: _accessToken!,
- refreshToken: null,
- userId: _userId,
- isLegacyToken: true,
- customHeaders: customHeaders,
- ));
+ await UserAccountService().saveAccount(
+ SavedAccount(
+ serverUrl: _serverUrl!,
+ username: _username ?? '',
+ token: _accessToken!,
+ refreshToken: null,
+ userId: _userId,
+ isLegacyToken: true,
+ customHeaders: customHeaders,
+ ),
+ );
} catch (_) {}
await _onAccountActivated();
@@ -773,7 +839,8 @@ class AuthProvider extends ChangeNotifier {
final user = result['user'] as Map<String, dynamic>?;
if (user == null) {
- _errorMessage = l?.authSsoUnexpectedResponse ?? 'SSO returned an unexpected response';
+ _errorMessage =
+ l?.authSsoUnexpectedResponse ?? 'SSO returned an unexpected response';
notifyListeners();
return false;
}
@@ -781,7 +848,8 @@ class AuthProvider extends ChangeNotifier {
_serverUrl = url;
final tokens = AuthTokens.fromResponse(result);
if (tokens.token == null) {
- _errorMessage = l?.authSsoUnexpectedResponse ?? 'SSO returned an unexpected response';
+ _errorMessage =
+ l?.authSsoUnexpectedResponse ?? 'SSO returned an unexpected response';
notifyListeners();
return false;
}
@@ -790,8 +858,12 @@ class AuthProvider extends ChangeNotifier {
_refreshToken = tokens.refreshToken;
debugPrint('[Auth] OIDC response keys: ${result.keys.toList()}');
debugPrint('[Auth] OIDC user keys: ${user.keys.toList()}');
- debugPrint('[Auth] accessToken=${tokens.accessToken != null}, refreshToken=${tokens.refreshToken != null}, legacyToken=${tokens.legacyToken != null}, isLegacy=$_isLegacyToken');
- debugPrint('[Auth] Token being used: ${_accessToken != null ? '${_accessToken!.substring(0, _accessToken!.length.clamp(0, 20))}... (${_accessToken!.length} chars)' : 'null'}');
+ debugPrint(
+ '[Auth] accessToken=${tokens.accessToken != null}, refreshToken=${tokens.refreshToken != null}, legacyToken=${tokens.legacyToken != null}, isLegacy=$_isLegacyToken',
+ );
+ debugPrint(
+ '[Auth] Token being used: ${_accessToken != null ? '${_accessToken!.substring(0, _accessToken!.length.clamp(0, 20))}... (${_accessToken!.length} chars)' : 'null'}',
+ );
_username = user['username'] as String?;
_userId = user['id'] as String?;
_defaultLibraryId = result['userDefaultLibraryId'] as String?;
@@ -804,8 +876,9 @@ class AuthProvider extends ChangeNotifier {
await _persistEreaderDevices();
// Try to get version from response first, fall back to /status
- final oidcVersion = result['serverVersion'] as String?
- ?? (_serverSettings?['version'] as String?);
+ final oidcVersion =
+ result['serverVersion'] as String? ??
+ (_serverSettings?['version'] as String?);
if (oidcVersion != null && oidcVersion.isNotEmpty) {
_serverVersion = oidcVersion;
} else {
@@ -817,7 +890,8 @@ class AuthProvider extends ChangeNotifier {
final prefs = await SharedPreferences.getInstance();
await prefs.setString('server_url', _serverUrl!);
if (_accessToken != null) await prefs.setString('token', _accessToken!);
- if (_refreshToken != null) await prefs.setString('refresh_token', _refreshToken!);
+ if (_refreshToken != null)
+ await prefs.setString('refresh_token', _refreshToken!);
if (_username != null) await prefs.setString('username', _username!);
if (_userId != null) await prefs.setString('user_id', _userId!);
if (_defaultLibraryId != null) {
@@ -832,15 +906,17 @@ class AuthProvider extends ChangeNotifier {
// Save to multi-account service
try {
- await UserAccountService().saveAccount(SavedAccount(
- serverUrl: _serverUrl!,
- username: _username ?? '',
- token: _accessToken ?? '',
- refreshToken: _refreshToken,
- userId: _userId,
- isLegacyToken: _isLegacyToken,
- customHeaders: customHeaders,
- ));
+ await UserAccountService().saveAccount(
+ SavedAccount(
+ serverUrl: _serverUrl!,
+ username: _username ?? '',
+ token: _accessToken ?? '',
+ refreshToken: _refreshToken,
+ userId: _userId,
+ isLegacyToken: _isLegacyToken,
+ customHeaders: customHeaders,
+ ),
+ );
} catch (_) {}
await _onAccountActivated();
@@ -865,7 +941,9 @@ class AuthProvider extends ChangeNotifier {
await PlayerSettings.setLocalServerUrl(_localServerUrl);
}
if (_localServerEnabled) {
- debugPrint('[Auth] Local server config loaded: enabled=$_localServerEnabled, url=${_localServerUrl.isNotEmpty ? "(set)" : "(empty)"}');
+ debugPrint(
+ '[Auth] Local server config loaded: enabled=$_localServerEnabled, url=${_localServerUrl.isNotEmpty ? "(set)" : "(empty)"}',
+ );
}
}
@@ -884,8 +962,9 @@ class AuthProvider extends ChangeNotifier {
final connectivity = await Connectivity().checkConnectivity();
if (connectivity.contains(ConnectivityResult.wifi)) {
final localReachable = await ApiService.pingServer(
- _localServerUrl, customHeaders: _customHeaders)
- .timeout(const Duration(seconds: 2), onTimeout: () => false);
+ _localServerUrl,
+ customHeaders: _customHeaders,
+ ).timeout(const Duration(seconds: 2), onTimeout: () => false);
if (localReachable) {
debugPrint('[Auth] Local server reachable - using local');
_useLocalServer = true;
@@ -897,11 +976,14 @@ class AuthProvider extends ChangeNotifier {
/// Check if the configured local server is reachable.
/// Called on WiFi connectivity changes by LibraryProvider.
Future<void> checkLocalServer() async {
- if (!_localServerEnabled || _localServerUrl.isEmpty || _serverUrl == null) return;
+ if (!_localServerEnabled || _localServerUrl.isEmpty || _serverUrl == null)
+ return;
final wasLocal = _useLocalServer;
try {
- final reachable = await ApiService.pingServer(_localServerUrl, customHeaders: _customHeaders)
- .timeout(const Duration(seconds: 3), onTimeout: () => false);
+ final reachable = await ApiService.pingServer(
+ _localServerUrl,
+ customHeaders: _customHeaders,
+ ).timeout(const Duration(seconds: 3), onTimeout: () => false);
_useLocalServer = reachable;
if (reachable) _serverReachable = true;
} catch (_) {
@@ -912,9 +994,11 @@ class AuthProvider extends ChangeNotifier {
SocketService().switchServer(activeServerUrl!);
final ctx = rootNavigatorKey.currentContext;
final l = ctx != null ? AppLocalizations.of(ctx) : null;
- _showServerToast(_useLocalServer
- ? (l?.authSwitchedToLocalServer ?? 'Switched to local server')
- : (l?.authSwitchedToRemoteServer ?? 'Switched to remote server'));
+ _showServerToast(
+ _useLocalServer
+ ? (l?.authSwitchedToLocalServer ?? 'Switched to local server')
+ : (l?.authSwitchedToRemoteServer ?? 'Switched to remote server'),
+ );
notifyListeners();
}
}
@@ -929,7 +1013,9 @@ class AuthProvider extends ChangeNotifier {
}
final ctx = rootNavigatorKey.currentContext;
final l = ctx != null ? AppLocalizations.of(ctx) : null;
- _showServerToast(l?.authSwitchedToRemoteServer ?? 'Switched to remote server');
+ _showServerToast(
+ l?.authSwitchedToRemoteServer ?? 'Switched to remote server',
+ );
notifyListeners();
}
@@ -942,7 +1028,10 @@ class AuthProvider extends ChangeNotifier {
}
/// Update local server settings from the UI.
- Future<void> setLocalServerConfig({required bool enabled, required String url}) async {
+ Future<void> setLocalServerConfig({
+ required bool enabled,
+ required String url,
+ }) async {
final normalizedUrl = normalizeServerUrl(url);
_localServerEnabled = enabled;
_localServerUrl = normalizedUrl;
@@ -955,7 +1044,10 @@ class AuthProvider extends ChangeNotifier {
/// Fetch server version asynchronously (non-blocking).
void _fetchServerVersion(String url) async {
try {
- final version = await ApiService.getServerVersion(url, customHeaders: _customHeaders);
+ final version = await ApiService.getServerVersion(
+ url,
+ customHeaders: _customHeaders,
+ );
if (version != null) {
_serverVersion = version;
notifyListeners();
@@ -1081,8 +1173,10 @@ class AuthProvider extends ChangeNotifier {
// Set the new account as active in the account service. It may have been
// removed since the caller loaded its saved-account row.
- final selected =
- UserAccountService().switchTo(account.serverUrl, account.username);
+ final selected = UserAccountService().switchTo(
+ account.serverUrl,
+ account.username,
+ );
if (selected == null) return false;
_startOnAbsorbingAfterAccountChange = true;
@@ -1094,7 +1188,8 @@ class AuthProvider extends ChangeNotifier {
// Synchronous PlayerSettings caches are loaded at startup, so refresh
// them from the new account's scope or playback keeps the old account's
// values until restart.
- PlayerSettings.showExplicitBadge = await PlayerSettings.getShowExplicitBadge();
+ PlayerSettings.showExplicitBadge =
+ await PlayerSettings.getShowExplicitBadge();
PlayerSettings.mp3IndexSeeking = await PlayerSettings.getMp3IndexSeeking();
// Reload EQ settings from the new account's scope. Without this the
@@ -1183,10 +1278,14 @@ class AuthProvider extends ChangeNotifier {
if (_localServerEnabled && _localServerUrl.isNotEmpty) {
final connectivity = await Connectivity().checkConnectivity();
if (connectivity.contains(ConnectivityResult.wifi)) {
- final localReachable = await ApiService.pingServer(_localServerUrl, customHeaders: _customHeaders)
- .timeout(const Duration(seconds: 2), onTimeout: () => false);
+ final localReachable = await ApiService.pingServer(
+ _localServerUrl,
+ customHeaders: _customHeaders,
+ ).timeout(const Duration(seconds: 2), onTimeout: () => false);
if (localReachable) {
- debugPrint('[Auth] switchToAccount: local server reachable - using local');
+ debugPrint(
+ '[Auth] switchToAccount: local server reachable - using local',
+ );
_useLocalServer = true;
}
}
@@ -1204,11 +1303,7 @@ class AuthProvider extends ChangeNotifier {
/// next API call (and the [apiService] getter) uses the new address.
/// Returns true if the account was found and updated.
Future<bool> editServerUrl(SavedAccount account, String newServerUrl) async {
- return editServerConnection(
- account,
- newServerUrl,
- account.customHeaders,
- );
+ return editServerConnection(account, newServerUrl, account.customHeaders);
}
/// Update the connection details for one saved account. Custom headers are
@@ -1228,13 +1323,12 @@ class AuthProvider extends ChangeNotifier {
);
if (url == account.serverUrl && headersUnchanged) return true;
- final ok = await UserAccountService()
- .updateAccountConnection(
- account.serverUrl,
- account.username,
- url,
- customHeaders,
- );
+ final ok = await UserAccountService().updateAccountConnection(
+ account.serverUrl,
+ account.username,
+ url,
+ customHeaders,
+ );
if (!ok) return false;
// If we just edited the currently active session, update it live.
diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dart
index 40c21dfc..169a643d 100644
--- a/lib/providers/library_provider.dart
+++ b/lib/providers/library_provider.dart
@@ -21,6 +21,7 @@ import '../services/session_cache.dart';
import '../services/socket_service.dart';
import '../services/book_search_index.dart';
import '../services/home_widget_service.dart';
+import '../services/queue_download_policy.dart';
import '../utils/absorbing_inclusion.dart';
import '../l10n/app_localizations.dart';
import '../main.dart' show rootNavigatorKey;
@@ -57,19 +58,28 @@ class LibraryProvider extends ChangeNotifier
markFinishedLocally(oldItemId, skipAutoAdvance: true);
});
AudioPlayerService.setOnPeekNextItemCallback(peekNextQueueItemForPreBuffer);
- AudioPlayerService.setOnPlayStartedCallback((key) {
+ AudioPlayerService.setOnPlayStartedCallback((key, duration) async {
+ await _prepareAbsorbingForPlayback(key, duration);
// Auto-download the book/episode you're listening to kicks off quickly so
// it doesn't feel broken; the short wait still skips it if you stop or
// switch right away. Rolling/queue look-ahead stays deferred to keep the
// moment playback starts light.
Future.delayed(const Duration(seconds: 5), () {
- if (!AudioPlayerService().isPlaying) return;
+ final player = AudioPlayerService();
+ final currentKey = player.currentEpisodeId == null
+ ? player.currentItemId
+ : '${player.currentItemId}-${player.currentEpisodeId}';
+ if (!player.isPlaying || currentKey != key) return;
_checkAutoDownloadOnStream(key);
});
Future.delayed(const Duration(seconds: 30), () {
- if (!AudioPlayerService().isPlaying) return;
+ final player = AudioPlayerService();
+ final currentKey = player.currentEpisodeId == null
+ ? player.currentItemId
+ : '${player.currentItemId}-${player.currentEpisodeId}';
+ if (!player.isPlaying || currentKey != key) return;
_checkRollingDownloads(key);
- _checkQueueAutoDownloads(key);
+ unawaited(_checkQueueAutoDownloads(key));
});
});
AudioPlayerService.setOnPlaybackStateChangedCallback((playing) {
@@ -141,6 +151,7 @@ class LibraryProvider extends ChangeNotifier
_localProgressOverrides.clear();
_resetItems.clear();
_manualAbsorbAdds.clear();
+ _finishedManualAbsorbAdds.clear();
_manualAbsorbRemoves.clear();
_absorbingBookIds.clear();
_absorbingItemCache.clear();
@@ -307,7 +318,7 @@ class LibraryProvider extends ChangeNotifier
notifyListeners();
_catchUpRollingDownloads();
- _catchUpQueueAutoDownloads();
+ unawaited(_catchUpQueueAutoDownloads());
catchUpSubscribedPodcasts();
}
diff --git a/lib/screens/absorbing_screen.dart b/lib/screens/absorbing_screen.dart
index 2f12af46..b565238d 100644
--- a/lib/screens/absorbing_screen.dart
+++ b/lib/screens/absorbing_screen.dart
@@ -116,10 +116,13 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {
String mode;
final bm = await PlayerSettings.getBookQueueMode();
final pm = await PlayerSettings.getPodcastQueueMode();
+ final activeIsPodcast = _player.currentItemId == null
+ ? lib.isPodcastLibrary
+ : _player.currentEpisodeId != null;
if (bm == 'playlist' || pm == 'playlist') {
mode = 'playlist';
} else if (bm == 'collection') {
- mode = 'collection';
+ mode = activeIsPodcast ? pm : 'collection';
} else if (_mergeLibraries) {
// When merged, use the more restrictive of the two modes
// (matches Settings screen's _mergedQueueMode logic)
@@ -128,7 +131,7 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {
final pi = order.indexOf(pm);
mode = order[(bi < pi ? bi : pi).clamp(0, 2)];
} else {
- mode = lib.isPodcastLibrary ? pm : bm;
+ mode = activeIsPodcast ? pm : bm;
}
final qpId = await PlayerSettings.getQueuePlaylistId();
final qcName = await PlayerSettings.getQueueCollectionName();
@@ -932,6 +935,9 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {
void _showReorderSheet(BuildContext context, LibraryProvider lib, List<Map<String, dynamic>> books) {
final keys = books.map((b) => _absorbingKey(b)).toList();
+ final media = MediaQuery.of(context);
+ final needsMoreRoom = media.size.height < 600 ||
+ media.textScaler.scale(1) > 1.2;
showModalBottomSheet(
context: context,
isScrollControlled: true,
@@ -939,9 +945,9 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {
backgroundColor: Colors.transparent,
builder: (_) => DraggableScrollableSheet(
expand: false,
- initialChildSize: 0.6,
- minChildSize: 0.3,
- maxChildSize: 0.9,
+ initialChildSize: needsMoreRoom ? 0.9 : 0.7,
+ minChildSize: needsMoreRoom ? 0.85 : 0.5,
+ maxChildSize: 0.95,
builder: (_, __) => _ReorderAbsorbingSheet(
keys: keys,
books: books,
@@ -965,13 +971,16 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {
return;
}
await PlayerSettings.setQueueModePlaylist(pid);
+ unawaited(lib.syncQueueAutoDownloads());
return;
}
if (_mergeLibraries || _queueMode == 'playlist') {
await PlayerSettings.setBookQueueMode(mode);
await PlayerSettings.setPodcastQueueMode(mode);
} else {
- final isPod = lib.isPodcastLibrary;
+ final isPod = _player.currentItemId == null
+ ? lib.isPodcastLibrary
+ : _player.currentEpisodeId != null;
if (isPod) {
await PlayerSettings.setPodcastQueueMode(mode);
} else {
@@ -979,6 +988,7 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {
}
}
PlayerSettings.notifySettingsChanged();
+ unawaited(lib.syncQueueAutoDownloads());
},
),
),
@@ -1075,6 +1085,9 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {
late List<String> _order;
late Map<String, Map<String, dynamic>> _booksByKey;
late String _queueMode;
+ late final DownloadService _downloads;
+ late final AudioPlayerService _player;
+ String? _currentItemId;
@override
void initState() {
@@ -1084,31 +1097,89 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {
for (final b in widget.books) widget.absorbingKeyFn(b): b,
};
_queueMode = widget.queueMode;
+ _currentItemId = widget.currentItemId;
+ _downloads = DownloadService()..addListener(_onDownloadsChanged);
+ _player = AudioPlayerService()..addListener(_onPlayerChanged);
PlayerSettings.settingsChanged.addListener(_refreshMode);
PlayerSettings.getShowUpNextLabel().then((v) {
if (mounted) setState(() => _showUpNext = v);
});
+ Future.wait([
+ PlayerSettings.getQueueAutoDownload(),
+ PlayerSettings.getRollingDownloadCount(),
+ ]).then((values) {
+ if (!mounted) return;
+ setState(() {
+ _queueAutoDownload = values[0] as bool;
+ _rollingDownloadCount = values[1] as int;
+ _queueDownloadSettingsLoaded = true;
+ });
+ });
final showId = _currentPodcastShowId;
if (showId != null) {
PlayerSettings.getPodcastAdvanceDir(showId).then((v) {
- if (mounted) setState(() => _podcastAdvanceDir = v);
+ if (mounted && _currentPodcastShowId == showId) {
+ setState(() => _podcastAdvanceDir = v);
+ }
});
}
- _loadModeContent();
+ unawaited(_refreshMode());
+ unawaited(_loadModeContent());
}
bool _showUpNext = true;
+ bool _queueAutoDownload = false;
+ bool _queueDownloadSettingsLoaded = false;
+ int _rollingDownloadCount = 3;
String _podcastAdvanceDir = 'oldest_first';
+ void _onDownloadsChanged() {
+ if (mounted) setState(() {});
+ }
+
+ void _onPlayerChanged() {
+ final itemId = _player.currentItemId;
+ final episodeId = _player.currentEpisodeId;
+ final nextKey = itemId == null
+ ? null
+ : episodeId == null
+ ? itemId
+ : '$itemId-$episodeId';
+ if (!mounted || nextKey == _currentItemId) return;
+ setState(() {
+ _currentItemId = nextKey;
+ _seriesBooks = null;
+ _seriesId = null;
+ _seriesName = null;
+ _showEpisodes = null;
+ _showItem = null;
+ _showName = null;
+ });
+ final showId = _currentPodcastShowId;
+ if (showId != null) {
+ PlayerSettings.getPodcastAdvanceDir(showId).then((value) {
+ if (mounted && _currentPodcastShowId == showId) {
+ setState(() => _podcastAdvanceDir = value);
+ }
+ });
+ }
+ unawaited(_refreshMode());
+ unawaited(_loadModeContent());
+ }
+
// Show id of the currently playing podcast, or null if a book (or nothing)
- // is playing. currentItemId is the compound "<itemId>-<episodeId>" key for
+ // is playing. _currentItemId is the compound "<itemId>-<episodeId>" key for
// podcasts, so a length past 36 means an episode is playing.
String? get _currentPodcastShowId {
- final id = widget.currentItemId;
+ final id = _currentItemId;
if (id == null || id.length <= 36) return null;
return id.substring(0, 36);
}
+ bool get _currentIsPodcast =>
+ _currentPodcastShowId != null ||
+ (_currentItemId == null && widget.isPodcast);
+
// Stage 3: mode-aware rendering. For auto_next we show the active series'
// books; for playlist we show the active playlist's items. Cached here so
// the list paints without a flash while the API call completes.
@@ -1121,6 +1192,8 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {
List<Map<String, dynamic>>? _collectionBooks;
String? _collectionId;
String? _collectionName;
+ String? _activeQueueSourceId;
+ int _modeContentGeneration = 0;
// Podcast auto_next: the current show's episodes (unsorted - the list sorts
// by _podcastAdvanceDir at build so flipping the toggle reorders live).
List<Map<String, dynamic>>? _showEpisodes;
@@ -1128,29 +1201,36 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {
String? _showName;
Future<void> _loadModeContent() async {
+ final generation = ++_modeContentGeneration;
if (_queueMode == 'auto_next') {
// Discriminate on the playing item, not the library: a podcast can be
// playing inside a book library (and vice versa). Podcast auto advances
// within the current show; books advance through the series.
if (_currentPodcastShowId != null) {
- await _loadShowEpisodes();
- } else if (!widget.isPodcast) {
- await _loadSeriesBooks();
+ await _loadShowEpisodes(generation);
+ } else if (_currentItemId != null) {
+ await _loadSeriesBooks(generation);
}
} else if (_queueMode == 'playlist') {
- await _loadPlaylistContent();
+ await _loadPlaylistContent(generation);
} else if (_queueMode == 'collection') {
- await _loadCollectionContent();
+ await _loadCollectionContent(generation);
}
}
- Future<void> _loadShowEpisodes() async {
+ Future<void> _loadShowEpisodes(int generation) async {
final showId = _currentPodcastShowId;
if (showId == null) return;
// The absorbing cache only holds per-episode synthetic entries, so fetch
// the show fresh to get the full episode list.
final item = await widget.lib.fetchLibraryItem(showId);
- if (!mounted || item == null) return;
+ if (!mounted ||
+ generation != _modeContentGeneration ||
+ _queueMode != 'auto_next' ||
+ item == null ||
+ _currentPodcastShowId != showId) {
+ return;
+ }
final media = item['media'] as Map<String, dynamic>? ?? const {};
final eps = (media['episodes'] as List<dynamic>? ?? const [])
.whereType<Map<String, dynamic>>()
@@ -1163,8 +1243,8 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {
});
}
- Future<void> _loadSeriesBooks() async {
- final currentId = widget.currentItemId;
+ Future<void> _loadSeriesBooks(int generation) async {
+ final currentId = _currentItemId;
if (currentId == null) return;
final cache = widget.lib.absorbingItemCache;
Map<String, dynamic>? data = cache[currentId];
@@ -1180,7 +1260,12 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {
final libraryId = data['libraryId'] as String? ?? widget.lib.selectedLibraryId;
if (libraryId == null) return;
final books = await auth.fetchBooksBySeries(libraryId, sid);
- if (!mounted) return;
+ if (!mounted ||
+ generation != _modeContentGeneration ||
+ _queueMode != 'auto_next' ||
+ _currentItemId != currentId) {
+ return;
+ }
// Pull the series name from the current book's metadata.
final media = data['media'] as Map<String, dynamic>? ?? const {};
final metadata = media['metadata'] as Map<String, dynamic>? ?? const {};
@@ -1203,12 +1288,19 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {
});
}
- Future<void> _loadPlaylistContent() async {
- final pid = await PlayerSettings.getQueuePlaylistId();
+ Future<void> _loadPlaylistContent(int generation) async {
+ final pid =
+ _activeQueueSourceId ?? await PlayerSettings.getQueuePlaylistId();
if (pid == null) return;
final pl = await widget.lib.fetchPlaylistById(pid);
- if (!mounted) return;
- if (pl == null) return;
+ final currentPid = await PlayerSettings.getQueuePlaylistId();
+ if (!mounted ||
+ generation != _modeContentGeneration ||
+ _queueMode != 'playlist' ||
+ currentPid != pid ||
+ pl == null) {
+ return;
+ }
final items = ((pl['items'] as List<dynamic>?) ?? const [])
.whereType<Map<String, dynamic>>()
.toList();
@@ -1216,14 +1308,23 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {
_playlistItems = items;
_playlistId = pid;
_playlistName = pl['name'] as String?;
+ _activeQueueSourceId = pid;
});
}
- Future<void> _loadCollectionContent() async {
- final cid = await PlayerSettings.getQueueCollectionId();
+ Future<void> _loadCollectionContent(int generation) async {
+ final cid =
+ _activeQueueSourceId ?? await PlayerSettings.getQueueCollectionId();
if (cid == null) return;
final c = await widget.lib.fetchCollectionById(cid);
- if (!mounted || c == null) return;
+ final currentCid = await PlayerSettings.getQueueCollectionId();
+ if (!mounted ||
+ generation != _modeContentGeneration ||
+ _queueMode != 'collection' ||
+ currentCid != cid ||
+ c == null) {
+ return;
+ }
final books = ((c['books'] as List<dynamic>?) ?? const [])
.whereType<Map<String, dynamic>>()
.toList();
@@ -1231,11 +1332,14 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {
_collectionBooks = books;
_collectionId = cid;
_collectionName = c['name'] as String?;
+ _activeQueueSourceId = cid;
});
}
@override
void dispose() {
+ _downloads.removeListener(_onDownloadsChanged);
+ _player.removeListener(_onPlayerChanged);
PlayerSettings.settingsChanged.removeListener(_refreshMode);
super.dispose();
}
@@ -1247,18 +1351,39 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {
if (bm == 'playlist' || pm == 'playlist') {
mode = 'playlist';
} else if (bm == 'collection') {
- mode = 'collection';
+ mode = _currentIsPodcast ? pm : 'collection';
} else if (widget.isMerged) {
const order = ['off', 'manual', 'auto_next'];
final bi = order.indexOf(bm);
final pi = order.indexOf(pm);
mode = order[(bi < pi ? bi : pi).clamp(0, 2)];
} else {
- mode = widget.isPodcast ? pm : bm;
+ mode = _currentIsPodcast ? pm : bm;
}
- if (mounted && mode != _queueMode) {
- setState(() => _queueMode = mode);
- _loadModeContent();
+ final sourceId = mode == 'playlist'
+ ? await PlayerSettings.getQueuePlaylistId()
+ : mode == 'collection'
+ ? await PlayerSettings.getQueueCollectionId()
+ : null;
+ if (!mounted) return;
+ final modeChanged = mode != _queueMode;
+ final sourceChanged = sourceId != _activeQueueSourceId;
+ if (modeChanged || sourceChanged) {
+ setState(() {
+ _queueMode = mode;
+ _activeQueueSourceId = sourceId;
+ if (modeChanged || mode == 'playlist') {
+ _playlistItems = null;
+ _playlistId = null;
+ _playlistName = null;
+ }
+ if (modeChanged || mode == 'collection') {
+ _collectionBooks = null;
+ _collectionId = null;
+ _collectionName = null;
+ }
+ });
+ await _loadModeContent();
}
}
@@ -1307,7 +1432,7 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {
ButtonSegment(value: 'off', icon: const Icon(Icons.stop_rounded, size: 16), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModeOff, maxLines: 1))),
ButtonSegment(value: 'manual', icon: const Icon(Icons.queue_music_rounded, size: 16), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModeManual, maxLines: 1))),
ButtonSegment(value: 'auto_next', icon: const Icon(Icons.skip_next_rounded, size: 16),
- label: FittedBox(fit: BoxFit.scaleDown, child: Text(widget.isMerged ? l.queueModeAuto : widget.isPodcast ? l.queueModeShowLabel : l.queueModeSeriesLabel, maxLines: 1))),
+ label: FittedBox(fit: BoxFit.scaleDown, child: Text(widget.isMerged ? l.queueModeAuto : _currentIsPodcast ? l.queueModeShowLabel : l.queueModeSeriesLabel, maxLines: 1))),
ButtonSegment(value: 'playlist', icon: const Icon(Icons.playlist_play_rounded, size: 16), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModePlaylist, maxLines: 1))),
// Collection mode is entered via a collection's Play button, not
// picked here - shown only while active so the selection is valid.
@@ -1324,6 +1449,69 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {
),
),
),
+ if (_queueMode != 'off')
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 0, 16, 4),
+ child: Column(children: [
+ Row(children: [
+ Expanded(child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(l.autoDownloadQueue,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ Text(
+ _queueAutoDownload
+ ? l.autoDownloadQueueOnSubtitle(_rollingDownloadCount)
+ : l.autoDownloadQueueOffSubtitle,
+ style: tt.bodySmall?.copyWith(
+ color: cs.onSurfaceVariant, fontSize: 11.5),
+ ),
+ ],
+ )),
+ Switch(
+ value: _queueAutoDownload,
+ onChanged: _queueDownloadSettingsLoaded
+ ? (value) async {
+ setState(() => _queueAutoDownload = value);
+ await PlayerSettings.setQueueAutoDownload(value);
+ unawaited(widget.lib.syncQueueAutoDownloads());
+ }
+ : null,
+ materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ ),
+ ]),
+ if (_queueAutoDownload)
+ Padding(
+ padding: const EdgeInsets.only(top: 4, bottom: 4),
+ child: Row(children: [
+ Text(l.keepNext,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ const SizedBox(width: 12),
+ Expanded(child: SegmentedButton<int>(
+ showSelectedIcon: false,
+ 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: (values) async {
+ if (values.isEmpty) return;
+ final value = values.first;
+ setState(() => _rollingDownloadCount = value);
+ await PlayerSettings.setRollingDownloadCount(value);
+ unawaited(widget.lib.syncQueueAutoDownloads());
+ },
+ style: const ButtonStyle(
+ visualDensity: VisualDensity.compact,
+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ ),
+ )),
+ ]),
+ ),
+ ]),
+ ),
if (_queueMode != 'off')
Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 4),
@@ -1357,17 +1545,18 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {
])),
Switch(
value: _podcastAdvanceDir == 'newest_first',
- onChanged: (v) {
+ onChanged: (v) async {
final dir = v ? 'newest_first' : 'oldest_first';
setState(() => _podcastAdvanceDir = dir);
- PlayerSettings.setPodcastAdvanceDir(
+ await PlayerSettings.setPodcastAdvanceDir(
_currentPodcastShowId!, dir);
+ unawaited(widget.lib.syncQueueAutoDownloads());
},
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
]),
),
- if (_queueMode == 'auto_next' && !widget.isPodcast && _seriesId != null)
+ if (_queueMode == 'auto_next' && !_currentIsPodcast && _seriesId != null)
_modeHeaderButton(
cs, tt,
label: l.openSeries,
@@ -1482,7 +1671,7 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {
}
// A book library with nothing playing has no series context to load, so
// fall through to the manual queue rather than spinning forever.
- if (!widget.isPodcast && widget.currentItemId != null) {
+ if (!_currentIsPodcast && _currentItemId != null) {
return _buildSeriesList(cs, tt, l, bottomInset);
}
return _buildManualList(cs, tt, l, bottomInset);
@@ -1626,6 +1815,31 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {
);
}
+ Widget _downloadStatus(String key, ColorScheme cs) {
+ if (_downloads.isDownloaded(key)) {
+ return Padding(
+ padding: const EdgeInsets.only(left: 8),
+ child: Icon(Icons.download_done_rounded, size: 18, color: cs.primary),
+ );
+ }
+ if (_downloads.isDownloading(key)) {
+ final progress = _downloads.downloadProgress(key);
+ return Padding(
+ padding: const EdgeInsets.only(left: 8),
+ child: SizedBox(
+ width: 16,
+ height: 16,
+ child: CircularProgressIndicator(
+ value: progress > 0 ? progress : null,
+ strokeWidth: 2,
+ color: cs.primary,
+ ),
+ ),
+ );
+ }
+ return const SizedBox.shrink();
+ }
+
Widget _readOnlyQueueItem(
ColorScheme cs,
TextTheme tt,
@@ -1641,7 +1855,7 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {
final author = metadata['authorName'] as String? ?? '';
final epTitle = episodeOverride?['title'] as String?;
final isFinished = widget.lib.isItemFinishedByKey(key);
- final isPlaying = widget.currentItemId == key;
+ final isPlaying = _currentItemId == key;
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 2),
child: InkWell(
@@ -1653,11 +1867,12 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {
Navigator.pop(context);
final api = context.read<AuthProvider>().apiService;
if (api == null) return;
+ late Future<String?> playback;
if (key.length > 36) {
// podcast compound key
final showId = key.substring(0, 36);
final epId = key.substring(37);
- AudioPlayerService().playItem(
+ playback = AudioPlayerService().playItem(
api: api,
itemId: showId,
title: epTitle ?? title,
@@ -1670,7 +1885,7 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {
libraryId: book['libraryId'] as String? ?? widget.lib.selectedLibraryId,
);
} else {
- AudioPlayerService().playItem(
+ playback = AudioPlayerService().playItem(
api: api,
itemId: key,
title: title,
@@ -1681,6 +1896,11 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {
libraryId: book['libraryId'] as String? ?? widget.lib.selectedLibraryId,
);
}
+ unawaited(playback.then((error) async {
+ if (error == null) {
+ await widget.lib.syncQueueAutoDownloads();
+ }
+ }));
},
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
@@ -1746,6 +1966,7 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {
],
),
),
+ _downloadStatus(key, cs),
]),
),
),
@@ -1860,6 +2081,7 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {
style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
],
)),
+ _downloadStatus(key, cs),
// Drag handle (long-press to avoid conflict with system home gesture)
_DragHandle(index: i, color: cs.onSurface),
]),
diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart
index 279704cf..f635c261 100644
--- a/lib/screens/settings_screen.dart
+++ b/lib/screens/settings_screen.dart
@@ -78,6 +78,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
CardScrubberMode _cardScrubberMode = CardScrubberMode.chapter;
bool _notifChapterProgress = false;
bool _notifSpeedBookmark = false;
+ bool _duckBriefInterruptions = false;
bool _lockSeekBar = false;
bool _mp3IndexSeeking = false;
bool _speedAdjustedTime = true;
@@ -298,6 +299,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
_bookQueueMode = 'playlist';
_podcastQueueMode = 'playlist';
});
+ unawaited(context.read<LibraryProvider>().syncQueueAutoDownloads());
}
Future<void> _setBookQueueMode(String mode) async {
@@ -314,6 +316,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
if (wasPlaylist) _podcastQueueMode = mode;
});
PlayerSettings.notifySettingsChanged();
+ unawaited(context.read<LibraryProvider>().syncQueueAutoDownloads());
}
Future<void> _setPodcastQueueMode(String mode) async {
@@ -330,6 +333,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
if (wasPlaylist) _bookQueueMode = mode;
});
PlayerSettings.notifySettingsChanged();
+ unawaited(context.read<LibraryProvider>().syncQueueAutoDownloads());
}
Future<void> _setMergedQueueMode(String mode) async {
@@ -342,6 +346,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
_podcastQueueMode = mode;
});
PlayerSettings.notifySettingsChanged();
+ unawaited(context.read<LibraryProvider>().syncQueueAutoDownloads());
}
void _setManualColor(int argb) {
@@ -846,6 +851,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
final podcastTabEnabled = await PlayerSettings.getPodcastTabEnabled();
final podcastTabLibraryId = await PlayerSettings.getPodcastTabLibraryId();
final episodeNotifMinutes = await PlayerSettings.getEpisodeNotifIntervalMinutes();
+ final duckBriefInterruptions = await PlayerSettings.getDuckBriefInterruptions();
if (mounted) setState(() {
_podcastTabEnabled = podcastTabEnabled;
_podcastTabLibraryId = podcastTabLibraryId;
@@ -864,6 +870,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
_cardScrubberMode = cardScrubberMode;
_notifChapterProgress = notifChapter;
_notifSpeedBookmark = notifSpeedBookmark;
+ _duckBriefInterruptions = duckBriefInterruptions;
_lockSeekBar = lockSeek;
_speedAdjustedTime = speedAdj;
_forwardSkip = fwd;
@@ -1902,9 +1909,10 @@ class _SettingsScreenState extends State<SettingsScreen> {
: w.mergeLibrariesOffSubtitle,
style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
value: effectiveMerge,
- onChanged: (_loaded && !_podcastTabEnabled) ? (v) {
+ onChanged: (_loaded && !_podcastTabEnabled) ? (v) async {
setState(() => _mergeAbsorbingLibraries = v);
- PlayerSettings.setMergeAbsorbingLibraries(v);
+ await PlayerSettings.setMergeAbsorbingLibraries(v);
+ unawaited(lib.syncQueueAutoDownloads());
} : null,
);
},
@@ -2006,7 +2014,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
)),
],
],
- if (_bookQueueMode == 'manual' || _podcastQueueMode == 'manual') ...[
+ if (_bookQueueMode != 'off' || _podcastQueueMode != 'off') ...[
const SizedBox(height: 4),
SwitchListTile(
title: Text(l.autoDownloadQueue),
@@ -2016,9 +2024,10 @@ class _SettingsScreenState extends State<SettingsScreen> {
: l.autoDownloadQueueOffSubtitle,
style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
value: _queueAutoDownload,
- onChanged: _loaded ? (v) {
+ onChanged: _loaded ? (v) async {
setState(() => _queueAutoDownload = v);
- PlayerSettings.setQueueAutoDownload(v);
+ await PlayerSettings.setQueueAutoDownload(v);
+ unawaited(lib.syncQueueAutoDownloads());
} : null,
dense: true,
contentPadding: EdgeInsets.zero,
@@ -2471,6 +2480,20 @@ class _SettingsScreenState extends State<SettingsScreen> {
// Android only: chooses which pair fills the phone media
// player's two extra slots. iOS uses CarPlay's own buttons.
if (Platform.isAndroid) ...[
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ SwitchListTile(
+ title: const Text('Duck brief interruptions'),
+ subtitle: Text(
+ _duckBriefInterruptions
+ ? 'Notifications and prompts lower the volume instead of pausing'
+ : 'Notifications and prompts pause playback',
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _duckBriefInterruptions,
+ onChanged: _loaded ? (v) {
+ setState(() => _duckBriefInterruptions = v);
+ PlayerSettings.setDuckBriefInterruptions(v);
+ } : null,
+ ),
const Divider(height: 1, indent: 16, endIndent: 16),
SwitchListTile(
title: Text(l.speedBookmarkInControls),
@@ -2920,9 +2943,12 @@ class _SettingsScreenState extends State<SettingsScreen> {
ButtonSegment(value: 5, label: Text('5')),
],
selected: {_rollingDownloadCount},
- onSelectionChanged: (v) {
+ onSelectionChanged: (v) async {
setState(() => _rollingDownloadCount = v.first);
- PlayerSettings.setRollingDownloadCount(v.first);
+ await PlayerSettings.setRollingDownloadCount(v.first);
+ if (_queueAutoDownload) {
+ unawaited(lib.syncQueueAutoDownloads());
+ }
},
)),
const SizedBox(height: 8),
diff --git a/lib/services/android_auto_service.dart b/lib/services/android_auto_service.dart
index 7b2e5ac9..0d18f41e 100644
--- a/lib/services/android_auto_service.dart
+++ b/lib/services/android_auto_service.dart
@@ -211,8 +211,23 @@ class AndroidAutoService {
}
Timer? _downloadsRefreshDebounce;
+ String? _downloadsSignature;
+
+ String _currentDownloadsSignature() {
+ final entries = DownloadService()
+ .downloadedItems
+ .map((d) => '${d.itemId}|${d.title ?? ''}|${d.author ?? ''}|'
+ '${d.localCoverPath ?? ''}|${d.libraryId ?? ''}')
+ .toList()
+ ..sort();
+ return entries.join('\n');
+ }
+
void _onDownloadsChanged() {
- // Coalesce bursts (multiple state ticks during a download).
+ final signature = _currentDownloadsSignature();
+ if (signature == _downloadsSignature) return;
+ _downloadsSignature = signature;
+
_downloadsRefreshDebounce?.cancel();
_downloadsRefreshDebounce = Timer(const Duration(milliseconds: 500), () async {
await _refreshDownloaded();
@@ -450,16 +465,17 @@ class AndroidAutoService {
debugPrint('[AutoBrowse] notifyItemUpdated listener threw: $e');
}
if (Platform.isAndroid) {
- try {
- // ignore: deprecated_member_use
- AudioServiceBackground.notifyChildrenChanged(AutoMediaIds.root);
- } catch (_) {}
+ // ignore: deprecated_member_use
+ unawaited(AudioServiceBackground
+ .notifyChildrenChanged(AutoMediaIds.root)
+ .catchError((_) {}));
}
}
Future<void> _refreshDownloaded() async {
final ds = DownloadService();
final items = ds.downloadedItems;
+ _downloadsSignature = _currentDownloadsSignature();
final entries = <AutoBookEntry>[];
for (final dl in items) {
diff --git a/lib/services/api_service.dart b/lib/services/api_service.dart
index f34d1c49..89acf027 100644
--- a/lib/services/api_service.dart
+++ b/lib/services/api_service.dart
@@ -153,9 +153,11 @@ class ApiService {
final Duration _refreshRetryDelay;
- // Concurrency lock for refresh
+ // Each ApiService instance already deduplicates its own refreshes. This lock
+ // also serializes token rotation across the short-lived instances created by
+ // providers, widgets, and the background browse service.
Completer<_RefreshOutcome>? _refreshCompleter;
- Completer<void>? _tokenMutationCompleter;
+ static Completer<void>? _tokenMutationCompleter;
// Device info - set once at app start
static String deviceManufacturer = '';
@@ -211,6 +213,12 @@ class ApiService {
'Authorization': 'Bearer $_accessToken',
};
+ /// Playback-session tracks use ABS's unguessable public session URLs, so
+ /// only reverse-proxy headers belong on the media request. Keeping the
+ /// account token off the AVPlayer/ExoPlayer source prevents token rotation
+ /// from invalidating a stream that is already playing.
+ Map<String, String> get playbackSessionHeaders => {...customHeaders};
+
String get _cleanBaseUrl => normalizeServerUrl(baseUrl);
Future<http.Response> _get(Uri url, {Map<String, String>? headers}) {
@@ -1371,20 +1379,44 @@ class ApiService {
/// Build a full audio track URL from a contentUrl returned by the play session.
String buildTrackUrl(String contentUrl) {
- if (contentUrl.startsWith('http')) return contentUrl;
// ABS servers with ROUTER_BASE_PATH set return contentUrls that already
// include the base path (e.g. "/abs/public/session/.../track/0"). If the
// user's server URL also includes that base path, blindly concatenating
// would double it ("/abs/abs/..."). Detect and use origin only.
final baseUri = Uri.parse(_cleanBaseUrl);
final basePath = baseUri.path;
- if (basePath.isNotEmpty && contentUrl.startsWith('$basePath/')) {
- return '${baseUri.origin}$contentUrl?token=$token';
+ final isAbsolute = contentUrl.startsWith('http');
+ final Uri trackUri;
+ if (isAbsolute) {
+ trackUri = Uri.parse(contentUrl);
+ } else if (basePath.isNotEmpty && contentUrl.startsWith('$basePath/')) {
+ trackUri = Uri.parse('${baseUri.origin}$contentUrl');
+ } else {
+ trackUri = Uri.parse('$_cleanBaseUrl$contentUrl');
+ }
+
+ if (trackUri.path.contains('/public/session/')) {
+ final query = Map<String, dynamic>.from(trackUri.queryParametersAll)
+ ..remove('token');
+ if (query.isEmpty) {
+ final value = trackUri.toString();
+ final queryStart = value.indexOf('?');
+ if (queryStart < 0) return value;
+ final fragmentStart = value.indexOf('#', queryStart);
+ return value.substring(0, queryStart) +
+ (fragmentStart < 0 ? '' : value.substring(fragmentStart));
+ }
+ return trackUri.replace(queryParameters: query).toString();
}
+
+ if (isAbsolute) return contentUrl;
+
// No per-track logging here: this runs in a hot loop over every track, and
// books with thousands of files would flood (and roll over) the log buffer.
// The session's "First track contentUrl" line already gives a sample.
- return '$_cleanBaseUrl$contentUrl?token=$token';
+ final query = Map<String, dynamic>.from(trackUri.queryParametersAll)
+ ..['token'] = token;
+ return trackUri.replace(queryParameters: query).toString();
}
/// Build a durable, session-independent file download URL for [ino] within
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index de4006c1..e8e5ac82 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -29,6 +29,9 @@ import 'bookmark_service.dart';
import 'review_service.dart';
export 'player_settings.dart';
+String playbackDownloadKey(String itemId, String? episodeId) =>
+ episodeId == null ? itemId : '$itemId-$episodeId';
+
// ─── AudioHandler (runs in background, controls notification) ───
class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
@@ -83,19 +86,28 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
static Future<Map<String, dynamic>?> _absorbDiagSnapshot() async {
if (!Platform.isAndroid) return null;
try {
- return await _absorbDiagChannel.invokeMapMethod<String, dynamic>('snapshot');
+ return await _absorbDiagChannel.invokeMapMethod<String, dynamic>(
+ 'snapshot',
+ );
+ } on MissingPluginException {
+ return null;
} catch (e) {
debugPrint('[AbsorbDiag] snapshot failed: $e');
return null;
}
}
- static void _logAbsorbDiagFromSnapshot(String tag, Map<String, dynamic>? snap) {
+ static void _logAbsorbDiagFromSnapshot(
+ String tag,
+ Map<String, dynamic>? snap,
+ ) {
if (snap == null) return;
- debugPrint('[AbsorbDiag] $tag: '
- 'keyCode=${snap['lastKeyCode']} keyAgeMs=${snap['lastKeyAgeMs']} '
- 'lastPlayCaller=${snap['lastPlayCaller']} playAgeMs=${snap['lastPlayCallerAgeMs']} '
- 'lastPauseCaller=${snap['lastPauseCaller']} pauseAgeMs=${snap['lastPauseCallerAgeMs']}');
+ debugPrint(
+ '[AbsorbDiag] $tag: '
+ 'keyCode=${snap['lastKeyCode']} keyAgeMs=${snap['lastKeyAgeMs']} '
+ 'lastPlayCaller=${snap['lastPlayCaller']} playAgeMs=${snap['lastPlayCallerAgeMs']} '
+ 'lastPauseCaller=${snap['lastPauseCaller']} pauseAgeMs=${snap['lastPauseCallerAgeMs']}',
+ );
}
static Future<void> _logAbsorbDiag(String tag) async {
@@ -148,9 +160,7 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
_advanceBufferingMinimumTimer = null;
final changed = _advanceBuffering != value;
_advanceBuffering = value;
- _advanceBufferingUntil = value
- ? DateTime.now().add(minimumDuration)
- : null;
+ _advanceBufferingUntil = value ? DateTime.now().add(minimumDuration) : null;
if (value) _clearAdvanceBufferingIfReady();
if (!changed && !value) return;
refreshPlaybackState();
@@ -161,8 +171,8 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
_player.processingState != ProcessingState.ready) {
return;
}
- final remaining = _advanceBufferingUntil?.difference(DateTime.now()) ??
- Duration.zero;
+ final remaining =
+ _advanceBufferingUntil?.difference(DateTime.now()) ?? Duration.zero;
if (remaining > Duration.zero) {
_advanceBufferingMinimumTimer?.cancel();
_advanceBufferingMinimumTimer = Timer(remaining, () {
@@ -185,7 +195,8 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
// or at most every 5 seconds for position updates
final now = DateTime.now();
final playingChanged = _player.playing != _lastPlaying;
- final processingChanged = _player.processingState != _lastProcessingState;
+ final processingChanged =
+ _player.processingState != _lastProcessingState;
final elapsed = now.difference(_lastPlaybackStateUpdate);
if (playingChanged || processingChanged || elapsed.inSeconds >= 5) {
@@ -199,7 +210,9 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
},
onError: (Object e, StackTrace st) {
if (PlaybackErrorPolicy.isSourceError(e)) {
- debugPrint('[Player] playbackEvent source error - restarting stream: $e');
+ debugPrint(
+ '[Player] playbackEvent source error - restarting stream: $e',
+ );
AudioPlayerService()._attemptStreamRetry(e);
return;
}
@@ -213,11 +226,15 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
_resubscribeCount++;
if (_resubscribeCount <= 3) {
- debugPrint('[Player] playbackEvent error ($_resubscribeCount/3) - re-subscribing: $e');
+ debugPrint(
+ '[Player] playbackEvent error ($_resubscribeCount/3) - re-subscribing: $e',
+ );
refreshPlaybackState();
Future.delayed(const Duration(seconds: 1), _subscribePlaybackEvents);
} else {
- debugPrint('[Player] playbackEvent error - too many rapid failures, stopping re-subscribe: $e');
+ debugPrint(
+ '[Player] playbackEvent error - too many rapid failures, stopping re-subscribe: $e',
+ );
if (PlaybackErrorPolicy.shouldRetryWithTranscode(e)) {
AudioPlayerService()._retryWithTranscode();
}
@@ -226,17 +243,20 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
onDone: () {
_resubscribeCount++;
if (_resubscribeCount <= 3) {
- debugPrint('[Player] playbackEvent stream completed ($_resubscribeCount/3) - re-subscribing');
+ debugPrint(
+ '[Player] playbackEvent stream completed ($_resubscribeCount/3) - re-subscribing',
+ );
refreshPlaybackState();
Future.delayed(const Duration(seconds: 1), _subscribePlaybackEvents);
} else {
- debugPrint('[Player] playbackEvent stream completed - too many rapid re-subscribes, stopping');
+ debugPrint(
+ '[Player] playbackEvent stream completed - too many rapid re-subscribes, stopping',
+ );
}
},
);
}
-
// The Android Auto speed button shows a pre-baked badge for the current rate.
// We snap to the nearest 0.05 within the baked range (0.5x..3.0x); every step
// has a generated ic_speed_*x drawable (rendered from Roboto Bold).
@@ -270,7 +290,11 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
// Base 3 controls (rewind | play | forward) feed both the phone
// notification and Android Auto. compactIndices keeps the glanceable
// notification to just these three.
- final controls = <MediaControl>[rewindControl, playPause, fastForwardControl];
+ final controls = <MediaControl>[
+ rewindControl,
+ playPause,
+ fastForwardControl,
+ ];
final compactIndices = const [0, 1, 2];
// Extra Android Auto controls (custom actions). On Android 12 and below they
@@ -299,7 +323,9 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
// Bookmark icon/label briefly flip to a checkmark + "Saved" after a save,
// as on-screen confirmation for Android Auto (the CarPlay banner equivalent).
final bookmark = MediaControl.custom(
- androidIcon: _bookmarkSavedFlash ? 'drawable/ic_check' : 'drawable/ic_bookmark',
+ androidIcon: _bookmarkSavedFlash
+ ? 'drawable/ic_check'
+ : 'drawable/ic_bookmark',
label: _bookmarkSavedFlash ? 'Saved' : 'Bookmark',
name: 'bookmark',
);
@@ -389,11 +415,15 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
@override
Future<void> play() async {
- debugPrint('[Handler] play() called - routing to service (state=${_player.processingState.name})');
+ debugPrint(
+ '[Handler] play() called - routing to service (state=${_player.processingState.name})',
+ );
await _logAbsorbDiag('play');
final entryBt = await AudioPlayerService._isBluetoothAudioConnected();
if (entryBt) AudioPlayerService._lastPlayedOnBtAt = DateTime.now();
- debugPrint('[ClickDebug] play() entry: ${_clickDebugSnapshot(btNow: entryBt)}');
+ debugPrint(
+ '[ClickDebug] play() entry: ${_clickDebugSnapshot(btNow: entryBt)}',
+ );
// Mirror the click() guard: a raw play() arriving within 5s of a
// headphone/AA/BT disconnect is almost always the platform echoing a
// resume command, not the user. Drop it so playback doesn't jump to
@@ -401,7 +431,9 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
if (_noisyPauseAt != null) {
final elapsed = DateTime.now().difference(_noisyPauseAt!).inMilliseconds;
if (elapsed < 5000) {
- debugPrint('[Handler] Ignoring phantom play (${elapsed}ms after platform pause)');
+ debugPrint(
+ '[Handler] Ignoring phantom play (${elapsed}ms after platform pause)',
+ );
return;
}
_noisyPauseAt = null;
@@ -421,7 +453,9 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
debugPrint('[Handler] pause() called - routing to service');
await _logAbsorbDiag('pause');
final pauseEntryBt = await AudioPlayerService._isBluetoothAudioConnected();
- debugPrint('[ClickDebug] pause() entry: ${_clickDebugSnapshot(btNow: pauseEntryBt)}');
+ debugPrint(
+ '[ClickDebug] pause() entry: ${_clickDebugSnapshot(btNow: pauseEntryBt)}',
+ );
_lastHandlerPauseAt = DateTime.now();
// Android Auto disconnect can dispatch both a MediaButton click and a
// pause() action simultaneously. The click's 400ms debounce timer would
@@ -482,11 +516,17 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
// Alpha: stack trace tells us who is calling stop() so we can decide if
// any caller deserves a true teardown. Strip [Handler] stop trace before
// beta.
- debugPrint('[Handler] stop() - keeping MediaSession alive '
- '(playing=${_player.playing}, processingState=${_player.processingState.name}, '
- 'hasService=${_service != null})');
+ debugPrint(
+ '[Handler] stop() - keeping MediaSession alive '
+ '(playing=${_player.playing}, processingState=${_player.processingState.name}, '
+ 'hasService=${_service != null})',
+ );
debugPrint('[Handler] stop() trace:\n${StackTrace.current}');
- try { await _player.stop(); } catch (e) { debugPrint('[Handler] stop() player.stop error: $e'); }
+ try {
+ await _player.stop();
+ } catch (e) {
+ debugPrint('[Handler] stop() player.stop error: $e');
+ }
}
/// Called when the user swipes the app away from recents.
@@ -514,8 +554,11 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
Future<void> fastForward() async {
debugPrint('[Handler] fastForward() - seeking forward');
final skipAmount = await PlayerSettings.getEffectiveForwardSkip(
- libraryId: _service?.currentLibraryId);
- debugPrint('[SkipDebug] fastForward: lib=${_service?.currentLibraryId} amount=${skipAmount}s');
+ libraryId: _service?.currentLibraryId,
+ );
+ debugPrint(
+ '[SkipDebug] fastForward: lib=${_service?.currentLibraryId} amount=${skipAmount}s',
+ );
if (_service != null) {
await _service!.skipForward(skipAmount);
} else {
@@ -528,8 +571,11 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
Future<void> rewind() async {
debugPrint('[Handler] rewind() - seeking back');
final skipAmount = await PlayerSettings.getEffectiveBackSkip(
- libraryId: _service?.currentLibraryId);
- debugPrint('[SkipDebug] rewind: lib=${_service?.currentLibraryId} amount=${skipAmount}s');
+ libraryId: _service?.currentLibraryId,
+ );
+ debugPrint(
+ '[SkipDebug] rewind: lib=${_service?.currentLibraryId} amount=${skipAmount}s',
+ );
if (_service != null) {
await _service!.skipBackward(skipAmount);
} else {
@@ -589,7 +635,9 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
}
int sinceForegroundMs = -1;
if (AudioPlayerService._lastForegroundAt != null) {
- sinceForegroundMs = now.difference(AudioPlayerService._lastForegroundAt!).inMilliseconds;
+ sinceForegroundMs = now
+ .difference(AudioPlayerService._lastForegroundAt!)
+ .inMilliseconds;
}
int sinceNoisyPauseMs = -1;
if (_noisyPauseAt != null) {
@@ -599,10 +647,11 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
// Variant-3 fingerprint: raw pause fires within 5s of a click-initiated
// play while still playing in background. Flag it so the pause log line
// is self-describing without having to cross-reference timestamps.
- final phantomSuspect = sincePrevPlayMs >= 0
- && sincePrevPlayMs < 5000
- && _player.playing
- && (backgrounded ?? false);
+ final phantomSuspect =
+ sincePrevPlayMs >= 0 &&
+ sincePrevPlayMs < 5000 &&
+ _player.playing &&
+ (backgrounded ?? false);
// AA-disconnect fingerprint: BT/AA was the audio route within the last
// 10 min, isn't anymore, and the click came in while bg + not playing.
int sinceBtMs = -1;
@@ -612,10 +661,8 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
if (btNow == null) {
aaDisconnect = 'unknown';
} else {
- final fired = lastBt != null
- && !btNow
- && sinceBtMs >= 0
- && sinceBtMs < 600000;
+ final fired =
+ lastBt != null && !btNow && sinceBtMs >= 0 && sinceBtMs < 600000;
aaDisconnect = fired ? 'true' : 'false';
}
return 'bg=$backgrounded, sincePrevPauseMs=$sincePrevPauseMs, '
@@ -632,7 +679,9 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
@override
Future<void> click([MediaButton button = MediaButton.media]) async {
- debugPrint('[Handler] click(button=$button) count=${_clickCount + 1} playing=${_player.playing}');
+ debugPrint(
+ '[Handler] click(button=$button) count=${_clickCount + 1} playing=${_player.playing}',
+ );
final diagSnap = await _absorbDiagSnapshot();
_logAbsorbDiagFromSnapshot('click', diagSnap);
// Pre-fetch BT-route state so the snapshot can fill in the AA-disconnect
@@ -640,7 +689,10 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
final btNow = await AudioPlayerService._isBluetoothAudioConnected();
final snapshot = _clickDebugSnapshot(btNow: btNow);
debugPrint('[ClickDebug] click arrival (button=$button): $snapshot');
- _service?._logEvent(PlaybackEventType.clickDebounce, detail: 'button=$button | $snapshot');
+ _service?._logEvent(
+ PlaybackEventType.clickDebounce,
+ detail: 'button=$button | $snapshot',
+ );
if (button != MediaButton.media) {
// Hardware next/prev button — set cooldown to ignore phantom media click
@@ -657,9 +709,13 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
// Ignore phantom media click that follows hardware next/prev within 500ms
if (_hardwareButtonTime != null) {
- final elapsed = DateTime.now().difference(_hardwareButtonTime!).inMilliseconds;
+ final elapsed = DateTime.now()
+ .difference(_hardwareButtonTime!)
+ .inMilliseconds;
if (elapsed < 500) {
- debugPrint('[Handler] Ignoring phantom media click (${elapsed}ms after hardware button)');
+ debugPrint(
+ '[Handler] Ignoring phantom media click (${elapsed}ms after hardware button)',
+ );
_hardwareButtonTime = null;
return;
}
@@ -670,7 +726,9 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
if (_noisyPauseAt != null) {
final elapsed = DateTime.now().difference(_noisyPauseAt!).inMilliseconds;
if (elapsed < 5000) {
- debugPrint('[Handler] Ignoring phantom click (${elapsed}ms after noisy pause)');
+ debugPrint(
+ '[Handler] Ignoring phantom click (${elapsed}ms after noisy pause)',
+ );
return;
}
_noisyPauseAt = null;
@@ -686,10 +744,14 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
if (bg && !_player.playing && lastBt != null && !btNow) {
final ageMs = DateTime.now().difference(lastBt).inMilliseconds;
if (ageMs < 600000) {
- debugPrint('[Handler] Ignoring phantom click after AA/BT disconnect '
- '(${ageMs}ms since last BT-on, btNow=false, bg=true, playing=false)');
- _service?._logEvent(PlaybackEventType.clickDebounce,
- detail: 'phantom AA/BT click suppressed | sinceBtMs=$ageMs');
+ debugPrint(
+ '[Handler] Ignoring phantom click after AA/BT disconnect '
+ '(${ageMs}ms since last BT-on, btNow=false, bg=true, playing=false)',
+ );
+ _service?._logEvent(
+ PlaybackEventType.clickDebounce,
+ detail: 'phantom AA/BT click suppressed | sinceBtMs=$ageMs',
+ );
// Re-arm the 5s noisy guard so a follow-up click in the same
// burst is also ignored, matching the BT-disconnect suppression flow.
_noisyPauseAt = DateTime.now();
@@ -715,9 +777,13 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
_clickTimer = Timer(const Duration(milliseconds: 400), () async {
final count = _clickCount;
_clickCount = 0;
- debugPrint('[Handler] click resolved: count=$count playing=${_player.playing}');
+ debugPrint(
+ '[Handler] click resolved: count=$count playing=${_player.playing}',
+ );
final resolveBt = await AudioPlayerService._isBluetoothAudioConnected();
- debugPrint('[ClickDebug] click resolve (count=$count): ${_clickDebugSnapshot(btNow: resolveBt)}');
+ debugPrint(
+ '[ClickDebug] click resolve (count=$count): ${_clickDebugSnapshot(btNow: resolveBt)}',
+ );
switch (count) {
case 1:
_inClickResolver = true;
@@ -739,14 +805,18 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
debugPrint('[Handler] → single press (MEDIA_PAUSE) → PAUSE');
await pause();
} else {
- debugPrint('[Handler] → single press (MEDIA_PAUSE while paused) → no-op (suppressed phantom toggle to PLAY)');
+ debugPrint(
+ '[Handler] → single press (MEDIA_PAUSE while paused) → no-op (suppressed phantom toggle to PLAY)',
+ );
}
} else if (kc == keycodeMediaPlay) {
if (!_player.playing) {
debugPrint('[Handler] → single press (MEDIA_PLAY) → PLAY');
await play();
} else {
- debugPrint('[Handler] → single press (MEDIA_PLAY while playing) → no-op');
+ debugPrint(
+ '[Handler] → single press (MEDIA_PLAY while playing) → no-op',
+ );
}
} else if (_player.playing) {
debugPrint('[Handler] → single press → PAUSE');
@@ -787,7 +857,10 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
Future<void> setSpeed(double speed) => _player.setSpeed(speed);
@override
- Future<dynamic> customAction(String name, [Map<String, dynamic>? extras]) async {
+ Future<dynamic> customAction(
+ String name, [
+ Map<String, dynamic>? extras,
+ ]) async {
debugPrint('[Handler] customAction($name)');
switch (name) {
case 'nextChapter':
@@ -893,8 +966,10 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
final _autoService = AndroidAutoService();
@override
- Future<List<MediaItem>> getChildren(String parentMediaId,
- [Map<String, dynamic>? options]) async {
+ Future<List<MediaItem>> getChildren(
+ String parentMediaId, [
+ Map<String, dynamic>? options,
+ ]) async {
debugPrint('[Handler] getChildren($parentMediaId)');
// Don't await refresh() here — getChildrenOf() handles it:
// downloads are populated instantly, server data loads in background.
@@ -908,22 +983,28 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
}
@override
- Future<List<MediaItem>> search(String query,
- [Map<String, dynamic>? extras]) async {
+ Future<List<MediaItem>> search(
+ String query, [
+ Map<String, dynamic>? extras,
+ ]) async {
debugPrint('[Handler] search("$query")');
return _autoService.search(query);
}
@override
- Future<void> prepareFromMediaId(String mediaId,
- [Map<String, dynamic>? extras]) async {
+ Future<void> prepareFromMediaId(
+ String mediaId, [
+ Map<String, dynamic>? extras,
+ ]) async {
debugPrint('[Handler] prepareFromMediaId($mediaId)');
await _playFromAutoMediaId(mediaId);
}
@override
- Future<void> playFromMediaId(String mediaId,
- [Map<String, dynamic>? extras]) async {
+ Future<void> playFromMediaId(
+ String mediaId, [
+ Map<String, dynamic>? extras,
+ ]) async {
debugPrint('[Handler] playFromMediaId($mediaId)');
await _playFromAutoMediaId(mediaId);
}
@@ -962,7 +1043,9 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
if (entry == null) {
final ds = DownloadService();
if (ds.isDownloaded(absId)) {
- debugPrint('[Handler] Item not in AA cache but downloaded locally: $absId');
+ debugPrint(
+ '[Handler] Item not in AA cache but downloaded locally: $absId',
+ );
final dl = ds.getInfo(absId);
double duration = 0;
List<dynamic> chapters = [];
@@ -1038,7 +1121,9 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
return;
}
- debugPrint('[Handler] Android Auto play: "${entry.title}" by ${entry.author}');
+ debugPrint(
+ '[Handler] Android Auto play: "${entry.title}" by ${entry.author}',
+ );
// Always generate a fresh HTTP cover URL for Now Playing — api is
// available here, so use it directly rather than relying on the cached
@@ -1087,9 +1172,11 @@ class AudioPlayerService extends ChangeNotifier {
// natively (no fresh setAudioSource in background, so iOS keeps granting
// audio output). The map must contain at least: itemId, title, author,
// duration, and either localPaths or audioTracks.
- static Future<Map<String, dynamic>?> Function(String currentItemId)? _onPeekNextItemCallback;
+ static Future<Map<String, dynamic>?> Function(String currentItemId)?
+ _onPeekNextItemCallback;
static void setOnPeekNextItemCallback(
- Future<Map<String, dynamic>?> Function(String)? cb) {
+ Future<Map<String, dynamic>?> Function(String)? cb,
+ ) {
_onPeekNextItemCallback = cb;
}
@@ -1115,7 +1202,9 @@ class AudioPlayerService extends ChangeNotifier {
// Drop the stale completion instead.
final loaded = _instance._currentItemId;
if (loaded != null) {
- debugPrint('[Player] Dropping stale book-finished drain (player has item=$loaded, buffered key=$pending)');
+ debugPrint(
+ '[Player] Dropping stale book-finished drain (player has item=$loaded, buffered key=$pending)',
+ );
return;
}
@@ -1125,8 +1214,11 @@ class AudioPlayerService extends ChangeNotifier {
/// Called when a new item starts playing. Used by LibraryProvider to trigger
/// rolling downloads for the next items in a series/podcast.
- static void Function(String key)? _onPlayStartedCallback;
- static void setOnPlayStartedCallback(void Function(String key)? cb) {
+ static Future<void> Function(String key, double duration)?
+ _onPlayStartedCallback;
+ static void setOnPlayStartedCallback(
+ Future<void> Function(String key, double duration)? cb,
+ ) {
_onPlayStartedCallback = cb;
}
@@ -1140,7 +1232,9 @@ class AudioPlayerService extends ChangeNotifier {
/// Called when playback state changes (playing/paused). Used by
/// LibraryProvider for battery-saving socket lifecycle.
static void Function(bool isPlaying)? _onPlaybackStateChangedCallback;
- static void setOnPlaybackStateChangedCallback(void Function(bool isPlaying)? cb) {
+ static void setOnPlaybackStateChangedCallback(
+ void Function(bool isPlaying)? cb,
+ ) {
_onPlaybackStateChangedCallback = cb;
}
@@ -1171,6 +1265,7 @@ class AudioPlayerService extends ChangeNotifier {
ApiService? _api;
ApiService? get currentApi => _api;
String? _playbackSessionId;
+
/// Phase 1.7: latest streaming URLs (with auth token already in the
/// query string) and custom HTTP headers needed by reverse proxies like
/// Cloudflare Access. Stashed to the iOS app group on each player update
@@ -1247,6 +1342,7 @@ class AudioPlayerService extends ChangeNotifier {
_advanceBufferingBackstop = null;
_handler?.setAdvanceBuffering(false);
}
+
/// Last known position in seconds — used to detect end→0 position jumps.
double _lastKnownPositionSec = 0;
// ── Stream error retry tracking ──
@@ -1310,11 +1406,18 @@ class AudioPlayerService extends ChangeNotifier {
_notifChapterMode = v;
// Re-push MediaItem + PlaybackState so notification updates immediately
if (_currentItemId != null) {
- _pushMediaItem(_mediaItemKey, _currentTitle ?? '', _currentAuthor ?? '',
- _currentCoverUrl, _totalDuration,
- chapter: _lastNotifiedChapterIndex >= 0 && _chapters.isNotEmpty
- ? (_chapters[_lastNotifiedChapterIndex] as Map<String, dynamic>)['title'] as String?
- : null);
+ _pushMediaItem(
+ _mediaItemKey,
+ _currentTitle ?? '',
+ _currentAuthor ?? '',
+ _currentCoverUrl,
+ _totalDuration,
+ chapter: _lastNotifiedChapterIndex >= 0 && _chapters.isNotEmpty
+ ? (_chapters[_lastNotifiedChapterIndex]
+ as Map<String, dynamic>)['title']
+ as String?
+ : null,
+ );
_handler?.refreshPlaybackState();
}
});
@@ -1332,6 +1435,17 @@ class AudioPlayerService extends ChangeNotifier {
_handler!.refreshPlaybackState();
}
});
+ if (Platform.isAndroid) {
+ PlayerSettings.getDuckBriefInterruptions().then((v) async {
+ if (v == _duckBriefInterruptions) return;
+ final previousVolume = _volumeBeforeInterruptionDuck;
+ _volumeBeforeInterruptionDuck = null;
+ if (previousVolume != null) {
+ await _player?.setVolume(previousVolume);
+ }
+ await _configureAudioSession();
+ });
+ }
}
/// Refresh the notification's cached skip labels with the amounts for the
@@ -1340,7 +1454,9 @@ class AudioPlayerService extends ChangeNotifier {
void _syncNotifSkipCache() {
final libId = _currentLibraryId;
PlayerSettings.getEffectiveForwardSkip(libraryId: libId).then((v) {
- debugPrint('[SkipDebug] notif cache: lib=$libId fwd=${v}s (was ${_handler?._cachedForwardSkip})');
+ debugPrint(
+ '[SkipDebug] notif cache: lib=$libId fwd=${v}s (was ${_handler?._cachedForwardSkip})',
+ );
if (_handler != null && v != _handler!._cachedForwardSkip) {
_handler!._cachedForwardSkip = v;
_handler!.refreshPlaybackState();
@@ -1365,7 +1481,9 @@ class AudioPlayerService extends ChangeNotifier {
final key = episodeId != null ? '$itemId-$episodeId' : itemId;
final fromDownload = DownloadService().getInfo(key).libraryId;
if (fromDownload != null && fromDownload.isNotEmpty) {
- debugPrint('[SkipDebug] libraryId resolved from download metadata: $fromDownload');
+ debugPrint(
+ '[SkipDebug] libraryId resolved from download metadata: $fromDownload',
+ );
_currentLibraryId = fromDownload;
return;
}
@@ -1419,7 +1537,11 @@ class AudioPlayerService extends ChangeNotifier {
final _history = PlaybackHistoryService();
/// Log a playback event to history.
- void _logEvent(PlaybackEventType type, {String? detail, double? overridePosition}) {
+ void _logEvent(
+ PlaybackEventType type, {
+ String? detail,
+ double? overridePosition,
+ }) {
if (_currentItemId == null) return;
_history.log(
itemId: _currentItemId!,
@@ -1433,7 +1555,8 @@ class AudioPlayerService extends ChangeNotifier {
final h = d.inHours;
final m = d.inMinutes % 60;
final s = d.inSeconds % 60;
- if (h > 0) return '$h:${m.toString().padLeft(2, '0')}:${s.toString().padLeft(2, '0')}';
+ if (h > 0)
+ return '$h:${m.toString().padLeft(2, '0')}:${s.toString().padLeft(2, '0')}';
return '$m:${s.toString().padLeft(2, '0')}';
}
@@ -1442,7 +1565,8 @@ class AudioPlayerService extends ChangeNotifier {
String? get currentAuthor => _currentAuthor;
String? get currentCoverUrl => _currentCoverUrl;
double get totalDuration => _totalDuration;
- double get displayDuration => _metaDuration > 0 ? _metaDuration : _totalDuration;
+ double get displayDuration =>
+ _metaDuration > 0 ? _metaDuration : _totalDuration;
List<dynamic> get chapters => _chapters;
/// GH #298: how every "now playing" surface (lock screen, CarPlay, Android
@@ -1451,7 +1575,10 @@ class AudioPlayerService extends ChangeNotifier {
/// Chapterless content (podcasts, books with no chapters) keeps the
/// book/episode on the primary line.
static ({String title, String subtitle}) nowPlayingLabels(
- String primaryTitle, String author, String? chapter) {
+ String primaryTitle,
+ String author,
+ String? chapter,
+ ) {
final ch = chapter?.trim() ?? '';
if (ch.isEmpty) return (title: primaryTitle, subtitle: author);
final a = author.trim();
@@ -1467,26 +1594,36 @@ class AudioPlayerService extends ChangeNotifier {
}
/// Chapter-aware primary line for the current item (GH #298).
- String get nowPlayingTitle => nowPlayingLabels(_currentTitle ?? '',
- _currentAuthor ?? '', currentChapter?['title'] as String?).title;
+ String get nowPlayingTitle => nowPlayingLabels(
+ _currentTitle ?? '',
+ _currentAuthor ?? '',
+ currentChapter?['title'] as String?,
+ ).title;
/// Chapter-aware secondary line ("Author · Book") for the current item.
- String get nowPlayingSubtitle => nowPlayingLabels(_currentTitle ?? '',
- _currentAuthor ?? '', currentChapter?['title'] as String?).subtitle;
+ String get nowPlayingSubtitle => nowPlayingLabels(
+ _currentTitle ?? '',
+ _currentAuthor ?? '',
+ currentChapter?['title'] as String?,
+ ).subtitle;
void updateChapters(List<dynamic> chapters) {
_chapters = chapters;
_handler?.updateChaptersQueue(chapters);
notifyListeners();
}
+
bool get hasBook => _currentItemId != null;
+
/// True when a loaded item is in an active session - playing OR paused.
/// stop() drops the engine to idle while keeping _currentItemId, so this is
/// false for a stopped session even though [hasBook] stays true.
bool get hasActiveSession =>
_currentItemId != null &&
- (_player?.processingState ?? ProcessingState.idle) != ProcessingState.idle;
+ (_player?.processingState ?? ProcessingState.idle) !=
+ ProcessingState.idle;
bool get isPlaying => _player?.playing ?? false;
+
/// True while [playItem] is setting up a new audio source.
bool _isLoadingNewItem = false;
bool get isLoadingNewItem => _isLoadingNewItem;
@@ -1495,13 +1632,15 @@ class AudioPlayerService extends ChangeNotifier {
final s = _player?.processingState;
return s == ProcessingState.loading || s == ProcessingState.buffering;
}
+
bool get isOfflineMode => _isOfflineMode;
double get volume => _player?.volume ?? 1.0;
Future<void> setVolume(double v) async => _player?.setVolume(v);
static const _eqChannelForDiag = MethodChannel('com.absorb.equalizer');
- static const _queueAdvancerChannel = MethodChannel('com.absorb.queue_advancer');
-
+ static const _queueAdvancerChannel = MethodChannel(
+ 'com.absorb.queue_advancer',
+ );
void _resetPreBufferState() {
_activeConcatSource = null;
_currentBookTrackCount = 0;
@@ -1536,7 +1675,9 @@ class AudioPlayerService extends ChangeNotifier {
}
Future<void> _preloadNextBookAsync(
- Future<Map<String, dynamic>?> Function(String) cb, String currentId) async {
+ Future<Map<String, dynamic>?> Function(String) cb,
+ String currentId,
+ ) async {
try {
final next = await cb(currentId);
if (next == null) {
@@ -1570,11 +1711,15 @@ class AudioPlayerService extends ChangeNotifier {
nextTrackSources = localPaths.map((p) => localAudioSource(p)).toList();
} else if (audioTracks != null && audioTracks.isNotEmpty) {
nextTrackSources = audioTracks
- .map((t) => AudioSource.uri(
- Uri.parse((t as Map<String, dynamic>)['url'] as String),
- headers: audioHeaders,
- options: mp3ExtractorOptions(),
- ) as AudioSource)
+ .map(
+ (t) =>
+ AudioSource.uri(
+ Uri.parse((t as Map<String, dynamic>)['url'] as String),
+ headers: audioHeaders,
+ options: mp3ExtractorOptions(),
+ )
+ as AudioSource,
+ )
.toList();
}
if (nextTrackSources == null || nextTrackSources.isEmpty) {
@@ -1582,7 +1727,9 @@ class AudioPlayerService extends ChangeNotifier {
return;
}
if (nextTrackSources.length != 1) {
- debugPrint('[PreBuffer] Next item is multi-track, skipping (MVP supports single-track only)');
+ debugPrint(
+ '[PreBuffer] Next item is multi-track, skipping (MVP supports single-track only)',
+ );
return;
}
@@ -1602,7 +1749,9 @@ class AudioPlayerService extends ChangeNotifier {
return;
}
_preloadedNextBook = next;
- debugPrint('[PreBuffer] Pre-loaded native: ${next['title']} ($nextItemId) start=${startS.toStringAsFixed(1)}s');
+ debugPrint(
+ '[PreBuffer] Pre-loaded native: ${next['title']} ($nextItemId) start=${startS.toStringAsFixed(1)}s',
+ );
return;
}
@@ -1615,11 +1764,20 @@ class AudioPlayerService extends ChangeNotifier {
await concat.add(s);
}
_preloadedNextBook = next;
- debugPrint('[PreBuffer] Pre-loaded next item: ${next['title']} ($nextItemId)');
+ debugPrint(
+ '[PreBuffer] Pre-loaded next item: ${next['title']} ($nextItemId)',
+ );
if (Platform.isIOS) {
// Legacy native queue advancer kick (flag-off path).
- unawaited(_primeNativeQueueAdvancer(next, localPaths, audioTracks, audioHeaders));
+ unawaited(
+ _primeNativeQueueAdvancer(
+ next,
+ localPaths,
+ audioTracks,
+ audioHeaders,
+ ),
+ );
}
} catch (e, st) {
debugPrint('[PreBuffer] Failed: $e\n$st');
@@ -1629,10 +1787,11 @@ class AudioPlayerService extends ChangeNotifier {
}
Future<bool> _primeNativeQueueAdvancer(
- Map<String, dynamic> next,
- List<String>? localPaths,
- List<dynamic>? audioTracks,
- Map<String, String>? audioHeaders) async {
+ Map<String, dynamic> next,
+ List<String>? localPaths,
+ List<dynamic>? audioTracks,
+ Map<String, String>? audioHeaders,
+ ) async {
try {
String? url;
bool isLocal = false;
@@ -1656,9 +1815,13 @@ class AudioPlayerService extends ChangeNotifier {
// GH #298: label the pre-buffered next book like the lock screen — its
// chapter at the resume point as title, "Author · Book" beneath.
final nextLabels = nowPlayingLabels(
- (next['title'] as String?) ?? '',
- (next['author'] as String?) ?? '',
- _chapterTitleAt((next['chapters'] as List<dynamic>?) ?? const [], startS));
+ (next['title'] as String?) ?? '',
+ (next['author'] as String?) ?? '',
+ _chapterTitleAt(
+ (next['chapters'] as List<dynamic>?) ?? const [],
+ startS,
+ ),
+ );
final ok = await _queueAdvancerChannel.invokeMethod<bool>('prepareNext', {
'url': url,
@@ -1688,7 +1851,9 @@ class AudioPlayerService extends ChangeNotifier {
final oldItemId = _currentItemId;
final oldEpisodeId = _currentEpisodeId;
- final oldKey = oldEpisodeId != null ? '$oldItemId-$oldEpisodeId' : oldItemId;
+ final oldKey = oldEpisodeId != null
+ ? '$oldItemId-$oldEpisodeId'
+ : oldItemId;
// Promote next book's metadata to current state
_currentItemId = next['itemId'] as String?;
@@ -1715,15 +1880,23 @@ class AudioPlayerService extends ChangeNotifier {
// Push new media item to update Now Playing / lock screen
final initChapter = _initChapterInfo(startS);
- _pushMediaItem(_currentItemId!, _currentTitle ?? '', _currentAuthor ?? '',
- _currentCoverUrl, _totalDuration,
- chapter: initChapter);
- unawaited(_primeNowPlaying(
+ _pushMediaItem(
+ _currentItemId!,
+ _currentTitle ?? '',
+ _currentAuthor ?? '',
+ _currentCoverUrl,
+ _totalDuration,
+ chapter: initChapter,
+ );
+ unawaited(
+ _primeNowPlaying(
title: _currentTitle ?? '',
artist: _currentAuthor ?? '',
duration: _totalDuration,
elapsed: startS,
- chapter: initChapter));
+ chapter: initChapter,
+ ),
+ );
if (Platform.isIOS) {
unawaited(_iosAutoAdvanceKick());
@@ -1757,9 +1930,10 @@ class AudioPlayerService extends ChangeNotifier {
}
if (_isBackgrounded) {
try {
- final ok = await _queueAdvancerChannel.invokeMethod<bool>('commitAdvance', {
- 'speed': speed,
- });
+ final ok = await _queueAdvancerChannel.invokeMethod<bool>(
+ 'commitAdvance',
+ {'speed': speed},
+ );
if (ok == true) {
_iosResyncPending = true;
debugPrint('[QueueAdvance] native commit succeeded, resync armed');
@@ -1789,12 +1963,16 @@ class AudioPlayerService extends ChangeNotifier {
}
double startS = 0;
try {
- final pos = await _queueAdvancerChannel.invokeMethod<double>('getPositionS');
+ final pos = await _queueAdvancerChannel.invokeMethod<double>(
+ 'getPositionS',
+ );
if (pos != null && pos > 0) startS = pos;
} catch (e) {
debugPrint('[QueueAdvance] getPositionS failed: $e');
}
- debugPrint('[QueueAdvance] Resyncing just_audio for $itemId at ${startS.toStringAsFixed(1)}s');
+ debugPrint(
+ '[QueueAdvance] Resyncing just_audio for $itemId at ${startS.toStringAsFixed(1)}s',
+ );
try {
await playItem(
api: api,
@@ -1833,8 +2011,10 @@ class AudioPlayerService extends ChangeNotifier {
// Engine isn't on our book (stopped, disposed, or swapped) - nothing to
// adopt; the normal play()/idle-reinit path will rebuild if needed.
if (!state.isLoaded || state.itemId != itemId) {
- debugPrint('[Player] iOS resume: engine not on current book '
- '(engine=${state.itemId} loaded=${state.isLoaded}) - skipping adopt');
+ debugPrint(
+ '[Player] iOS resume: engine not on current book '
+ '(engine=${state.itemId} loaded=${state.isLoaded}) - skipping adopt',
+ );
return;
}
// Sync our track index to whatever track the engine actually reached while
@@ -1842,7 +2022,9 @@ class AudioPlayerService extends ChangeNotifier {
if (_trackStartOffsets.length > 1) {
final clamped = state.trackIndex.clamp(0, _trackStartOffsets.length - 2);
if (clamped != _currentTrackIndex) {
- debugPrint('[Player] iOS resume: track index $_currentTrackIndex -> $clamped (from engine)');
+ debugPrint(
+ '[Player] iOS resume: track index $_currentTrackIndex -> $clamped (from engine)',
+ );
_currentTrackIndex = clamped;
}
}
@@ -1850,14 +2032,17 @@ class AudioPlayerService extends ChangeNotifier {
// the handler re-publish so the lock screen / notification reflect reality.
final wasPlaying = isPlaying;
player.adoptPlayingState(state.isPlaying);
- debugPrint('[Player] iOS resume: adopted engine state playing=${state.isPlaying} '
- '(was $wasPlaying) global=${state.globalPositionS.toStringAsFixed(1)}s');
+ debugPrint(
+ '[Player] iOS resume: adopted engine state playing=${state.isPlaying} '
+ '(was $wasPlaying) global=${state.globalPositionS.toStringAsFixed(1)}s',
+ );
// Persist the adopted position locally so a subsequent sync/save doesn't
// overwrite it with a stale value.
if (state.globalPositionS > 0) {
_lastKnownPositionSec = state.globalPositionS;
await _saveProgressLocal(
- Duration(milliseconds: (state.globalPositionS * 1000).round()));
+ Duration(milliseconds: (state.globalPositionS * 1000).round()),
+ );
}
_handler?.refreshPlaybackState();
notifyListeners();
@@ -1880,7 +2065,9 @@ class AudioPlayerService extends ChangeNotifier {
'duration': duration,
'elapsed': elapsed,
});
- debugPrint('[Player] primeNowPlaying title="${labels.title}" elapsed=${elapsed.toStringAsFixed(1)}');
+ debugPrint(
+ '[Player] primeNowPlaying title="${labels.title}" elapsed=${elapsed.toStringAsFixed(1)}',
+ );
} catch (e) {
debugPrint('[Player] primeNowPlaying failed: $e');
}
@@ -1915,9 +2102,9 @@ class AudioPlayerService extends ChangeNotifier {
final info = await _eqChannelForDiag
.invokeMethod<Map<dynamic, dynamic>>('getAudioDiagnostics');
if (info != null) {
- final outputs = (info['outputs'] as List?)
- ?.map((o) =>
- '${(o as Map)["type"]}:${o["name"]}')
+ final outputs =
+ (info['outputs'] as List?)
+ ?.map((o) => '${(o as Map)["type"]}:${o["name"]}')
.join(',') ??
'?';
pieces.addAll([
@@ -1951,9 +2138,18 @@ class AudioPlayerService extends ChangeNotifier {
/// position-stuck-at-0" is a classic no-sound fingerprint).
void _scheduleAudioDiagnostics(String startStage) {
_logAudioDiagnostics('$startStage:t0');
- Future.delayed(const Duration(seconds: 1), () => _logAudioDiagnostics('$startStage:t1s'));
- Future.delayed(const Duration(seconds: 3), () => _logAudioDiagnostics('$startStage:t3s'));
- Future.delayed(const Duration(seconds: 10), () => _logAudioDiagnostics('$startStage:t10s'));
+ Future.delayed(
+ const Duration(seconds: 1),
+ () => _logAudioDiagnostics('$startStage:t1s'),
+ );
+ Future.delayed(
+ const Duration(seconds: 3),
+ () => _logAudioDiagnostics('$startStage:t3s'),
+ );
+ Future.delayed(
+ const Duration(seconds: 10),
+ () => _logAudioDiagnostics('$startStage:t10s'),
+ );
}
Stream<Duration> get positionStream =>
@@ -1987,7 +2183,8 @@ class AudioPlayerService extends ChangeNotifier {
Stream<Duration> get absolutePositionStream {
if (_player == null) return const Stream.empty();
return _player!.positionStream.map((trackRelative) {
- if (_trackStartOffsets.length <= 1) return trackRelative; // single file, no offset
+ if (_trackStartOffsets.length <= 1)
+ return trackRelative; // single file, no offset
final trackIdx = _currentTrackIndex;
final offsetMs = (_trackStartOffsets[trackIdx] * 1000).round();
final absolute = trackRelative + Duration(milliseconds: offsetMs);
@@ -2024,38 +2221,45 @@ class AudioPlayerService extends ChangeNotifier {
urls.add(api.buildTrackUrl(contentUrl));
}
_activeStreamUrls = urls;
- _activeStreamHeaders = Map<String, String>.from(api.mediaHeaders);
+ _activeStreamHeaders = Map<String, String>.from(api.playbackSessionHeaders);
}
/// Subscribe to track index changes for multi-file playback.
void _subscribeTrackIndex() {
_indexSub?.cancel();
if (_player == null) return;
- _indexSub = _player!.currentIndexStream.listen((index) {
- if (index == null) return;
- // Pre-buffer auto-advance: if the queue has grown past the current
- // book's tracks and AVQueuePlayer has stepped into the pre-loaded
- // next book's range, fire the book transition.
- if (_currentBookTrackCount > 0 &&
- index >= _currentBookTrackCount &&
- _preloadedNextBook != null) {
- debugPrint('[PreBuffer] currentIndex=$index crossed book boundary at $_currentBookTrackCount');
- _onAutoQueueAdvanced();
- return;
- }
- // Within-book multi-track advance (existing behavior).
- if (_trackStartOffsets.length > 1) {
- final clamped = index.clamp(0, _trackStartOffsets.length - 2);
- if (clamped != _currentTrackIndex) {
- _lastIndexAdvanceTime = DateTime.now();
- _pendingTrackAdvanceRefresh = true;
- debugPrint('[Player] Track index advance: $_currentTrackIndex -> $clamped');
+ _indexSub = _player!.currentIndexStream.listen(
+ (index) {
+ if (index == null) return;
+ // Pre-buffer auto-advance: if the queue has grown past the current
+ // book's tracks and AVQueuePlayer has stepped into the pre-loaded
+ // next book's range, fire the book transition.
+ if (_currentBookTrackCount > 0 &&
+ index >= _currentBookTrackCount &&
+ _preloadedNextBook != null) {
+ debugPrint(
+ '[PreBuffer] currentIndex=$index crossed book boundary at $_currentBookTrackCount',
+ );
+ _onAutoQueueAdvanced();
+ return;
}
- _currentTrackIndex = clamped;
- }
- }, onError: (Object e, StackTrace st) {
- debugPrint('[Player] Index stream error: $e');
- });
+ // Within-book multi-track advance (existing behavior).
+ if (_trackStartOffsets.length > 1) {
+ final clamped = index.clamp(0, _trackStartOffsets.length - 2);
+ if (clamped != _currentTrackIndex) {
+ _lastIndexAdvanceTime = DateTime.now();
+ _pendingTrackAdvanceRefresh = true;
+ debugPrint(
+ '[Player] Track index advance: $_currentTrackIndex -> $clamped',
+ );
+ }
+ _currentTrackIndex = clamped;
+ }
+ },
+ onError: (Object e, StackTrace st) {
+ debugPrint('[Player] Index stream error: $e');
+ },
+ );
}
/// Seek to an absolute book position, handling multi-file offset conversion.
@@ -2076,7 +2280,9 @@ class AudioPlayerService extends ChangeNotifier {
if (_trackStartOffsets.length <= 1) {
// Single file — seek directly
- await _player!.seek(Duration(milliseconds: (absoluteSeconds * 1000).round()));
+ await _player!.seek(
+ Duration(milliseconds: (absoluteSeconds * 1000).round()),
+ );
notifyListeners();
return;
}
@@ -2088,7 +2294,10 @@ class AudioPlayerService extends ChangeNotifier {
final localOffset = absoluteSeconds - trackStart;
// Update index BEFORE seeking so positionStream events use the right offset
_currentTrackIndex = i;
- await _player!.seek(Duration(milliseconds: (localOffset * 1000).round()), index: i);
+ await _player!.seek(
+ Duration(milliseconds: (localOffset * 1000).round()),
+ index: i,
+ );
notifyListeners();
return;
}
@@ -2174,7 +2383,8 @@ class AudioPlayerService extends ChangeNotifier {
}
}
// Load notification chapter progress setting and watch for changes
- _instance._notifChapterMode = await PlayerSettings.getNotificationChapterProgress();
+ _instance._notifChapterMode =
+ await PlayerSettings.getNotificationChapterProgress();
PlayerSettings.settingsChanged.addListener(_instance._onSettingsChanged);
// Configure audio session for audiobook playback
await _configureAudioSession();
@@ -2198,6 +2408,8 @@ class AudioPlayerService extends ChangeNotifier {
static bool _noisyPause = false;
// Whether BT audio was connected when the current interruption began.
static bool _wasOnBluetooth = false;
+ static bool _duckBriefInterruptions = false;
+ static double? _volumeBeforeInterruptionDuck;
// Last time the app entered the foreground. Used by [ClickDebug] to see
// whether a MediaSession click's 400ms debounce window overlapped with
// an app-foreground event — the fingerprint of an Android Auto disconnect
@@ -2216,7 +2428,9 @@ class AudioPlayerService extends ChangeNotifier {
/// Check if BT audio (A2DP/SCO) is currently connected via native AudioManager.
static Future<bool> _isBluetoothAudioConnected() async {
try {
- final result = await _eqChannel.invokeMethod<bool>('isBluetoothAudioConnected');
+ final result = await _eqChannel.invokeMethod<bool>(
+ 'isBluetoothAudioConnected',
+ );
return result ?? false;
} catch (e) {
debugPrint('[AudioSession] BT check failed: $e');
@@ -2230,27 +2444,31 @@ class AudioPlayerService extends ChangeNotifier {
static Future<void> _configureAudioSession() async {
final session = await AudioSession.instance;
-
- await session.configure(AudioSessionConfiguration(
- // iOS: playback category — no duckOthers so iOS properly recognises this
- // app as the Now Playing app and shows lock screen / Control Center controls.
- avAudioSessionCategory: AVAudioSessionCategory.playback,
- avAudioSessionMode: AVAudioSessionMode.spokenAudio,
- avAudioSessionRouteSharingPolicy:
- AVAudioSessionRouteSharingPolicy.longFormAudio,
- avAudioSessionCategoryOptions: Platform.isIOS
- ? AVAudioSessionCategoryOptions.none
- : AVAudioSessionCategoryOptions.duckOthers,
- // Android: speech content type enables OS voice-intelligibility
- // processing so audiobooks play at normal listening levels. Matches the
- // reference ABS Android client.
- androidAudioAttributes: AndroidAudioAttributes(
- contentType: AndroidAudioContentType.speech,
- usage: AndroidAudioUsage.media,
+ _duckBriefInterruptions =
+ Platform.isAndroid && await PlayerSettings.getDuckBriefInterruptions();
+
+ await session.configure(
+ AudioSessionConfiguration(
+ // iOS: playback category — no duckOthers so iOS properly recognises this
+ // app as the Now Playing app and shows lock screen / Control Center controls.
+ avAudioSessionCategory: AVAudioSessionCategory.playback,
+ avAudioSessionMode: AVAudioSessionMode.spokenAudio,
+ avAudioSessionRouteSharingPolicy:
+ AVAudioSessionRouteSharingPolicy.longFormAudio,
+ avAudioSessionCategoryOptions: Platform.isIOS
+ ? AVAudioSessionCategoryOptions.none
+ : AVAudioSessionCategoryOptions.duckOthers,
+ // Android: speech content type enables OS voice-intelligibility
+ // processing so audiobooks play at normal listening levels. Matches the
+ // reference ABS Android client.
+ androidAudioAttributes: AndroidAudioAttributes(
+ contentType: AndroidAudioContentType.speech,
+ usage: AndroidAudioUsage.media,
+ ),
+ androidAudioFocusGainType: AndroidAudioFocusGainType.gain,
+ androidWillPauseWhenDucked: !_duckBriefInterruptions,
),
- androidAudioFocusGainType: AndroidAudioFocusGainType.gain,
- androidWillPauseWhenDucked: true,
- ));
+ );
// Don't activate the session here — defer to first playback.
// Activating during init creates a stale MediaSession that Android
// can garbage-collect after hours in background, leaving bluetooth /
@@ -2258,89 +2476,140 @@ class AudioPlayerService extends ChangeNotifier {
// play() and startLocalPlayback() call setActive(true) before playing.
_interruptSub?.cancel();
- _interruptSub = session.interruptionEventStream.listen((event) async {
- try {
- final service = _instance;
+ _interruptSub = session.interruptionEventStream.listen(
+ (event) async {
+ try {
+ final service = _instance;
- if (event.begin) {
- if (service.isPlaying) {
- debugPrint('[AudioSession] Interrupted (${event.type}) — pausing');
- _wasOnBluetooth = await _isBluetoothAudioConnected();
- if (_wasOnBluetooth) _lastPlayedOnBtAt = DateTime.now();
- debugPrint('[AudioSession] Was on BT: $_wasOnBluetooth');
- // Pause the underlying player directly, not service.pause(), to keep
- // the interruption lightweight (service.pause() also saves and syncs,
- // which a transient duck doesn't need). Still stamp _lastPauseTime so
- // resume runs auto-rewind per the user's settings: calls and nav
- // prompts rewind like a manual pause, gated by activationDelay.
- await service._player?.pause();
- service._lastPauseTime = DateTime.now();
- service._wasPlayingBeforeInterrupt = true;
- }
- } else {
- // Don't auto-resume if the pause was caused by BT/headphone disconnect.
- // Some devices fire interruption-end AFTER becoming-noisy, which would
- // resume playback on the phone speaker.
- if (_noisyPause) {
- debugPrint('[AudioSession] Interruption ended after noisy — skipping resume');
- service._wasPlayingBeforeInterrupt = false;
- return;
- }
- if (service._wasPlayingBeforeInterrupt) {
- service._wasPlayingBeforeInterrupt = false;
- await Future.delayed(const Duration(milliseconds: 600));
- // Re-check: another event (like becoming-noisy) might have fired
- // during the delay.
- if (_noisyPause) return;
- // Don't double-resume: Assistant may already have called play().
- if (service._player?.playing == true) return;
- // If we were on BT when interrupted, check if BT is still connected.
- // Some car head units never send AUDIO_BECOMING_NOISY on disconnect,
- // so _noisyPause alone is not enough.
- if (_wasOnBluetooth) {
- final stillOnBt = await _isBluetoothAudioConnected();
- debugPrint('[AudioSession] Interruption ended — was BT, still BT: $stillOnBt');
- if (!stillOnBt) {
- debugPrint('[AudioSession] BT disconnected during interruption — skipping resume');
- _noisyPause = true;
- return;
+ if (event.begin) {
+ if (event.type == AudioInterruptionType.duck &&
+ _duckBriefInterruptions) {
+ if (service.isPlaying && _volumeBeforeInterruptionDuck == null) {
+ final currentVolume = service._player?.volume ?? 1.0;
+ _volumeBeforeInterruptionDuck = currentVolume;
+ await service._player?.setVolume(
+ (currentVolume * 0.35).clamp(0.0, 1.0).toDouble(),
+ );
+ debugPrint(
+ '[AudioSession] Interrupted (${event.type}) — ducking',
+ );
+ }
+ return;
+ }
+
+ final duckedVolume = _volumeBeforeInterruptionDuck;
+ if (duckedVolume != null) {
+ _volumeBeforeInterruptionDuck = null;
+ await service._player?.setVolume(duckedVolume);
+ }
+ if (service.isPlaying) {
+ debugPrint(
+ '[AudioSession] Interrupted (${event.type}) — pausing',
+ );
+ _wasOnBluetooth = await _isBluetoothAudioConnected();
+ if (_wasOnBluetooth) _lastPlayedOnBtAt = DateTime.now();
+ debugPrint('[AudioSession] Was on BT: $_wasOnBluetooth');
+ // Pause the underlying player directly, not service.pause(), to keep
+ // the interruption lightweight (service.pause() also saves and syncs,
+ // which a transient duck doesn't need). Still stamp _lastPauseTime so
+ // resume runs auto-rewind per the user's settings: calls and nav
+ // prompts rewind like a manual pause, gated by activationDelay.
+ await service._player?.pause();
+ service._lastPauseTime = DateTime.now();
+ service._wasPlayingBeforeInterrupt = true;
+ }
+ } else {
+ if (event.type == AudioInterruptionType.duck &&
+ _duckBriefInterruptions) {
+ final previousVolume = _volumeBeforeInterruptionDuck;
+ _volumeBeforeInterruptionDuck = null;
+ if (previousVolume != null) {
+ await service._player?.setVolume(previousVolume);
+ debugPrint(
+ '[AudioSession] Interruption ended — volume restored',
+ );
+ }
+ return;
+ }
+
+ // Don't auto-resume if the pause was caused by BT/headphone disconnect.
+ // Some devices fire interruption-end AFTER becoming-noisy, which would
+ // resume playback on the phone speaker.
+ if (_noisyPause) {
+ debugPrint(
+ '[AudioSession] Interruption ended after noisy — skipping resume',
+ );
+ service._wasPlayingBeforeInterrupt = false;
+ return;
+ }
+ if (service._wasPlayingBeforeInterrupt) {
+ service._wasPlayingBeforeInterrupt = false;
+ await Future.delayed(const Duration(milliseconds: 600));
+ // Re-check: another event (like becoming-noisy) might have fired
+ // during the delay.
+ if (_noisyPause) return;
+ // Don't double-resume: Assistant may already have called play().
+ if (service._player?.playing == true) return;
+ // If we were on BT when interrupted, check if BT is still connected.
+ // Some car head units never send AUDIO_BECOMING_NOISY on disconnect,
+ // so _noisyPause alone is not enough.
+ if (_wasOnBluetooth) {
+ final stillOnBt = await _isBluetoothAudioConnected();
+ debugPrint(
+ '[AudioSession] Interruption ended — was BT, still BT: $stillOnBt',
+ );
+ if (!stillOnBt) {
+ debugPrint(
+ '[AudioSession] BT disconnected during interruption — skipping resume',
+ );
+ _noisyPause = true;
+ return;
+ }
+ _lastPlayedOnBtAt = DateTime.now();
}
- _lastPlayedOnBtAt = DateTime.now();
+ debugPrint('[AudioSession] Interruption ended — resuming');
+ await service.play(logDetail: 'Auto-resumed after interruption');
}
- debugPrint('[AudioSession] Interruption ended — resuming');
- await service.play(logDetail: 'Auto-resumed after interruption');
}
+ } catch (e) {
+ debugPrint('[AudioSession] Interruption handler error: $e');
}
- } catch (e) {
- debugPrint('[AudioSession] Interruption handler error: $e');
- }
- }, onError: (e) {
- debugPrint('[AudioSession] Interruption stream error - re-subscribing: $e');
- _configureAudioSession();
- });
+ },
+ onError: (e) {
+ debugPrint(
+ '[AudioSession] Interruption stream error - re-subscribing: $e',
+ );
+ _configureAudioSession();
+ },
+ );
// Headphones unplugged / BT disconnected — pause, no auto-resume
_noisySub?.cancel();
- _noisySub = session.becomingNoisyEventStream.listen((_) async {
- try {
- final service = _instance;
- debugPrint('[AudioSession] Becoming noisy — pausing');
- debugPrint('[ClickDebug] becoming-noisy fired: bg=${service._isBackgrounded}, playing=${service.isPlaying}');
- _noisyPause = true;
- service._wasPlayingBeforeInterrupt = false;
- // Cancel any pending media-button click from the BT disconnect so the
- // delayed click handler doesn't resume playback on the phone speaker.
- _handler?.cancelPendingClick();
- if (service.isPlaying) {
- await service.pause();
+ _noisySub = session.becomingNoisyEventStream.listen(
+ (_) async {
+ try {
+ final service = _instance;
+ debugPrint('[AudioSession] Becoming noisy — pausing');
+ debugPrint(
+ '[ClickDebug] becoming-noisy fired: bg=${service._isBackgrounded}, playing=${service.isPlaying}',
+ );
+ _noisyPause = true;
+ service._wasPlayingBeforeInterrupt = false;
+ // Cancel any pending media-button click from the BT disconnect so the
+ // delayed click handler doesn't resume playback on the phone speaker.
+ _handler?.cancelPendingClick();
+ if (service.isPlaying) {
+ await service.pause();
+ }
+ } catch (e) {
+ debugPrint('[AudioSession] Noisy handler error: $e');
}
- } catch (e) {
- debugPrint('[AudioSession] Noisy handler error: $e');
- }
- }, onError: (e) {
- debugPrint('[AudioSession] Noisy stream error - re-subscribing: $e');
- _configureAudioSession();
- });
+ },
+ onError: (e) {
+ debugPrint('[AudioSession] Noisy stream error - re-subscribing: $e');
+ _configureAudioSession();
+ },
+ );
// Pause when an output route we could be playing through disappears, even
// if another output stays connected - the silent-playback case becomingNoisy
@@ -2349,32 +2618,42 @@ class AudioPlayerService extends ChangeNotifier {
// you weren't actually listening on, undone with a single tap on play.
_devicesSub?.cancel();
if (Platform.isAndroid) {
- _devicesSub = session.devicesChangedEventStream.listen((event) async {
- try {
- final service = _instance;
- if (!service.isPlaying) return;
- final lost = event.devicesRemoved
- .where((d) => d.isOutput && externalAudioOutputTypes.contains(d.type))
- .toSet();
- if (lost.isEmpty) return;
- // Settle re-check: some devices briefly drop and re-add a route when
- // playback starts. Only pause if the output is genuinely gone.
- await Future.delayed(const Duration(milliseconds: 500));
- if (!service.isPlaying) return;
- final current = await session.getDevices(includeInputs: false);
- if (!lost.any((d) => !current.contains(d))) return;
- debugPrint('[AudioSession] Output route removed while playing - pausing');
- _noisyPause = true;
- service._wasPlayingBeforeInterrupt = false;
- _handler?.cancelPendingClick();
- if (service.isPlaying) await service.pause();
- } catch (e) {
- debugPrint('[AudioSession] Device-change handler error: $e');
- }
- }, onError: (e) {
- debugPrint('[AudioSession] Device-change stream error - re-subscribing: $e');
- _configureAudioSession();
- });
+ _devicesSub = session.devicesChangedEventStream.listen(
+ (event) async {
+ try {
+ final service = _instance;
+ if (!service.isPlaying) return;
+ final lost = event.devicesRemoved
+ .where(
+ (d) =>
+ d.isOutput && externalAudioOutputTypes.contains(d.type),
+ )
+ .toSet();
+ if (lost.isEmpty) return;
+ // Settle re-check: some devices briefly drop and re-add a route when
+ // playback starts. Only pause if the output is genuinely gone.
+ await Future.delayed(const Duration(milliseconds: 500));
+ if (!service.isPlaying) return;
+ final current = await session.getDevices(includeInputs: false);
+ if (!lost.any((d) => !current.contains(d))) return;
+ debugPrint(
+ '[AudioSession] Output route removed while playing - pausing',
+ );
+ _noisyPause = true;
+ service._wasPlayingBeforeInterrupt = false;
+ _handler?.cancelPendingClick();
+ if (service.isPlaying) await service.pause();
+ } catch (e) {
+ debugPrint('[AudioSession] Device-change handler error: $e');
+ }
+ },
+ onError: (e) {
+ debugPrint(
+ '[AudioSession] Device-change stream error - re-subscribing: $e',
+ );
+ _configureAudioSession();
+ },
+ );
}
}
@@ -2400,15 +2679,22 @@ class AudioPlayerService extends ChangeNotifier {
int sincePrevPlayMs = -1;
if (handler != null) {
if (handler._lastHandlerPauseAt != null) {
- sincePrevPauseMs = _lastForegroundAt!.difference(handler._lastHandlerPauseAt!).inMilliseconds;
+ sincePrevPauseMs = _lastForegroundAt!
+ .difference(handler._lastHandlerPauseAt!)
+ .inMilliseconds;
}
if (handler._lastHandlerPlayAt != null) {
- sincePrevPlayMs = _lastForegroundAt!.difference(handler._lastHandlerPlayAt!).inMilliseconds;
+ sincePrevPlayMs = _lastForegroundAt!
+ .difference(handler._lastHandlerPlayAt!)
+ .inMilliseconds;
}
}
- final aaDisconnectSuspect = sincePrevPauseMs >= 0 && sincePrevPauseMs < 3000;
- debugPrint('[ClickDebug] App foregrounded: sincePrevPauseMs=$sincePrevPauseMs, '
- 'sincePrevPlayMs=$sincePrevPlayMs, aaDisconnectSuspect=$aaDisconnectSuspect');
+ final aaDisconnectSuspect =
+ sincePrevPauseMs >= 0 && sincePrevPauseMs < 3000;
+ debugPrint(
+ '[ClickDebug] App foregrounded: sincePrevPauseMs=$sincePrevPauseMs, '
+ 'sincePrevPlayMs=$sincePrevPlayMs, aaDisconnectSuspect=$aaDisconnectSuspect',
+ );
service._positionSyncFailures = 0; // retry on foreground
if (Platform.isIOS && service._iosResyncPending) {
unawaited(service._iosForegroundResyncIfNeeded());
@@ -2421,17 +2707,21 @@ class AudioPlayerService extends ChangeNotifier {
}
if (!service.hasBook) return;
final sessionAlive = service._playbackSessionId != null;
- debugPrint('[MediaSession] Foregrounded - refreshing (playing=${service.isPlaying}, session=$sessionAlive, item=${service._currentItemId})');
+ debugPrint(
+ '[MediaSession] Foregrounded - refreshing (playing=${service.isPlaying}, session=$sessionAlive, item=${service._currentItemId})',
+ );
// Alpha: when session=false, the playback session was closed (pause
// timeout) and likely handler.stop() ran too. Log handler state so we
// can see whether the MediaSession is recoverable. Strip before beta.
if (!sessionAlive && handler != null) {
try {
final ps = handler.playbackState.value;
- debugPrint('[MediaSession] Recovery diagnostic: handlerPlaying=${ps.playing}, '
- 'processingState=${ps.processingState.name}, '
- 'playerPlaying=${handler.player.playing}, '
- 'playerProcessing=${handler.player.processingState.name}');
+ debugPrint(
+ '[MediaSession] Recovery diagnostic: handlerPlaying=${ps.playing}, '
+ 'processingState=${ps.processingState.name}, '
+ 'playerPlaying=${handler.player.playing}, '
+ 'playerProcessing=${handler.player.processingState.name}',
+ );
} catch (e) {
debugPrint('[MediaSession] Recovery diagnostic error: $e');
}
@@ -2440,7 +2730,9 @@ class AudioPlayerService extends ChangeNotifier {
service.notifyListeners();
// Flush overdue server sync
if (service.isPlaying && service._currentItemId != null) {
- final sinceSync = DateTime.now().difference(service._lastServerSync).inSeconds;
+ final sinceSync = DateTime.now()
+ .difference(service._lastServerSync)
+ .inSeconds;
if (sinceSync > 60) {
service._syncToServer(service.position);
}
@@ -2452,14 +2744,19 @@ class AudioPlayerService extends ChangeNotifier {
// playing we don't need focus; the MediaSession refresh below doesn't
// require it, and play()/startLocalPlayback reacquire focus themselves.
if (service.isPlaying) {
- try { (await AudioSession.instance).setActive(true); } catch (_) {}
+ try {
+ (await AudioSession.instance).setActive(true);
+ } catch (_) {}
}
// Re-push playback state so the system re-registers the MediaSession
_handler?.refreshPlaybackState();
// Re-push media item so notification metadata is fresh
if (service._currentItemId != null && service._currentTitle != null) {
- final chapterTitle = service._lastNotifiedChapterIndex >= 0 && service._chapters.isNotEmpty
- ? (service._chapters[service._lastNotifiedChapterIndex] as Map<String, dynamic>)['title'] as String?
+ final chapterTitle =
+ service._lastNotifiedChapterIndex >= 0 && service._chapters.isNotEmpty
+ ? (service._chapters[service._lastNotifiedChapterIndex]
+ as Map<String, dynamic>)['title']
+ as String?
: null;
service._pushMediaItem(
service._mediaItemKey,
@@ -2520,9 +2817,11 @@ class AudioPlayerService extends ChangeNotifier {
// Alpha: catalog every playItem caller so we can find the phantom
// resume that fires after an AA disconnect without going through
// Handler.play() / Service.play(). Strip before next beta.
- debugPrint('[PlayItemEntry] itemId=$itemId episodeId=$episodeId '
- 'startTime=$startTime forceStartTime=$forceStartTime\n'
- 'Caller:\n${StackTrace.current}');
+ debugPrint(
+ '[PlayItemEntry] itemId=$itemId episodeId=$episodeId '
+ 'startTime=$startTime forceStartTime=$forceStartTime\n'
+ 'Caller:\n${StackTrace.current}',
+ );
// Don't start local playback while casting
final cast = ChromecastService();
@@ -2557,7 +2856,9 @@ class AudioPlayerService extends ChangeNotifier {
_currentItemId = itemId;
_currentEpisodeId = episodeId;
_currentLibraryId = libraryId;
- debugPrint('[SkipDebug] playItem libraryId=$libraryId (item=$itemId ep=$episodeId)');
+ debugPrint(
+ '[SkipDebug] playItem libraryId=$libraryId (item=$itemId ep=$episodeId)',
+ );
_resolveMissingLibraryId(itemId, episodeId);
_syncNotifSkipCache();
// Reset local-session mode for every new play; _playFromLocal re-enables it
@@ -2577,10 +2878,14 @@ class AudioPlayerService extends ChangeNotifier {
SleepTimerService().resetDismiss();
// Progress key: compound for episodes, plain for books
- final progressKey = episodeId != null ? '$itemId-$episodeId' : itemId;
+ final progressKey = playbackDownloadKey(itemId, episodeId);
// Notify rolling download listener that a new item is playing
- _onPlayStartedCallback?.call(progressKey);
+ try {
+ await _onPlayStartedCallback?.call(progressKey, totalDuration);
+ } catch (e) {
+ debugPrint('[Player] Playback-start preparation failed: $e');
+ }
// Check for local saved position (skip if startTime was forced).
// Always prefer the local position when it's further ahead - the
@@ -2593,7 +2898,9 @@ class AudioPlayerService extends ChangeNotifier {
(localProgressAtStart?['timestamp'] as num?)?.toInt() ?? 0;
if (localPos > 0 && !forceStartTime) {
if (startTime == 0 || localPos > startTime + 1.0) {
- debugPrint('[Player] Resuming from local position: ${localPos}s (caller startTime was ${startTime}s)');
+ debugPrint(
+ '[Player] Resuming from local position: ${localPos}s (caller startTime was ${startTime}s)',
+ );
startTime = localPos;
}
}
@@ -2602,14 +2909,18 @@ class AudioPlayerService extends ChangeNotifier {
// That matters on Android Auto cold starts, where a long-lived headless
// engine can have an older browse entry and an older preferences snapshot.
if (!forceStartTime) {
- final stashedPos = await HomeWidgetService()
- .getStashedNowPlayingPosition(itemId, episodeId);
+ final stashedPos = await HomeWidgetService().getStashedNowPlayingPosition(
+ itemId,
+ episodeId,
+ );
final newerStashedPos = HomeWidgetService.newerStashedNowPlayingPosition(
startTime,
stashedPos,
);
if (newerStashedPos != null) {
- debugPrint('[Player] Resuming from stashed widget position: ${newerStashedPos}s (was ${startTime}s)');
+ debugPrint(
+ '[Player] Resuming from stashed widget position: ${newerStashedPos}s (was ${startTime}s)',
+ );
startTime = newerStashedPos;
localTimestampAtStart = DateTime.now().millisecondsSinceEpoch;
}
@@ -2640,14 +2951,24 @@ class AudioPlayerService extends ChangeNotifier {
// Check if downloaded — play locally
String? result;
if (_downloadService.isDownloaded(progressKey)) {
- result = await _playFromLocal(progressKey, title, author, coverUrl,
- totalDuration, chapters, startTime, forceStartTime);
+ result = await _playFromLocal(
+ progressKey,
+ title,
+ author,
+ coverUrl,
+ totalDuration,
+ chapters,
+ startTime,
+ forceStartTime,
+ );
} else {
// Check manual offline — don't stream from server
final prefs = await SharedPreferences.getInstance();
final manualOffline = prefs.getBool('manual_offline_mode') ?? false;
if (manualOffline) {
- debugPrint('[Player] Manual offline — cannot stream non-downloaded item');
+ debugPrint(
+ '[Player] Manual offline — cannot stream non-downloaded item',
+ );
_endAdvanceBuffering();
_clearState();
return 'This item isn\'t downloaded and offline mode is on';
@@ -2658,20 +2979,47 @@ class AudioPlayerService extends ChangeNotifier {
episodeId: episodeId,
);
if (cachedSession != null) {
- result = await _playFromSessionCache(api, itemId, title, author,
- coverUrl, totalDuration, chapters, startTime, cachedSession,
- localTimestampAtStart, playbackGeneration, forceStartTime);
+ result = await _playFromSessionCache(
+ api,
+ itemId,
+ title,
+ author,
+ coverUrl,
+ totalDuration,
+ chapters,
+ startTime,
+ cachedSession,
+ localTimestampAtStart,
+ playbackGeneration,
+ forceStartTime,
+ );
// Fall through to normal server path if cache was stale/invalid
if (result == 'cache-miss') {
- result = await _playFromServer(api, itemId, title, author, coverUrl,
- totalDuration, chapters, startTime,
- forceStartTime: forceStartTime);
+ result = await _playFromServer(
+ api,
+ itemId,
+ title,
+ author,
+ coverUrl,
+ totalDuration,
+ chapters,
+ startTime,
+ forceStartTime: forceStartTime,
+ );
}
} else {
// No cache - stream from server
- result = await _playFromServer(api, itemId, title, author, coverUrl,
- totalDuration, chapters, startTime,
- forceStartTime: forceStartTime);
+ result = await _playFromServer(
+ api,
+ itemId,
+ title,
+ author,
+ coverUrl,
+ totalDuration,
+ chapters,
+ startTime,
+ forceStartTime: forceStartTime,
+ );
}
}
@@ -2690,7 +3038,8 @@ class AudioPlayerService extends ChangeNotifier {
// re-orientation time regardless of playback speed - at 1.5x a 2s
// setting covers 3s of book content (= 2s of real listening time).
final currentSpeed = _player!.speed;
- var newPosSeconds = currentAbsolutePos - (rewindSeconds * currentSpeed);
+ var newPosSeconds =
+ currentAbsolutePos - (rewindSeconds * currentSpeed);
if (newPosSeconds < 0) newPosSeconds = 0;
if (rewindSettings.chapterBarrier && _chapters.isNotEmpty) {
for (final ch in _chapters) {
@@ -2711,8 +3060,9 @@ class AudioPlayerService extends ChangeNotifier {
: '${rewindSeconds.toStringAsFixed(1)}s (${actualDelta.toStringAsFixed(1)}s at ${currentSpeed.toStringAsFixed(2)}x, session start)';
_logEvent(PlaybackEventType.autoRewind, detail: detail);
debugPrint(
- '[Player] Session-start rewind ${rewindSeconds.toStringAsFixed(1)}s '
- '(${actualDelta.toStringAsFixed(1)}s at ${currentSpeed.toStringAsFixed(2)}x)');
+ '[Player] Session-start rewind ${rewindSeconds.toStringAsFixed(1)}s '
+ '(${actualDelta.toStringAsFixed(1)}s at ${currentSpeed.toStringAsFixed(2)}x)',
+ );
}
}
}
@@ -2727,15 +3077,26 @@ class AudioPlayerService extends ChangeNotifier {
/// Hot-swap from streaming to local files without interrupting playback position.
/// Called when a download completes for the currently-playing item.
Future<bool> switchToLocal(String itemId) async {
- if (_currentItemId != itemId) return false;
+ final currentItemId = _currentItemId;
+ if (currentItemId == null ||
+ playbackDownloadKey(currentItemId, _currentEpisodeId) != itemId) {
+ return false;
+ }
if (!_downloadService.isDownloaded(itemId)) return false;
if (_player == null) return false;
final wasPlaying = _player!.playing;
final currentAbsolutePos = position; // use absolute position getter
final currentSpeed = _player!.speed;
+ final reportingCutoverAt = DateTime.now();
+ final finalStreamingSeconds = reportingCutoverAt
+ .difference(_lastServerSync)
+ .inSeconds
+ .clamp(0, 300);
- debugPrint('[Player] Hot-swapping to local files at ${currentAbsolutePos.inSeconds}s');
+ debugPrint(
+ '[Player] Hot-swapping to local files at ${currentAbsolutePos.inSeconds}s',
+ );
final localPaths = _downloadService.getLocalPaths(itemId);
if (localPaths == null || localPaths.isEmpty) return false;
@@ -2781,6 +3142,11 @@ class AudioPlayerService extends ChangeNotifier {
// Resume if was playing
if (wasPlaying) _player!.play();
+ await _switchHotSwapReportingToLocal(
+ position: currentAbsolutePos,
+ streamingSeconds: finalStreamingSeconds,
+ );
+
_logEvent(PlaybackEventType.play, detail: 'Switched to local playback');
debugPrint('[Player] Hot-swap complete — now playing from local files');
notifyListeners();
@@ -2791,6 +3157,83 @@ class AudioPlayerService extends ChangeNotifier {
}
}
+ Future<void> _switchHotSwapReportingToLocal({
+ required Duration position,
+ required int streamingSeconds,
+ }) async {
+ if (_localSessionMode || _currentItemId == null) return;
+
+ final api = _api;
+ final streamingSessionId = _playbackSessionId;
+ final progressKey = playbackDownloadKey(
+ _currentItemId!,
+ _currentEpisodeId,
+ );
+ final currentTime = position.inMilliseconds / 1000.0;
+
+ try {
+ await LocalSessionService().beginSession(
+ progressKey: progressKey,
+ libraryItemId: _currentItemId!,
+ episodeId: _currentEpisodeId,
+ mediaType: _currentEpisodeId != null ? 'podcast' : 'book',
+ duration: _totalDuration,
+ startTime: currentTime,
+ displayTitle: _currentTitle,
+ displayAuthor: _currentAuthor,
+ );
+ } catch (e) {
+ debugPrint('[Player] Failed to start LOCAL reporting after hot-swap: $e');
+ return;
+ }
+
+ _logEvent(PlaybackEventType.sessionEnd, detail: 'stream hot-swap');
+ _localSessionMode = true;
+ _playbackSessionId = null;
+ _activeStreamUrls = const [];
+ _activeStreamHeaders = const {};
+ _lastServerSync = DateTime.now();
+ _lastAccrual = _lastServerSync;
+ _logEvent(PlaybackEventType.sessionStart, detail: 'local hot-swap');
+
+ if (api == null || streamingSessionId == null) return;
+
+ try {
+ final pendingBefore =
+ await _progressSync.getStreamingPendingTime(progressKey);
+ final synced = await api.syncPlaybackSession(
+ streamingSessionId,
+ currentTime: currentTime,
+ duration: _totalDuration,
+ timeListened: streamingSeconds,
+ );
+ if (synced) {
+ if (streamingSeconds > 0) {
+ unawaited(
+ _progressSync.addTimeSaved(streamingSeconds, _player?.speed ?? 1.0),
+ );
+ unawaited(
+ HomeWidgetService().addLocalListeningSeconds(streamingSeconds),
+ );
+ }
+ if (pendingBefore > 0) {
+ unawaited(
+ _progressSync.reduceStreamingPendingTime(
+ progressKey,
+ pendingBefore,
+ ),
+ );
+ }
+ }
+ } catch (e) {
+ debugPrint('[Player] Failed to finalize streaming hot-swap session: $e');
+ }
+
+ try {
+ await api.closePlaybackSession(streamingSessionId);
+ } catch (_) {}
+ }
+
Future<String?> _playFromLocal(
String itemId,
String title,
@@ -2806,7 +3249,9 @@ class AudioPlayerService extends ChangeNotifier {
// Android Auto progress bar missing for ~60s on cold-start podcast play
// because the first MediaItem push carries dur=0. We want to know what
// value arrived at this function, and what's available from nearby state.
- debugPrint('[PodDur] _playFromLocal entry: itemId=$itemId ep=$_currentEpisodeId totalDurationArg=${totalDuration.toStringAsFixed(1)}s _totalDuration=${_totalDuration.toStringAsFixed(1)}s chapters=${chapters.length}');
+ debugPrint(
+ '[PodDur] _playFromLocal entry: itemId=$itemId ep=$_currentEpisodeId totalDurationArg=${totalDuration.toStringAsFixed(1)}s _totalDuration=${_totalDuration.toStringAsFixed(1)}s chapters=${chapters.length}',
+ );
_isOfflineMode = false; // We still sync to server if possible
_playbackSessionId = null;
@@ -2832,12 +3277,15 @@ class AudioPlayerService extends ChangeNotifier {
final serverProgress = await _api!
.getItemProgress(pKey)
.timeout(const Duration(seconds: 5), onTimeout: () => null);
- final serverPos = (serverProgress?['currentTime'] as num?)?.toDouble() ?? 0;
+ final serverPos =
+ (serverProgress?['currentTime'] as num?)?.toDouble() ?? 0;
final serverLastUpdate =
(serverProgress?['lastUpdate'] as num?)?.toInt() ?? 0;
final localTs = await _progressSync.getSavedTimestamp(pKey);
if (serverPos > startTime + 1.0) {
- debugPrint('[Player] Server position is ahead: server=${serverPos}s vs local=${startTime}s — using server');
+ debugPrint(
+ '[Player] Server position is ahead: server=${serverPos}s vs local=${startTime}s — using server',
+ );
startTime = serverPos;
await _progressSync.saveLocal(
itemId: itemId,
@@ -2856,17 +3304,25 @@ class AudioPlayerService extends ChangeNotifier {
!hasPending &&
gap <= SyncLogic.localAheadSafetySeconds &&
serverLastUpdate > localTs) {
- debugPrint('[Player] Local position is ahead but stale: local=${startTime}s (ts=$localTs) vs server=${serverPos}s (ts=$serverLastUpdate) — using server');
+ debugPrint(
+ '[Player] Local position is ahead but stale: local=${startTime}s (ts=$localTs) vs server=${serverPos}s (ts=$serverLastUpdate) — using server',
+ );
startTime = serverPos;
useServer = true;
}
if (!useServer) {
if (hasPending) {
- debugPrint('[Player] Local position is ahead: local=${startTime}s vs server=${serverPos}s — keeping local (pending sync)');
+ debugPrint(
+ '[Player] Local position is ahead: local=${startTime}s vs server=${serverPos}s — keeping local (pending sync)',
+ );
} else if (gap > SyncLogic.localAheadSafetySeconds) {
- debugPrint('[Player] Local position is ahead: local=${startTime}s vs server=${serverPos}s — keeping local (gap ${gap.toStringAsFixed(1)}s exceeds safety threshold)');
+ debugPrint(
+ '[Player] Local position is ahead: local=${startTime}s vs server=${serverPos}s — keeping local (gap ${gap.toStringAsFixed(1)}s exceeds safety threshold)',
+ );
} else {
- debugPrint('[Player] Local position is ahead: local=${startTime}s vs server=${serverPos}s — keeping local');
+ debugPrint(
+ '[Player] Local position is ahead: local=${startTime}s vs server=${serverPos}s — keeping local',
+ );
}
}
} else if (serverPos > 0) {
@@ -2877,7 +3333,9 @@ class AudioPlayerService extends ChangeNotifier {
debugPrint('[Player] Local-play progress reconcile failed: $e');
}
} else {
- debugPrint('[Player] Skipping progress reconcile — manual offline or no API');
+ debugPrint(
+ '[Player] Skipping progress reconcile — manual offline or no API',
+ );
}
final localPaths = _downloadService.getLocalPaths(itemId);
@@ -2911,7 +3369,9 @@ class AudioPlayerService extends ChangeNotifier {
chapters = cachedChapters;
_chapters = cachedChapters;
_handler?.updateChaptersQueue(cachedChapters);
- debugPrint('[Player] Loaded ${cachedChapters.length} chapters from cached session');
+ debugPrint(
+ '[Player] Loaded ${cachedChapters.length} chapters from cached session',
+ );
}
}
} catch (_) {}
@@ -2938,7 +3398,10 @@ class AudioPlayerService extends ChangeNotifier {
debugPrint('[Player] Pre-source setActive failed (local): $e');
}
_resetPreBufferState();
- final decoded = await _player!.setAudioSource(source, itemId: _currentItemId);
+ final decoded = await _player!.setAudioSource(
+ source,
+ itemId: _currentItemId,
+ );
_activeConcatSource = source;
_currentBookTrackCount = trackSources.length;
@@ -2960,9 +3423,11 @@ class AudioPlayerService extends ChangeNotifier {
decodedSec > 0 &&
decodedSec < totalDuration - _kLocalTruncationMarginSec) {
_shortLocalDurationSec = decodedSec;
- debugPrint('[Player] Local audio decodes to ${decodedSec.toStringAsFixed(1)}s '
- 'but book is ${totalDuration.toStringAsFixed(1)}s — download looks '
- 'incomplete; clamping seeks and protecting saved progress (GH #278)');
+ debugPrint(
+ '[Player] Local audio decodes to ${decodedSec.toStringAsFixed(1)}s '
+ 'but book is ${totalDuration.toStringAsFixed(1)}s — download looks '
+ 'incomplete; clamping seeks and protecting saved progress (GH #278)',
+ );
}
// If the saved position is at (or past) the end, restart from the beginning
@@ -2982,13 +3447,28 @@ class AudioPlayerService extends ChangeNotifier {
final bookSpeed = await PlayerSettings.getBookSpeed(speedKey);
final speed = bookSpeed ?? await PlayerSettings.getDefaultSpeed();
await _player!.setSpeed(speed);
- _pushMediaItem(itemId, title, author, coverUrl, totalDuration, chapter: initChapter);
- await _primeNowPlaying(title: title, artist: author, duration: totalDuration, elapsed: startTime, chapter: initChapter);
+ _pushMediaItem(
+ itemId,
+ title,
+ author,
+ coverUrl,
+ totalDuration,
+ chapter: initChapter,
+ );
+ await _primeNowPlaying(
+ title: title,
+ artist: author,
+ duration: totalDuration,
+ elapsed: startTime,
+ chapter: initChapter,
+ );
await EqualizerService().switchItem(speedKey);
debugPrint('[Player] Starting local playback at ${speed}x');
_handler?.refreshPlaybackState();
await Future.delayed(const Duration(milliseconds: 200));
- try { (await AudioSession.instance).setActive(true); } catch (_) {}
+ try {
+ (await AudioSession.instance).setActive(true);
+ } catch (_) {}
_player!.play();
_scheduleAudioDiagnostics('local');
notifyListeners();
@@ -3024,7 +3504,9 @@ class AudioPlayerService extends ChangeNotifier {
!manualOffline &&
!_knownOffline &&
_currentItemId != null) {
- debugPrint('[Player] Local source failed - retrying with server transcoding');
+ debugPrint(
+ '[Player] Local source failed - retrying with server transcoding',
+ );
_shortLocalDurationSec = null;
_localSessionMode = false;
final fallbackResult = await _playFromServer(
@@ -3040,7 +3522,9 @@ class AudioPlayerService extends ChangeNotifier {
forceTranscode: true,
);
if (fallbackResult == null) return null;
- debugPrint('[Player] Transcoded fallback after local failure did not start: $fallbackResult');
+ debugPrint(
+ '[Player] Transcoded fallback after local failure did not start: $fallbackResult',
+ );
return fallbackResult;
}
@@ -3068,7 +3552,8 @@ class AudioPlayerService extends ChangeNotifier {
]) async {
debugPrint('[Player] Playing from session cache: $title');
_isOfflineMode = false;
- _playbackSessionId = null; // No server session yet; _refreshServerSession will set it
+ _playbackSessionId =
+ null; // No server session yet; _refreshServerSession will set it
final audioTracks = cached['audioTracks'] as List<dynamic>?;
if (audioTracks == null || audioTracks.isEmpty) {
@@ -3097,7 +3582,7 @@ class AudioPlayerService extends ChangeNotifier {
try {
_currentTrackIndex = 0;
- final audioHeaders = api.mediaHeaders;
+ final audioHeaders = api.playbackSessionHeaders;
_buildTrackOffsets(audioTracks);
_captureStreamUrls(audioTracks, api);
AudioSource source;
@@ -3106,14 +3591,22 @@ class AudioPlayerService extends ChangeNotifier {
final track = t as Map<String, dynamic>;
final contentUrl = track['contentUrl'] as String? ?? '';
final fullUrl = api.buildTrackUrl(contentUrl);
- trackSources.add(AudioSource.uri(Uri.parse(fullUrl), headers: audioHeaders, options: mp3ExtractorOptions()));
+ trackSources.add(
+ AudioSource.uri(
+ Uri.parse(fullUrl),
+ headers: audioHeaders,
+ options: mp3ExtractorOptions(),
+ ),
+ );
}
source = ConcatenatingAudioSource(children: trackSources);
await _configureAudioSession();
try {
final activated = await (await AudioSession.instance).setActive(true);
- debugPrint('[Player] Pre-source setActive(true)=$activated (cached-session)');
+ debugPrint(
+ '[Player] Pre-source setActive(true)=$activated (cached-session)',
+ );
} catch (e) {
debugPrint('[Player] Pre-source setActive failed (cached-session): $e');
}
@@ -3134,13 +3627,28 @@ class AudioPlayerService extends ChangeNotifier {
final bookSpeed = await PlayerSettings.getBookSpeed(itemId);
final speed = bookSpeed ?? await PlayerSettings.getDefaultSpeed();
await _player!.setSpeed(speed);
- _pushMediaItem(itemId, title, author, coverUrl, totalDuration, chapter: initChapter);
- await _primeNowPlaying(title: title, artist: author, duration: totalDuration, elapsed: startTime, chapter: initChapter);
+ _pushMediaItem(
+ itemId,
+ title,
+ author,
+ coverUrl,
+ totalDuration,
+ chapter: initChapter,
+ );
+ await _primeNowPlaying(
+ title: title,
+ artist: author,
+ duration: totalDuration,
+ elapsed: startTime,
+ chapter: initChapter,
+ );
await EqualizerService().switchItem(itemId);
debugPrint('[Player] Starting cached session playback at ${speed}x');
_handler?.refreshPlaybackState();
await Future.delayed(const Duration(milliseconds: 200));
- try { (await AudioSession.instance).setActive(true); } catch (_) {}
+ try {
+ (await AudioSession.instance).setActive(true);
+ } catch (_) {}
_cachedStartReconcileGeneration = playbackGeneration;
_player!.play();
_scheduleAudioDiagnostics('cached-session');
@@ -3205,7 +3713,9 @@ class AudioPlayerService extends ChangeNotifier {
if (_playbackGeneration != playbackGeneration ||
_currentItemId != itemId ||
_currentEpisodeId != episodeIdAtStart) {
- debugPrint('[Player] Ignoring stale background session refresh for $progressKey');
+ debugPrint(
+ '[Player] Ignoring stale background session refresh for $progressKey',
+ );
return;
}
_playbackSessionId = sessionData['id'] as String?;
@@ -3247,7 +3757,9 @@ class AudioPlayerService extends ChangeNotifier {
localTimeAtStart: localTimeAtStart,
currentPlaybackTime: localPos,
)) {
- debugPrint('[Player] Server is ahead on cache-start: server=${serverPos}s vs local=${localPos}s - seeking');
+ debugPrint(
+ '[Player] Server is ahead on cache-start: server=${serverPos}s vs local=${localPos}s - seeking',
+ );
await _seekAbsolute(serverPos);
await _progressSync.saveLocal(
itemId: progressKey,
@@ -3284,10 +3796,14 @@ class AudioPlayerService extends ChangeNotifier {
// Use episode endpoint if this is a podcast episode
final sessionData = _currentEpisodeId != null
? await api.startEpisodePlaybackSession(
- _currentItemId!, _currentEpisodeId!,
- forceTranscode: forceTranscode)
- : await api.startPlaybackSession(itemId,
- forceTranscode: forceTranscode);
+ _currentItemId!,
+ _currentEpisodeId!,
+ forceTranscode: forceTranscode,
+ )
+ : await api.startPlaybackSession(
+ itemId,
+ forceTranscode: forceTranscode,
+ );
if (sessionData == null) {
debugPrint('[Player] Failed to start playback session');
_clearState();
@@ -3299,8 +3815,11 @@ class AudioPlayerService extends ChangeNotifier {
// one so per-library skip amounts work for lean/merged shelf items.
final sessionLibId = sessionData['libraryId'] as String?;
if ((_currentLibraryId == null || _currentLibraryId!.isEmpty) &&
- sessionLibId != null && sessionLibId.isNotEmpty) {
- debugPrint('[SkipDebug] libraryId adopted from play session: $sessionLibId');
+ sessionLibId != null &&
+ sessionLibId.isNotEmpty) {
+ debugPrint(
+ '[SkipDebug] libraryId adopted from play session: $sessionLibId',
+ );
_currentLibraryId = sessionLibId;
_syncNotifSkipCache();
}
@@ -3315,21 +3834,36 @@ class AudioPlayerService extends ChangeNotifier {
// Detect Dolby Atmos / EAC-3 / AC-3 tracks. Samsung has a hardware Dolby
// decoder and iOS AVPlayer handles EAC3 natively, so only force transcode
// on other Android devices where the software codec often fails or outputs silence.
- if (!forceTranscode && Platform.isAndroid &&
+ if (!forceTranscode &&
+ Platform.isAndroid &&
!ApiService.deviceManufacturer.toLowerCase().contains('samsung')) {
final needsTranscode = audioTracks.any((t) {
- final mime = ((t as Map<String, dynamic>)['mimeType'] as String? ?? '').toLowerCase();
+ final mime = ((t as Map<String, dynamic>)['mimeType'] as String? ?? '')
+ .toLowerCase();
final codec = (t['codec'] as String? ?? '').toLowerCase();
- return mime.contains('eac3') || mime.contains('ac3') || mime.contains('ac4') ||
- mime.contains('atmos') || codec.contains('eac3') || codec.contains('ac3') ||
- codec.contains('ac4') || codec.contains('atmos');
+ return mime.contains('eac3') ||
+ mime.contains('ac3') ||
+ mime.contains('ac4') ||
+ mime.contains('atmos') ||
+ codec.contains('eac3') ||
+ codec.contains('ac3') ||
+ codec.contains('ac4') ||
+ codec.contains('atmos');
});
if (needsTranscode) {
- debugPrint('[Player] Dolby/EAC3 track detected - restarting with server transcoding');
- try { await api.closePlaybackSession(_playbackSessionId!); } catch (_) {}
+ debugPrint(
+ '[Player] Dolby/EAC3 track detected - restarting with server transcoding',
+ );
+ try {
+ await api.closePlaybackSession(_playbackSessionId!);
+ } catch (_) {}
_playbackSessionId = null;
final retrySession = _currentEpisodeId != null
- ? await api.startEpisodePlaybackSession(_currentItemId!, _currentEpisodeId!, forceTranscode: true)
+ ? await api.startEpisodePlaybackSession(
+ _currentItemId!,
+ _currentEpisodeId!,
+ forceTranscode: true,
+ )
: await api.startPlaybackSession(itemId, forceTranscode: true);
if (retrySession == null) {
_clearState();
@@ -3341,7 +3875,8 @@ class AudioPlayerService extends ChangeNotifier {
_clearState();
return 'No audio files in transcoded session';
}
- final sessionChapters = retrySession['chapters'] as List<dynamic>? ?? [];
+ final sessionChapters =
+ retrySession['chapters'] as List<dynamic>? ?? [];
if (sessionChapters.isNotEmpty) {
chapters = sessionChapters;
_chapters = sessionChapters;
@@ -3362,11 +3897,12 @@ class AudioPlayerService extends ChangeNotifier {
chapters = sessionChapters;
_chapters = sessionChapters;
_handler?.updateChaptersQueue(sessionChapters);
- debugPrint('[Player] Loaded ${sessionChapters.length} chapters from session');
+ debugPrint(
+ '[Player] Loaded ${sessionChapters.length} chapters from session',
+ );
}
}
-
// Update totalDuration from session if it was unknown (e.g. podcast episodes
// where the embedded recentEpisode didn't include a duration field)
if (totalDuration <= 0) {
@@ -3374,7 +3910,9 @@ class AudioPlayerService extends ChangeNotifier {
if (sessionDur > 0) {
totalDuration = sessionDur;
_totalDuration = sessionDur;
- debugPrint('[Player] Updated totalDuration from session: ${sessionDur}s');
+ debugPrint(
+ '[Player] Updated totalDuration from session: ${sessionDur}s',
+ );
}
}
@@ -3383,12 +3921,18 @@ class AudioPlayerService extends ChangeNotifier {
// check timestamps to catch stale local saves.
// Skip all of this when startTime was forced (bookmark/chapter jump).
final serverPos = (sessionData['currentTime'] as num?)?.toDouble() ?? 0;
- final pKey = _currentEpisodeId != null ? '$itemId-$_currentEpisodeId' : itemId;
+ final pKey = _currentEpisodeId != null
+ ? '$itemId-$_currentEpisodeId'
+ : itemId;
final localTs = await _progressSync.getSavedTimestamp(pKey);
if (forceStartTime) {
- debugPrint('[Player] Forced start time: ${startTime}s — skipping server/local position comparison');
+ debugPrint(
+ '[Player] Forced start time: ${startTime}s — skipping server/local position comparison',
+ );
} else if (serverPos > startTime + 1.0) {
- debugPrint('[Player] Server position is ahead: server=${serverPos}s vs local=${startTime}s — using server');
+ debugPrint(
+ '[Player] Server position is ahead: server=${serverPos}s vs local=${startTime}s — using server',
+ );
startTime = serverPos;
} else if (startTime > 0) {
// Skip the staleness override if we have a pending local sync: the
@@ -3400,12 +3944,17 @@ class AudioPlayerService extends ChangeNotifier {
bool useServer = false;
final hasPending = await _progressSync.hasPendingSync(pKey);
final gap = startTime - serverPos;
- if (localTs > 0 && !hasPending && gap <= SyncLogic.localAheadSafetySeconds) {
+ if (localTs > 0 &&
+ !hasPending &&
+ gap <= SyncLogic.localAheadSafetySeconds) {
try {
final serverProgress = await api.getItemProgress(pKey);
- final serverLastUpdate = (serverProgress?['lastUpdate'] as num?)?.toInt() ?? 0;
+ final serverLastUpdate =
+ (serverProgress?['lastUpdate'] as num?)?.toInt() ?? 0;
if (serverLastUpdate > localTs) {
- debugPrint('[Player] Local position is ahead but stale: local=${startTime}s (ts=$localTs) vs server=${serverPos}s (ts=$serverLastUpdate) — using server');
+ debugPrint(
+ '[Player] Local position is ahead but stale: local=${startTime}s (ts=$localTs) vs server=${serverPos}s (ts=$serverLastUpdate) — using server',
+ );
startTime = serverPos;
useServer = true;
}
@@ -3413,11 +3962,17 @@ class AudioPlayerService extends ChangeNotifier {
}
if (!useServer) {
if (hasPending) {
- debugPrint('[Player] Local position is ahead: local=${startTime}s vs server=${serverPos}s — keeping local (pending sync)');
+ debugPrint(
+ '[Player] Local position is ahead: local=${startTime}s vs server=${serverPos}s — keeping local (pending sync)',
+ );
} else if (gap > SyncLogic.localAheadSafetySeconds) {
- debugPrint('[Player] Local position is ahead: local=${startTime}s vs server=${serverPos}s — keeping local (gap ${gap.toStringAsFixed(1)}s exceeds safety threshold)');
+ debugPrint(
+ '[Player] Local position is ahead: local=${startTime}s vs server=${serverPos}s — keeping local (gap ${gap.toStringAsFixed(1)}s exceeds safety threshold)',
+ );
} else {
- debugPrint('[Player] Local position is ahead: local=${startTime}s vs server=${serverPos}s — keeping local');
+ debugPrint(
+ '[Player] Local position is ahead: local=${startTime}s vs server=${serverPos}s — keeping local',
+ );
}
}
} else if (serverPos > 0) {
@@ -3427,7 +3982,7 @@ class AudioPlayerService extends ChangeNotifier {
try {
_currentTrackIndex = 0;
- final audioHeaders = api.mediaHeaders;
+ final audioHeaders = api.playbackSessionHeaders;
// Build audio source - one source per track file
_buildTrackOffsets(audioTracks);
@@ -3437,7 +3992,13 @@ class AudioPlayerService extends ChangeNotifier {
final track = t as Map<String, dynamic>;
final contentUrl = track['contentUrl'] as String? ?? '';
final fullUrl = api.buildTrackUrl(contentUrl);
- trackSources.add(AudioSource.uri(Uri.parse(fullUrl), headers: audioHeaders, options: mp3ExtractorOptions()));
+ trackSources.add(
+ AudioSource.uri(
+ Uri.parse(fullUrl),
+ headers: audioHeaders,
+ options: mp3ExtractorOptions(),
+ ),
+ );
}
final source = ConcatenatingAudioSource(children: trackSources);
@@ -3466,13 +4027,28 @@ class AudioPlayerService extends ChangeNotifier {
final bookSpeed = await PlayerSettings.getBookSpeed(itemId);
final speed = bookSpeed ?? await PlayerSettings.getDefaultSpeed();
await _player!.setSpeed(speed);
- _pushMediaItem(itemId, title, author, coverUrl, totalDuration, chapter: initChapter);
- await _primeNowPlaying(title: title, artist: author, duration: totalDuration, elapsed: startTime, chapter: initChapter);
+ _pushMediaItem(
+ itemId,
+ title,
+ author,
+ coverUrl,
+ totalDuration,
+ chapter: initChapter,
+ );
+ await _primeNowPlaying(
+ title: title,
+ artist: author,
+ duration: totalDuration,
+ elapsed: startTime,
+ chapter: initChapter,
+ );
await EqualizerService().switchItem(itemId);
debugPrint('[Player] Starting stream playback at ${speed}x');
_handler?.refreshPlaybackState();
await Future.delayed(const Duration(milliseconds: 200));
- try { (await AudioSession.instance).setActive(true); } catch (_) {}
+ try {
+ (await AudioSession.instance).setActive(true);
+ } catch (_) {}
_player!.play();
_scheduleAudioDiagnostics('stream');
notifyListeners();
@@ -3499,11 +4075,14 @@ class AudioPlayerService extends ChangeNotifier {
// Retry source and codec failures through ABS once. A distinct flag from
// forceStartTime keeps bookmark/chapter seeks eligible for recovery while
// still preventing a transcode loop.
- if (!forceTranscode &&
- PlaybackErrorPolicy.shouldRetryWithTranscode(e)) {
- debugPrint('[Player] Source or codec error detected - retrying with server transcoding');
+ if (!forceTranscode && PlaybackErrorPolicy.shouldRetryWithTranscode(e)) {
+ debugPrint(
+ '[Player] Source or codec error detected - retrying with server transcoding',
+ );
if (_playbackSessionId != null) {
- try { await api.closePlaybackSession(_playbackSessionId!); } catch (_) {}
+ try {
+ await api.closePlaybackSession(_playbackSessionId!);
+ } catch (_) {}
_playbackSessionId = null;
}
return _playFromServer(
@@ -3533,7 +4112,9 @@ class AudioPlayerService extends ChangeNotifier {
try {
final api = _api;
if (api == null || _currentItemId == null) return;
- debugPrint('[Player] Playback error in stream - retrying with server transcoding');
+ debugPrint(
+ '[Player] Playback error in stream - retrying with server transcoding',
+ );
final itemId = _currentItemId!;
final retryEpId = _currentEpisodeId;
final retryEpTitle = _currentEpisodeTitle;
@@ -3554,22 +4135,30 @@ class AudioPlayerService extends ChangeNotifier {
_shortLocalDurationSec = null;
_syncNotifSkipCache();
if (failedSessionId != null) {
- try { await api.closePlaybackSession(failedSessionId); } catch (_) {}
+ try {
+ await api.closePlaybackSession(failedSessionId);
+ } catch (_) {}
}
final retrySession = retryEpId != null
- ? await api.startEpisodePlaybackSession(itemId, retryEpId, forceTranscode: true)
+ ? await api.startEpisodePlaybackSession(
+ itemId,
+ retryEpId,
+ forceTranscode: true,
+ )
: await api.startPlaybackSession(itemId, forceTranscode: true);
if (retrySession == null) return;
_playbackSessionId = retrySession['id'] as String?;
final retrySessionLibId = retrySession['libraryId'] as String?;
if ((_currentLibraryId == null || _currentLibraryId!.isEmpty) &&
- retrySessionLibId != null && retrySessionLibId.isNotEmpty) {
+ retrySessionLibId != null &&
+ retrySessionLibId.isNotEmpty) {
_currentLibraryId = retrySessionLibId;
_syncNotifSkipCache();
}
_lastServerSync = DateTime.now();
final retryTracks = retrySession['audioTracks'] as List<dynamic>?;
- final totalDuration = (retrySession['duration'] as num?)?.toDouble() ?? _totalDuration;
+ final totalDuration =
+ (retrySession['duration'] as num?)?.toDouble() ?? _totalDuration;
final chapters = retrySession['chapters'] as List<dynamic>? ?? _chapters;
_chapters = chapters;
_totalDuration = totalDuration;
@@ -3577,17 +4166,27 @@ class AudioPlayerService extends ChangeNotifier {
_currentTrackIndex = 0;
_buildTrackOffsets(retryTracks);
AudioSource retrySource;
- final audioHeaders = api.mediaHeaders;
+ final audioHeaders = api.playbackSessionHeaders;
if (retryTracks.length == 1) {
final track = retryTracks.first as Map<String, dynamic>;
final contentUrl = track['contentUrl'] as String? ?? '';
- retrySource = AudioSource.uri(Uri.parse(api.buildTrackUrl(contentUrl)), headers: audioHeaders, options: mp3ExtractorOptions());
+ retrySource = AudioSource.uri(
+ Uri.parse(api.buildTrackUrl(contentUrl)),
+ headers: audioHeaders,
+ options: mp3ExtractorOptions(),
+ );
} else {
final sources = <AudioSource>[];
for (final t in retryTracks) {
final track = t as Map<String, dynamic>;
final contentUrl = track['contentUrl'] as String? ?? '';
- sources.add(AudioSource.uri(Uri.parse(api.buildTrackUrl(contentUrl)), headers: audioHeaders, options: mp3ExtractorOptions()));
+ sources.add(
+ AudioSource.uri(
+ Uri.parse(api.buildTrackUrl(contentUrl)),
+ headers: audioHeaders,
+ options: mp3ExtractorOptions(),
+ ),
+ );
}
retrySource = ConcatenatingAudioSource(children: sources);
}
@@ -3600,10 +4199,19 @@ class AudioPlayerService extends ChangeNotifier {
final bookSpeed = await PlayerSettings.getBookSpeed(itemId);
final speed = bookSpeed ?? await PlayerSettings.getDefaultSpeed();
await _player!.setSpeed(speed);
- _pushMediaItem(itemId, retryTitle, retryAuthor, retryCover, totalDuration, chapter: initChapter);
+ _pushMediaItem(
+ itemId,
+ retryTitle,
+ retryAuthor,
+ retryCover,
+ totalDuration,
+ chapter: initChapter,
+ );
await EqualizerService().switchItem(itemId);
debugPrint('[Player] Transcoded playback starting at ${speed}x');
- try { (await AudioSession.instance).setActive(true); } catch (_) {}
+ try {
+ (await AudioSession.instance).setActive(true);
+ } catch (_) {}
_player!.play();
_scheduleAudioDiagnostics('transcoded');
notifyListeners();
@@ -3670,13 +4278,22 @@ class AudioPlayerService extends ChangeNotifier {
/// Content provider authority — must match CoverContentProvider and AndroidManifest.
static const _coverAuthority = 'com.barnabas.absorb.covers';
- void _pushMediaItem(String itemId, String title, String author,
- String? coverUrl, double totalDuration, {String? chapter, int? coverCacheBust}) {
+ void _pushMediaItem(
+ String itemId,
+ String title,
+ String author,
+ String? coverUrl,
+ double totalDuration, {
+ String? chapter,
+ int? coverCacheBust,
+ }) {
// Alpha [PodDur]: trace every push-site. We want to see which callers
// pass only the parent itemId (missing -episodeId suffix) and/or a zero
// duration, so we can pinpoint what to fix for the AA podcast progress
// bar. Includes the current _totalDuration so "stale 0" paths are visible.
- debugPrint('[PodDur] _pushMediaItem: itemId=$itemId ep=$_currentEpisodeId argDur=${totalDuration.toStringAsFixed(1)}s _totalDuration=${_totalDuration.toStringAsFixed(1)}s');
+ debugPrint(
+ '[PodDur] _pushMediaItem: itemId=$itemId ep=$_currentEpisodeId argDur=${totalDuration.toStringAsFixed(1)}s _totalDuration=${_totalDuration.toStringAsFixed(1)}s',
+ );
// Android: Always use content:// URI for Now Playing artwork - some OEMs
// (e.g. Vivo) don't load HTTP URLs in MediaSession. The CoverContentProvider
// handles both downloaded and streamed covers.
@@ -3703,7 +4320,14 @@ class AudioPlayerService extends ChangeNotifier {
_scheduleStreamedCoverRepush(itemId);
}
}
- _updateNotificationMediaItem(itemId, title, author, effectiveCoverUrl, totalDuration, chapter: chapter);
+ _updateNotificationMediaItem(
+ itemId,
+ title,
+ author,
+ effectiveCoverUrl,
+ totalDuration,
+ chapter: chapter,
+ );
}
void _scheduleStreamedCoverRepush(String itemId) {
@@ -3712,18 +4336,32 @@ class AudioPlayerService extends ChangeNotifier {
// Only re-push if we're still on the same item.
if (_currentItemId == null) return;
if (_currentItemId != itemId && _mediaItemKey != itemId) return;
- final chapterTitle = _lastNotifiedChapterIndex >= 0 && _chapters.isNotEmpty
- ? (_chapters[_lastNotifiedChapterIndex] as Map<String, dynamic>)['title'] as String?
+ final chapterTitle =
+ _lastNotifiedChapterIndex >= 0 && _chapters.isNotEmpty
+ ? (_chapters[_lastNotifiedChapterIndex]
+ as Map<String, dynamic>)['title']
+ as String?
: null;
- _pushMediaItem(itemId, _currentTitle ?? '', _currentAuthor ?? '',
- _currentCoverUrl, _totalDuration,
- chapter: chapterTitle,
- coverCacheBust: DateTime.now().millisecondsSinceEpoch);
+ _pushMediaItem(
+ itemId,
+ _currentTitle ?? '',
+ _currentAuthor ?? '',
+ _currentCoverUrl,
+ _totalDuration,
+ chapter: chapterTitle,
+ coverCacheBust: DateTime.now().millisecondsSinceEpoch,
+ );
});
}
- void _updateNotificationMediaItem(String itemId, String title, String author,
- String? coverUrl, double totalDuration, {String? chapter}) {
+ void _updateNotificationMediaItem(
+ String itemId,
+ String title,
+ String author,
+ String? coverUrl,
+ double totalDuration, {
+ String? chapter,
+ }) {
// GH #298: chapter becomes the title, book moves beside the author.
final labels = nowPlayingLabels(title, author, chapter);
// In chapter progress mode, show chapter duration instead of full book
@@ -3740,18 +4378,21 @@ class AudioPlayerService extends ChangeNotifier {
// (BT car display stuck on prior chapter). If this fires with fresh
// artist/chapter text but the car still shows old, the issue is downstream
// of audio_service's MediaSession push.
- debugPrint('[Handler] mediaItem.add: item=$itemId title="${labels.title}" artist="${labels.subtitle}" dur=${displayDuration.round()}s chapter=$chapter hasHandler=${_handler != null}');
- _handler!.mediaItem.add(MediaItem(
- id: itemId,
- title: labels.title,
- artist: labels.subtitle,
- album: title,
- duration: Duration(seconds: displayDuration.round()),
- artUri: coverUrl != null ? Uri.tryParse(coverUrl) : null,
- ));
+ debugPrint(
+ '[Handler] mediaItem.add: item=$itemId title="${labels.title}" artist="${labels.subtitle}" dur=${displayDuration.round()}s chapter=$chapter hasHandler=${_handler != null}',
+ );
+ _handler!.mediaItem.add(
+ MediaItem(
+ id: itemId,
+ title: labels.title,
+ artist: labels.subtitle,
+ album: title,
+ duration: Duration(seconds: displayDuration.round()),
+ artUri: coverUrl != null ? Uri.tryParse(coverUrl) : null,
+ ),
+ );
}
-
void _clearState() {
_currentItemId = null;
_currentEpisodeId = null;
@@ -3806,14 +4447,18 @@ class AudioPlayerService extends ChangeNotifier {
if (_retryInProgress) return;
if (_currentItemId == null || _api == null) return;
if (_streamRetryCount >= _maxStreamRetries) {
- debugPrint('[Player] Max retries reached ($_maxStreamRetries) — giving up');
+ debugPrint(
+ '[Player] Max retries reached ($_maxStreamRetries) — giving up',
+ );
return;
}
_retryInProgress = true;
_streamRetryCount++;
final delay = Duration(seconds: 1 << (_streamRetryCount - 1)); // 1s, 2s, 4s
- debugPrint('[Player] Stream error — retry $_streamRetryCount/$_maxStreamRetries in ${delay.inSeconds}s');
+ debugPrint(
+ '[Player] Stream error — retry $_streamRetryCount/$_maxStreamRetries in ${delay.inSeconds}s',
+ );
await Future<void>.delayed(delay);
@@ -3921,7 +4566,8 @@ class AudioPlayerService extends ChangeNotifier {
// listener saves every 5s; this only matters when that stream goes silent.
_bgSaveTimer = Timer.periodic(const Duration(seconds: 300), (_) async {
- if (_currentItemId == null || _player == null || !_player!.playing) return;
+ if (_currentItemId == null || _player == null || !_player!.playing)
+ return;
final pos = position;
final posSec = pos.inMilliseconds / 1000.0;
if (posSec <= 0) return;
@@ -3940,7 +4586,9 @@ class AudioPlayerService extends ChangeNotifier {
_nativeAutoAdvanceSub?.cancel();
_nativeAutoAdvanceSub = _player?.bookAutoAdvancedStream.listen((_) {
if (_preloadedNextBook != null) {
- debugPrint('[NativeEngine] bookAutoAdvanced received — firing auto-queue advance');
+ debugPrint(
+ '[NativeEngine] bookAutoAdvanced received — firing auto-queue advance',
+ );
_onAutoQueueAdvanced();
}
});
@@ -3948,264 +4596,317 @@ class AudioPlayerService extends ChangeNotifier {
// ─── Primary completion detection via processingState ───
// This fires reliably when ExoPlayer reaches STATE_ENDED, before any
// position-reset can confuse the position-based detection.
- _completionSub = _player?.processingStateStream.listen((state) {
- if (state == ProcessingState.completed && _currentItemId != null) {
- if (_preloadedNextBook != null) {
- debugPrint('[PreBuffer] processingState=completed with pre-buffer loaded — firing auto-queue advance');
- _onAutoQueueAdvanced();
- } else {
- _onPlaybackComplete();
- }
- }
- // Notify UI when buffering/loading state changes so spinners update.
- // Skip when backgrounded - no visible UI to rebuild; flushed on foreground.
- if (!_isBackgrounded &&
- (state == ProcessingState.ready || state == ProcessingState.loading || state == ProcessingState.buffering)) {
- notifyListeners();
- }
- }, onError: (Object e, StackTrace st) {
- debugPrint('[Player] processingState stream error: $e');
- _attemptStreamRetry(e);
- });
- _syncSub = _player?.positionStream.listen((trackRelativePos) async {
- // Reset retry counter on successful position updates
- _streamRetryCount = 0;
- // Convert track-relative position to absolute book position
- final absolutePos = position; // uses the getter which adds track offset
- final sec = absolutePos.inSeconds;
- final posSec = absolutePos.inMilliseconds / 1000.0;
-
- // After a track advance, push once now that the new position has landed
- // so the background lock screen isn't left stale until foreground.
- if (_pendingTrackAdvanceRefresh) {
- _pendingTrackAdvanceRefresh = false;
- _handler?.refreshPlaybackState();
- }
-
- // ─── Position-reset guard ────────────────────────────
- // ExoPlayer can seek to 0 on STATE_ENDED. If we were near the end
- // and suddenly jump to near 0 without a user seek, treat it as
- // completion rather than restarting playback.
- if (_lastKnownPositionSec > 0 && _totalDuration > 0) {
- final wasNearEnd = _lastKnownPositionSec >= _totalDuration - 5.0;
- final nowNearStart = posSec < 2.0;
- if (wasNearEnd && nowNearStart) {
+ _completionSub = _player?.processingStateStream.listen(
+ (state) {
+ if (state == ProcessingState.completed && _currentItemId != null) {
if (_preloadedNextBook != null) {
- debugPrint('[PreBuffer] Position jump near-end → 0 with pre-buffer loaded — firing auto-queue advance');
+ debugPrint(
+ '[PreBuffer] processingState=completed with pre-buffer loaded — firing auto-queue advance',
+ );
_onAutoQueueAdvanced();
- return;
+ } else {
+ _onPlaybackComplete();
}
- debugPrint('[Player] Position jumped from ${_lastKnownPositionSec.toStringAsFixed(1)}s to ${posSec.toStringAsFixed(1)}s — treating as completion');
- _onPlaybackComplete();
- return;
}
- }
- if (posSec > 0) _lastKnownPositionSec = posSec;
-
- _maybePreloadNextBook();
-
- // On iOS in background, fire the cross-book transition just before the
- // current item ends. The native handover swaps the player item in one
- // step, keeping the AVPlayer rate continuous so iOS doesn't drop the
- // background route. Foreground still uses the regular auto-advance path.
- if (Platform.isIOS &&
- _isBackgrounded &&
- _preloadedNextBook != null &&
- !_autoQueueAdvancing &&
- _totalDuration > 0 &&
- (_player?.playing ?? false)) {
- final remaining = _totalDuration - posSec;
- if (remaining > 0 && remaining <= 0.5) {
- debugPrint('[PreBuffer] Proactive iOS transition at remaining=${remaining.toStringAsFixed(2)}s');
- _onAutoQueueAdvanced();
- return;
+ // Notify UI when buffering/loading state changes so spinners update.
+ // Skip when backgrounded - no visible UI to rebuild; flushed on foreground.
+ if (!_isBackgrounded &&
+ (state == ProcessingState.ready ||
+ state == ProcessingState.loading ||
+ state == ProcessingState.buffering)) {
+ notifyListeners();
+ }
+ },
+ onError: (Object e, StackTrace st) {
+ debugPrint('[Player] processingState stream error: $e');
+ _attemptStreamRetry(e);
+ },
+ );
+ _syncSub = _player?.positionStream.listen(
+ (trackRelativePos) async {
+ // Reset retry counter on successful position updates
+ _streamRetryCount = 0;
+ // Convert track-relative position to absolute book position
+ final absolutePos = position; // uses the getter which adds track offset
+ final sec = absolutePos.inSeconds;
+ final posSec = absolutePos.inMilliseconds / 1000.0;
+
+ // After a track advance, push once now that the new position has landed
+ // so the background lock screen isn't left stale until foreground.
+ if (_pendingTrackAdvanceRefresh) {
+ _pendingTrackAdvanceRefresh = false;
+ _handler?.refreshPlaybackState();
}
- }
- if (sec <= 0) return;
+ // ─── Position-reset guard ────────────────────────────
+ // ExoPlayer can seek to 0 on STATE_ENDED. If we were near the end
+ // and suddenly jump to near 0 without a user seek, treat it as
+ // completion rather than restarting playback.
+ if (_lastKnownPositionSec > 0 && _totalDuration > 0) {
+ final wasNearEnd = _lastKnownPositionSec >= _totalDuration - 5.0;
+ final nowNearStart = posSec < 2.0;
+ if (wasNearEnd && nowNearStart) {
+ if (_preloadedNextBook != null) {
+ debugPrint(
+ '[PreBuffer] Position jump near-end → 0 with pre-buffer loaded — firing auto-queue advance',
+ );
+ _onAutoQueueAdvanced();
+ return;
+ }
+ debugPrint(
+ '[Player] Position jumped from ${_lastKnownPositionSec.toStringAsFixed(1)}s to ${posSec.toStringAsFixed(1)}s — treating as completion',
+ );
+ _onPlaybackComplete();
+ return;
+ }
+ }
+ if (posSec > 0) _lastKnownPositionSec = posSec;
+
+ _maybePreloadNextBook();
+
+ // On iOS in background, fire the cross-book transition just before the
+ // current item ends. The native handover swaps the player item in one
+ // step, keeping the AVPlayer rate continuous so iOS doesn't drop the
+ // background route. Foreground still uses the regular auto-advance path.
+ if (Platform.isIOS &&
+ _isBackgrounded &&
+ _preloadedNextBook != null &&
+ !_autoQueueAdvancing &&
+ _totalDuration > 0 &&
+ (_player?.playing ?? false)) {
+ final remaining = _totalDuration - posSec;
+ if (remaining > 0 && remaining <= 0.5) {
+ debugPrint(
+ '[PreBuffer] Proactive iOS transition at remaining=${remaining.toStringAsFixed(2)}s',
+ );
+ _onAutoQueueAdvanced();
+ return;
+ }
+ }
- // In background, only process once per second to save CPU.
- if (_isBackgrounded) {
- if (sec == _lastBgProcessedSec) return;
- _lastBgProcessedSec = sec;
- }
+ if (sec <= 0) return;
- // ─── Chapter change detection ──────────────────────────
- // Update notification subtitle when the chapter changes.
- // Throttled to once per second — chapters can't change faster than that.
- if (_chapters.isNotEmpty && _currentItemId != null && sec != _lastChapterCheckSec) {
- _lastChapterCheckSec = sec;
- int chapterIdx = -1;
- String? chapterTitle;
- double chapterStart = 0;
- double chapterEnd = _totalDuration;
-
- // Fast path: check if still in the cached chapter
- if (_lastNotifiedChapterIndex >= 0 && _lastNotifiedChapterIndex < _chapters.length) {
- final ch = _chapters[_lastNotifiedChapterIndex] as Map<String, dynamic>;
- final s = (ch['start'] as num?)?.toDouble() ?? 0;
- final e = (ch['end'] as num?)?.toDouble() ?? _totalDuration;
- if (posSec >= s && posSec < e) {
- chapterIdx = _lastNotifiedChapterIndex;
- chapterTitle = ch['title'] as String?;
- chapterStart = s;
- chapterEnd = e;
- }
+ // In background, only process once per second to save CPU.
+ if (_isBackgrounded) {
+ if (sec == _lastBgProcessedSec) return;
+ _lastBgProcessedSec = sec;
}
- // Slow path: linear scan only if cached chapter didn't match
- if (chapterIdx < 0) {
- for (int i = 0; i < _chapters.length; i++) {
- final ch = _chapters[i] as Map<String, dynamic>;
- final start = (ch['start'] as num?)?.toDouble() ?? 0;
- final end = (ch['end'] as num?)?.toDouble() ?? _totalDuration;
- if (posSec >= start && posSec < end) {
- chapterIdx = i;
+ // ─── Chapter change detection ──────────────────────────
+ // Update notification subtitle when the chapter changes.
+ // Throttled to once per second — chapters can't change faster than that.
+ if (_chapters.isNotEmpty &&
+ _currentItemId != null &&
+ sec != _lastChapterCheckSec) {
+ _lastChapterCheckSec = sec;
+ int chapterIdx = -1;
+ String? chapterTitle;
+ double chapterStart = 0;
+ double chapterEnd = _totalDuration;
+
+ // Fast path: check if still in the cached chapter
+ if (_lastNotifiedChapterIndex >= 0 &&
+ _lastNotifiedChapterIndex < _chapters.length) {
+ final ch =
+ _chapters[_lastNotifiedChapterIndex] as Map<String, dynamic>;
+ final s = (ch['start'] as num?)?.toDouble() ?? 0;
+ final e = (ch['end'] as num?)?.toDouble() ?? _totalDuration;
+ if (posSec >= s && posSec < e) {
+ chapterIdx = _lastNotifiedChapterIndex;
chapterTitle = ch['title'] as String?;
- chapterStart = start;
- chapterEnd = end;
- break;
+ chapterStart = s;
+ chapterEnd = e;
}
}
- }
- if (chapterIdx >= 0 && chapterIdx != _lastNotifiedChapterIndex) {
- debugPrint('[Battery] Chapter change: idx=$chapterIdx "$chapterTitle" at ${posSec.toStringAsFixed(1)}s');
- _lastNotifiedChapterIndex = chapterIdx;
- _currentChapterStart = chapterStart;
- _currentChapterEnd = chapterEnd;
- _pushMediaItem(
- _currentItemId!, _currentTitle ?? '', _currentAuthor ?? '',
- _currentCoverUrl, _totalDuration,
- chapter: chapterTitle,
- );
- // Force PlaybackState refresh so the notification position resets
- // to 0 immediately instead of waiting for the next stream event.
- if (_notifChapterMode) _handler?.refreshPlaybackState();
+ // Slow path: linear scan only if cached chapter didn't match
+ if (chapterIdx < 0) {
+ for (int i = 0; i < _chapters.length; i++) {
+ final ch = _chapters[i] as Map<String, dynamic>;
+ final start = (ch['start'] as num?)?.toDouble() ?? 0;
+ final end = (ch['end'] as num?)?.toDouble() ?? _totalDuration;
+ if (posSec >= start && posSec < end) {
+ chapterIdx = i;
+ chapterTitle = ch['title'] as String?;
+ chapterStart = start;
+ chapterEnd = end;
+ break;
+ }
+ }
+ }
+
+ if (chapterIdx >= 0 && chapterIdx != _lastNotifiedChapterIndex) {
+ debugPrint(
+ '[Battery] Chapter change: idx=$chapterIdx "$chapterTitle" at ${posSec.toStringAsFixed(1)}s',
+ );
+ _lastNotifiedChapterIndex = chapterIdx;
+ _currentChapterStart = chapterStart;
+ _currentChapterEnd = chapterEnd;
+ _pushMediaItem(
+ _currentItemId!,
+ _currentTitle ?? '',
+ _currentAuthor ?? '',
+ _currentCoverUrl,
+ _totalDuration,
+ chapter: chapterTitle,
+ );
+ // Force PlaybackState refresh so the notification position resets
+ // to 0 immediately instead of waiting for the next stream event.
+ if (_notifChapterMode) _handler?.refreshPlaybackState();
+ }
}
- }
- // ─── Completion detection (fallback) ───────────────────
- // processingStateStream is the primary signal; this is a safety net.
- if (_totalDuration > 0 && posSec >= _totalDuration - 1.0) {
- if (_preloadedNextBook != null && _isBackgrounded && Platform.isIOS) {
- debugPrint('[PreBuffer] Position-fallback near end with pre-buffer loaded — firing auto-queue advance');
- _onAutoQueueAdvanced();
+ // ─── Completion detection (fallback) ───────────────────
+ // processingStateStream is the primary signal; this is a safety net.
+ if (_totalDuration > 0 && posSec >= _totalDuration - 1.0) {
+ if (_preloadedNextBook != null && _isBackgrounded && Platform.isIOS) {
+ debugPrint(
+ '[PreBuffer] Position-fallback near end with pre-buffer loaded — firing auto-queue advance',
+ );
+ _onAutoQueueAdvanced();
+ return;
+ }
+ _onPlaybackComplete();
return;
}
- _onPlaybackComplete();
- return;
- }
- // Save locally every 5 seconds (always works, even offline)
- if (sec % 5 == 0 && sec != _lastSyncSecond && _currentItemId != null) {
- _lastSyncSecond = sec;
- _saveProgressLocal(absolutePos);
- // Bank listening to durable storage every tick, decoupled from the
- // server push below, so an abrupt kill loses at most one tick.
- await _accrueListening(absolutePos);
- if (_isCachedStartReconcilePending) return;
-
- // Push to server: 15s foreground, 60s background. Accuracy rides on the
- // accrual above, not this cadence — this is just server freshness.
- final syncInterval = _isBackgrounded ? 60 : 15;
- final sinceLastSync = DateTime.now().difference(_lastServerSync).inSeconds;
- if (sinceLastSync >= syncInterval && !_positionSyncInProgress) {
- _positionSyncInProgress = true;
- try {
- final manualOffline = (_prefs ?? await SharedPreferences.getInstance())
- .getBool('manual_offline_mode') ?? false;
-
- // If we're online but lost the playback session (e.g. pause-
- // timeout closed it and _resumeServerSync silently failed when
- // playback resumed), recreate it before the accumulator branch.
- // Without this the offline accumulator fills for hours and gets
- // dumped later as one phantom session with startTime==lastTime.
- // Skipped for local-session plays — they never open a /play session.
- if (!_localSessionMode &&
- !manualOffline &&
- !_isOfflineMode &&
- _playbackSessionId == null &&
- _api != null &&
- _currentItemId != null &&
- !_recreatingSession) {
- _recreatingSession = true;
- try {
- final sessionData = _currentEpisodeId != null
- ? await _api!.startEpisodePlaybackSession(
- _currentItemId!, _currentEpisodeId!)
- : await _api!.startPlaybackSession(_currentItemId!);
- if (sessionData != null) {
- _playbackSessionId = sessionData['id'] as String?;
- if (_playbackSessionId != null) {
- debugPrint('[Player] Recreated session in sync tick: '
- '$_playbackSessionId');
+ // Save locally every 5 seconds (always works, even offline)
+ if (sec % 5 == 0 && sec != _lastSyncSecond && _currentItemId != null) {
+ _lastSyncSecond = sec;
+ _saveProgressLocal(absolutePos);
+ // Bank listening to durable storage every tick, decoupled from the
+ // server push below, so an abrupt kill loses at most one tick.
+ await _accrueListening(absolutePos);
+ if (_isCachedStartReconcilePending) return;
+
+ // Push to server: 15s foreground, 60s background. Accuracy rides on the
+ // accrual above, not this cadence — this is just server freshness.
+ final syncInterval = _isBackgrounded ? 60 : 15;
+ final sinceLastSync = DateTime.now()
+ .difference(_lastServerSync)
+ .inSeconds;
+ if (sinceLastSync >= syncInterval && !_positionSyncInProgress) {
+ _positionSyncInProgress = true;
+ try {
+ final manualOffline =
+ (_prefs ?? await SharedPreferences.getInstance()).getBool(
+ 'manual_offline_mode',
+ ) ??
+ false;
+
+ // If we're online but lost the playback session (e.g. pause-
+ // timeout closed it and _resumeServerSync silently failed when
+ // playback resumed), recreate it before the accumulator branch.
+ // Without this the offline accumulator fills for hours and gets
+ // dumped later as one phantom session with startTime==lastTime.
+ // Skipped for local-session plays — they never open a /play session.
+ if (!_localSessionMode &&
+ !manualOffline &&
+ !_isOfflineMode &&
+ _playbackSessionId == null &&
+ _api != null &&
+ _currentItemId != null &&
+ !_recreatingSession) {
+ _recreatingSession = true;
+ try {
+ final sessionData = _currentEpisodeId != null
+ ? await _api!.startEpisodePlaybackSession(
+ _currentItemId!,
+ _currentEpisodeId!,
+ )
+ : await _api!.startPlaybackSession(_currentItemId!);
+ if (sessionData != null) {
+ _playbackSessionId = sessionData['id'] as String?;
+ if (_playbackSessionId != null) {
+ debugPrint(
+ '[Player] Recreated session in sync tick: '
+ '$_playbackSessionId',
+ );
+ }
}
+ } catch (e) {
+ debugPrint(
+ '[Player] Session recreate in sync tick failed: $e',
+ );
+ } finally {
+ _recreatingSession = false;
}
- } catch (e) {
- debugPrint('[Player] Session recreate in sync tick failed: $e');
- } finally {
- _recreatingSession = false;
}
- }
- // Listening itself is banked every tick by _accrueListening. These
- // branches only handle the interval-rate bookkeeping (time-saved,
- // widget tick) and, for downloaded plays, pushing the local session.
- final secs = sinceLastSync.clamp(0, 300);
- if (_localSessionMode) {
- final online = !manualOffline && !_isOfflineMode && _api != null;
- unawaited(_progressSync.addTimeSaved(secs, _player?.speed ?? 1.0));
- unawaited(HomeWidgetService().addLocalListeningSeconds(secs));
- if (online) await LocalSessionService().pushActive(api: _api!);
- _lastServerSync = DateTime.now();
- } else if (manualOffline || _isOfflineMode || _playbackSessionId == null) {
- unawaited(_progressSync.addTimeSaved(secs, _player?.speed ?? 1.0));
- // Widget ticks forward even when the server is unreachable.
- unawaited(HomeWidgetService().addLocalListeningSeconds(secs));
- _lastServerSync = DateTime.now();
- }
+ // Listening itself is banked every tick by _accrueListening. These
+ // branches only handle the interval-rate bookkeeping (time-saved,
+ // widget tick) and, for downloaded plays, pushing the local session.
+ final secs = sinceLastSync.clamp(0, 300);
+ if (_localSessionMode) {
+ final online =
+ !manualOffline && !_isOfflineMode && _api != null;
+ unawaited(
+ _progressSync.addTimeSaved(secs, _player?.speed ?? 1.0),
+ );
+ unawaited(HomeWidgetService().addLocalListeningSeconds(secs));
+ if (online) await LocalSessionService().pushActive(api: _api!);
+ _lastServerSync = DateTime.now();
+ } else if (manualOffline ||
+ _isOfflineMode ||
+ _playbackSessionId == null) {
+ unawaited(
+ _progressSync.addTimeSaved(secs, _player?.speed ?? 1.0),
+ );
+ // Widget ticks forward even when the server is unreachable.
+ unawaited(HomeWidgetService().addLocalListeningSeconds(secs));
+ _lastServerSync = DateTime.now();
+ }
- // Back off when the server is unreachable to avoid hammering
- // every sync interval with requests that will just timeout.
- if (_positionSyncFailures >= 3) {
- // Skip server sync - will retry after connectivity change
- // or app foreground resets the counter.
- _lastServerSync = DateTime.now();
- } else if (manualOffline) {
- // Manual offline - local save only, no server sync
- } else if (!_isOfflineMode && _playbackSessionId != null) {
- // Streaming/local with session: sync via session
- _syncToServer(absolutePos);
- } else if (!_isOfflineMode && _api != null && _currentItemId != null) {
- // No session but online - sync via progress update endpoint
- try {
- final syncKey = _currentEpisodeId != null
- ? '$_currentItemId-$_currentEpisodeId'
- : _currentItemId!;
- final ok = await _progressSync.syncToServer(
- api: _api!, itemId: syncKey);
- if (ok) {
- debugPrint('[Player] No-session sync succeeded');
- _positionSyncFailures = 0;
- } else {
+ // Back off when the server is unreachable to avoid hammering
+ // every sync interval with requests that will just timeout.
+ if (_positionSyncFailures >= 3) {
+ // Skip server sync - will retry after connectivity change
+ // or app foreground resets the counter.
+ _lastServerSync = DateTime.now();
+ } else if (manualOffline) {
+ // Manual offline - local save only, no server sync
+ } else if (!_isOfflineMode && _playbackSessionId != null) {
+ // Streaming/local with session: sync via session
+ _syncToServer(absolutePos);
+ } else if (!_isOfflineMode &&
+ _api != null &&
+ _currentItemId != null) {
+ // No session but online - sync via progress update endpoint
+ try {
+ final syncKey = _currentEpisodeId != null
+ ? '$_currentItemId-$_currentEpisodeId'
+ : _currentItemId!;
+ final ok = await _progressSync.syncToServer(
+ api: _api!,
+ itemId: syncKey,
+ );
+ if (ok) {
+ debugPrint('[Player] No-session sync succeeded');
+ _positionSyncFailures = 0;
+ } else {
+ _positionSyncFailures++;
+ debugPrint(
+ '[Player] No-session sync returned false (failures=$_positionSyncFailures)',
+ );
+ }
+ } catch (e) {
_positionSyncFailures++;
- debugPrint('[Player] No-session sync returned false (failures=$_positionSyncFailures)');
+ debugPrint(
+ '[Player] No-session sync error (failures=$_positionSyncFailures): $e',
+ );
}
- } catch (e) {
- _positionSyncFailures++;
- debugPrint('[Player] No-session sync error (failures=$_positionSyncFailures): $e');
}
+ } finally {
+ _positionSyncInProgress = false;
}
- } finally {
- _positionSyncInProgress = false;
}
}
- }
- }, onError: (Object e, StackTrace st) {
- debugPrint('[Player] Position stream error: $e');
- _attemptStreamRetry(e);
- });
+ },
+ onError: (Object e, StackTrace st) {
+ debugPrint('[Player] Position stream error: $e');
+ _attemptStreamRetry(e);
+ },
+ );
// Start stuck position detection (xHE-AAC/USAC iOS seek failures)
_startStuckDetection();
@@ -4231,12 +4932,16 @@ class AudioPlayerService extends ChangeNotifier {
// If playing or actively loading/buffering, all is well
if (_player!.playing) return;
final state = _player!.processingState;
- if (state == ProcessingState.loading || state == ProcessingState.buffering) return;
+ if (state == ProcessingState.loading ||
+ state == ProcessingState.buffering)
+ return;
// Player is idle/ready but not playing — silent failure
final currentPos = position.inMilliseconds / 1000.0;
- debugPrint('[Player] Play verify failed: not playing after 3s '
- '(state=${state.name}, pos=${currentPos.toStringAsFixed(1)}s, '
- 'posAtPlay=${posAtPlay.toStringAsFixed(1)}s)');
+ debugPrint(
+ '[Player] Play verify failed: not playing after 3s '
+ '(state=${state.name}, pos=${currentPos.toStringAsFixed(1)}s, '
+ 'posAtPlay=${posAtPlay.toStringAsFixed(1)}s)',
+ );
// Re-seek to current position to kick the decoder, then retry play
await _seekAbsolute(currentPos > 0 ? currentPos : posAtPlay);
_player?.play();
@@ -4255,7 +4960,6 @@ class AudioPlayerService extends ChangeNotifier {
// Skip on Android to reduce background CPU wakeups.
if (!Platform.isIOS) return;
-
_stuckCheckTimer = Timer.periodic(const Duration(seconds: 10), (_) async {
// Only check while actively playing
if (_player == null || !_player!.playing) {
@@ -4266,7 +4970,8 @@ class AudioPlayerService extends ChangeNotifier {
// Don't check during loading/buffering
final state = _player!.processingState;
- if (state == ProcessingState.loading || state == ProcessingState.buffering) {
+ if (state == ProcessingState.loading ||
+ state == ProcessingState.buffering) {
return;
}
@@ -4290,9 +4995,11 @@ class AudioPlayerService extends ChangeNotifier {
// Stuck for ~20 seconds - force re-seek
_stuckReseekAttempts++;
_stuckConsecutiveCount = 0;
- debugPrint('[Player] Stuck position detected - re-seeking '
- '(attempt $_stuckReseekAttempts/$_maxStuckReseekAttempts '
- 'at ${currentPos.toStringAsFixed(1)}s)');
+ debugPrint(
+ '[Player] Stuck position detected - re-seeking '
+ '(attempt $_stuckReseekAttempts/$_maxStuckReseekAttempts '
+ 'at ${currentPos.toStringAsFixed(1)}s)',
+ );
await _seekAbsolute(currentPos);
}
}
@@ -4309,7 +5016,9 @@ class AudioPlayerService extends ChangeNotifier {
// Re-entry attempts are logged too so we can see if completion fires
// multiple times from different signals (processingState, position-jump,
// fallback) and races with auto-advance.
- debugPrint('[Complete] entry: pos=${_lastKnownPositionSec.toStringAsFixed(1)}s totalDur=${_totalDuration.toStringAsFixed(1)}s item=$_currentItemId ep=$_currentEpisodeId reentry=$_isCompletingBook');
+ debugPrint(
+ '[Complete] entry: pos=${_lastKnownPositionSec.toStringAsFixed(1)}s totalDur=${_totalDuration.toStringAsFixed(1)}s item=$_currentItemId ep=$_currentEpisodeId reentry=$_isCompletingBook',
+ );
if (_isCompletingBook) return; // prevent re-entry
_isCompletingBook = true;
@@ -4337,11 +5046,16 @@ class AudioPlayerService extends ChangeNotifier {
_iosLastTrackRecoveryAttempts < _maxIosLastTrackRecoveries) {
_iosLastTrackRecoveryAttempts++;
final recoveryTarget = lastTrackStart + 0.5;
- debugPrint('[Player] iOS premature last-track completion detected '
- '(idx=$_currentTrackIndex/$lastIdx, lastTrackDur=${lastTrackDur.toStringAsFixed(1)}s, '
- 'advance=${msSinceAdvance}ms ago) — recovery attempt $_iosLastTrackRecoveryAttempts: '
- 'seeking to ${recoveryTarget.toStringAsFixed(1)}s');
- _logEvent(PlaybackEventType.pause, detail: 'iOS premature completion blocked');
+ debugPrint(
+ '[Player] iOS premature last-track completion detected '
+ '(idx=$_currentTrackIndex/$lastIdx, lastTrackDur=${lastTrackDur.toStringAsFixed(1)}s, '
+ 'advance=${msSinceAdvance}ms ago) — recovery attempt $_iosLastTrackRecoveryAttempts: '
+ 'seeking to ${recoveryTarget.toStringAsFixed(1)}s',
+ );
+ _logEvent(
+ PlaybackEventType.pause,
+ detail: 'iOS premature completion blocked',
+ );
_isCompletingBook = false;
try {
await _seekAbsolute(recoveryTarget);
@@ -4362,7 +5076,9 @@ class AudioPlayerService extends ChangeNotifier {
_lastKnownPositionSec > 0 &&
_lastKnownPositionSec < _totalDuration * 0.9 &&
_lastKnownPositionSec < _totalDuration - 30) {
- debugPrint('[Player] Spurious completion at ${_lastKnownPositionSec.toStringAsFixed(1)}s / ${_totalDuration.toStringAsFixed(1)}s — saving position instead of marking finished');
+ debugPrint(
+ '[Player] Spurious completion at ${_lastKnownPositionSec.toStringAsFixed(1)}s / ${_totalDuration.toStringAsFixed(1)}s — saving position instead of marking finished',
+ );
_logEvent(PlaybackEventType.pause, detail: 'Spurious completion blocked');
_syncSub?.cancel();
_syncSub = null;
@@ -4371,7 +5087,9 @@ class AudioPlayerService extends ChangeNotifier {
_bgSaveTimer?.cancel();
_bgSaveTimer = null;
await _player?.stop();
- await _saveProgressLocal(Duration(milliseconds: (_lastKnownPositionSec * 1000).round()));
+ await _saveProgressLocal(
+ Duration(milliseconds: (_lastKnownPositionSec * 1000).round()),
+ );
_isCompletingBook = false;
notifyListeners();
return;
@@ -4418,7 +5136,8 @@ class AudioPlayerService extends ChangeNotifier {
try {
if (episodeId != null) {
await api.updateEpisodeProgress(
- itemId, episodeId,
+ itemId,
+ episodeId,
currentTime: dur,
duration: dur,
isFinished: true,
@@ -4476,7 +5195,9 @@ class AudioPlayerService extends ChangeNotifier {
_onBookFinishedCallback!(key);
} else {
_pendingBookFinishedKey = key;
- debugPrint('[Player] Book-finished callback not registered, buffering key=$key');
+ debugPrint(
+ '[Player] Book-finished callback not registered, buffering key=$key',
+ );
}
}
@@ -4503,9 +5224,11 @@ class AudioPlayerService extends ChangeNotifier {
if (_shortLocalDurationSec != null && ct >= _shortLocalDurationSec! - 2.0) {
final saved = await _progressSync.getSavedPosition(progressKey);
if (saved > ct + 1.0) {
- debugPrint('[Player] Skipping save ${ct.toStringAsFixed(1)}s — would '
- 'clobber further saved ${saved.toStringAsFixed(1)}s from incomplete '
- 'download (GH #278)');
+ debugPrint(
+ '[Player] Skipping save ${ct.toStringAsFixed(1)}s — would '
+ 'clobber further saved ${saved.toStringAsFixed(1)}s from incomplete '
+ 'download (GH #278)',
+ );
return;
}
}
@@ -4547,12 +5270,15 @@ class AudioPlayerService extends ChangeNotifier {
final key = _currentEpisodeId != null
? '$_currentItemId-$_currentEpisodeId'
: _currentItemId!;
- final manualOffline =
- (_prefs?.getBool('manual_offline_mode')) ?? false;
+ final manualOffline = (_prefs?.getBool('manual_offline_mode')) ?? false;
final ct = absolutePos.inMilliseconds / 1000.0;
if (_localSessionMode) {
await LocalSessionService().accrue(
- progressKey: key, seconds: secs, currentTime: ct, api: null);
+ progressKey: key,
+ seconds: secs,
+ currentTime: ct,
+ api: null,
+ );
} else if (manualOffline || _isOfflineMode || _playbackSessionId == null) {
await _progressSync.addOfflineListeningTime(key, secs);
} else {
@@ -4571,7 +5297,8 @@ class AudioPlayerService extends ChangeNotifier {
return;
}
final now = DateTime.now();
- final elapsed = timeListenedOverride ??
+ final elapsed =
+ timeListenedOverride ??
now.difference(_lastServerSync).inSeconds.clamp(0, 300);
_lastServerSync = now;
// The streaming safety buffer mirrors this same span; read it before the
@@ -4579,20 +5306,24 @@ class AudioPlayerService extends ChangeNotifier {
// timeListened (not an override) is what the buffer is shadowing.
final streamKey = (timeListenedOverride == null && _currentItemId != null)
? (_currentEpisodeId != null
- ? '$_currentItemId-$_currentEpisodeId'
- : _currentItemId!)
+ ? '$_currentItemId-$_currentEpisodeId'
+ : _currentItemId!)
: null;
final pendingBefore = streamKey != null
? await _progressSync.getStreamingPendingTime(streamKey)
: 0;
if (elapsed > 0) {
- unawaited(_progressSync.addTimeSaved(elapsed.toInt(), _player?.speed ?? 1.0));
+ unawaited(
+ _progressSync.addTimeSaved(elapsed.toInt(), _player?.speed ?? 1.0),
+ );
}
// Alpha: volume/sessionId piggybacked for GH #179 (volume falls off).
// We sample these on each sync tick so drift over time is visible.
final vol = _player?.volume;
final eqSid = _player?.androidAudioSessionId;
- debugPrint('[Player] Sync session ${_playbackSessionId!.substring(0, 8)}... | currentTime=${ct.toStringAsFixed(1)}s, timeListened=${elapsed}s, volume=$vol, eqSession=$eqSid');
+ debugPrint(
+ '[Player] Sync session ${_playbackSessionId!.substring(0, 8)}... | currentTime=${ct.toStringAsFixed(1)}s, timeListened=${elapsed}s, volume=$vol, eqSession=$eqSid',
+ );
final ok = await _api!.syncPlaybackSession(
_playbackSessionId!,
currentTime: ct,
@@ -4605,7 +5336,9 @@ class AudioPlayerService extends ChangeNotifier {
unawaited(HomeWidgetService().addLocalListeningSeconds(elapsed));
}
if (ok && streamKey != null && pendingBefore > 0) {
- unawaited(_progressSync.reduceStreamingPendingTime(streamKey, pendingBefore));
+ unawaited(
+ _progressSync.reduceStreamingPendingTime(streamKey, pendingBefore),
+ );
}
if (ok) {
_logEvent(PlaybackEventType.syncServer, detail: '+${elapsed}s');
@@ -4626,7 +5359,10 @@ class AudioPlayerService extends ChangeNotifier {
if (_api == null || _currentItemId == null) return;
try {
final sessionData = _currentEpisodeId != null
- ? await _api!.startEpisodePlaybackSession(_currentItemId!, _currentEpisodeId!)
+ ? await _api!.startEpisodePlaybackSession(
+ _currentItemId!,
+ _currentEpisodeId!,
+ )
: await _api!.startPlaybackSession(_currentItemId!);
if (sessionData != null) {
_playbackSessionId = sessionData['id'] as String?;
@@ -4674,8 +5410,11 @@ class AudioPlayerService extends ChangeNotifier {
/// Scales linearly from minRewind at activationDelay to maxRewind at 1 hour.
/// activationDelay = minimum pause before rewind kicks in (0 = always).
static double calculateAutoRewind(
- Duration pauseDuration, double minRewind, double maxRewind,
- {double activationDelay = 0}) {
+ Duration pauseDuration,
+ double minRewind,
+ double maxRewind, {
+ double activationDelay = 0,
+ }) {
final pauseSeconds = pauseDuration.inSeconds.toDouble();
// Don't rewind if pause is shorter than activation delay
@@ -4683,7 +5422,10 @@ class AudioPlayerService extends ChangeNotifier {
// Linear from min to max over 1 hour of pause time
const maxPause = 3600.0; // 1 hour = full rewind
- final effectivePause = (pauseSeconds - activationDelay).clamp(0.0, maxPause);
+ final effectivePause = (pauseSeconds - activationDelay).clamp(
+ 0.0,
+ maxPause,
+ );
final t = effectivePause / maxPause;
final rewind = minRewind + (maxRewind - minRewind) * t;
return rewind.clamp(minRewind, maxRewind);
@@ -4706,23 +5448,30 @@ class AudioPlayerService extends ChangeNotifier {
lastPlayedItemId: prefs.getString('widget_item_id'),
);
if (decision == ColdStartPlayDecision.restoreLastPlayed) {
- debugPrint('[Service] play() on cold-started service - routing to cold-start restore');
+ debugPrint(
+ '[Service] play() on cold-started service - routing to cold-start restore',
+ );
final restore = AudioPlayerService.onColdStartPlayRequested;
if (restore != null) {
unawaited(restore());
} else {
- debugPrint('[Service] No cold-start restore handler registered - ignoring play');
+ debugPrint(
+ '[Service] No cold-start restore handler registered - ignoring play',
+ );
}
return;
}
if (decision == ColdStartPlayDecision.nothing) {
- debugPrint('[Service] play() called with no current item and no history - ignoring');
+ debugPrint(
+ '[Service] play() called with no current item and no history - ignoring',
+ );
return;
}
_pauseStopTimer?.cancel();
_pauseStopTimer = null;
- _noisyPause = false; // User explicitly resumed — allow interrupt-resume again
+ _noisyPause =
+ false; // User explicitly resumed — allow interrupt-resume again
_handler?._noisyPauseAt = null; // Clear noisy suppression window
_lastAutoRewindAmount = 0;
// Auto-rewind on resume if enabled
@@ -4731,12 +5480,16 @@ class AudioPlayerService extends ChangeNotifier {
if (settings.enabled) {
final pauseDuration = DateTime.now().difference(_lastPauseTime!);
final rewindSeconds = calculateAutoRewind(
- pauseDuration, settings.minRewind, settings.maxRewind,
- activationDelay: settings.activationDelay);
+ pauseDuration,
+ settings.minRewind,
+ settings.maxRewind,
+ activationDelay: settings.activationDelay,
+ );
if (rewindSeconds > 0.5) {
final currentAbsolutePos = position.inMilliseconds / 1000.0;
final currentSpeed = _player!.speed;
- var newPosSeconds = currentAbsolutePos - (rewindSeconds * currentSpeed);
+ var newPosSeconds =
+ currentAbsolutePos - (rewindSeconds * currentSpeed);
if (newPosSeconds < 0) newPosSeconds = 0;
// Chapter barrier: don't rewind past the current chapter start
if (settings.chapterBarrier && _chapters.isNotEmpty) {
@@ -4763,8 +5516,9 @@ class AudioPlayerService extends ChangeNotifier {
: '${rewindSeconds.toStringAsFixed(1)}s (${actualDelta.toStringAsFixed(1)}s at ${currentSpeed.toStringAsFixed(2)}x)';
_logEvent(PlaybackEventType.autoRewind, detail: rewindDetail);
debugPrint(
- '[Player] Auto-rewind ${rewindSeconds.toStringAsFixed(1)}s '
- '(paused ${pauseDuration.inSeconds}s)');
+ '[Player] Auto-rewind ${rewindSeconds.toStringAsFixed(1)}s '
+ '(paused ${pauseDuration.inSeconds}s)',
+ );
}
}
}
@@ -4774,24 +5528,33 @@ class AudioPlayerService extends ChangeNotifier {
_lastServerSync = DateTime.now();
_lastAccrual = DateTime.now();
// Re-activate audio session in case a prior stop released it.
- try { (await AudioSession.instance).setActive(true); } catch (_) {}
+ try {
+ (await AudioSession.instance).setActive(true);
+ } catch (_) {}
// If the player is idle (source was disposed), we need to fully re-initialize
// playback instead of just calling play() on an empty player.
- if (_player?.processingState == ProcessingState.idle && _currentItemId != null && _api != null) {
+ if (_player?.processingState == ProcessingState.idle &&
+ _currentItemId != null &&
+ _api != null) {
// Cap re-inits within a window so a book the engine can't start doesn't
// spin here forever, hammering the server with fresh play sessions.
final now = DateTime.now();
- if (_lastIdleReinit != null && now.difference(_lastIdleReinit!) < _idleReinitWindow) {
+ if (_lastIdleReinit != null &&
+ now.difference(_lastIdleReinit!) < _idleReinitWindow) {
_idleReinitCount++;
} else {
_idleReinitCount = 1;
}
_lastIdleReinit = now;
if (_idleReinitCount > _idleReinitMaxAttempts) {
- debugPrint('[Player] Idle-on-resume re-init capped after $_idleReinitCount attempts — giving up to avoid a retry storm');
+ debugPrint(
+ '[Player] Idle-on-resume re-init capped after $_idleReinitCount attempts — giving up to avoid a retry storm',
+ );
return;
}
- debugPrint('[Player] Player is idle on resume - re-initializing playback for $_currentItemId (attempt $_idleReinitCount)');
+ debugPrint(
+ '[Player] Player is idle on resume - re-initializing playback for $_currentItemId (attempt $_idleReinitCount)',
+ );
playItem(
api: _api!,
itemId: _currentItemId!,
@@ -4824,7 +5587,8 @@ class AudioPlayerService extends ChangeNotifier {
if (_bgSaveTimer == null || !_bgSaveTimer!.isActive) {
_bgSaveTimer?.cancel();
_bgSaveTimer = Timer.periodic(const Duration(seconds: 300), (_) async {
- if (_currentItemId == null || _player == null || !_player!.playing) return;
+ if (_currentItemId == null || _player == null || !_player!.playing)
+ return;
final pos = position;
final posSec = pos.inMilliseconds / 1000.0;
if (posSec <= 0) return;
@@ -4851,10 +5615,15 @@ class AudioPlayerService extends ChangeNotifier {
void _resumeServerSync() async {
if (_api == null || _currentItemId == null) return;
if (_recreatingSession) return;
- final manualOffline = (_prefs ?? await SharedPreferences.getInstance())
- .getBool('manual_offline_mode') ?? false;
+ final manualOffline =
+ (_prefs ?? await SharedPreferences.getInstance()).getBool(
+ 'manual_offline_mode',
+ ) ??
+ false;
if (manualOffline || _isOfflineMode || _localSessionMode) {
- debugPrint('[Player] Skipping session re-create on resume (manualOffline=$manualOffline, isOffline=$_isOfflineMode, localSession=$_localSessionMode)');
+ debugPrint(
+ '[Player] Skipping session re-create on resume (manualOffline=$manualOffline, isOffline=$_isOfflineMode, localSession=$_localSessionMode)',
+ );
return;
}
// Skip server position override if user manually seeked while paused
@@ -4875,18 +5644,28 @@ class AudioPlayerService extends ChangeNotifier {
if (_playbackSessionId == null) {
// Session expired - re-create it
final sessionData = _currentEpisodeId != null
- ? await _api!.startEpisodePlaybackSession(_currentItemId!, _currentEpisodeId!)
+ ? await _api!.startEpisodePlaybackSession(
+ _currentItemId!,
+ _currentEpisodeId!,
+ )
: await _api!.startPlaybackSession(_currentItemId!);
if (sessionData != null) {
_playbackSessionId = sessionData['id'] as String?;
- debugPrint('[Player] Re-created session on resume: $_playbackSessionId');
+ debugPrint(
+ '[Player] Re-created session on resume: $_playbackSessionId',
+ );
if (!skipOverride) {
- final serverPos = (sessionData['currentTime'] as num?)?.toDouble() ?? 0;
+ final serverPos =
+ (sessionData['currentTime'] as num?)?.toDouble() ?? 0;
final serverTs = (sessionData['updatedAt'] as num?)?.toInt() ?? 0;
final localPos = position.inMilliseconds / 1000.0;
- final ahead = serverTs > localTs && serverPos > localPos + _lastAutoRewindAmount + 5.0;
+ final ahead =
+ serverTs > localTs &&
+ serverPos > localPos + _lastAutoRewindAmount + 5.0;
// [AlphaDiag] log inputs; strip before beta.
- debugPrint('[Player] Resume server-check (recreated): server=${serverPos}s(ts=$serverTs) vs local=${localPos}s(ts=$localTs) rewindAmt=$_lastAutoRewindAmount -> ${ahead ? "SEEKING" : "keep local"}');
+ debugPrint(
+ '[Player] Resume server-check (recreated): server=${serverPos}s(ts=$serverTs) vs local=${localPos}s(ts=$localTs) rewindAmt=$_lastAutoRewindAmount -> ${ahead ? "SEEKING" : "keep local"}',
+ );
if (ahead) {
await _seekAbsolute(serverPos);
}
@@ -4897,13 +5676,19 @@ class AudioPlayerService extends ChangeNotifier {
if (!skipOverride) {
final serverProgress = await _api!.getItemProgress(pKey);
if (serverProgress != null) {
- final serverPos = (serverProgress['currentTime'] as num?)?.toDouble() ?? 0;
- final serverTs = (serverProgress['lastUpdate'] as num?)?.toInt() ?? 0;
+ final serverPos =
+ (serverProgress['currentTime'] as num?)?.toDouble() ?? 0;
+ final serverTs =
+ (serverProgress['lastUpdate'] as num?)?.toInt() ?? 0;
final localPos = position.inMilliseconds / 1000.0;
- final ahead = serverTs > localTs && serverPos > localPos + _lastAutoRewindAmount + 5.0;
+ final ahead =
+ serverTs > localTs &&
+ serverPos > localPos + _lastAutoRewindAmount + 5.0;
// [AlphaDiag] log the inputs so we can tell a stale pre-rewind server
// position from a real cross-device advance. Strip before beta.
- debugPrint('[Player] Resume server-check (active): server=${serverPos}s(ts=$serverTs) vs local=${localPos}s(ts=$localTs) rewindAmt=$_lastAutoRewindAmount -> ${ahead ? "SEEKING" : "keep local"}');
+ debugPrint(
+ '[Player] Resume server-check (active): server=${serverPos}s(ts=$serverTs) vs local=${localPos}s(ts=$localTs) rewindAmt=$_lastAutoRewindAmount -> ${ahead ? "SEEKING" : "keep local"}',
+ );
if (ahead) {
await _seekAbsolute(serverPos);
}
@@ -4926,9 +5711,11 @@ class AudioPlayerService extends ChangeNotifier {
_lastPauseTime = DateTime.now();
// Stamp BT-route observation for AA-disconnect phantom-click detection.
// Fire-and-forget: pause shouldn't block on a native call.
- unawaited(_isBluetoothAudioConnected().then((bt) {
- if (bt) _lastPlayedOnBtAt = DateTime.now();
- }));
+ unawaited(
+ _isBluetoothAudioConnected().then((bt) {
+ if (bt) _lastPlayedOnBtAt = DateTime.now();
+ }),
+ );
// Stop timers to avoid background wakes while paused
if (_bgSaveTimer != null) {
_bgSaveTimer!.cancel();
@@ -4944,12 +5731,17 @@ class AudioPlayerService extends ChangeNotifier {
notifyListeners();
final pos = position;
- debugPrint('[Player] Saving on pause: ${(pos.inMilliseconds / 1000.0).toStringAsFixed(1)}s');
+ debugPrint(
+ '[Player] Saving on pause: ${(pos.inMilliseconds / 1000.0).toStringAsFixed(1)}s',
+ );
await _saveProgressLocal(pos);
// Check manual offline before syncing
- final manualOffline = (_prefs ?? await SharedPreferences.getInstance())
- .getBool('manual_offline_mode') ?? false;
+ final manualOffline =
+ (_prefs ?? await SharedPreferences.getInstance()).getBool(
+ 'manual_offline_mode',
+ ) ??
+ false;
// Credit listening right up to the pause for whatever mode is active — we
// were playing until now — then let the push below ship it. resume (play())
@@ -5011,8 +5803,11 @@ class AudioPlayerService extends ChangeNotifier {
}
}
- Future<void> seekTo(Duration pos,
- {PlaybackEventType logAs = PlaybackEventType.seek, String? logDetail}) async {
+ Future<void> seekTo(
+ Duration pos, {
+ PlaybackEventType logAs = PlaybackEventType.seek,
+ String? logDetail,
+ }) async {
// While this item is casting, the Chromecast is the real player - route
// the seek there too or bookmark/chapter jumps only move the stopped
// local player (GH #273).
@@ -5027,9 +5822,11 @@ class AudioPlayerService extends ChangeNotifier {
if (_player != null && !_player!.playing) _seekedWhilePaused = true;
final from = position;
await _seekAbsolute(pos.inMilliseconds / 1000.0);
- _logEvent(logAs,
- detail: logDetail ?? '${_formatPos(from)} → ${_formatPos(pos)}',
- overridePosition: from.inMilliseconds / 1000.0);
+ _logEvent(
+ logAs,
+ detail: logDetail ?? '${_formatPos(from)} → ${_formatPos(pos)}',
+ overridePosition: from.inMilliseconds / 1000.0,
+ );
notifyListeners();
}
@@ -5041,8 +5838,11 @@ class AudioPlayerService extends ChangeNotifier {
var target = position - Duration(seconds: seconds);
if (target < Duration.zero) target = Duration.zero;
final amount = seconds % 60 == 0 ? '${seconds ~/ 60}m' : '${seconds}s';
- await seekTo(target,
- logAs: PlaybackEventType.autoRewind, logDetail: '$amount (sleep timer)');
+ await seekTo(
+ target,
+ logAs: PlaybackEventType.autoRewind,
+ logDetail: '$amount (sleep timer)',
+ );
}
Future<void> skipForward([int seconds = 30]) async {
@@ -5051,10 +5851,15 @@ class AudioPlayerService extends ChangeNotifier {
if (!_player!.playing) _seekedWhilePaused = true;
// Multiply by speed so the skip feels like the configured amount of real time
final adjusted = (seconds * speed).round();
- debugPrint('[Service] skipForward(${seconds}s × ${speed}x = ${adjusted}s) — playing=${_player!.playing}');
+ debugPrint(
+ '[Service] skipForward(${seconds}s × ${speed}x = ${adjusted}s) — playing=${_player!.playing}',
+ );
final newPos = position + Duration(seconds: adjusted);
await _seekAbsolute(newPos.inMilliseconds / 1000.0);
- _logEvent(PlaybackEventType.skipForward, detail: '+${seconds}s (${adjusted}s @ ${speed}x)');
+ _logEvent(
+ PlaybackEventType.skipForward,
+ detail: '+${seconds}s (${adjusted}s @ ${speed}x)',
+ );
debugPrint('[Service] skipForward done — playing=${_player!.playing}');
}
@@ -5075,20 +5880,27 @@ class AudioPlayerService extends ChangeNotifier {
double chapterStart = 0;
for (int i = _chapters.length - 1; i >= 0; i--) {
final s = (_chapters[i]['start'] as num?)?.toDouble() ?? 0;
- if (s <= posS + 0.5) { chapterStart = s; break; }
+ if (s <= posS + 0.5) {
+ chapterStart = s;
+ break;
+ }
}
final intoChapter = posS - chapterStart;
// If the rewind would cross the chapter boundary
if (targetS < chapterStart && intoChapter > 0.5) {
final now = DateTime.now();
- final recentSnap = _lastRewindChapterSnap != null &&
+ final recentSnap =
+ _lastRewindChapterSnap != null &&
now.difference(_lastRewindChapterSnap!).inMilliseconds < 2000;
if (!recentSnap) {
// Snap to chapter start instead of crossing
_lastRewindChapterSnap = now;
await _seekAbsolute(chapterStart);
- _logEvent(PlaybackEventType.skipBackward, detail: 'snap to chapter start');
+ _logEvent(
+ PlaybackEventType.skipBackward,
+ detail: 'snap to chapter start',
+ );
return;
}
// Double-tap within 2s - break through the barrier
@@ -5098,7 +5910,10 @@ class AudioPlayerService extends ChangeNotifier {
var n = targetS < 0 ? 0.0 : targetS;
await _seekAbsolute(n);
- _logEvent(PlaybackEventType.skipBackward, detail: '-${seconds}s (${adjusted}s @ ${speed}x)');
+ _logEvent(
+ PlaybackEventType.skipBackward,
+ detail: '-${seconds}s (${adjusted}s @ ${speed}x)',
+ );
}
Future<void> skipToNextChapter() async {
@@ -5119,9 +5934,7 @@ class AudioPlayerService extends ChangeNotifier {
await _onPlaybackComplete(userRequested: true);
return;
}
- debugPrint(
- '[Service] skipToNextChapter → ${target.seconds}s',
- );
+ debugPrint('[Service] skipToNextChapter → ${target.seconds}s');
await _seekAbsolute(target.seconds);
_logEvent(PlaybackEventType.seek, detail: 'next chapter');
notifyListeners();
@@ -5154,15 +5967,24 @@ class AudioPlayerService extends ChangeNotifier {
debugPrint('[Service] setSpeed(${s}x) — before: ${_player!.speed}x');
await _player!.setSpeed(s);
debugPrint('[Service] setSpeed done — after: ${_player!.speed}x');
- _logEvent(PlaybackEventType.speedChange, detail: '${s.toStringAsFixed(2)}x');
+ _logEvent(
+ PlaybackEventType.speedChange,
+ detail: '${s.toStringAsFixed(2)}x',
+ );
if (_currentItemId != null) {
PlayerSettings.setBookSpeed(_currentItemId!, s);
// Re-push MediaItem so the notification/AA duration updates for the
// new speed (duration is divided by speed for speed-adjusted time).
if (_handler != null) {
final chTitle = currentChapter?['title'] as String?;
- _pushMediaItem(_mediaItemKey, _currentTitle ?? '', _currentAuthor ?? '',
- _currentCoverUrl, _totalDuration, chapter: chTitle);
+ _pushMediaItem(
+ _mediaItemKey,
+ _currentTitle ?? '',
+ _currentAuthor ?? '',
+ _currentCoverUrl,
+ _totalDuration,
+ chapter: chTitle,
+ );
}
}
// Refresh the PlaybackState so Android Auto's speed badge tracks the rate.
@@ -5189,7 +6011,9 @@ class AudioPlayerService extends ChangeNotifier {
// Save final position locally
if (_currentItemId != null) {
final pos = position;
- debugPrint('[Player] Saving on stop: ${(pos.inMilliseconds / 1000.0).toStringAsFixed(1)}s');
+ debugPrint(
+ '[Player] Saving on stop: ${(pos.inMilliseconds / 1000.0).toStringAsFixed(1)}s',
+ );
await _saveProgressLocal(pos);
// Credit the final playing tail before the push/close below. Skipped when
// stopped from a paused state so the idle span isn't counted.
@@ -5197,8 +6021,11 @@ class AudioPlayerService extends ChangeNotifier {
}
// Check manual offline before syncing
- final manualOffline = (_prefs ?? await SharedPreferences.getInstance())
- .getBool('manual_offline_mode') ?? false;
+ final manualOffline =
+ (_prefs ?? await SharedPreferences.getInstance()).getBool(
+ 'manual_offline_mode',
+ ) ??
+ false;
if (!manualOffline) {
// Try server sync. If stop() was called while already paused, we were
@@ -5206,8 +6033,10 @@ class AudioPlayerService extends ChangeNotifier {
// so the wall-clock diff doesn't inflate server listening stats.
if (_playbackSessionId != null && _api != null) {
_logEvent(PlaybackEventType.sessionEnd, detail: 'stop');
- await _syncToServer(position,
- timeListenedOverride: wasPlaying ? null : 0);
+ await _syncToServer(
+ position,
+ timeListenedOverride: wasPlaying ? null : 0,
+ );
try {
debugPrint('[Player] Closing session (stop)');
await _api!.closePlaybackSession(_playbackSessionId!);
@@ -5241,7 +6070,9 @@ class AudioPlayerService extends ChangeNotifier {
// because deactivating the session can interfere with cast playback.
if (!ChromecastService().isCasting) {
debugPrint('[Battery] AudioSession DEACTIVATED (stop)');
- try { (await AudioSession.instance).setActive(false); } catch (_) {}
+ try {
+ (await AudioSession.instance).setActive(false);
+ } catch (_) {}
}
}
diff --git a/lib/services/backup_service.dart b/lib/services/backup_service.dart
index e35aca87..88193122 100644
--- a/lib/services/backup_service.dart
+++ b/lib/services/backup_service.dart
@@ -196,6 +196,8 @@ class BackupService {
// Podcast subscriptions + manually-curated Absorbing list (scoped)
final subscribedPodcasts = await ScopedPrefs.getStringList('subscribed_podcasts');
final absorbingManualAdds = await ScopedPrefs.getStringList('absorbing_manual_adds');
+ final absorbingFinishedManualAdds =
+ await ScopedPrefs.getStringList('absorbing_finished_manual_adds');
final absorbingManualRemoves = await ScopedPrefs.getStringList('absorbing_manual_removes');
// Pending offline state (scoped) - server hasn't received these yet
@@ -340,6 +342,7 @@ class BackupService {
'rollingDownloadSeries': rollingDownloadSeries,
'subscribedPodcasts': subscribedPodcasts,
'absorbingManualAdds': absorbingManualAdds,
+ 'absorbingFinishedManualAdds': absorbingFinishedManualAdds,
'absorbingManualRemoves': absorbingManualRemoves,
'pendingSyncs': pendingSyncs,
'pendingOfflineListening': pendingOfflineListening,
@@ -647,6 +650,14 @@ class BackupService {
if (absorbingManualAdds != null) {
await ScopedPrefs.setStringList('absorbing_manual_adds', absorbingManualAdds.cast<String>());
}
+ final absorbingFinishedManualAdds =
+ data['absorbingFinishedManualAdds'] as List<dynamic>?;
+ if (absorbingFinishedManualAdds != null) {
+ await ScopedPrefs.setStringList(
+ 'absorbing_finished_manual_adds',
+ absorbingFinishedManualAdds.cast<String>(),
+ );
+ }
final absorbingManualRemoves = data['absorbingManualRemoves'] as List<dynamic>?;
if (absorbingManualRemoves != null) {
await ScopedPrefs.setStringList('absorbing_manual_removes', absorbingManualRemoves.cast<String>());
diff --git a/lib/services/download_service.dart b/lib/services/download_service.dart
index 79d8268a..2d6d6659 100644
--- a/lib/services/download_service.dart
+++ b/lib/services/download_service.dart
@@ -1255,6 +1255,7 @@ class DownloadService extends ChangeNotifier {
/// Returns null on success, error message string on failure.
/// For podcast episodes, pass [episodeId] so the correct API endpoint is used.
+ /// [shouldStart] lets a caller invalidate the request while setup is waiting.
Future<String?> downloadItem({
required ApiService api,
required String itemId,
@@ -1263,7 +1264,9 @@ class DownloadService extends ChangeNotifier {
String? coverUrl,
String? episodeId,
String? libraryId,
+ bool Function()? shouldStart,
}) async {
+ if (shouldStart?.call() == false) return null;
try {
await init().timeout(const Duration(seconds: 8));
} on TimeoutException catch (e) {
@@ -1273,6 +1276,7 @@ class DownloadService extends ChangeNotifier {
debugPrint('[Download] Downloader initialization failed: $e');
return 'Downloads could not start. Please try again.';
}
+ if (shouldStart?.call() == false) return null;
if (_activeDownloadIds.contains(itemId)) return null;
if (isDownloaded(itemId)) return null;
@@ -1281,14 +1285,17 @@ class DownloadService extends ChangeNotifier {
// Check wifi-only setting
final wifiOnly = await PlayerSettings.getWifiOnlyDownloads();
+ if (shouldStart?.call() == false) return null;
if (wifiOnly) {
final connectivity = await Connectivity().checkConnectivity();
+ if (shouldStart?.call() == false) return null;
if (!connectivity.contains(ConnectivityResult.wifi)) {
return 'Downloads are set to Wi-Fi only. Connect to Wi-Fi or change this in Settings.';
}
}
final maxConcurrent = await PlayerSettings.getMaxConcurrentDownloads();
+ if (shouldStart?.call() == false) return null;
// The checks above ran before settings were loaded, so another tap may
// have started or queued this item in the meantime.
@@ -1300,6 +1307,7 @@ class DownloadService extends ChangeNotifier {
// If at capacity, queue this one
if (_activeDownloadIds.length >= maxConcurrent) {
+ if (shouldStart?.call() == false) return null;
debugPrint('[Download] Queued "$title" ($itemId); slots ${_activeDownloadIds.length}/$maxConcurrent full, ${_queue.length} waiting');
_queue.add(_QueuedDownload(
api: api,
@@ -1324,6 +1332,7 @@ class DownloadService extends ChangeNotifier {
}
// Launch immediately (fire-and-forget so caller doesn't block)
+ if (shouldStart?.call() == false) return null;
unawaited(_executeDownload(
api: api,
itemId: itemId,
@@ -1974,7 +1983,7 @@ class DownloadService extends ChangeNotifier {
// live position, so it's safe even when this fires from a background update.
try {
final player = AudioPlayerService();
- if (player.currentItemId == itemId && player.hasBook) {
+ if (player.hasBook) {
await player.switchToLocal(itemId);
}
} catch (_) {}
diff --git a/lib/services/equalizer_service.dart b/lib/services/equalizer_service.dart
index d12e7338..c5862e36 100644
--- a/lib/services/equalizer_service.dart
+++ b/lib/services/equalizer_service.dart
@@ -87,7 +87,11 @@ class EqualizerService extends ChangeNotifier {
if (_bandLevels.length != numBands) {
_bandLevels = List.filled(numBands, 0.0);
}
- debugPrint('[EQ] Platform EQ available: ${_bandFrequencies.length} bands');
+ if (result['deferred'] == true) {
+ debugPrint('[EQ] Platform EQ will initialize when playback starts');
+ } else {
+ debugPrint('[EQ] Platform EQ available: ${_bandFrequencies.length} bands');
+ }
if (_enabled) _applyCurrentSettings();
}
} on MissingPluginException {
diff --git a/lib/services/player_settings.dart b/lib/services/player_settings.dart
index c48a4bd2..efe101ea 100644
--- a/lib/services/player_settings.dart
+++ b/lib/services/player_settings.dart
@@ -487,6 +487,12 @@ class PlayerSettings {
static Future<bool> getMediaControlsSpeedBookmark() => _get('mediaControlsSpeedBookmark', false);
static Future<void> setMediaControlsSpeedBookmark(bool value) => _set('mediaControlsSpeedBookmark', value, notify: true);
+ // Android only: lower the volume for brief focus interruptions instead of
+ // pausing. Pausing remains the default.
+ static Future<bool> getDuckBriefInterruptions() => _get('duckBriefInterruptions', false);
+ static Future<void> setDuckBriefInterruptions(bool value) =>
+ _set('duckBriefInterruptions', value, notify: true);
+
// When true, the system media scrubber still shows progress but can't be
// dragged to seek - stops accidental position jumps from the notification,
// lockscreen, Android Auto and CarPlay. Implemented by dropping the seek
diff --git a/lib/services/queue_download_policy.dart b/lib/services/queue_download_policy.dart
new file mode 100644
index 00000000..add9494f
--- /dev/null
+++ b/lib/services/queue_download_policy.dart
@@ -0,0 +1,133 @@
+List<T> queueTailFrom<T>({
+ required List<T> items,
+ required String currentKey,
+ required String Function(T item) keyOf,
+ bool startAtBeginningWhenMissing = false,
+}) {
+ final currentIndex = items.indexWhere((item) => keyOf(item) == currentKey);
+ if (currentIndex < 0) {
+ return startAtBeginningWhenMissing ? List<T>.from(items) : const [];
+ }
+ return items.sublist(currentIndex);
+}
+
+List<T> manualQueueTail<T>({
+ required List<T> items,
+ required String currentKey,
+ required String Function(T item) keyOf,
+ required bool Function(T item) isFinished,
+ required bool Function(T item) isPodcast,
+ required String Function(T item) queueMode,
+ required String? Function(T item) libraryId,
+ required bool merged,
+ required bool currentIsPodcast,
+ required String? currentLibraryId,
+}) {
+ final tail = queueTailFrom(
+ items: items,
+ currentKey: currentKey,
+ keyOf: keyOf,
+ startAtBeginningWhenMissing: true,
+ );
+ return tail.where((item) {
+ if (isFinished(item) || queueMode(item) == 'off') return false;
+ if (!merged && isPodcast(item) != currentIsPodcast) return false;
+ if (!merged && currentLibraryId != null) {
+ final candidateLibraryId = libraryId(item);
+ if (candidateLibraryId != null &&
+ candidateLibraryId != currentLibraryId) {
+ return false;
+ }
+ }
+ return true;
+ }).toList();
+}
+
+List<T> podcastQueueTail<T>({
+ required List<T> episodes,
+ required String currentEpisodeId,
+ required String Function(T episode) idOf,
+ required int Function(T episode) publishedAt,
+ required bool newestFirst,
+}) {
+ final ordered = List<T>.from(episodes)
+ ..sort((a, b) {
+ final comparison = publishedAt(a).compareTo(publishedAt(b));
+ return newestFirst ? -comparison : comparison;
+ });
+ return queueTailFrom(
+ items: ordered,
+ currentKey: currentEpisodeId,
+ keyOf: idOf,
+ );
+}
+
+List<T> seriesQueueTail<T>({
+ required T current,
+ required Iterable<T> books,
+ required String currentKey,
+ required String currentSeriesId,
+ required double currentSequence,
+ required String Function(T book) keyOf,
+ required String? Function(T book) seriesId,
+ required double? Function(T book) sequence,
+}) {
+ final candidates = <String, T>{currentKey: current};
+ for (final book in books) {
+ final key = keyOf(book);
+ final candidateSequence = sequence(book);
+ if (key.isEmpty ||
+ key == currentKey ||
+ seriesId(book) != currentSeriesId ||
+ candidateSequence == null ||
+ candidateSequence <= currentSequence) {
+ continue;
+ }
+ candidates.putIfAbsent(key, () => book);
+ }
+ final ordered = candidates.values.toList()
+ ..sort((a, b) {
+ final aSequence = keyOf(a) == currentKey
+ ? currentSequence
+ : sequence(a) ?? double.maxFinite;
+ final bSequence = keyOf(b) == currentKey
+ ? currentSequence
+ : sequence(b) ?? double.maxFinite;
+ return aSequence.compareTo(bSequence);
+ });
+ return ordered;
+}
+
+List<T> queueDownloadWindow<T>({
+ required Iterable<T> items,
+ required int count,
+ required String Function(T item) keyOf,
+ required bool Function(T item) isFinished,
+}) {
+ if (count <= 0) return const [];
+ final result = <T>[];
+ final seen = <String>{};
+ for (final item in items) {
+ final key = keyOf(item);
+ if (key.isEmpty || !seen.add(key)) continue;
+ if (isFinished(item)) continue;
+ result.add(item);
+ if (result.length == count) break;
+ }
+ return result;
+}
+
+List<T> queueItemsNeedingDownload<T>({
+ required Iterable<T> items,
+ required int count,
+ required String Function(T item) keyOf,
+ required bool Function(T item) isFinished,
+ required bool Function(T item) isAvailable,
+}) {
+ return queueDownloadWindow(
+ items: items,
+ count: count,
+ keyOf: keyOf,
+ isFinished: isFinished,
+ ).where((item) => !isAvailable(item)).toList();
+}
diff --git a/lib/utils/absorbing_inclusion.dart b/lib/utils/absorbing_inclusion.dart
index 4a198338..34311f8c 100644
--- a/lib/utils/absorbing_inclusion.dart
+++ b/lib/utils/absorbing_inclusion.dart
@@ -1,6 +1,7 @@
bool shouldIncludeBookInAbsorbing({
required bool isFinished,
- required bool manuallyAdded,
+ required bool addedAfterFinish,
+ bool isActive = false,
}) {
- return !isFinished || manuallyAdded;
+ return !isFinished || addedAfterFinish || isActive;
}
diff --git a/lib/widgets/book_detail_sheet.dart b/lib/widgets/book_detail_sheet.dart
index e56f34b2..0875610b 100644
--- a/lib/widgets/book_detail_sheet.dart
+++ b/lib/widgets/book_detail_sheet.dart
@@ -2044,16 +2044,6 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
// Grab the root navigator before we pop the sheet
final rootNav = Navigator.of(context, rootNavigator: true);
- // Ensure this book is on the absorbing list (clear any manual remove)
- // Clear finished state so the card updates immediately
- if (context.mounted) {
- final lib = context.read<LibraryProvider>();
- lib.addToAbsorbing(widget.itemId);
- if (lib.getProgressData(widget.itemId)?['isFinished'] == true) {
- lib.resetProgressFor(widget.itemId);
- }
- }
-
if (player.currentItemId == widget.itemId) {
if (!player.isPlaying) player.play();
rootNav.popUntil((route) => route.isFirst);
@@ -2387,4 +2377,3 @@ class _FullCoverViewerState extends State<_FullCoverViewer> {
);
}
}
-
diff --git a/lib/widgets/collection_detail_sheet.dart b/lib/widgets/collection_detail_sheet.dart
index f354f305..51614d4d 100644
--- a/lib/widgets/collection_detail_sheet.dart
+++ b/lib/widgets/collection_detail_sheet.dart
@@ -345,7 +345,8 @@ class _CollectionDetailSheetState extends State<CollectionDetailSheet> {
Navigator.pop(context);
AppShell.goToAbsorbingGlobal();
await PlayerSettings.setQueueModeCollection(id, name);
- await lib.playCollectionFromStart(id);
+ final started = await lib.playCollectionFromStart(id);
+ if (started) unawaited(lib.syncQueueAutoDownloads());
}
: null,
icon: Icon(allFinished
diff --git a/lib/widgets/expanded_card.dart b/lib/widgets/expanded_card.dart
index 188bee6a..a17956d0 100644
--- a/lib/widgets/expanded_card.dart
+++ b/lib/widgets/expanded_card.dart
@@ -175,6 +175,16 @@ class _ExpandedCardState extends State<ExpandedCard> {
}
String? get _coverUrl {
+ final episodeId = _episodeId;
+ final downloadKey = episodeId == null ? _itemId : '$_itemId-$episodeId';
+ final localCover = DownloadService().getInfo(downloadKey).localCoverPath;
+ if (localCover != null && File(localCover).existsSync()) return localCover;
+
+ if (_isActive) {
+ final playingCover = widget.player.currentCoverUrl;
+ if (playingCover != null && playingCover.isNotEmpty) return playingCover;
+ }
+
final lib = context.read<LibraryProvider>();
return lib.getCoverUrl(_itemId, width: 800);
}
diff --git a/lib/widgets/playlist_detail_sheet.dart b/lib/widgets/playlist_detail_sheet.dart
index 2fbcf7d7..5427a6d7 100644
--- a/lib/widgets/playlist_detail_sheet.dart
+++ b/lib/widgets/playlist_detail_sheet.dart
@@ -467,7 +467,8 @@ class _PlaylistDetailSheetState extends State<PlaylistDetailSheet> {
Navigator.pop(context);
AppShell.goToAbsorbingGlobal();
await PlayerSettings.setQueueModePlaylist(playlistId);
- await lib.playPlaylistFromStart(playlistId);
+ final started = await lib.playPlaylistFromStart(playlistId);
+ if (started) unawaited(lib.syncQueueAutoDownloads());
}
: null,
icon: Icon(allFinished
diff --git a/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/AudioService.java b/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/AudioService.java
index 16090fda..acdd65f6 100644
--- a/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/AudioService.java
+++ b/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/AudioService.java
@@ -17,6 +17,7 @@ import android.os.Handler;
import android.os.Looper;
import android.os.ParcelFileDescriptor;
import android.os.PowerManager;
+import android.os.SystemClock;
import android.support.v4.media.MediaBrowserCompat;
import android.support.v4.media.MediaDescriptionCompat;
import android.support.v4.media.MediaMetadataCompat;
@@ -106,6 +107,22 @@ public class AudioService extends MediaBrowserServiceCompat {
private static ServiceListener listener;
private static List<MediaSessionCompat.QueueItem> queue = new ArrayList<>();
private static final Map<String, MediaMetadataCompat> mediaMetadataCache = new HashMap<>();
+ private static volatile int lastMediaKeyCode = -1;
+ private static volatile long lastMediaKeyAt = 0;
+ private static volatile long lastPlayAt = 0;
+ private static volatile long lastPauseAt = 0;
+
+ public static Map<String, Object> getDiagnosticSnapshot() {
+ final long now = SystemClock.elapsedRealtime();
+ final Map<String, Object> snapshot = new HashMap<>();
+ snapshot.put("lastKeyCode", lastMediaKeyCode);
+ snapshot.put("lastKeyAgeMs", lastMediaKeyAt == 0 ? -1 : now - lastMediaKeyAt);
+ snapshot.put("lastPlayCaller", "mediaSession");
+ snapshot.put("lastPlayCallerAgeMs", lastPlayAt == 0 ? -1 : now - lastPlayAt);
+ snapshot.put("lastPauseCaller", "mediaSession");
+ snapshot.put("lastPauseCallerAgeMs", lastPauseAt == 0 ? -1 : now - lastPauseAt);
+ return snapshot;
+ }
public static void init(ServiceListener listener) {
AudioService.listener = listener;
@@ -954,6 +971,7 @@ public class AudioService extends MediaBrowserServiceCompat {
@Override
public void onPlay() {
if (listener == null) return;
+ lastPlayAt = SystemClock.elapsedRealtime();
listener.onPlay();
}
@@ -982,6 +1000,8 @@ public class AudioService extends MediaBrowserServiceCompat {
@SuppressWarnings("deprecation")
final KeyEvent event = (KeyEvent)mediaButtonEvent.getExtras().getParcelable(Intent.EXTRA_KEY_EVENT);
if (event.getAction() == KeyEvent.ACTION_DOWN) {
+ lastMediaKeyCode = event.getKeyCode();
+ lastMediaKeyAt = SystemClock.elapsedRealtime();
switch (event.getKeyCode()) {
case KEYCODE_BYPASS_PLAY:
onPlay();
@@ -1037,6 +1057,7 @@ public class AudioService extends MediaBrowserServiceCompat {
@Override
public void onPause() {
if (listener == null) return;
+ lastPauseAt = SystemClock.elapsedRealtime();
listener.onPause();
}
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 9066c805..c4e7f308 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
@@ -987,7 +987,11 @@ public class AudioServicePlugin implements FlutterPlugin, ActivityAware {
case "notifyChildrenChanged": {
String parentMediaId = (String)args.get("parentMediaId");
Map<?, ?> options = (Map<?, ?>)args.get("options");
- AudioService.instance.notifyChildrenChanged(parentMediaId, mapToBundle(options));
+ if (options == null) {
+ AudioService.instance.notifyChildrenChanged(parentMediaId);
+ } else {
+ AudioService.instance.notifyChildrenChanged(parentMediaId, mapToBundle(options));
+ }
result.success(null);
break;
}