diff --git a/app/src/main/java/fr/free/nrw/commons/filepicker/FilePicker.kt b/app/src/main/java/fr/free/nrw/commons/filepicker/FilePicker.kt index ccccfbd34..bb0a371e1 100644 --- a/app/src/main/java/fr/free/nrw/commons/filepicker/FilePicker.kt +++ b/app/src/main/java/fr/free/nrw/commons/filepicker/FilePicker.kt @@ -256,7 +256,9 @@ object FilePicker : Constants { * */ val intent = if (openDocumentIntentPreferred) { - Intent(Intent.ACTION_OPEN_DOCUMENT) + Intent(Intent.ACTION_OPEN_DOCUMENT).apply { + addCategory(Intent.CATEGORY_OPENABLE) + } } else { Intent(Intent.ACTION_GET_CONTENT) } @@ -271,6 +273,7 @@ object FilePicker : Constants { callbacks: Callbacks ) { if (result.resultCode == Activity.RESULT_OK && !isPhoto(result.data)) { + takePersistableUriPermissions(activity, result) try { val files = getFilesFromGalleryPictures(result.data, activity) callbacks.onImagesPicked(files, ImageSource.DOCUMENTS, restoreType(activity)) @@ -283,6 +286,23 @@ object FilePicker : Constants { } } + /** + * takePersistableUriPermission is necessary to persist the URI permission as + * the permission granted by the system for read or write access on ACTION_OPEN_DOCUMENT + * lasts only until the user's device restarts. + * Ref: https://developer.android.com/training/data-storage/shared/documents-files#persist-permissions + * + * This helps fix the SecurityException reported in this issue: + * https://github.com/commons-app/apps-android-commons/issues/6357 + */ + private fun takePersistableUriPermissions(context: Context, result: ActivityResult) { + result.data?.data?.also { uri -> + val takeFlags: Int = (Intent.FLAG_GRANT_READ_URI_PERMISSION + or Intent.FLAG_GRANT_WRITE_URI_PERMISSION) + context.contentResolver.takePersistableUriPermission(uri, takeFlags) + } + } + /** * onPictureReturnedFromCustomSelector. * Retrieve and forward the images to upload wizard through callback.