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
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
5 changes: 5 additions & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,11 @@
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="magnet" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>

<activity
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import com.example.downloadmanager.model.DownloadType
import com.example.downloadmanager.service.DownloadService
import com.example.downloadmanager.utils.EdgeToEdgeHelper
import com.example.downloadmanager.utils.MediaAssetHelper
import com.example.downloadmanager.utils.DownloadStorage
import kotlinx.coroutines.launch
import java.io.File
import java.text.SimpleDateFormat
Expand Down Expand Up @@ -485,6 +486,21 @@ class DownloadDetailActivity : AppCompatActivity() {
}

private fun openFile(downloadItem: DownloadItem) {
val sharedUri = DownloadStorage.sharedFileUri(this, downloadItem)
if (sharedUri != null) {
val mime = contentResolver.getType(sharedUri) ?: downloadItem.mimeType
if (mime.startsWith("audio/") || mime.startsWith("video/")) {
startActivity(Intent(this, MediaPlayerActivity::class.java).putExtra("download_id", downloadItem.id))
} else {
try {
val view = DownloadStorage.sharedFileIntent(this, downloadItem, Intent.ACTION_VIEW)
if (view != null) startActivity(view)
} catch (_: android.content.ActivityNotFoundException) {
Toast.makeText(this, R.string.error_file_not_found, Toast.LENGTH_SHORT).show()
}
}
return
}
val resolvedFile = MediaAssetHelper.resolveTargetFileForOpenOrShare(downloadItem)
if (resolvedFile == null || !resolvedFile.exists() || !resolvedFile.isFile) {
Toast.makeText(this, R.string.error_file_not_found, Toast.LENGTH_SHORT).show()
Expand Down Expand Up @@ -543,6 +559,10 @@ class DownloadDetailActivity : AppCompatActivity() {

private fun shareFile(downloadItem: DownloadItem) {
try {
DownloadStorage.sharedFileIntent(this, downloadItem, Intent.ACTION_SEND)?.let {
startActivity(Intent.createChooser(it, downloadItem.filename))
return
}
val file = MediaAssetHelper.resolveTargetFileForOpenOrShare(downloadItem)
if (file != null && file.exists() && file.isFile) {
val uri = FileProvider.getUriForFile(this, "${packageName}.fileprovider", file)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import com.example.downloadmanager.model.DownloadType
import com.example.downloadmanager.service.DownloadService
import com.example.downloadmanager.utils.EdgeToEdgeHelper
import com.example.downloadmanager.utils.MediaAssetHelper
import com.example.downloadmanager.utils.DownloadStorage
import com.google.android.material.bottomsheet.BottomSheetDialog
import java.io.File

Expand Down Expand Up @@ -379,6 +380,21 @@ class MainActivity : AppCompatActivity() {
}

private fun openFile(downloadItem: DownloadItem) {
val sharedUri = DownloadStorage.sharedFileUri(this, downloadItem)
if (sharedUri != null) {
val mime = contentResolver.getType(sharedUri) ?: downloadItem.mimeType
if (mime.startsWith("audio/") || mime.startsWith("video/")) {
startActivity(Intent(this, MediaPlayerActivity::class.java).putExtra("download_id", downloadItem.id))
} else {
try {
val view = DownloadStorage.sharedFileIntent(this, downloadItem, Intent.ACTION_VIEW)
if (view != null) startActivity(view)
} catch (_: android.content.ActivityNotFoundException) {
Toast.makeText(this, R.string.error_file_not_found, Toast.LENGTH_SHORT).show()
}
}
return
}
val resolvedFile = MediaAssetHelper.resolveTargetFileForOpenOrShare(downloadItem)
val candidateName = resolvedFile?.name ?: downloadItem.filename
val effectiveMime = resolvedFile?.let {
Expand Down Expand Up @@ -426,6 +442,10 @@ class MainActivity : AppCompatActivity() {

private fun shareFile(downloadItem: DownloadItem) {
try {
DownloadStorage.sharedFileIntent(this, downloadItem, Intent.ACTION_SEND)?.let {
startActivity(Intent.createChooser(it, downloadItem.filename))
return
}
val file = MediaAssetHelper.resolveTargetFileForOpenOrShare(downloadItem)
?: File(downloadItem.savePath, downloadItem.filename)
if (file.exists() && file.isFile) {
Expand Down Expand Up @@ -531,12 +551,31 @@ class MainActivity : AppCompatActivity() {
val url = intent.dataString
url?.let { handleUrl(it) }
} else if (intent.hasExtra(Intent.EXTRA_TEXT)) {
val text = intent.getStringExtra(Intent.EXTRA_TEXT)
text?.let { handleUrl(it) }
val text = intent.getCharSequenceExtra(Intent.EXTRA_TEXT)?.toString().orEmpty()
val links = sharedDownloadLinks(text)
when {
links.size > 1 -> confirmSharedDownloads(links)
links.size == 1 -> handleUrl(links.single())
text.isNotBlank() -> handleUrl(text)
}
}
}
}

internal fun sharedDownloadLinks(text: String): List<String> =
Regex("""(?:https?://|magnet:\?)[^\s<>"]+""", RegexOption.IGNORE_CASE)
.findAll(text).mapNotNull { AddDownloadActivity.normalizeAndValidateUrl(it.value) }
.distinct().take(50).toList()

private fun confirmSharedDownloads(links: List<String>) {
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) ||
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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()
Expand All @@ -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() }
Expand All @@ -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()
Expand Down Expand Up @@ -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
}
}
Expand Down Expand Up @@ -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
}
}
Expand Down Expand Up @@ -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()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
}
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
Expand All @@ -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()
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -998,6 +1020,7 @@ class DownloadService : Service() {
try {
connectivityManager.unregisterNetworkCallback(networkCallback)
} catch (_: Exception) {}
runCatching { unregisterReceiver(powerReceiver) }
prefs.unregisterOnSharedPreferenceChangeListener(prefChangeListener)
serviceScope.cancel()
super.onDestroy()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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()
Expand All @@ -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)
Expand All @@ -98,6 +102,7 @@ class DownloadRecoveryWorker(

val constraints = Constraints.Builder()
.setRequiredNetworkType(requiredNetwork)
.setRequiresCharging(prefs.getBoolean(CHARGING_ONLY_KEY, false))
.build()

val request = OneTimeWorkRequestBuilder<DownloadRecoveryWorker>()
Expand Down
Loading
Loading