Skip to content

Commit

Permalink
Checking permission of fileDescriptor is it has the read access or not.
Browse files Browse the repository at this point in the history
  • Loading branch information
MohitMaliDeveloper committed Dec 30, 2023
1 parent 7c59193 commit 21b34e2
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -309,8 +309,8 @@ class LocalLibraryFragment : BaseFragment() {

private fun showFileChooser() {
val intent = Intent().apply {
action = Intent.ACTION_OPEN_DOCUMENT
type = "application/octet-stream"
action = Intent.ACTION_GET_CONTENT
type = "*/*"
addCategory(Intent.CATEGORY_OPENABLE)
}
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,10 @@ import org.kiwix.kiwixmobile.core.reader.ZimReaderContainer
import org.kiwix.kiwixmobile.core.utils.SharedPreferenceUtil
import java.io.BufferedReader
import java.io.File
import java.io.FileDescriptor
import java.io.FileInputStream
import java.io.IOException
import java.nio.ByteBuffer

object FileUtils {

Expand Down Expand Up @@ -416,7 +419,21 @@ object FileUtils {
uri: Uri
): AssetFileDescriptor? {
return try {
context.contentResolver.openFileDescriptor(uri, "r").use {
val documentFile = DocumentFile.fromSingleUri(context, uri)
if (documentFile?.uri == null) {
return null
}
Log.e(
"PERMISSION",
"getAssetFileDescriptorFromUri: can Read file = ${documentFile.canRead()}\n" +
" can right file = ${documentFile.canWrite()}"
)
context.contentResolver.openFileDescriptor(documentFile.uri, "r", null).use {
Log.e(
"PERMISSION",
"getAssetFileDescriptorFromUri: check file descriptor permission = " +
"${checkReadFileDescriptorPermission(it?.fileDescriptor)}"
)
AssetFileDescriptor(
ParcelFileDescriptor.dup(it?.fileDescriptor),
0, AssetFileDescriptor.UNKNOWN_LENGTH
Expand All @@ -430,4 +447,22 @@ object FileUtils {
null
}
}

private fun checkReadFileDescriptorPermission(fileDescriptor: FileDescriptor?): Boolean {
if (fileDescriptor?.valid() == false) {
// The FileDescriptor is not valid
return false
}

return try {
val channel = FileInputStream(fileDescriptor).channel
// Try to check read access
channel.position(0)
channel.read(ByteBuffer.allocate(1))
true
} catch (ignore: Exception) {
// An exception occurred, indicating a lack of read permission
false
}
}
}

0 comments on commit 21b34e2

Please sign in to comment.