Skip to content
This repository has been archived by the owner on Jul 2, 2024. It is now read-only.

Commit

Permalink
Add createMediaStoreUri & createUriForDownload
Browse files Browse the repository at this point in the history
  • Loading branch information
SanmerDev committed Jun 5, 2024
1 parent a33e09a commit 3307bd8
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 30 deletions.
82 changes: 70 additions & 12 deletions app/src/main/kotlin/com/sanmer/mrepo/compat/MediaStoreCompat.kt
Original file line number Diff line number Diff line change
@@ -1,27 +1,73 @@
package com.sanmer.mrepo.compat

import android.content.ContentValues
import android.content.Context
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.DocumentsContract
import android.provider.OpenableColumns
import android.provider.MediaStore
import android.system.Os
import androidx.annotation.RequiresApi
import androidx.core.net.toFile
import androidx.core.net.toUri
import androidx.documentfile.provider.DocumentFile
import java.io.File
import java.io.IOException

object MediaStoreCompat {
@RequiresApi(Build.VERSION_CODES.R)
fun Context.createMediaStoreUri(
file: File,
collection: Uri = MediaStore.Downloads.EXTERNAL_CONTENT_URI,
mimeType: String
): Uri {
val entry = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, file.name)
put(MediaStore.MediaColumns.RELATIVE_PATH, file.parent)
put(MediaStore.MediaColumns.MIME_TYPE, mimeType)
put(MediaStore.MediaColumns.IS_PENDING, 0)
}

return contentResolver.insert(collection, entry) ?: throw IOException("Can't insert $file")
}

fun Context.createUriForDownload(
path: String,
mimeType: String
) = when {
BuildCompat.atLeastR -> createMediaStoreUri(
file = File(Environment.DIRECTORY_DOWNLOADS, path),
mimeType = mimeType
)
else -> {
val downloadsPath = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS
)
val file = File(downloadsPath, path)
file.parentFile?.apply { if (!exists()) mkdirs() }
file.toUri()
}
}

fun Context.getDisplayNameForUri(uri: Uri): String {
if (uri.scheme == "file") {
return uri.toFile().name
}

require(uri.scheme == "content") { "Uri lacks 'content' scheme: $uri" }

val projection = arrayOf(OpenableColumns.DISPLAY_NAME)
contentResolver.query(uri, projection, null, null, null)?.use { cursor ->
val displayNameColumn = cursor.getColumnIndexOrThrow(OpenableColumns.DISPLAY_NAME)
contentResolver.query(
uri,
arrayOf(MediaStore.MediaColumns.DISPLAY_NAME),
null,
null,
null
)?.use { cursor ->
if (cursor.moveToFirst()) {
return cursor.getString(displayNameColumn)
return cursor.getString(
cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DISPLAY_NAME)
)
}
}

Expand All @@ -35,21 +81,33 @@ object MediaStoreCompat {

require(uri.scheme == "content") { "Uri lacks 'content' scheme: $uri" }

val real = if (DocumentsContract.isTreeUri(uri)) {
DocumentFile.fromTreeUri(this, uri)?.uri ?: uri
} else {
uri
contentResolver.openFileDescriptor(
getDocumentUri(this, uri),
"r"
)?.use {
return Os.readlink("/proc/self/fd/${it.fd}")
}

return contentResolver.openFileDescriptor(real, "r")?.use {
Os.readlink("/proc/self/fd/${it.fd}")
} ?: uri.toString()
return uri.toString()
}

fun Context.getFileForUri(uri: Uri) = File(getPathForUri(uri))

fun getDocumentUri(context: Context, uri: Uri): Uri {
return when {
DocumentsContract.isTreeUri(uri) -> {
DocumentFile.fromTreeUri(context, uri)?.uri ?: uri
}
else -> {
uri
}
}
}

fun Context.copyToDir(uri: Uri, dir: File): File {
if (!dir.exists()) dir.mkdirs()
val tmp = dir.resolve(getDisplayNameForUri(uri))

contentResolver.openInputStream(uri)?.buffered()?.use { input ->
tmp.outputStream().use { output ->
input.copyTo(output)
Expand Down
28 changes: 11 additions & 17 deletions app/src/main/kotlin/com/sanmer/mrepo/service/DownloadService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,13 @@ import android.os.Parcelable
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.app.ServiceCompat
import androidx.documentfile.provider.DocumentFile
import androidx.lifecycle.LifecycleService
import androidx.lifecycle.lifecycleScope
import com.sanmer.mrepo.R
import com.sanmer.mrepo.app.Const
import com.sanmer.mrepo.app.utils.NotificationUtils
import com.sanmer.mrepo.compat.BuildCompat
import com.sanmer.mrepo.compat.MediaStoreCompat.createUriForDownload
import com.sanmer.mrepo.compat.PermissionCompat
import com.sanmer.mrepo.network.NetworkUtils
import com.sanmer.mrepo.repository.UserPreferencesRepository
Expand All @@ -37,7 +38,7 @@ import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.parcelize.Parcelize
import timber.log.Timber
import java.io.FileNotFoundException
import java.io.File
import javax.inject.Inject

@AndroidEntryPoint
Expand Down Expand Up @@ -82,24 +83,17 @@ class DownloadService : LifecycleService() {
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
lifecycleScope.launch {
val item = intent?.taskItemOrNull ?: return@launch
val downloadPath = userPreferencesRepository.data
.first().downloadPath
.let {
if (!it.exists()) it.mkdirs()
DocumentFile.fromFile(it)
}

val df = downloadPath.createFile("*/*", item.filename)
if (df == null) {
onDownloadFailed(item, "Failed to create file")
return@launch
}
val userPreferences = userPreferencesRepository.data.first()
val downloadPath = userPreferences.downloadPath
val file = File(downloadPath, item.filename)

val output = try {
checkNotNull(
contentResolver.openOutputStream(df.uri)
val uri = createUriForDownload(
path = file.toRelativeString(Const.PUBLIC_DOWNLOADS),
mimeType = "android/zip"
)
} catch (e: FileNotFoundException) {
checkNotNull(contentResolver.openOutputStream(uri))
} catch (e: Throwable) {
onDownloadFailed(item, e.message)
return@launch
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ private fun OpenDocumentTreeDialog(
confirmButton = {
TextButton(
onClick = {
val new = Const.PUBLIC_DOWNLOADS.resolve(name)
val new = File(Const.PUBLIC_DOWNLOADS, name.trim())
onConfirm(new)
onClose()
},
Expand Down

0 comments on commit 3307bd8

Please sign in to comment.