🛠️ Fix error when getting file from full path

This commit is contained in:
Acclorite 2025-03-16 10:01:02 +02:00
parent 3fb8c18cec
commit 19c294779a

View file

@ -10,6 +10,7 @@ import android.content.Context
import android.net.Uri
import android.provider.DocumentsContract
import com.anggrayudi.storage.file.DocumentFileCompat
import com.anggrayudi.storage.file.getAbsolutePath
object CachedFileCompat {
fun fromUri(context: Context, uri: Uri, builder: CachedFileBuilder? = null): CachedFile {
@ -37,38 +38,33 @@ object CachedFileCompat {
builder: CachedFileBuilder? = null
): CachedFile? {
val uri = try {
val fullPathUri = DocumentFileCompat.fromFullPath(context, path)?.uri
?: throw NullPointerException("Could not get URI from full path.")
fullPathUri
} catch (e: Exception) {
e.printStackTrace()
try {
val parentUri = DocumentFileCompat.getAccessibleRootDocumentFile(
context = context,
fullPath = path
)?.uri
?: throw NullPointerException("Could not get parent URI.")
val storageId = DocumentFileCompat.getStorageId(context, path)
if (storageId.isBlank()) throw NullPointerException("Could not get storageId.")
val basePath = DocumentFileCompat.getBasePath(context, path)
if (basePath.isBlank()) throw NullPointerException("Could not get basePath.")
val documentUri = DocumentsContract.buildDocumentUriUsingTree(
parentUri,
"$storageId:$basePath"
)
if (documentUri == null) throw NullPointerException("Could not get document URI.")
val parentUri = context.contentResolver.persistedUriPermissions.find {
try {
val persistedUri = DocumentFileCompat.fromUri(context, it.uri)
val persistedUriPath = persistedUri?.getAbsolutePath(context)
documentUri
return@find !(persistedUri == null ||
!persistedUri.canRead() ||
persistedUriPath.isNullOrBlank() ||
!path.startsWith(persistedUriPath, ignoreCase = true))
} catch (e: Exception) {
e.printStackTrace()
return@find false
}
}?.uri
if (parentUri == null) throw NullPointerException("Could not get parentUri.")
DocumentsContract.buildDocumentUriUsingTree(parentUri, "$storageId:$basePath")
} catch (e: Exception) {
e.printStackTrace()
return null
}
}
val cachedFile = CachedFile(
context = context,