Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Use the system folder picker for custom download folders

Barnabasceeea7fe1749
diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts
index 58df9909..7d3d9e1d 100644
--- a/android/app/build.gradle.kts
+++ b/android/app/build.gradle.kts
@@ -115,6 +115,9 @@ flutter {
dependencies {
coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.0.4")
+ // SAF document moves for custom download folders (MainActivity.moveBookToSaf).
+ implementation("androidx.documentfile:documentfile:1.0.1")
+
// Google Play Services — Chromecast + Wearable Data Layer (pushes ABS
// session credentials to the paired Wear OS app so the watch can sign in
// without typing on the watch keyboard). Scoped to github + playstore so
diff --git a/android/app/src/fdroid/AndroidManifest.xml b/android/app/src/fdroid/AndroidManifest.xml
index 73f9d17f..6455c020 100644
--- a/android/app/src/fdroid/AndroidManifest.xml
+++ b/android/app/src/fdroid/AndroidManifest.xml
@@ -1,10 +1,9 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
- <!-- F-Droid (GMS-free) overlay. MANAGE_EXTERNAL_STORAGE is kept on purpose
- so custom download locations still work. Everything below is removed
- because it depends on Google Play Services or is superseded by
- F-Droid's own update mechanism. -->
+ <!-- F-Droid (GMS-free) overlay. Everything below is removed because it
+ depends on Google Play Services or is superseded by F-Droid's own
+ update mechanism. -->
<!-- In-app APK updater: F-Droid updates apps itself -->
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" tools:node="remove"/>
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
index 3559e0f6..6baaa638 100644
--- a/android/app/src/main/AndroidManifest.xml
+++ b/android/app/src/main/AndroidManifest.xml
@@ -13,9 +13,6 @@
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="29" tools:replace="android:maxSdkVersion"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="29" tools:replace="android:maxSdkVersion"/>
- <!-- Full file access for custom download locations (Android 11+) -->
- <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
-
<!-- In-app APK updater (GitHub flavor only; stripped from Play Store build) -->
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
@@ -95,6 +92,14 @@
android:exported="false"
android:foregroundServiceType="dataSync" />
+ <!-- background_downloader runs downloads in WorkManager's foreground
+ service. Declare its dataSync type so startForeground doesn't crash
+ on API 34+ (the library's own declaration has no type). -->
+ <service
+ android:name="androidx.work.impl.foreground.SystemForegroundService"
+ android:foregroundServiceType="dataSync"
+ tools:node="merge" />
+
<!-- Keeps the Absorb process alive (out of Doze) during Chromecast
playback so the Dart-side listening-time sync timer isn't
throttled. Fixes GH #184. -->
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 2d9427c1..66f0de47 100644
--- a/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt
+++ b/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt
@@ -4,7 +4,11 @@ import android.content.Context
import android.content.Intent
import android.media.AudioDeviceInfo
import android.media.AudioManager
+import android.net.Uri
import android.provider.MediaStore
+import androidx.documentfile.provider.DocumentFile
+import java.io.File
+import java.io.FileInputStream
import android.media.audiofx.BassBoost
import android.media.audiofx.Equalizer
import android.media.audiofx.LoudnessEnhancer
@@ -17,6 +21,7 @@ import android.util.Log
import com.ryanheise.audioservice.AudioServiceActivity
import com.ryanheise.just_audio.MonoController
import io.flutter.embedding.engine.FlutterEngine
+import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
class MainActivity : AudioServiceActivity() {
@@ -100,6 +105,7 @@ class MainActivity : AudioServiceActivity() {
result.error("STORAGE_ERROR", e.message, null)
}
}
+ "moveBookToSaf" -> handleMoveBookToSaf(call, result)
else -> result.notImplemented()
}
}
@@ -109,6 +115,61 @@ class MainActivity : AudioServiceActivity() {
PlatformIntegration.registerChannels(this, flutterEngine)
}
+ // Move downloaded temp files into the user's SAF folder, creating the nested
+ // [subfolder] (e.g. "Author/Title") under the granted tree via the DocumentFile
+ // chain so files nest correctly and stay readable through the original grant.
+ // The byte copy runs off the main thread.
+ private fun handleMoveBookToSaf(call: MethodCall, result: MethodChannel.Result) {
+ val treeUri = call.argument<String>("treeUri")
+ val subfolder = call.argument<String>("subfolder") ?: ""
+ val filenames = call.argument<List<String>>("filenames")
+ val tempPaths = call.argument<List<String>>("tempPaths")
+ if (treeUri == null || filenames == null || tempPaths == null || filenames.size != tempPaths.size) {
+ result.error("SAF_ARGS", "Invalid arguments", null)
+ return
+ }
+ Thread {
+ try {
+ val tree = DocumentFile.fromTreeUri(applicationContext, Uri.parse(treeUri))
+ ?: throw IllegalStateException("Download folder not accessible")
+ var dir: DocumentFile = tree
+ for (segment in subfolder.split('/').filter { it.isNotBlank() }) {
+ val existing = dir.findFile(segment)
+ dir = if (existing != null && existing.isDirectory) existing
+ else (dir.createDirectory(segment)
+ ?: throw IllegalStateException("Could not create folder: $segment"))
+ }
+ val fileUris = ArrayList<String>(filenames.size)
+ val temps = ArrayList<File>(filenames.size)
+ for (i in filenames.indices) {
+ val name = filenames[i]
+ val temp = File(tempPaths[i])
+ if (!temp.exists()) throw IllegalStateException("Missing downloaded file: ${tempPaths[i]}")
+ // Replace any existing file of the same name (e.g. re-download).
+ dir.findFile(name)?.delete()
+ // octet-stream so SAF keeps the exact filename + extension (a
+ // real audio MIME makes the provider rewrite e.g. .m4b to .m4a).
+ // ExoPlayer detects the format from the file content anyway.
+ val doc = dir.createFile("application/octet-stream", name)
+ ?: throw IllegalStateException("Could not create file: $name")
+ contentResolver.openOutputStream(doc.uri)?.use { output ->
+ FileInputStream(temp).use { input -> input.copyTo(output, 64 * 1024) }
+ } ?: throw IllegalStateException("Could not write: $name")
+ temps.add(temp)
+ fileUris.add(doc.uri.toString())
+ }
+ // Only remove the internal copies once every file moved, so a
+ // mid-way failure leaves the internal download intact to fall back on.
+ temps.forEach { it.delete() }
+ val dirUri = dir.uri.toString()
+ runOnUiThread { result.success(mapOf("dirUri" to dirUri, "fileUris" to fileUris)) }
+ } catch (e: Exception) {
+ Log.e(TAG, "moveBookToSaf failed: ${e.message}", e)
+ runOnUiThread { result.error("SAF_MOVE_ERROR", e.message, null) }
+ }
+ }.start()
+ }
+
private fun handleInit(result: MethodChannel.Result) {
try {
val tempEq = Equalizer(0, 0)
diff --git a/android/app/src/playstore/AndroidManifest.xml b/android/app/src/playstore/AndroidManifest.xml
index f9d7f087..7cd8327c 100644
--- a/android/app/src/playstore/AndroidManifest.xml
+++ b/android/app/src/playstore/AndroidManifest.xml
@@ -1,9 +1,6 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
- <!-- Remove MANAGE_EXTERNAL_STORAGE for Play Store compliance -->
- <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" tools:node="remove"/>
-
<!-- Remove APK installer permission: Play Store flavor never sideloads -->
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" tools:node="remove"/>
diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb
index 34ed52e9..8457adb7 100644
--- a/lib/l10n/app_en.arb
+++ b/lib/l10n/app_en.arb
@@ -964,6 +964,17 @@
},
"resetToDefault": "Reset to default",
"resetToDefaultStorage": "Reset to default storage",
+ "legacyDownloadsNotice": "{count, plural, =1{1 download is in an old custom folder that can no longer be opened. Re-download it or dismiss this notice.} other{{count} downloads are in an old custom folder that can no longer be opened. Re-download them or dismiss this notice.}}",
+ "@legacyDownloadsNotice": {
+ "placeholders": {
+ "count": {
+ "type": "int"
+ }
+ }
+ },
+ "redownload": "Re-download",
+ "redownloadStarted": "Re-downloading",
+ "dismiss": "Dismiss",
"tipsAndHiddenFeatures": "Tips & Hidden Features",
"tipsSubtitle": "Get the most out of Absorb",
"adminTitle": "Server Admin",
diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart
index ab37d2d4..08b982a1 100644
--- a/lib/l10n/app_localizations.dart
+++ b/lib/l10n/app_localizations.dart
@@ -3472,6 +3472,30 @@ abstract class AppLocalizations {
/// **'Reset to default storage'**
String get resetToDefaultStorage;
+ /// No description provided for @legacyDownloadsNotice.
+ ///
+ /// In en, this message translates to:
+ /// **'{count, plural, =1{1 download is in an old custom folder that can no longer be opened. Re-download it or dismiss this notice.} other{{count} downloads are in an old custom folder that can no longer be opened. Re-download them or dismiss this notice.}}'**
+ String legacyDownloadsNotice(int count);
+
+ /// No description provided for @redownload.
+ ///
+ /// In en, this message translates to:
+ /// **'Re-download'**
+ String get redownload;
+
+ /// No description provided for @redownloadStarted.
+ ///
+ /// In en, this message translates to:
+ /// **'Re-downloading'**
+ String get redownloadStarted;
+
+ /// No description provided for @dismiss.
+ ///
+ /// In en, this message translates to:
+ /// **'Dismiss'**
+ String get dismiss;
+
/// No description provided for @tipsAndHiddenFeatures.
///
/// In en, this message translates to:
diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart
index 9199c5dd..1f26dde0 100644
--- a/lib/l10n/app_localizations_de.dart
+++ b/lib/l10n/app_localizations_de.dart
@@ -1904,6 +1904,28 @@ class AppLocalizationsDe extends AppLocalizations {
@override
String get resetToDefaultStorage => 'Auf Standardspeicher zurücksetzen';
+ @override
+ String legacyDownloadsNotice(int count) {
+ String _temp0 = intl.Intl.pluralLogic(
+ count,
+ locale: localeName,
+ other:
+ '$count downloads are in an old custom folder that can no longer be opened. Re-download them or dismiss this notice.',
+ one:
+ '1 download is in an old custom folder that can no longer be opened. Re-download it or dismiss this notice.',
+ );
+ return '$_temp0';
+ }
+
+ @override
+ String get redownload => 'Re-download';
+
+ @override
+ String get redownloadStarted => 'Re-downloading';
+
+ @override
+ String get dismiss => 'Dismiss';
+
@override
String get tipsAndHiddenFeatures => 'Tipps & versteckte Funktionen';
diff --git a/lib/l10n/app_localizations_el.dart b/lib/l10n/app_localizations_el.dart
index 01d67d24..2d2cc189 100644
--- a/lib/l10n/app_localizations_el.dart
+++ b/lib/l10n/app_localizations_el.dart
@@ -1885,6 +1885,28 @@ class AppLocalizationsEl extends AppLocalizations {
@override
String get resetToDefaultStorage => 'Reset to default storage';
+ @override
+ String legacyDownloadsNotice(int count) {
+ String _temp0 = intl.Intl.pluralLogic(
+ count,
+ locale: localeName,
+ other:
+ '$count downloads are in an old custom folder that can no longer be opened. Re-download them or dismiss this notice.',
+ one:
+ '1 download is in an old custom folder that can no longer be opened. Re-download it or dismiss this notice.',
+ );
+ return '$_temp0';
+ }
+
+ @override
+ String get redownload => 'Re-download';
+
+ @override
+ String get redownloadStarted => 'Re-downloading';
+
+ @override
+ String get dismiss => 'Dismiss';
+
@override
String get tipsAndHiddenFeatures => 'Tips & Hidden Features';
diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart
index 369f8be0..73890481 100644
--- a/lib/l10n/app_localizations_en.dart
+++ b/lib/l10n/app_localizations_en.dart
@@ -1885,6 +1885,28 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get resetToDefaultStorage => 'Reset to default storage';
+ @override
+ String legacyDownloadsNotice(int count) {
+ String _temp0 = intl.Intl.pluralLogic(
+ count,
+ locale: localeName,
+ other:
+ '$count downloads are in an old custom folder that can no longer be opened. Re-download them or dismiss this notice.',
+ one:
+ '1 download is in an old custom folder that can no longer be opened. Re-download it or dismiss this notice.',
+ );
+ return '$_temp0';
+ }
+
+ @override
+ String get redownload => 'Re-download';
+
+ @override
+ String get redownloadStarted => 'Re-downloading';
+
+ @override
+ String get dismiss => 'Dismiss';
+
@override
String get tipsAndHiddenFeatures => 'Tips & Hidden Features';
diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart
index f120329f..750288b8 100644
--- a/lib/l10n/app_localizations_es.dart
+++ b/lib/l10n/app_localizations_es.dart
@@ -1885,6 +1885,28 @@ class AppLocalizationsEs extends AppLocalizations {
@override
String get resetToDefaultStorage => 'Reset to default storage';
+ @override
+ String legacyDownloadsNotice(int count) {
+ String _temp0 = intl.Intl.pluralLogic(
+ count,
+ locale: localeName,
+ other:
+ '$count downloads are in an old custom folder that can no longer be opened. Re-download them or dismiss this notice.',
+ one:
+ '1 download is in an old custom folder that can no longer be opened. Re-download it or dismiss this notice.',
+ );
+ return '$_temp0';
+ }
+
+ @override
+ String get redownload => 'Re-download';
+
+ @override
+ String get redownloadStarted => 'Re-downloading';
+
+ @override
+ String get dismiss => 'Dismiss';
+
@override
String get tipsAndHiddenFeatures => 'Tips & Hidden Features';
diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart
index 0f509b5b..83d272aa 100644
--- a/lib/l10n/app_localizations_fr.dart
+++ b/lib/l10n/app_localizations_fr.dart
@@ -1887,6 +1887,28 @@ class AppLocalizationsFr extends AppLocalizations {
@override
String get resetToDefaultStorage => 'Reset to default storage';
+ @override
+ String legacyDownloadsNotice(int count) {
+ String _temp0 = intl.Intl.pluralLogic(
+ count,
+ locale: localeName,
+ other:
+ '$count downloads are in an old custom folder that can no longer be opened. Re-download them or dismiss this notice.',
+ one:
+ '1 download is in an old custom folder that can no longer be opened. Re-download it or dismiss this notice.',
+ );
+ return '$_temp0';
+ }
+
+ @override
+ String get redownload => 'Re-download';
+
+ @override
+ String get redownloadStarted => 'Re-downloading';
+
+ @override
+ String get dismiss => 'Dismiss';
+
@override
String get tipsAndHiddenFeatures => 'Tips & Hidden Features';
diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart
index e3c7f153..5aaf36b8 100644
--- a/lib/l10n/app_localizations_it.dart
+++ b/lib/l10n/app_localizations_it.dart
@@ -1885,6 +1885,28 @@ class AppLocalizationsIt extends AppLocalizations {
@override
String get resetToDefaultStorage => 'Reset to default storage';
+ @override
+ String legacyDownloadsNotice(int count) {
+ String _temp0 = intl.Intl.pluralLogic(
+ count,
+ locale: localeName,
+ other:
+ '$count downloads are in an old custom folder that can no longer be opened. Re-download them or dismiss this notice.',
+ one:
+ '1 download is in an old custom folder that can no longer be opened. Re-download it or dismiss this notice.',
+ );
+ return '$_temp0';
+ }
+
+ @override
+ String get redownload => 'Re-download';
+
+ @override
+ String get redownloadStarted => 'Re-downloading';
+
+ @override
+ String get dismiss => 'Dismiss';
+
@override
String get tipsAndHiddenFeatures => 'Tips & Hidden Features';
diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart
index 6fe59180..bb080e72 100644
--- a/lib/l10n/app_localizations_ja.dart
+++ b/lib/l10n/app_localizations_ja.dart
@@ -1885,6 +1885,28 @@ class AppLocalizationsJa extends AppLocalizations {
@override
String get resetToDefaultStorage => 'Reset to default storage';
+ @override
+ String legacyDownloadsNotice(int count) {
+ String _temp0 = intl.Intl.pluralLogic(
+ count,
+ locale: localeName,
+ other:
+ '$count downloads are in an old custom folder that can no longer be opened. Re-download them or dismiss this notice.',
+ one:
+ '1 download is in an old custom folder that can no longer be opened. Re-download it or dismiss this notice.',
+ );
+ return '$_temp0';
+ }
+
+ @override
+ String get redownload => 'Re-download';
+
+ @override
+ String get redownloadStarted => 'Re-downloading';
+
+ @override
+ String get dismiss => 'Dismiss';
+
@override
String get tipsAndHiddenFeatures => 'Tips & Hidden Features';
diff --git a/lib/l10n/app_localizations_no.dart b/lib/l10n/app_localizations_no.dart
index 320fbb3b..04933896 100644
--- a/lib/l10n/app_localizations_no.dart
+++ b/lib/l10n/app_localizations_no.dart
@@ -1885,6 +1885,28 @@ class AppLocalizationsNo extends AppLocalizations {
@override
String get resetToDefaultStorage => 'Reset to default storage';
+ @override
+ String legacyDownloadsNotice(int count) {
+ String _temp0 = intl.Intl.pluralLogic(
+ count,
+ locale: localeName,
+ other:
+ '$count downloads are in an old custom folder that can no longer be opened. Re-download them or dismiss this notice.',
+ one:
+ '1 download is in an old custom folder that can no longer be opened. Re-download it or dismiss this notice.',
+ );
+ return '$_temp0';
+ }
+
+ @override
+ String get redownload => 'Re-download';
+
+ @override
+ String get redownloadStarted => 'Re-downloading';
+
+ @override
+ String get dismiss => 'Dismiss';
+
@override
String get tipsAndHiddenFeatures => 'Tips & Hidden Features';
diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart
index 3cbec407..fa304d3b 100644
--- a/lib/l10n/app_localizations_pt.dart
+++ b/lib/l10n/app_localizations_pt.dart
@@ -1885,6 +1885,28 @@ class AppLocalizationsPt extends AppLocalizations {
@override
String get resetToDefaultStorage => 'Reset to default storage';
+ @override
+ String legacyDownloadsNotice(int count) {
+ String _temp0 = intl.Intl.pluralLogic(
+ count,
+ locale: localeName,
+ other:
+ '$count downloads are in an old custom folder that can no longer be opened. Re-download them or dismiss this notice.',
+ one:
+ '1 download is in an old custom folder that can no longer be opened. Re-download it or dismiss this notice.',
+ );
+ return '$_temp0';
+ }
+
+ @override
+ String get redownload => 'Re-download';
+
+ @override
+ String get redownloadStarted => 'Re-downloading';
+
+ @override
+ String get dismiss => 'Dismiss';
+
@override
String get tipsAndHiddenFeatures => 'Tips & Hidden Features';
diff --git a/lib/l10n/app_localizations_ro.dart b/lib/l10n/app_localizations_ro.dart
index e8c8bb98..850f6253 100644
--- a/lib/l10n/app_localizations_ro.dart
+++ b/lib/l10n/app_localizations_ro.dart
@@ -1885,6 +1885,28 @@ class AppLocalizationsRo extends AppLocalizations {
@override
String get resetToDefaultStorage => 'Reset to default storage';
+ @override
+ String legacyDownloadsNotice(int count) {
+ String _temp0 = intl.Intl.pluralLogic(
+ count,
+ locale: localeName,
+ other:
+ '$count downloads are in an old custom folder that can no longer be opened. Re-download them or dismiss this notice.',
+ one:
+ '1 download is in an old custom folder that can no longer be opened. Re-download it or dismiss this notice.',
+ );
+ return '$_temp0';
+ }
+
+ @override
+ String get redownload => 'Re-download';
+
+ @override
+ String get redownloadStarted => 'Re-downloading';
+
+ @override
+ String get dismiss => 'Dismiss';
+
@override
String get tipsAndHiddenFeatures => 'Tips & Hidden Features';
diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart
index c55ccdec..70b071f3 100644
--- a/lib/l10n/app_localizations_ru.dart
+++ b/lib/l10n/app_localizations_ru.dart
@@ -1888,6 +1888,28 @@ class AppLocalizationsRu extends AppLocalizations {
@override
String get resetToDefaultStorage => 'Reset to default storage';
+ @override
+ String legacyDownloadsNotice(int count) {
+ String _temp0 = intl.Intl.pluralLogic(
+ count,
+ locale: localeName,
+ other:
+ '$count downloads are in an old custom folder that can no longer be opened. Re-download them or dismiss this notice.',
+ one:
+ '1 download is in an old custom folder that can no longer be opened. Re-download it or dismiss this notice.',
+ );
+ return '$_temp0';
+ }
+
+ @override
+ String get redownload => 'Re-download';
+
+ @override
+ String get redownloadStarted => 'Re-downloading';
+
+ @override
+ String get dismiss => 'Dismiss';
+
@override
String get tipsAndHiddenFeatures => 'Советы и скрытые возможности';
diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart
index b31a2c20..178b77cd 100644
--- a/lib/l10n/app_localizations_zh.dart
+++ b/lib/l10n/app_localizations_zh.dart
@@ -1827,6 +1827,28 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get resetToDefaultStorage => '重置为默认存储';
+ @override
+ String legacyDownloadsNotice(int count) {
+ String _temp0 = intl.Intl.pluralLogic(
+ count,
+ locale: localeName,
+ other:
+ '$count downloads are in an old custom folder that can no longer be opened. Re-download them or dismiss this notice.',
+ one:
+ '1 download is in an old custom folder that can no longer be opened. Re-download it or dismiss this notice.',
+ );
+ return '$_temp0';
+ }
+
+ @override
+ String get redownload => 'Re-download';
+
+ @override
+ String get redownloadStarted => 'Re-downloading';
+
+ @override
+ String get dismiss => 'Dismiss';
+
@override
String get tipsAndHiddenFeatures => '技巧与隐藏功能';
diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart
index 84fdf188..93bd5bd0 100644
--- a/lib/screens/settings_screen.dart
+++ b/lib/screens/settings_screen.dart
@@ -5,6 +5,7 @@ import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:file_picker/file_picker.dart';
+import 'package:background_downloader/background_downloader.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:just_audio/just_audio.dart' show AudioPlayer;
@@ -646,7 +647,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
_sleepChimeVolume = chimeVol;
_shakeSensitivity = shakeSens;
_language = language;
- _canPickDownloadLocation = !_isPlayStoreBuild;
+ _canPickDownloadLocation = true;
_statsGoalType = statsGoalType;
_statsGoalMinutes = statsGoalMinutes;
_statsBookGoal = statsBookGoal;
@@ -3061,6 +3062,8 @@ class _SettingsScreenState extends State<SettingsScreen> {
final l = AppLocalizations.of(context)!;
final dl = DownloadService();
final hasExistingDownloads = dl.downloadedItems.isNotEmpty;
+ final api = context.read<AuthProvider>().apiService;
+ final legacyCount = dl.legacyExternalDownloads.length;
showModalBottomSheet(
context: context,
@@ -3115,6 +3118,64 @@ class _SettingsScreenState extends State<SettingsScreen> {
),
const SizedBox(height: 16),
+ if (legacyCount > 0) ...[
+ Container(
+ width: double.infinity,
+ padding: const EdgeInsets.all(14),
+ decoration: BoxDecoration(
+ color: cs.errorContainer.withValues(alpha: 0.2),
+ borderRadius: BorderRadius.circular(12),
+ border: Border.all(color: cs.error.withValues(alpha: 0.2)),
+ ),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Row(children: [
+ Icon(Icons.warning_amber_rounded, size: 18, color: cs.error),
+ const SizedBox(width: 10),
+ Expanded(
+ child: Text(l.legacyDownloadsNotice(legacyCount),
+ style: tt.bodySmall?.copyWith(color: cs.onSurface)),
+ ),
+ ]),
+ const SizedBox(height: 8),
+ Row(
+ mainAxisAlignment: MainAxisAlignment.end,
+ children: [
+ TextButton(
+ onPressed: () async {
+ Navigator.pop(ctx);
+ await dl.dismissLegacyDownloads();
+ if (mounted) setState(() {});
+ },
+ child: Text(l.dismiss),
+ ),
+ const SizedBox(width: 8),
+ FilledButton(
+ onPressed: api == null
+ ? null
+ : () async {
+ Navigator.pop(ctx);
+ await dl.redownloadAllLegacy(api);
+ if (mounted) {
+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(
+ content: Text(l.redownloadStarted),
+ behavior: SnackBarBehavior.floating,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(12)),
+ ));
+ }
+ },
+ child: Text(l.redownload),
+ ),
+ ],
+ ),
+ ],
+ ),
+ ),
+ const SizedBox(height: 16),
+ ],
+
if (hasExistingDownloads)
Padding(
padding: const EdgeInsets.only(bottom: 12),
@@ -3148,83 +3209,53 @@ class _SettingsScreenState extends State<SettingsScreen> {
label: Text(l.chooseFolder),
onPressed: () async {
Navigator.pop(ctx);
- if (Platform.isAndroid) {
- // Android 11+ needs MANAGE_EXTERNAL_STORAGE for custom paths.
- // Android 9-10 use WRITE_EXTERNAL_STORAGE.
- // If manageExternalStorage is restricted, the OS doesn't
- // support it (Android 10 or below) so fall back to storage.
- final manageStatus = await Permission.manageExternalStorage.status;
- final Permission perm = manageStatus == PermissionStatus.restricted
- ? Permission.storage
- : Permission.manageExternalStorage;
- final status = await perm.status;
- if (status.isPermanentlyDenied) {
- if (mounted) {
- ScaffoldMessenger.of(context).showSnackBar(SnackBar(
- content: Text(l.storagePermissionDenied),
- behavior: SnackBarBehavior.floating,
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(12)),
- action: SnackBarAction(
- label: l.openSettings,
- onPressed: openAppSettings,
- ),
- ));
- }
- return;
- }
- if (!status.isGranted) {
- final result = await perm.request();
- if (!result.isGranted) {
- if (mounted) {
- ScaffoldMessenger.of(context).showSnackBar(SnackBar(
- content: Text(l.storagePermissionRequired),
- behavior: SnackBarBehavior.floating,
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(12)),
- ));
- }
- return;
- }
+ // Storage Access Framework: the user grants a folder through
+ // the system picker, no storage permission needed.
+ Uri? treeUri;
+ try {
+ treeUri = await FileDownloader().uri.pickDirectory(
+ startLocation: SharedStorage.downloads,
+ persistedUriPermission: true,
+ );
+ } catch (e) {
+ if (mounted) {
+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(
+ content: Text(l.cannotWriteToFolder),
+ behavior: SnackBarBehavior.floating,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(12)),
+ ));
}
+ return;
}
- final result = await FilePicker.platform.getDirectoryPath(
- dialogTitle: l.chooseDownloadFolder,
- );
- if (result != null) {
- // Write test - verify we can actually create files here
- try {
- final testDir = Directory(result);
- if (!testDir.existsSync()) testDir.createSync(recursive: true);
- final testFile = File('${testDir.path}/.absorb_write_test');
- testFile.writeAsStringSync('test');
- testFile.deleteSync();
- } catch (e) {
- if (mounted) {
- ScaffoldMessenger.of(context).showSnackBar(SnackBar(
- content: Text(l.cannotWriteToFolder),
- behavior: SnackBarBehavior.floating,
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(12)),
- action: SnackBarAction(
- label: l.openSettings,
- onPressed: openAppSettings,
- ),
- ));
- }
- return;
- }
- await dl.setCustomDownloadPath(result);
- final label = await dl.downloadLocationLabel;
+ if (treeUri == null) return; // user cancelled
+ // Verify we can actually create files in the chosen folder.
+ try {
+ final probe = await FileDownloader()
+ .uri
+ .createDirectory(treeUri, '.absorb_write_test');
+ await FileDownloader().uri.deleteFile(probe);
+ } catch (e) {
if (mounted) {
- setState(() => _downloadLocationLabel = label);
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
- content: Text(l.downloadLocationSetTo(label)),
+ content: Text(l.cannotWriteToFolder),
behavior: SnackBarBehavior.floating,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12)),
));
}
+ return;
+ }
+ await dl.setCustomDownloadUri(treeUri);
+ final label = await dl.downloadLocationLabel;
+ if (mounted) {
+ setState(() => _downloadLocationLabel = label);
+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(
+ content: Text(l.downloadLocationSetTo(label)),
+ behavior: SnackBarBehavior.floating,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(12)),
+ ));
}
},
),
@@ -3232,7 +3263,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
const SizedBox(height: 8),
// Reset to default button
- if (dl.customDownloadPath != null)
+ if (dl.customDownloadUri != null)
SizedBox(
width: double.infinity,
child: OutlinedButton.icon(
@@ -3240,7 +3271,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
label: Text(l.resetToDefault),
onPressed: () async {
Navigator.pop(ctx);
- await dl.setCustomDownloadPath(null);
+ await dl.setCustomDownloadUri(null);
final label = await dl.downloadLocationLabel;
if (mounted) {
setState(() => _downloadLocationLabel = label);
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index 4c278c62..8b06566c 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -9,6 +9,7 @@ import 'package:audio_session/audio_session.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'api_service.dart';
import 'download_service.dart';
+import 'offline_source.dart';
import 'playback_history_service.dart' hide PlaybackEvent;
import 'progress_sync_service.dart';
import 'sync_logic.dart';
@@ -1381,8 +1382,7 @@ class AudioPlayerService extends ChangeNotifier {
List<AudioSource>? nextTrackSources;
if (localPaths != null && localPaths.isNotEmpty) {
- nextTrackSources =
- localPaths.map((p) => AudioSource.file(p) as AudioSource).toList();
+ nextTrackSources = localPaths.map((p) => localAudioSource(p)).toList();
} else if (audioTracks != null && audioTracks.isNotEmpty) {
nextTrackSources = audioTracks
.map((t) => AudioSource.uri(
@@ -2455,9 +2455,9 @@ class AudioPlayerService extends ChangeNotifier {
try {
AudioSource source;
if (localPaths.length == 1) {
- source = AudioSource.file(localPaths.first);
+ source = localAudioSource(localPaths.first);
} else {
- final sources = localPaths.map((p) => AudioSource.file(p) as AudioSource).toList();
+ final sources = localPaths.map((p) => localAudioSource(p)).toList();
source = ConcatenatingAudioSource(children: sources);
}
@@ -2656,9 +2656,7 @@ class AudioPlayerService extends ChangeNotifier {
_trackStartOffsets = [0.0]; // single file fallback
}
- final trackSources = localPaths
- .map((p) => AudioSource.file(p) as AudioSource)
- .toList();
+ final trackSources = localPaths.map((p) => localAudioSource(p)).toList();
final source = ConcatenatingAudioSource(children: trackSources);
await _configureAudioSession();
diff --git a/lib/services/bookmark_preview_player.dart b/lib/services/bookmark_preview_player.dart
index acd6d12b..f2a42e8e 100644
--- a/lib/services/bookmark_preview_player.dart
+++ b/lib/services/bookmark_preview_player.dart
@@ -7,6 +7,7 @@ import 'package:just_audio/just_audio.dart';
import 'api_service.dart';
import 'audio_player_service.dart';
import 'download_service.dart';
+import 'offline_source.dart';
/// Auditions a book at a given position WITHOUT moving the user's real playback
/// position. Resolves audio for ANY book - downloaded (local files) or streamed
@@ -105,7 +106,7 @@ class BookmarkPreviewPlayer extends ChangeNotifier {
if (done) player.pause();
});
if (track.local) {
- await player.setAudioSource(AudioSource.file(track.source));
+ await player.setAudioSource(localAudioSource(track.source));
} else {
await player.setAudioSource(
AudioSource.uri(Uri.parse(track.source), headers: api?.mediaHeaders));
diff --git a/lib/services/download_service.dart b/lib/services/download_service.dart
index 78039939..3e9ba480 100644
--- a/lib/services/download_service.dart
+++ b/lib/services/download_service.dart
@@ -12,6 +12,7 @@ import '../l10n/app_localizations.dart';
import '../main.dart' show rootNavigatorKey;
import 'api_service.dart';
import 'audio_player_service.dart';
+import 'offline_source.dart';
enum DownloadStatus { none, downloading, downloaded, error }
@@ -140,6 +141,11 @@ class _PendingBook {
final int trackCount;
final List<String> expectedPaths; // index-aligned final file paths
final String? slimSessionJson;
+ /// When set, this book downloads to internal storage first, then its files
+ /// are moved into the user's SAF folder ([safTreeUri]) under [safSubfolder]
+ /// (e.g. "Author/Title") on completion. Null for internal / iOS downloads.
+ final String? safTreeUri;
+ final String? safSubfolder;
/// True once the user cancels, so terminal handling cleans up instead of
/// surfacing an error.
@@ -157,6 +163,12 @@ class _PendingBook {
final Map<int, double> trackProgress = {};
final Map<int, TaskStatus> trackStatus = {};
DateTime lastUi = DateTime.fromMillisecondsSinceEpoch(0);
+ /// Last time any track update arrived, so the slot-leak reconciler can spot a
+ /// book whose terminal updates were missed.
+ DateTime lastUpdate = DateTime.fromMillisecondsSinceEpoch(0);
+
+ /// True when this book's files get moved into a SAF folder on completion.
+ bool get isSaf => safTreeUri != null;
_PendingBook({
required this.itemId,
@@ -171,7 +183,12 @@ class _PendingBook {
this.localCoverPath,
this.libraryId,
this.slimSessionJson,
- });
+ this.safTreeUri,
+ this.safSubfolder,
+ }) {
+ // Start the no-progress watchdog clock at creation (fresh or restored).
+ lastUpdate = DateTime.now();
+ }
double get overallProgress {
if (trackCount == 0) return 0;
@@ -195,6 +212,8 @@ class _PendingBook {
'trackCount': trackCount,
'expectedPaths': expectedPaths,
'slimSessionJson': slimSessionJson,
+ if (safTreeUri != null) 'safTreeUri': safTreeUri,
+ if (safSubfolder != null) 'safSubfolder': safSubfolder,
};
factory _PendingBook.fromJson(Map<String, dynamic> j) => _PendingBook(
@@ -213,6 +232,8 @@ class _PendingBook {
.toList() ??
const [],
slimSessionJson: j['slimSessionJson'] as String?,
+ safTreeUri: j['safTreeUri'] as String?,
+ safSubfolder: j['safSubfolder'] as String?,
);
}
@@ -251,7 +272,14 @@ class DownloadService extends ChangeNotifier {
final Map<String, DownloadInfo> _downloads = {};
final Set<String> _activeDownloadIds = {};
final Set<String> _cancelledIds = {};
- String? _customDownloadPath;
+ /// SAF tree URI (content://) for the Android custom download folder, or null
+ /// to use internal storage. This is the only custom-location mechanism now;
+ /// the old raw-path approach (MANAGE_EXTERNAL_STORAGE) is gone.
+ String? _customDownloadUri;
+ /// Downloaded items still pointing at raw external paths from before the SAF
+ /// switch. Unreadable without the dropped storage permission, so they're kept
+ /// listed for the user to re-download rather than silently deleted.
+ final Set<String> _legacyExternalIds = {};
/// All `background_downloader` tasks share this group, so a single grouped
/// progress notification covers every active download.
@@ -264,22 +292,28 @@ class DownloadService extends ChangeNotifier {
StreamSubscription<TaskUpdate>? _updatesSub;
bool _downloaderConfigured = false;
+ /// Periodically reconverges in-flight books with the package task DB so a
+ /// missed terminal update can't leave a slot leaked and wedge the queue.
+ Timer? _reconcileTimer;
+
/// Queue of pending download requests.
final List<_QueuedDownload> _queue = [];
- /// The current download directory path, or null if using default.
- String? get customDownloadPath => _customDownloadPath;
+ /// The current Android SAF folder URI (content://), or null if using default.
+ String? get customDownloadUri => _customDownloadUri;
- /// Get the effective download base directory.
+ /// Items left pointing at unreadable raw external paths from before SAF.
+ List<DownloadInfo> get legacyExternalDownloads =>
+ _legacyExternalIds.map((id) => _downloads[id]).whereType<DownloadInfo>().toList();
+
+ /// Get the effective default (non-custom) download base directory.
///
- /// On iOS, audio files live in the app group container so the widget
- /// extension and the native player core can read them. We fall back to
- /// Documents/ if the app group lookup fails (entitlement not yet rolled
- /// out, etc.) so existing users don't lose their downloads.
+ /// Android custom folders no longer use a filesystem base path - they go
+ /// through SAF ([_customDownloadUri]) in the task builder. This getter now
+ /// only resolves the built-in location: the iOS app group container (so the
+ /// widget extension and native player core can read it; falls back to
+ /// Documents/ if the app group lookup fails) or Android internal storage.
Future<String> get downloadBasePath async {
- if (_customDownloadPath != null && _customDownloadPath!.isNotEmpty) {
- return _customDownloadPath!;
- }
if (Platform.isIOS) {
final groupPath = await _iosAppGroupAudioBase();
if (groupPath != null) return groupPath;
@@ -296,46 +330,49 @@ class DownloadService extends ChangeNotifier {
return '${appDir.path}/downloads';
}
- /// Set a custom download location. Pass null to revert to default.
- Future<void> setCustomDownloadPath(String? path) async {
- _customDownloadPath = path;
+ /// Set the Android SAF custom download folder. Pass null to revert to default.
+ Future<void> setCustomDownloadUri(Uri? uri) async {
+ _customDownloadUri = uri?.toString();
final prefs = await SharedPreferences.getInstance();
- if (path != null && path.isNotEmpty) {
- await prefs.setString('custom_download_path', path);
+ if (_customDownloadUri != null && _customDownloadUri!.isNotEmpty) {
+ await prefs.setString('custom_download_uri', _customDownloadUri!);
} else {
- await prefs.remove('custom_download_path');
+ await prefs.remove('custom_download_uri');
}
notifyListeners();
}
/// Get a human-readable label for the current download location.
Future<String> get downloadLocationLabel async {
- if (_customDownloadPath != null && _customDownloadPath!.isNotEmpty) {
- // Shorten the path for display
- final path = _customDownloadPath!;
- // Try to show a friendly path relative to common roots
- if (path.contains('/emulated/0/')) {
- return path.split('/emulated/0/').last;
- }
- if (path.contains('/storage/')) {
- return path.split('/storage/').last;
- }
- // Last two segments
- final segments = path.split('/').where((s) => s.isNotEmpty).toList();
- if (segments.length >= 2) {
- return '${segments[segments.length - 2]}/${segments.last}';
- }
- return path;
- }
+ final uri = _customDownloadUri;
+ if (uri != null && uri.isNotEmpty) return _friendlySafLabel(uri);
return 'App Internal Storage (Default)';
}
+ /// Turn a SAF tree URI into a friendly folder name. Tree URIs encode the
+ /// location in their last path segment, e.g.
+ /// `.../tree/primary%3ADownload%2FAudiobooks` -> `Download/Audiobooks`.
+ String _friendlySafLabel(String uriString) {
+ try {
+ final uri = Uri.parse(uriString);
+ var docId =
+ uri.pathSegments.isNotEmpty ? uri.pathSegments.last : uriString;
+ docId = Uri.decodeComponent(docId);
+ final colon = docId.indexOf(':');
+ final rel = colon >= 0 ? docId.substring(colon + 1) : docId;
+ return rel.isEmpty ? docId : rel;
+ } catch (_) {
+ return uriString;
+ }
+ }
+
/// Calculate total size of all downloaded files.
Future<int> get totalDownloadSize async {
int total = 0;
for (final info in _downloads.values) {
if (info.status == DownloadStatus.downloaded) {
for (final path in info.localPaths) {
+ if (isContentUri(path)) continue; // SAF audio not counted in the tally
try {
final file = File(path);
if (file.existsSync()) {
@@ -354,6 +391,7 @@ class DownloadService extends ChangeNotifier {
if (info == null || info.status != DownloadStatus.downloaded) return 0;
int total = 0;
for (final path in info.localPaths) {
+ if (isContentUri(path)) continue; // SAF audio not counted in the tally
try {
final file = File(path);
if (file.existsSync()) {
@@ -463,7 +501,13 @@ class DownloadService extends ChangeNotifier {
Future<void> init() async {
final prefs = await SharedPreferences.getInstance();
- _customDownloadPath = prefs.getString('custom_download_path');
+ _customDownloadUri = prefs.getString('custom_download_uri');
+ // Legacy raw-path custom folders can't be converted to a SAF content URI
+ // without a fresh user pick, and we no longer hold the storage permission
+ // to write them. Drop the old setting so new downloads use SAF or internal.
+ if (prefs.getString('custom_download_path') != null) {
+ await prefs.remove('custom_download_path');
+ }
final json = prefs.getString('downloads');
if (json != null) {
try {
@@ -488,6 +532,10 @@ class DownloadService extends ChangeNotifier {
// On iOS, remap paths when the app container UUID changes after updates
await _migrateIOSPaths();
+ // On Android, flag downloads still pointing at raw external paths from
+ // before the SAF switch so the UI can offer a re-download.
+ await _detectLegacyExternal();
+
// On iOS, move existing audio downloads from Documents/ into the app
// group container so the widget / native player core can read them.
// Runs in background so it doesn't block init() if the user has many
@@ -509,6 +557,7 @@ class DownloadService extends ChangeNotifier {
await _loadPending();
await _rehydratePending();
await FileDownloader().resumeFromBackground();
+ _startReconciler();
notifyListeners();
@@ -516,12 +565,87 @@ class DownloadService extends ChangeNotifier {
_validateDownloads();
}
+ void _startReconciler() {
+ _reconcileTimer?.cancel();
+ _reconcileTimer = Timer.periodic(
+ const Duration(minutes: 2), (_) => unawaited(_reconcilePending()));
+ }
+
+ /// Reconcile in-flight books against the package task DB. Two jobs:
+ /// 1. If a book's terminal updates were missed (e.g. an OEM ROM killed our
+ /// callback), finalize / fail it from the DB so its slot frees.
+ /// 2. If a book has made no progress and gone silent for a while, it's a dead
+ /// or zombie record (e.g. left over after an app update) holding a slot -
+ /// fail it so the queue can move on. Healthy or wifi-waiting downloads keep
+ /// emitting updates, so their lastUpdate stays fresh and they're left be.
+ Future<void> _reconcilePending() async {
+ if (_pending.isEmpty) return;
+ List<TaskRecord> records;
+ try {
+ records = await FileDownloader().database.allRecords();
+ } catch (_) {
+ return;
+ }
+ final byItem = <String, Map<int, TaskStatus>>{};
+ for (final r in records) {
+ final meta = _decodeMeta(r.task.metaData);
+ if (meta == null) continue;
+ if (!_pending.containsKey(meta.$1)) continue;
+ (byItem[meta.$1] ??= {})[meta.$2] = r.status;
+ }
+ for (final itemId in _pending.keys.toList()) {
+ final p = _pending[itemId];
+ if (p == null || p.finalizing) continue;
+ final statuses = byItem[itemId];
+ if (statuses != null && statuses.length >= p.trackCount) {
+ statuses.forEach((i, s) => p.trackStatus[i] = s);
+ bool allComplete = p.trackCount > 0;
+ bool allTerminal = true;
+ for (int i = 0; i < p.trackCount; i++) {
+ final s = p.trackStatus[i];
+ if (s != TaskStatus.complete) allComplete = false;
+ if (s == null || !_terminal.contains(s)) allTerminal = false;
+ }
+ if (allComplete) {
+ debugPrint('[Download] Reconciler finalizing missed-complete $itemId');
+ p.finalizing = true;
+ await _finalizeSuccess(itemId);
+ continue;
+ }
+ if (allTerminal) {
+ debugPrint('[Download] Reconciler failing stalled $itemId');
+ p.finalizing = true;
+ await _failBook(itemId, cause: 'Interrupted download');
+ continue;
+ }
+ }
+ // No progress and no updates for a while: a dead/zombie slot. Fail it.
+ if (p.overallProgress == 0 &&
+ DateTime.now().difference(p.lastUpdate) > const Duration(minutes: 3)) {
+ debugPrint('[Download] Reconciler failing stale $itemId (no progress)');
+ p.finalizing = true;
+ await _failBook(itemId, cause: 'Interrupted download');
+ }
+ }
+ }
+
/// Configure the single grouped download notification (replaces the old
/// per-slot notifications + hand-rolled Android foreground service). The
/// package runs a background URLSession on iOS and a foreground service on
/// Android, so downloads continue when backgrounded, locked, or killed.
Future<void> _configureDownloader() async {
if (_downloaderConfigured) return;
+ // Always run downloads in the Android foreground service. Without this,
+ // smaller books can run as background WorkManager jobs that some OEM ROMs
+ // throttle or kill, leaving downloads stuck.
+ if (Platform.isAndroid) {
+ try {
+ await FileDownloader()
+ .configure(androidConfig: [(Config.runInForeground, Config.always)]);
+ } catch (e) {
+ debugPrint('[Download] androidConfig failed: $e');
+ }
+ }
final l = _l();
// NOTE: for group notifications, the count tokens ({numFinished}/{numTotal})
// only substitute in the TITLE - in the body they print literally. {progress}
@@ -733,6 +857,68 @@ class DownloadService extends ChangeNotifier {
return '$groupAudioBase${path.substring(idx + marker.length)}';
}
+ /// Flag downloaded items whose files sit at a raw external path from before
+ /// the SAF switch (not a content URI, not under internal storage). Without
+ /// the dropped storage permission these can't be read, so they're kept listed
+ /// for re-download instead of being silently dropped by the validator.
+ Future<void> _detectLegacyExternal() async {
+ if (!Platform.isAndroid || _downloads.isEmpty) return;
+ final appDir = await getApplicationDocumentsDirectory();
+ final internalPrefix = appDir.path;
+ for (final entry in _downloads.entries) {
+ final info = entry.value;
+ if (info.status != DownloadStatus.downloaded || info.localPaths.isEmpty) {
+ continue;
+ }
+ final first = info.localPaths.first;
+ if (isContentUri(first) || first.startsWith(internalPrefix)) continue;
+ _legacyExternalIds.add(entry.key);
+ }
+ if (_legacyExternalIds.isNotEmpty) {
+ debugPrint('[Download] ${_legacyExternalIds.length} legacy external download(s) need re-download');
+ }
+ }
+
+ /// Drop a legacy external entry (its files are orphaned on storage we can no
+ /// longer reach) and re-enqueue it from stored metadata so it lands in the
+ /// current location (SAF folder or internal).
+ Future<void> redownloadLegacy(ApiService api, String itemId) async {
+ final info = _downloads[itemId];
+ if (info == null) return;
+ _downloads.remove(itemId);
+ _legacyExternalIds.remove(itemId);
+ await _save();
+ notifyListeners();
+ final episodeId = itemId.length > 36 ? itemId.substring(37) : null;
+ await downloadItem(
+ api: api,
+ itemId: itemId,
+ title: info.title ?? '',
+ author: info.author,
+ coverUrl: info.coverUrl,
+ episodeId: episodeId,
+ libraryId: info.libraryId,
+ );
+ }
+
+ /// Re-download every flagged legacy external item.
+ Future<void> redownloadAllLegacy(ApiService api) async {
+ for (final id in _legacyExternalIds.toList()) {
+ await redownloadLegacy(api, id);
+ }
+ }
+
+ /// Forget the legacy external entries without re-downloading (user dismissed).
+ Future<void> dismissLegacyDownloads() async {
+ if (_legacyExternalIds.isEmpty) return;
+ for (final id in _legacyExternalIds) {
+ _downloads.remove(id);
+ }
+ _legacyExternalIds.clear();
+ await _save();
+ notifyListeners();
+ }
+
/// Validate that downloaded files still exist on disk and clean up orphans.
/// Runs in background so it doesn't block app startup.
Future<void> _validateDownloads() async {
@@ -741,8 +927,13 @@ class DownloadService extends ChangeNotifier {
final entries = Map<String, DownloadInfo>.from(_downloads);
for (final entry in entries.entries) {
if (entry.value.status != DownloadStatus.downloaded) continue;
+ // Legacy external entries are kept for re-download, not validated away.
+ if (_legacyExternalIds.contains(entry.key)) continue;
bool allExist = true;
for (final path in entry.value.localPaths) {
+ // No cheap existence check for a SAF content URI; assume present and
+ // let a real playback failure surface a re-download instead.
+ if (isContentUri(path)) continue;
try {
final exists = await File(path).exists()
.timeout(const Duration(seconds: 3));
@@ -1050,7 +1241,13 @@ class DownloadService extends ChangeNotifier {
);
notifyListeners();
- Directory? bookDir;
+ // SAF custom folder (Android only): files go to a flat per-book folder
+ // under the user-granted tree via content URIs, no storage permission.
+ final useSaf = Platform.isAndroid &&
+ _customDownloadUri != null &&
+ _customDownloadUri!.isNotEmpty;
+ String? bookDirRef; // filesystem path or content:// URI, for cleanup
+ Directory? bookDir; // filesystem branches only
try {
// For episodes, itemId is a composite key like 'podcastId-episodeId'.
// Extract the real library item ID for the API call.
@@ -1073,16 +1270,26 @@ class DownloadService extends ChangeNotifier {
final files = await _resolveDurableFiles(api, apiItemId, episodeId, audioTracks);
- final basePath = await downloadBasePath;
- final dirName = (author != null && author.isNotEmpty)
+ // Per-book destination. Android downloads to internal storage first - for
+ // both the internal default AND SAF custom folders. SAF books are then
+ // moved into the user's chosen folder under "Author/Title" on completion
+ // (a direct SAF write can't nest subfolders). iOS downloads into the app
+ // group container.
+ final nestedName = (author != null && author.isNotEmpty)
? '${_sanitizePath(author)}/${_sanitizePath(title)}'
: _sanitizePath(title);
- bookDir = Directory('$basePath/$dirName');
- if (!bookDir.existsSync()) {
- bookDir.createSync(recursive: true);
+ String? relDir; // Android: relative to applicationDocuments
+ if (Platform.isIOS) {
+ final basePath = await downloadBasePath;
+ bookDir = Directory('$basePath/$nestedName');
+ } else {
+ final appDir = await getApplicationDocumentsDirectory();
+ relDir = 'downloads/$nestedName';
+ bookDir = Directory('${appDir.path}/$relDir');
}
- final usingCustom = _customDownloadPath != null && _customDownloadPath!.isNotEmpty;
- debugPrint('[Download] "$title" location=${usingCustom ? 'custom' : 'default'} dir=${bookDir.path} tracks=${files.length}');
+ if (!bookDir.existsSync()) bookDir.createSync(recursive: true);
+ bookDirRef = bookDir.path;
+ debugPrint('[Download] "$title" location=${useSaf ? 'SAF' : 'default'} dir=${bookDir.path} tracks=${files.length}');
final localCoverPath = await _cacheCover(api, itemId, coverUrl);
@@ -1093,7 +1300,7 @@ class DownloadService extends ChangeNotifier {
// Cancelled while we were resolving? Bail before enqueueing anything.
if (_cancelledIds.remove(itemId)) {
- _cleanupBookDir(bookDir);
+ await _cleanupBookDir(bookDirRef);
_activeDownloadIds.remove(itemId);
_downloads.remove(itemId);
notifyListeners();
@@ -1113,29 +1320,50 @@ class DownloadService extends ChangeNotifier {
coverUrl: coverUrl,
localCoverPath: localCoverPath,
libraryId: libraryId,
- bookDir: bookDir.path,
+ bookDir: bookDirRef,
trackCount: files.length,
expectedPaths: expectedPaths,
slimSessionJson: jsonEncode(slimSession),
+ safTreeUri: useSaf ? _customDownloadUri : null,
+ safSubfolder: useSaf ? nestedName : null,
);
_pending[itemId] = pending;
await _persistPending();
for (int i = 0; i < files.length; i++) {
- final task = DownloadTask(
- taskId: _taskId(itemId, i),
- url: files[i].url,
- headers: api.mediaHeaders,
- filename: files[i].filename,
- baseDirectory: BaseDirectory.root,
- directory: bookDir.path,
- group: _dlGroup,
- metaData: jsonEncode({'itemId': itemId, 'i': i, 'n': files.length}),
- updates: Updates.statusAndProgress,
- requiresWiFi: wifiOnly,
- retries: 3,
- allowPause: true,
- );
+ final meta = jsonEncode({'itemId': itemId, 'i': i, 'n': files.length});
+ final Task task;
+ if (Platform.isIOS) {
+ task = DownloadTask(
+ taskId: _taskId(itemId, i),
+ url: files[i].url,
+ headers: api.mediaHeaders,
+ filename: files[i].filename,
+ baseDirectory: BaseDirectory.root,
+ directory: bookDir.path,
+ group: _dlGroup,
+ metaData: meta,
+ updates: Updates.statusAndProgress,
+ requiresWiFi: wifiOnly,
+ retries: 3,
+ allowPause: true,
+ );
+ } else {
+ task = DownloadTask(
+ taskId: _taskId(itemId, i),
+ url: files[i].url,
+ headers: api.mediaHeaders,
+ filename: files[i].filename,
+ baseDirectory: BaseDirectory.applicationDocuments,
+ directory: relDir!,
+ group: _dlGroup,
+ metaData: meta,
+ updates: Updates.statusAndProgress,
+ requiresWiFi: wifiOnly,
+ retries: 3,
+ allowPause: true,
+ );
+ }
final ok = await FileDownloader().enqueue(task);
debugPrint('[Download] enqueue ${i + 1}/${files.length} ok=$ok file=${files[i].filename}');
if (!ok) throw Exception('Failed to enqueue track ${i + 1}');
@@ -1143,7 +1371,7 @@ class DownloadService extends ChangeNotifier {
debugPrint('[Download] Enqueued ${files.length} task(s) for "$title"');
} catch (e) {
await _failBook(itemId,
- cause: e, bookDir: bookDir, title: title, author: author, coverUrl: coverUrl);
+ cause: e, bookDirRef: bookDirRef, title: title, author: author, coverUrl: coverUrl);
}
}
@@ -1258,6 +1486,7 @@ class DownloadService extends ChangeNotifier {
final i = meta.$2;
final p = _pending[itemId];
if (p == null) return;
+ p.lastUpdate = DateTime.now();
if (update is TaskProgressUpdate) {
final prog = update.progress;
@@ -1318,10 +1547,36 @@ class DownloadService extends ChangeNotifier {
}
}
+ /// Move a completed book's internal files into the SAF folder [treeUri] under
+ /// [subfolder] (e.g. "Author/Title"), via the native DocumentFile helper.
+ /// Returns the created folder URI and the per-file content URIs, or null if
+ /// the move failed.
+ Future<({String dirUri, List<String> fileUris})?> _moveBookToSaf(
+ String treeUri, String subfolder, List<String> filenames, List<String> tempPaths) async {
+ try {
+ final res = await _storageChannel.invokeMethod<Map>('moveBookToSaf', {
+ 'treeUri': treeUri,
+ 'subfolder': subfolder,
+ 'filenames': filenames,
+ 'tempPaths': tempPaths,
+ });
+ final dirUri = res?['dirUri'] as String?;
+ final fileUris = (res?['fileUris'] as List?)?.map((e) => e as String).toList();
+ if (dirUri == null || fileUris == null || fileUris.length != filenames.length) {
+ return null;
+ }
+ return (dirUri: dirUri, fileUris: fileUris);
+ } catch (e) {
+ debugPrint('[Download] moveBookToSaf failed: $e');
+ return null;
+ }
+ }
+
Future<void> _finalizeSuccess(String itemId) async {
final p = _pending[itemId];
if (p == null) return;
+ // Files always land in internal storage first.
final localPaths = p.expectedPaths.where((path) => File(path).existsSync()).toList();
if (localPaths.length != p.trackCount) {
debugPrint('[Download] Finalize "$itemId": only ${localPaths.length}/${p.trackCount} '
@@ -1331,7 +1586,24 @@ class DownloadService extends ChangeNotifier {
return;
}
- if (Platform.isIOS) {
+ var finalPaths = localPaths;
+ String? finalDirPath = p.bookDir;
+
+ // SAF: move the downloaded files into the user's chosen folder under
+ // "Author/Title" and play/delete via the returned content URIs. If the move
+ // fails the book stays usable from its internal copy.
+ if (p.isSaf) {
+ final filenames = [for (final path in localPaths) path.split('/').last];
+ final moved = await _moveBookToSaf(
+ p.safTreeUri!, p.safSubfolder ?? '', filenames, localPaths);
+ if (moved != null) {
+ finalPaths = moved.fileUris;
+ finalDirPath = moved.dirUri;
+ await _cleanupBookDir(p.bookDir); // drop the now-empty internal temp dir
+ } else {
+ debugPrint('[Download] SAF move failed for "$itemId", keeping internal copy');
+ }
+ } else if (Platform.isIOS) {
for (final path in localPaths) {
await _excludeFromBackup(path);
}
@@ -1340,13 +1612,13 @@ class DownloadService extends ChangeNotifier {
_downloads[itemId] = DownloadInfo(
itemId: itemId,
status: DownloadStatus.downloaded,
- localPaths: localPaths,
+ localPaths: finalPaths,
sessionData: p.slimSessionJson,
title: p.title,
author: p.author,
coverUrl: p.coverUrl,
localCoverPath: p.localCoverPath,
- localDirPath: p.bookDir,
+ localDirPath: finalDirPath,
libraryId: p.libraryId,
);
await _save();
@@ -1377,7 +1649,7 @@ class DownloadService extends ChangeNotifier {
String? title,
String? author,
String? coverUrl,
- Directory? bookDir,
+ String? bookDirRef,
}) async {
final p = _pending[itemId];
if (p != null) {
@@ -1387,10 +1659,10 @@ class DownloadService extends ChangeNotifier {
final t = title ?? p?.title ?? '';
final a = author ?? p?.author;
final c = coverUrl ?? p?.coverUrl;
- final dir = bookDir ?? (p != null ? Directory(p.bookDir) : null);
+ final dir = bookDirRef ?? p?.bookDir;
if (p != null) await _cancelSiblings(itemId, p, force: true);
- _cleanupBookDir(dir);
+ await _cleanupBookDir(dir);
final msg = _mapError(cause, taskException, responseCode);
_downloads[itemId] = DownloadInfo(
@@ -1412,7 +1684,7 @@ class DownloadService extends ChangeNotifier {
Future<void> _handleCanceled(String itemId) async {
final p = _pending[itemId];
- _cleanupBookDir(p != null ? Directory(p.bookDir) : null);
+ await _cleanupBookDir(p?.bookDir);
_downloads.remove(itemId);
_activeDownloadIds.remove(itemId);
_pending.remove(itemId);
@@ -1437,8 +1709,12 @@ class DownloadService extends ChangeNotifier {
}
}
- void _cleanupBookDir(Directory? dir) {
- if (dir == null) return;
+ /// Remove a book's download folder. [bookDir] is a filesystem path. SAF
+ /// downloads share the user's granted folder, so there's no per-book folder
+ /// to remove (cleanup of SAF files is per-file via [deleteDownload]).
+ Future<void> _cleanupBookDir(String? bookDir) async {
+ if (bookDir == null || isContentUri(bookDir)) return;
+ final dir = Directory(bookDir);
try {
if (dir.existsSync()) {
dir.deleteSync(recursive: true);
@@ -1579,15 +1855,24 @@ class DownloadService extends ChangeNotifier {
for (final path in info.localPaths) {
try {
- final file = File(path);
- if (file.existsSync()) file.deleteSync();
+ if (isContentUri(path)) {
+ await FileDownloader().uri.deleteFile(Uri.parse(path));
+ } else {
+ final file = File(path);
+ if (file.existsSync()) file.deleteSync();
+ }
} catch (_) {}
}
// Remove the download directory (new-style path from DownloadInfo, or legacy UUID path)
try {
final dirPath = info.localDirPath;
- if (dirPath != null && Directory(dirPath).existsSync()) {
+ if (dirPath != null && isContentUri(dirPath)) {
+ // SAF book folder: best-effort delete (harmless if already emptied).
+ try {
+ await FileDownloader().uri.deleteFile(Uri.parse(dirPath));
+ } catch (_) {}
+ } else if (dirPath != null && Directory(dirPath).existsSync()) {
Directory(dirPath).deleteSync(recursive: true);
// Clean up empty parent (Author folder) if it's now empty
final parent = Directory(dirPath).parent;
@@ -1631,15 +1916,20 @@ class DownloadService extends ChangeNotifier {
_cancelledIds.add(itemId);
final p = _pending[itemId];
- if (p != null) {
+ if (p != null && !p.finalizing) {
p.cancelled = true;
- // Cancel every task; the resulting `canceled` updates drive _handleCanceled
- // which removes partial files, the pending record, and the DB rows.
+ // Ask the package to cancel any live tasks, then clean up ourselves. We do
+ // NOT wait for the package's `canceled` update: it never fires for tasks
+ // the package no longer tracks (e.g. records left over after an app
+ // update), which would leak the slot and wedge the whole queue.
final ids = [for (int i = 0; i < p.trackCount; i++) _taskId(itemId, i)];
unawaited(FileDownloader().cancelTasksWithIds(ids));
+ unawaited(_handleCanceled(itemId)); // frees the slot + processes the queue
+ } else {
+ _activeDownloadIds.remove(itemId);
}
- // Instant UI feedback; full cleanup happens on the canceled updates.
+ // Instant UI feedback (cleanup paths also notify).
_downloads.remove(itemId);
notifyListeners();
}
diff --git a/lib/services/offline_source.dart b/lib/services/offline_source.dart
new file mode 100644
index 00000000..80703340
--- /dev/null
+++ b/lib/services/offline_source.dart
@@ -0,0 +1,14 @@
+import 'package:just_audio/just_audio.dart';
+
+/// True when a stored download location is an Android Storage Access Framework
+/// content URI rather than a filesystem path. SAF custom folders store
+/// content:// URIs in DownloadInfo.localPaths; everything else (iOS app-group,
+/// Android internal and legacy downloads) stays a filesystem path.
+bool isContentUri(String pathOrUri) => pathOrUri.startsWith('content://');
+
+/// Build the right AudioSource for a downloaded track. Content URIs play via
+/// AudioSource.uri (media3's ContentDataSource opens them through the persisted
+/// SAF permission); filesystem paths play via AudioSource.file.
+AudioSource localAudioSource(String pathOrUri) => isContentUri(pathOrUri)
+ ? AudioSource.uri(Uri.parse(pathOrUri))
+ : AudioSource.file(pathOrUri);
diff --git a/lib/services/scoped_prefs.dart b/lib/services/scoped_prefs.dart
index cd38f561..f8542dd5 100644
--- a/lib/services/scoped_prefs.dart
+++ b/lib/services/scoped_prefs.dart
@@ -25,7 +25,7 @@ class ScopedPrefs {
'server_url', 'token', 'username', 'user_id', 'default_library_id',
'custom_headers',
'loggingEnabled', 'manual_offline_mode',
- 'custom_download_path', 'downloads',
+ 'custom_download_path', 'custom_download_uri', 'downloads',
'absorb_device_id',
'widget_item_id', 'widget_episode_id',
'cached_stats', 'cached_sessions',