From 48d04a701bed2e4be29b417c589056f928371796 Mon Sep 17 00:00:00 2001 From: Ossama Hashim Date: Wed, 2 Dec 2026 16:03:59 +0200 Subject: [PATCH 1/2] feat: default downloads to Download/Luca --- .../activity/AddDownloadActivity.kt | 17 +- .../activity/SettingsActivity.kt | 16 +- .../manager/DownloadManager.kt | 19 +-- .../service/DownloadService.kt | 79 +++++---- .../downloadmanager/utils/DownloadStorage.kt | 158 ++++++++++++++++++ app/src/main/res/values/strings.xml | 1 + app/src/main/res/xml/file_paths.xml | 3 + .../DownloadManagerCoreVerificationTest.kt | 15 ++ 8 files changed, 245 insertions(+), 63 deletions(-) create mode 100644 app/src/main/java/com/example/downloadmanager/utils/DownloadStorage.kt diff --git a/app/src/main/java/com/example/downloadmanager/activity/AddDownloadActivity.kt b/app/src/main/java/com/example/downloadmanager/activity/AddDownloadActivity.kt index 8a343d4..5a9eff2 100644 --- a/app/src/main/java/com/example/downloadmanager/activity/AddDownloadActivity.kt +++ b/app/src/main/java/com/example/downloadmanager/activity/AddDownloadActivity.kt @@ -35,6 +35,7 @@ import com.example.downloadmanager.model.DownloadType import com.example.downloadmanager.model.TorrentFileInfo import com.example.downloadmanager.model.VideoFormat import com.example.downloadmanager.service.DownloadService +import com.example.downloadmanager.utils.DownloadStorage import com.example.downloadmanager.utils.EdgeToEdgeHelper import com.example.downloadmanager.utils.FilenameResolver import com.example.downloadmanager.utils.UrlClassifier @@ -292,8 +293,9 @@ class AddDownloadActivity : AppCompatActivity() { } private fun applySavePath(chosenPath: String) { - binding.etSavePath.setText(chosenPath) - binding.etTorrentSavePath.setText(chosenPath) + val displayPath = DownloadStorage.displayPath(this, chosenPath) + binding.etSavePath.setText(displayPath) + binding.etTorrentSavePath.setText(displayPath) val baseDir = downloadManager.getDefaultDownloadPath() val musicDir = File(baseDir, "Music").absolutePath val videosDir = File(baseDir, "Videos").absolutePath @@ -959,18 +961,16 @@ class AddDownloadActivity : AppCompatActivity() { private fun showSavePathSelectorDialog(@Suppress("UNUSED_PARAMETER") isTorrent: Boolean) { val baseDir = downloadManager.getDefaultDownloadPath() - val options = arrayOf( - "Default Downloads ($baseDir)", - "Music (${File(baseDir, "Music").absolutePath})", - "Videos (${File(baseDir, "Videos").absolutePath})", - "Torrents (${File(baseDir, "Torrents").absolutePath})" - ) val paths = arrayOf( baseDir, File(baseDir, "Music").apply { mkdirs() }.absolutePath, File(baseDir, "Videos").apply { mkdirs() }.absolutePath, File(baseDir, "Torrents").apply { mkdirs() }.absolutePath ) + val names = arrayOf("Default Downloads", "Music", "Videos", "Torrents") + val options = paths.mapIndexed { index, path -> + "${names[index]} (${DownloadStorage.displayPath(this, path)})" + }.toTypedArray() MaterialAlertDialogBuilder(this) .setTitle(R.string.select_file) @@ -1018,6 +1018,7 @@ class AddDownloadActivity : AppCompatActivity() { metadataExtractJob?.cancel() val savePath = binding.etSavePath.text?.toString()?.trim()?.takeIf { it.isNotEmpty() } + ?.let { DownloadStorage.resolveEnteredPath(this, it) } ?: downloadManager.getDefaultDownloadPath() val inputFilename = binding.etFilename.text?.toString()?.trim().orEmpty() diff --git a/app/src/main/java/com/example/downloadmanager/activity/SettingsActivity.kt b/app/src/main/java/com/example/downloadmanager/activity/SettingsActivity.kt index e0bf6dc..07eea1a 100644 --- a/app/src/main/java/com/example/downloadmanager/activity/SettingsActivity.kt +++ b/app/src/main/java/com/example/downloadmanager/activity/SettingsActivity.kt @@ -1,7 +1,6 @@ package com.example.downloadmanager.activity import android.os.Bundle -import android.os.Environment import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatDelegate @@ -12,6 +11,7 @@ import androidx.preference.SwitchPreferenceCompat import android.view.View import com.example.downloadmanager.BuildConfig import com.example.downloadmanager.R +import com.example.downloadmanager.utils.DownloadStorage import com.example.downloadmanager.utils.EdgeToEdgeHelper class SettingsActivity : AppCompatActivity() { @@ -51,12 +51,14 @@ class SettingsActivity : AppCompatActivity() { findPreference("pref_app_version")?.summary = "Luca Download Manager v${BuildConfig.VERSION_NAME}" - // Populate default save location if empty - val savePathPref = findPreference("default_save_path") - if (savePathPref != null && savePathPref.text.isNullOrBlank()) { - val defaultDir = requireContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)?.absolutePath - ?: Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).absolutePath - savePathPref.text = defaultDir + val savePathPref = findPreference(DownloadStorage.DEFAULT_PATH_KEY) + savePathPref?.summaryProvider = Preference.SummaryProvider { preference -> + val context = preference.context + if (DownloadStorage.isBuiltInPreference(context, preference.text)) { + DownloadStorage.displayPath(context, DownloadStorage.defaultDirectory(context).absolutePath) + } else { + preference.text.orEmpty() + } } // Apply Dark Mode immediately when toggled diff --git a/app/src/main/java/com/example/downloadmanager/manager/DownloadManager.kt b/app/src/main/java/com/example/downloadmanager/manager/DownloadManager.kt index 46120ed..205e04f 100644 --- a/app/src/main/java/com/example/downloadmanager/manager/DownloadManager.kt +++ b/app/src/main/java/com/example/downloadmanager/manager/DownloadManager.kt @@ -1,7 +1,6 @@ package com.example.downloadmanager.manager import android.app.Application -import android.os.Environment import android.util.Log import android.webkit.MimeTypeMap import androidx.preference.PreferenceManager @@ -9,6 +8,7 @@ import com.example.downloadmanager.extraction.BrowserSessionBridge import com.example.downloadmanager.model.DownloadItem import com.example.downloadmanager.model.DownloadRepository import com.example.downloadmanager.model.DownloadStatus +import com.example.downloadmanager.utils.DownloadStorage import com.example.downloadmanager.utils.FilenameResolver import com.example.downloadmanager.utils.HttpRangeValidator import com.example.downloadmanager.utils.MediaAssetHelper @@ -1207,22 +1207,7 @@ class DownloadManager( ?: "download_${System.currentTimeMillis()}" } - fun getDefaultDownloadPath(): String { - val ctx = context ?: return File(System.getProperty("java.io.tmpdir"), "Downloads").apply { mkdirs() }.absolutePath - val prefs = PreferenceManager.getDefaultSharedPreferences(ctx) - val saved = prefs.getString("default_save_path", null) - if (!saved.isNullOrBlank()) { - val dir = File(saved) - if (dir.exists() || dir.mkdirs()) return dir.absolutePath - } - val appExternal = ctx.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) - if (appExternal != null && (appExternal.exists() || appExternal.mkdirs())) { - return appExternal.absolutePath - } - val internalDir = File(ctx.filesDir, "Downloads") - if (!internalDir.exists()) internalDir.mkdirs() - return internalDir.absolutePath - } + fun getDefaultDownloadPath(): String = DownloadStorage.defaultDirectory(context).absolutePath private fun getMimeTypeFromFilename(filename: String): String { val ext = filename.substringAfterLast('.', "").lowercase(Locale.US) diff --git a/app/src/main/java/com/example/downloadmanager/service/DownloadService.kt b/app/src/main/java/com/example/downloadmanager/service/DownloadService.kt index 41e0d6b..350ffd7 100644 --- a/app/src/main/java/com/example/downloadmanager/service/DownloadService.kt +++ b/app/src/main/java/com/example/downloadmanager/service/DownloadService.kt @@ -36,6 +36,7 @@ import com.example.downloadmanager.model.DownloadRepository import com.example.downloadmanager.model.DownloadStatus import com.example.downloadmanager.model.DownloadType import com.example.downloadmanager.utils.DownloadRecoveryWorker +import com.example.downloadmanager.utils.DownloadStorage import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers @@ -53,6 +54,7 @@ class DownloadService : Service() { private val binder = LocalBinder() private val serviceScope = CoroutineScope(Dispatchers.IO + SupervisorJob()) + private val publicationMutex = Mutex() private lateinit var repository: DownloadRepository private lateinit var notificationManager: NotificationManager private lateinit var prefs: SharedPreferences @@ -566,16 +568,8 @@ class DownloadService : Service() { } } - val onCompleteCallback: (DownloadItem) -> Unit = { completedItem -> - serviceScope.launch { - showCompletionNotification(completedItem.id, completedItem.filename) - if ((completedItem.downloadType == DownloadType.TORRENT || completedItem.downloadType == DownloadType.MAGNET) && - torrentDownloadManager.isSeedingEnabled() - ) { - startSeeding(completedItem.id) - } - } - } + var completedForPublication: DownloadItem? = null + val onCompleteCallback: (DownloadItem) -> Unit = { completedForPublication = it } val onErrorCallback: (DownloadItem, String) -> Unit = { failedItem, errorMsg -> serviceScope.launch { @@ -633,6 +627,26 @@ class DownloadService : Service() { } job.join() + completedForPublication?.let { completed -> + val publishFailed = publicationMutex.withLock { + if (repository.getDownloadById(completed.id)?.status != DownloadStatus.COMPLETED) return@let + try { + DownloadStorage.publishCompleted(this, completed) + false + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.w(TAG, "Could not publish completed download ${completed.id}", e) + true + } + } + showCompletionNotification(completed.id, completed.filename, publishFailed) + if ((completed.downloadType == DownloadType.TORRENT || completed.downloadType == DownloadType.MAGNET) && + torrentDownloadManager.isSeedingEnabled() + ) { + startSeeding(completed.id) + } + } } catch (e: CancellationException) { throw e } catch (e: Exception) { @@ -772,30 +786,33 @@ class DownloadService : Service() { fun deleteDownload(id: Long, deleteFile: Boolean = false) { serviceScope.launch { val item = repository.getDownloadById(id) - if (item != null) { - stopManagerForDownload(id, item.downloadType) - cleanupStagingFilesForItem(item) - if (deleteFile) { - runCatching { - val baseDir = File(item.savePath) - val cleanName = com.example.downloadmanager.utils.TorrentPathSafety.validateComponent(item.filename) - val target = com.example.downloadmanager.utils.TorrentPathSafety.resolveContainedFile(baseDir, cleanName) - if (target.exists()) { - val markerFile = File(target, com.example.downloadmanager.utils.TorrentPathSafety.TORRENT_IDENTITY_MARKER) - val ownedByOtherJob = if (markerFile.exists()) { - val markerText = runCatching { markerFile.readText(Charsets.UTF_8).trim() }.getOrDefault("") - markerText.startsWith("job:") && markerText.substringBefore("|") != "job:${item.id}" - } else { - false - } - if (!ownedByOtherJob) { - if (target.isDirectory) target.deleteRecursively() else target.delete() + if (item != null) stopManagerForDownload(id, item.downloadType) + publicationMutex.withLock { + if (item != null) { + cleanupStagingFilesForItem(item) + if (deleteFile) { + runCatching { + val baseDir = File(item.savePath) + val cleanName = com.example.downloadmanager.utils.TorrentPathSafety.validateComponent(item.filename) + val target = com.example.downloadmanager.utils.TorrentPathSafety.resolveContainedFile(baseDir, cleanName) + if (target.exists()) { + val markerFile = File(target, com.example.downloadmanager.utils.TorrentPathSafety.TORRENT_IDENTITY_MARKER) + val ownedByOtherJob = if (markerFile.exists()) { + val markerText = runCatching { markerFile.readText(Charsets.UTF_8).trim() }.getOrDefault("") + markerText.startsWith("job:") && markerText.substringBefore("|") != "job:${item.id}" + } else { + false + } + if (!ownedByOtherJob) { + if (target.isDirectory) target.deleteRecursively() else target.delete() + } } } } } + DownloadStorage.removeRecord(this, id, deleteFile) + repository.delete(id) } - repository.delete(id) notificationManager.cancel(id.toInt() + 1000) processQueue() } @@ -934,7 +951,7 @@ class DownloadService : Service() { notificationManager.notify(id.toInt() + 1000, notification) } - private fun showCompletionNotification(id: Long, title: String) { + private fun showCompletionNotification(id: Long, title: String, publishFailed: Boolean = false) { notificationManager.cancel(id.toInt() + 1000) if (!areNotificationsEnabled()) return @@ -946,7 +963,7 @@ class DownloadService : Service() { ) val notification = NotificationCompat.Builder(this, COMPLETE_CHANNEL_ID) - .setContentTitle("Download Complete") + .setContentTitle(if (publishFailed) getString(R.string.download_saved_in_app) else "Download Complete") .setContentText(title) .setSmallIcon(R.drawable.ic_download) .setContentIntent(pendingIntent) diff --git a/app/src/main/java/com/example/downloadmanager/utils/DownloadStorage.kt b/app/src/main/java/com/example/downloadmanager/utils/DownloadStorage.kt new file mode 100644 index 0000000..9ea3bcd --- /dev/null +++ b/app/src/main/java/com/example/downloadmanager/utils/DownloadStorage.kt @@ -0,0 +1,158 @@ +package com.example.downloadmanager.utils + +import android.content.ContentValues +import android.content.Context +import android.net.Uri +import android.os.Build +import android.os.Environment +import android.provider.MediaStore +import androidx.preference.PreferenceManager +import com.example.downloadmanager.model.DownloadItem +import kotlinx.coroutines.ensureActive +import java.io.File +import java.io.IOException +import kotlin.coroutines.coroutineContext + +object DownloadStorage { + const val PUBLIC_FOLDER = "Download/Luca" + const val DEFAULT_PATH_KEY = "default_save_path" + + private fun managedRoots(context: Context): List = listOfNotNull( + context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)?.resolve("Luca"), + File(context.filesDir, PUBLIC_FOLDER) + ) + + fun isBuiltInPreference(context: Context, value: String?): Boolean { + if (value.isNullOrBlank() || value.trim() == PUBLIC_FOLDER) return true + val path = File(value.trim()).absoluteFile + return managedRoots(context).any { it.absoluteFile == path } || + context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)?.absoluteFile == path || + File(context.filesDir, "Downloads").absoluteFile == path + } + + fun defaultDirectory(context: Context?): File { + if (context == null) return File(System.getProperty("java.io.tmpdir"), PUBLIC_FOLDER).apply { mkdirs() } + val value = PreferenceManager.getDefaultSharedPreferences(context).getString(DEFAULT_PATH_KEY, null) + if (!isBuiltInPreference(context, value) && value != null) { + File(value.trim()).let { if ((it.isDirectory || it.mkdirs()) && it.canWrite()) return it } + } + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { + val public = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).resolve("Luca") + if ((public.isDirectory || public.mkdirs()) && public.canWrite()) return public + } + val roots = managedRoots(context) + return roots.firstOrNull { (it.isDirectory || it.mkdirs()) && it.canWrite() } ?: roots.last() + } + + private fun managedRelativePath(context: Context, directory: File): String? { + val path = directory.canonicalFile + return managedRoots(context).firstNotNullOfOrNull { relativeDirectory(it, path) } + } + + internal fun relativeDirectory(root: File, directory: File): String? { + val base = root.canonicalFile + val path = directory.canonicalFile + return if (path == base || path.path.startsWith(base.path + File.separator)) { + path.relativeTo(base).invariantSeparatorsPath + } else null + } + + fun displayPath(context: Context, path: String): String { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return path + val relative = managedRelativePath(context, File(path)) ?: return path + return listOf(PUBLIC_FOLDER, relative).filter(String::isNotEmpty).joinToString("/") + } + + fun resolveEnteredPath(context: Context, path: String): String { + if (path != PUBLIC_FOLDER && !path.startsWith("$PUBLIC_FOLDER/")) return path + val managed = managedRoots(context) + val base = managed.firstOrNull { (it.isDirectory || it.mkdirs()) && it.canWrite() } ?: managed.last() + if (path == PUBLIC_FOLDER) return base.absolutePath + val relative = path.removePrefix("$PUBLIC_FOLDER/") + return runCatching { TorrentPathSafety.resolveContainedFile(base, relative).absolutePath } + .getOrDefault(base.absolutePath) + } + + private fun exports(context: Context) = context.getSharedPreferences("shared_downloads", Context.MODE_PRIVATE) + + suspend fun publishCompleted(context: Context, item: DownloadItem) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return + val parent = File(item.savePath) + val relativeParent = managedRelativePath(context, parent) ?: return + val root = TorrentPathSafety.resolveContainedFile(parent, item.filename) + TorrentPathSafety.ensureNotSymlink(root) + check(root.exists()) { "Completed download is missing" } + + val key = item.id.toString() + val records = exports(context) + if (records.contains(key)) return + val resolver = context.contentResolver + val pending = mutableListOf() + try { + val files = if (root.isDirectory) { + root.walkTopDown().onEnter { + TorrentPathSafety.ensureNotSymlink(it) + it.name != TorrentPathSafety.STAGING_DIR_NAME + }.filter { it.isFile && it.name != TorrentPathSafety.TORRENT_IDENTITY_MARKER } + } else sequenceOf(root) + + for (file in files) { + coroutineContext.ensureActive() + TorrentPathSafety.ensureNotSymlink(file) + val subfolder = file.parentFile?.relativeTo(parent)?.invariantSeparatorsPath.orEmpty() + val destination = if (root.isDirectory) subfolder else relativeParent + val relativePath = listOf(PUBLIC_FOLDER, destination).filter(String::isNotEmpty).joinToString("/") + val mime = if (root.isFile && item.mimeType.contains('/')) { + item.mimeType + } else { + MediaAssetHelper.getMimeTypeForAnyFile(file) + } + val uri = resolver.insert( + MediaStore.Downloads.EXTERNAL_CONTENT_URI, + ContentValues().apply { + put(MediaStore.Downloads.DISPLAY_NAME, file.name) + put(MediaStore.Downloads.MIME_TYPE, mime) + put(MediaStore.Downloads.RELATIVE_PATH, "$relativePath/") + put(MediaStore.Downloads.IS_PENDING, 1) + } + ) ?: throw IOException("Could not create a file in $relativePath") + pending += uri + val output = resolver.openOutputStream(uri, "w") ?: throw IOException("Could not open $relativePath") + output.use { sink -> + file.inputStream().use { input -> + val buffer = ByteArray(64 * 1024) + while (true) { + coroutineContext.ensureActive() + val count = input.read(buffer) + if (count < 0) break + sink.write(buffer, 0, count) + } + } + } + } + if (pending.isEmpty()) throw IOException("No completed files to publish") + for (uri in pending) { + coroutineContext.ensureActive() + val published = resolver.update(uri, ContentValues().apply { put(MediaStore.Downloads.IS_PENDING, 0) }, null, null) + if (published != 1) throw IOException("Could not publish the downloaded file") + } + check(records.edit().putStringSet(key, pending.map(Uri::toString).toSet()).commit()) { + "Could not record the published downloads" + } + } catch (failure: Exception) { + pending.forEach { uri -> runCatching { resolver.delete(uri, null, null) } } + throw failure + } + } + + fun removeRecord(context: Context, id: Long, deleteFiles: Boolean) { + val records = exports(context) + val key = id.toString() + if (deleteFiles) { + records.getStringSet(key, emptySet()).orEmpty().forEach { value -> + runCatching { context.contentResolver.delete(Uri.parse(value), null, null) } + } + } + records.edit().remove(key).apply() + } +} diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index fcae1e5..7e7734d 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -203,4 +203,5 @@ Download Media (%d) Stop Loading Independent public download manager. Download only public-domain, Creative Commons, or authorized files. + Download available in Luca. Shared folder copy failed. diff --git a/app/src/main/res/xml/file_paths.xml b/app/src/main/res/xml/file_paths.xml index 36926c9..7689c26 100644 --- a/app/src/main/res/xml/file_paths.xml +++ b/app/src/main/res/xml/file_paths.xml @@ -18,6 +18,9 @@ + diff --git a/app/src/test/java/com/example/downloadmanager/DownloadManagerCoreVerificationTest.kt b/app/src/test/java/com/example/downloadmanager/DownloadManagerCoreVerificationTest.kt index 67a5ca2..4eb12ec 100644 --- a/app/src/test/java/com/example/downloadmanager/DownloadManagerCoreVerificationTest.kt +++ b/app/src/test/java/com/example/downloadmanager/DownloadManagerCoreVerificationTest.kt @@ -835,6 +835,21 @@ class DownloadManagerCoreVerificationTest { // Phase 3: Narrow Atomic DAO Updates & Worker Lifecycle Serialization Tests // ========================================================================= + @Test + fun lucaSaveLocationPreservesSubfoldersAndRejectsPathsOutsideTheRoot() { + val temp = createTempDirectory("luca_storage").toFile() + try { + val base = File(temp, "Download/Luca") + assertEquals("", com.example.downloadmanager.utils.DownloadStorage.relativeDirectory(base, base)) + assertEquals("Torrents/Example", com.example.downloadmanager.utils.DownloadStorage.relativeDirectory( + base, File(base, "Torrents/Example") + )) + assertNull(com.example.downloadmanager.utils.DownloadStorage.relativeDirectory(base, File(base, "../Luca-other"))) + } finally { + temp.deleteRecursively() + } + } + @Test fun fullHttpDownloadRejectsAnUnrequestedPartialBody() = runBlocking { val target = createTempDirectory("http_unsolicited_partial").toFile() From 35cc95c0e3bb6e1ead5143b0d551b0886741ab0c Mon Sep 17 00:00:00 2001 From: Ossama Hashim Date: Wed, 2 Dec 2026 16:06:07 +0200 Subject: [PATCH 2/2] fix: use service context when deleting shared downloads --- .../java/com/example/downloadmanager/service/DownloadService.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/java/com/example/downloadmanager/service/DownloadService.kt b/app/src/main/java/com/example/downloadmanager/service/DownloadService.kt index 350ffd7..7a1ae27 100644 --- a/app/src/main/java/com/example/downloadmanager/service/DownloadService.kt +++ b/app/src/main/java/com/example/downloadmanager/service/DownloadService.kt @@ -810,7 +810,7 @@ class DownloadService : Service() { } } } - DownloadStorage.removeRecord(this, id, deleteFile) + DownloadStorage.removeRecord(this@DownloadService, id, deleteFile) repository.delete(id) } notificationManager.cancel(id.toInt() + 1000)