Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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()
Expand Down
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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() {
Expand Down Expand Up @@ -51,12 +51,14 @@ class SettingsActivity : AppCompatActivity() {
findPreference<Preference>("pref_app_version")?.summary =
"Luca Download Manager v${BuildConfig.VERSION_NAME}"

// Populate default save location if empty
val savePathPref = findPreference<EditTextPreference>("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<EditTextPreference>(DownloadStorage.DEFAULT_PATH_KEY)
savePathPref?.summaryProvider = Preference.SummaryProvider<EditTextPreference> { 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
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
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
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
Expand Down Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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@DownloadService, id, deleteFile)
repository.delete(id)
}
repository.delete(id)
notificationManager.cancel(id.toInt() + 1000)
processQueue()
}
Expand Down Expand Up @@ -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

Expand All @@ -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)
Expand Down
Loading
Loading