From efd82dd53bb8568eafc496faf4a668bc1c021536 Mon Sep 17 00:00:00 2001 From: Ossama Hashim Date: Wed, 2 Dec 2026 16:57:04 +0200 Subject: [PATCH] feat: improve Luca storage, queue recovery and Android sharing --- README.md | 4 ++ app/src/main/AndroidManifest.xml | 5 ++ .../activity/DownloadDetailActivity.kt | 20 ++++++++ .../downloadmanager/activity/MainActivity.kt | 43 +++++++++++++++- .../activity/MediaPlayerActivity.kt | 41 ++++++++++++--- .../service/DownloadService.kt | 51 ++++++++++++++----- .../utils/DownloadRecoveryWorker.kt | 5 ++ .../downloadmanager/utils/DownloadStorage.kt | 34 +++++++++++++ app/src/main/res/values-ar/strings.xml | 5 ++ app/src/main/res/values/strings.xml | 5 ++ app/src/main/res/xml/preferences.xml | 5 ++ docs/DEVICE_VALIDATION.md | 13 +++++ 12 files changed, 208 insertions(+), 23 deletions(-) create mode 100644 docs/DEVICE_VALIDATION.md diff --git a/README.md b/README.md index 95874bd..54d30ec 100644 --- a/README.md +++ b/README.md @@ -60,3 +60,7 @@ An Android download manager for direct HTTP/HTTPS files, BitTorrent/Magnet trans # Run Android Lint ./gradlew :app:lintDebug ``` + +## On-device verification + +Use [the device and competitor protocol](docs/DEVICE_VALIDATION.md) to measure resumability, storage, battery, and playback from the shared downloads folder. Android background-start restrictions can defer a queued transfer until Luca is reopened. diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 88f7efa..0de0fa3 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -46,6 +46,11 @@ + + + + + 1 -> confirmSharedDownloads(links) + links.size == 1 -> handleUrl(links.single()) + text.isNotBlank() -> handleUrl(text) + } } } } + internal fun sharedDownloadLinks(text: String): List = + Regex("""(?:https?://|magnet:\?)[^\s<>"]+""", RegexOption.IGNORE_CASE) + .findAll(text).mapNotNull { AddDownloadActivity.normalizeAndValidateUrl(it.value) } + .distinct().take(50).toList() + + private fun confirmSharedDownloads(links: List) { + android.app.AlertDialog.Builder(this) + .setTitle(R.string.add_download) + .setMessage(getString(R.string.download_batch_confirmation, links.size)) + .setPositiveButton(R.string.yes) { _, _ -> links.forEach { startDownload(it) } } + .setNegativeButton(R.string.no, null) + .show() + } + private fun handleUrl(url: String) { val cleaned = AddDownloadActivity.normalizeAndValidateUrl(url) ?: url.trim() if (cleaned.startsWith("http", ignoreCase = true) || diff --git a/app/src/main/java/com/example/downloadmanager/activity/MediaPlayerActivity.kt b/app/src/main/java/com/example/downloadmanager/activity/MediaPlayerActivity.kt index f932da6..eca7310 100644 --- a/app/src/main/java/com/example/downloadmanager/activity/MediaPlayerActivity.kt +++ b/app/src/main/java/com/example/downloadmanager/activity/MediaPlayerActivity.kt @@ -44,6 +44,7 @@ import com.example.downloadmanager.model.DownloadRepository import com.example.downloadmanager.model.DownloadStatus import com.example.downloadmanager.utils.EdgeToEdgeHelper import com.example.downloadmanager.utils.MediaAssetHelper +import com.example.downloadmanager.utils.DownloadStorage import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @@ -328,6 +329,24 @@ class MediaPlayerActivity : AppCompatActivity() { private fun playDownloadItem(item: DownloadItem) { currentDownloadItem = item lifecycleScope.launch { + val sharedUri = DownloadStorage.sharedFileUri(this@MediaPlayerActivity, item) + if (sharedUri != null) { + val mime = withContext(Dispatchers.IO) { + contentResolver.getType(sharedUri) ?: item.mimeType + } + hasRepairedCurrentFile = false + currentMediaFile = null + currentIsVideo = mime.startsWith("video/") + currentTitle = item.videoTitle?.takeIf { it.isNotBlank() } ?: item.filename + supportActionBar?.title = currentTitle + runCatching { platformAudioPlayer?.release() } + platformAudioPlayer = null + isUsingPlatformAudioPlayer = false + binding.platformVideoView.stopPlayback() + isUsingPlatformVideoPlayer = false + startExoMedia(sharedUri, currentIsVideo, null, item.fileSize) + return@launch + } val resolvedPair = withContext(Dispatchers.IO) { val candidate = MediaAssetHelper.resolvePlayableFile(item) ?: File(item.savePath, item.filename) @@ -427,7 +446,7 @@ class MediaPlayerActivity : AppCompatActivity() { val repairedSummary = withContext(Dispatchers.IO) { MediaAssetHelper.inspectMediaCodecSummary(repairedFile, repairedIsVideo) } - startValidatedExoPlayer(repairedFile, repairedMime, repairedIsVideo, repairedSummary) + startValidatedExoPlayer(repairedFile, repairedIsVideo, repairedSummary) } else { updateMediaTitles(title, "Media file is incomplete or unsupported — tap Retry in Downloads") Toast.makeText(this@MediaPlayerActivity, R.string.error_open_file, Toast.LENGTH_SHORT).show() @@ -437,17 +456,20 @@ class MediaPlayerActivity : AppCompatActivity() { val effectiveIsVideo = detectedMime.startsWith("video/") || (isVideo && !detectedMime.startsWith("audio/")) currentIsVideo = effectiveIsVideo - startValidatedExoPlayer(file, detectedMime, effectiveIsVideo, resolvedSummary) + startValidatedExoPlayer(file, effectiveIsVideo, resolvedSummary) } } private fun startValidatedExoPlayer( file: File, - detectedMime: String, isVideo: Boolean, subtitle: String? ) { - val sizeStr = formatBytes(file.length()) + startExoMedia(Uri.fromFile(file), isVideo, subtitle, file.length()) + } + + private fun startExoMedia(uri: Uri, isVideo: Boolean, subtitle: String?, size: Long) { + val sizeStr = formatBytes(size) val infoLine = listOfNotNull( subtitle ?: if (isVideo) "HD Video" else "Studio Audio", sizeStr.takeIf { it.isNotEmpty() } @@ -468,7 +490,7 @@ class MediaPlayerActivity : AppCompatActivity() { binding.playerView.player = player // Build MediaItem from file:// URI without forcing a restrictive container MIME hint // so DefaultExtractorsFactory sniffs the exact header bytes (MP4, fMP4, MPEG-TS, WebM, MKV, MP3, ADTS, FLAC, OGG, WAV) - val mediaItem = MediaItem.fromUri(Uri.fromFile(file)) + val mediaItem = MediaItem.fromUri(uri) player.setMediaItem(mediaItem) player.setPlaybackSpeed(currentSpeed) player.prepare() @@ -587,7 +609,7 @@ class MediaPlayerActivity : AppCompatActivity() { val repairedSummary = withContext(Dispatchers.IO) { MediaAssetHelper.inspectMediaCodecSummary(repairedFile, repairedIsVideo) } - startValidatedExoPlayer(repairedFile, repairedMime, repairedIsVideo, repairedSummary) + startValidatedExoPlayer(repairedFile, repairedIsVideo, repairedSummary) return@launch } } @@ -620,7 +642,7 @@ class MediaPlayerActivity : AppCompatActivity() { if (remuxedFile != null && remuxedFile.exists()) { currentMediaFile = remuxedFile currentIsVideo = false - startValidatedExoPlayer(remuxedFile, "audio/mp4", isVideo = false, subtitle = "AAC Audio (Remuxed)") + startValidatedExoPlayer(remuxedFile, isVideo = false, subtitle = "AAC Audio (Remuxed)") return@launch } } @@ -838,6 +860,11 @@ class MediaPlayerActivity : AppCompatActivity() { } binding.btnShareMedia.setOnClickListener { + val shared = currentDownloadItem?.let { DownloadStorage.sharedFileIntent(this, it, Intent.ACTION_SEND) } + if (shared != null && currentMediaFile == null) { + startActivity(Intent.createChooser(shared, currentTitle)) + return@setOnClickListener + } val file = currentMediaFile if (file == null || !file.exists()) { Toast.makeText(this, R.string.error_file_not_found, Toast.LENGTH_SHORT).show() 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 7a1ae27..7622537 100644 --- a/app/src/main/java/com/example/downloadmanager/service/DownloadService.kt +++ b/app/src/main/java/com/example/downloadmanager/service/DownloadService.kt @@ -5,19 +5,23 @@ import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.app.Service +import android.content.BroadcastReceiver import android.content.Context +import android.content.IntentFilter import android.content.Intent import android.content.SharedPreferences import android.content.pm.ServiceInfo import android.net.ConnectivityManager import android.net.Network import android.net.NetworkCapabilities +import android.os.BatteryManager import android.os.Binder import android.os.Build import android.os.IBinder import android.os.PowerManager import android.util.Log import androidx.core.app.NotificationCompat +import androidx.core.content.ContextCompat import androidx.preference.PreferenceManager import com.example.downloadmanager.R import com.example.downloadmanager.activity.MainActivity @@ -126,8 +130,14 @@ class DownloadService : Service() { } } + private val powerReceiver = object : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + serviceScope.launch { enforceNetworkPolicyAndProcessQueue() } + } + } + private val prefChangeListener = SharedPreferences.OnSharedPreferenceChangeListener { _, key -> - if (key == "use_mobile_data" || key == "max_concurrent_downloads" || key == "auto_resume_failed") { + if (key == "use_mobile_data" || key == "max_concurrent_downloads" || key == "auto_resume_failed" || key == DownloadRecoveryWorker.CHARGING_ONLY_KEY) { serviceScope.launch { enforceNetworkPolicyAndProcessQueue() } @@ -164,6 +174,10 @@ class DownloadService : Service() { Log.w(TAG, "Failed to register network callback: ${e.message}") } prefs.registerOnSharedPreferenceChangeListener(prefChangeListener) + ContextCompat.registerReceiver(this, powerReceiver, IntentFilter().apply { + addAction(Intent.ACTION_POWER_CONNECTED) + addAction(Intent.ACTION_POWER_DISCONNECTED) + }, ContextCompat.RECEIVER_NOT_EXPORTED) // Recover any leftover DOWNLOADING rows from previous process death into QUEUED serviceScope.launch { @@ -276,10 +290,23 @@ class DownloadService : Service() { private enum class NetworkEligibility { ELIGIBLE, NO_NETWORK, - WAITING_FOR_WIFI + WAITING_FOR_WIFI, + WAITING_FOR_CHARGE; + + fun message(context: Context): String = context.getString(when (this) { + WAITING_FOR_WIFI -> R.string.download_waiting_for_wifi + WAITING_FOR_CHARGE -> R.string.download_waiting_for_charge + else -> R.string.download_waiting_for_network + }) } private fun checkNetworkEligibility(): NetworkEligibility { + if (prefs.getBoolean(DownloadRecoveryWorker.CHARGING_ONLY_KEY, false)) { + val battery = registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED)) + if ((battery?.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) ?: 0) == 0) { + return NetworkEligibility.WAITING_FOR_CHARGE + } + } return try { val activeNetwork = connectivityManager.activeNetwork ?: return NetworkEligibility.NO_NETWORK val caps = connectivityManager.getNetworkCapabilities(activeNetwork) @@ -302,16 +329,15 @@ class DownloadService : Service() { private suspend fun enforceNetworkPolicyAndProcessQueue() { val eligibility = checkNetworkEligibility() - if (eligibility == NetworkEligibility.WAITING_FOR_WIFI && activeDownloadIds.isNotEmpty()) { + if (eligibility != NetworkEligibility.ELIGIBLE && activeDownloadIds.isNotEmpty()) { val runningIds = activeDownloadIds.toList() for (id in runningIds) { val item = repository.getDownloadById(id) - stopManagerForDownload(id, item?.downloadType) - repository.updateStatus( - id = id, - status = DownloadStatus.QUEUED, - error = "Waiting for Wi-Fi" - ) + if (item?.status != DownloadStatus.DOWNLOADING) continue + stopManagerForDownload(id, item.downloadType) + if (repository.getDownloadById(id)?.status == DownloadStatus.DOWNLOADING) { + repository.updateStatus(id, DownloadStatus.QUEUED, eligibility.message(this)) + } } DownloadRecoveryWorker.enqueueRecovery(this) demoteForegroundIfIdle() @@ -496,11 +522,7 @@ class DownloadService : Service() { val eligibility = checkNetworkEligibility() if (eligibility != NetworkEligibility.ELIGIBLE) { - val waitingMessage = if (eligibility == NetworkEligibility.WAITING_FOR_WIFI) { - "Waiting for Wi-Fi" - } else { - "Waiting for network connection" - } + val waitingMessage = eligibility.message(this) for (queued in queuedItems) { if (queued.errorMessage != waitingMessage) { repository.updateStatus( @@ -998,6 +1020,7 @@ class DownloadService : Service() { try { connectivityManager.unregisterNetworkCallback(networkCallback) } catch (_: Exception) {} + runCatching { unregisterReceiver(powerReceiver) } prefs.unregisterOnSharedPreferenceChangeListener(prefChangeListener) serviceScope.cancel() super.onDestroy() diff --git a/app/src/main/java/com/example/downloadmanager/utils/DownloadRecoveryWorker.kt b/app/src/main/java/com/example/downloadmanager/utils/DownloadRecoveryWorker.kt index 1955eab..efa2c61 100644 --- a/app/src/main/java/com/example/downloadmanager/utils/DownloadRecoveryWorker.kt +++ b/app/src/main/java/com/example/downloadmanager/utils/DownloadRecoveryWorker.kt @@ -14,6 +14,7 @@ import androidx.work.WorkerParameters import com.example.downloadmanager.model.DownloadDatabase import com.example.downloadmanager.model.DownloadStatus import com.example.downloadmanager.service.DownloadService +import kotlinx.coroutines.CancellationException /** * WorkManager worker used for post-boot and background download state recovery. @@ -80,6 +81,8 @@ class DownloadRecoveryWorker( } Result.success() + } catch (cancelled: CancellationException) { + throw cancelled } catch (e: Exception) { Log.e(TAG, "Recovery worker failed", e) Result.retry() @@ -90,6 +93,7 @@ class DownloadRecoveryWorker( private const val TAG = "DownloadRecoveryWorker" private const val UNIQUE_WORK_NAME = "luca_download_recovery_work" const val MAX_AUTO_RETRIES = 3 + const val CHARGING_ONLY_KEY = "download_only_while_charging" fun enqueueRecovery(context: Context) { val prefs = PreferenceManager.getDefaultSharedPreferences(context) @@ -98,6 +102,7 @@ class DownloadRecoveryWorker( val constraints = Constraints.Builder() .setRequiredNetworkType(requiredNetwork) + .setRequiresCharging(prefs.getBoolean(CHARGING_ONLY_KEY, false)) .build() val request = OneTimeWorkRequestBuilder() diff --git a/app/src/main/java/com/example/downloadmanager/utils/DownloadStorage.kt b/app/src/main/java/com/example/downloadmanager/utils/DownloadStorage.kt index 9ea3bcd..7c1a0c9 100644 --- a/app/src/main/java/com/example/downloadmanager/utils/DownloadStorage.kt +++ b/app/src/main/java/com/example/downloadmanager/utils/DownloadStorage.kt @@ -2,12 +2,16 @@ package com.example.downloadmanager.utils import android.content.ContentValues import android.content.Context +import android.content.ClipData +import android.content.Intent 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 com.example.downloadmanager.model.DownloadStatus +import com.example.downloadmanager.model.DownloadType import kotlinx.coroutines.ensureActive import java.io.File import java.io.IOException @@ -75,6 +79,30 @@ object DownloadStorage { private fun exports(context: Context) = context.getSharedPreferences("shared_downloads", Context.MODE_PRIVATE) + private fun keepsWorkingCopy(item: DownloadItem): Boolean = + item.downloadType == DownloadType.TORRENT || item.downloadType == DownloadType.MAGNET + + fun sharedFileUri(context: Context, item: DownloadItem): Uri? { + if (item.status != DownloadStatus.COMPLETED || keepsWorkingCopy(item)) return null + return exports(context).getStringSet(item.id.toString(), emptySet()) + ?.singleOrNull()?.let(Uri::parse) + } + + fun sharedFileIntent(context: Context, item: DownloadItem, action: String): Intent? { + val uri = sharedFileUri(context, item) ?: return null + val mime = context.contentResolver.getType(uri) ?: item.mimeType.ifBlank { "*/*" } + return Intent(action).apply { + if (action == Intent.ACTION_VIEW) setDataAndType(uri, mime) + else { + type = mime + putExtra(Intent.EXTRA_STREAM, uri) + putExtra(Intent.EXTRA_TITLE, item.filename) + } + clipData = ClipData.newRawUri(item.filename, uri) + addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) + } + } + suspend fun publishCompleted(context: Context, item: DownloadItem) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return val parent = File(item.savePath) @@ -117,6 +145,8 @@ object DownloadStorage { } ) ?: throw IOException("Could not create a file in $relativePath") pending += uri + val expectedSize = file.length() + var copied = 0L val output = resolver.openOutputStream(uri, "w") ?: throw IOException("Could not open $relativePath") output.use { sink -> file.inputStream().use { input -> @@ -126,9 +156,11 @@ object DownloadStorage { val count = input.read(buffer) if (count < 0) break sink.write(buffer, 0, count) + copied += count } } } + if (copied != expectedSize) throw IOException("The completed file changed during publication") } if (pending.isEmpty()) throw IOException("No completed files to publish") for (uri in pending) { @@ -143,6 +175,8 @@ object DownloadStorage { pending.forEach { uri -> runCatching { resolver.delete(uri, null, null) } } throw failure } + // The URI is durable before the private copy is removed. Keep torrent payloads for seeding. + if (root.isFile && !keepsWorkingCopy(item)) root.delete() } fun removeRecord(context: Context, id: Long, deleteFiles: Boolean) { diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 8ed0713..4c593da 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -186,4 +186,9 @@ الروابط المكتشفة القابلة للتحميل تحميل الكل مشغل الوسائط + التنزيل أثناء الشحن فقط + في انتظار واي فاي + في انتظار الشحن + في انتظار الاتصال بالشبكة + تضيف %1$d رابط لطابور التنزيل؟ diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 7e7734d..3e69b8c 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -204,4 +204,9 @@ Stop Loading Independent public download manager. Download only public-domain, Creative Commons, or authorized files. Download available in Luca. Shared folder copy failed. + Download only while charging + Waiting for Wi-Fi + Waiting for charging + Waiting for network connection + Add %1$d links to the download queue? diff --git a/app/src/main/res/xml/preferences.xml b/app/src/main/res/xml/preferences.xml index 57fdd01..8aa050e 100644 --- a/app/src/main/res/xml/preferences.xml +++ b/app/src/main/res/xml/preferences.xml @@ -31,6 +31,11 @@ android:title="@string/use_mobile_data" android:defaultValue="true" /> + +