Skip to content

Commit

Permalink
Moved isFileExist method to IO thread.
Browse files Browse the repository at this point in the history
  • Loading branch information
MohitMaliDeveloper committed Dec 5, 2024
1 parent 116180e commit bbb0122
Show file tree
Hide file tree
Showing 35 changed files with 515 additions and 365 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -174,13 +174,15 @@ class CopyMoveFileHandlerTest : BaseActivityTest() {
clickOnMove()
assertZimFileCopiedAndShowingIntoTheReader()
}
assertZimFileAddedInTheLocalLibrary()
assertSelectedZimFileIsDeletedFromTheStorage(selectedFile)
deleteAllFilesInDirectory(parentFile)
kiwixMainActivity.lifecycleScope.launch {
assertZimFileAddedInTheLocalLibrary()
assertSelectedZimFileIsDeletedFromTheStorage(selectedFile)
deleteAllFilesInDirectory(parentFile)
}
}
}

private fun assertSelectedZimFileIsDeletedFromTheStorage(selectedZimFile: File) {
private suspend fun assertSelectedZimFileIsDeletedFromTheStorage(selectedZimFile: File) {
if (selectedZimFile.isFileExist()) {
throw RuntimeException("Selected zim file is not deleted from the storage")
}
Expand All @@ -194,7 +196,7 @@ class CopyMoveFileHandlerTest : BaseActivityTest() {
}

private fun showMoveFileToPublicDirectoryDialog() {
UiThreadStatement.runOnUiThread {
kiwixMainActivity.lifecycleScope.launch {
val navHostFragment: NavHostFragment =
kiwixMainActivity.supportFragmentManager
.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
Expand Down Expand Up @@ -268,22 +270,22 @@ class CopyMoveFileHandlerTest : BaseActivityTest() {
StorageCalculator(sharedPreferenceUtil),
Fat32Checker(sharedPreferenceUtil, listOf(FileWritingFileSystemChecker()))
)
// test fileName when there is already a file available with same name.
// it should return different name
selectedFile = File(parentFile, selectedFileName).apply {
if (!isFileExist()) createNewFile()
}
copyMoveFileHandler.setSelectedFileAndUri(null, DocumentFile.fromFile(selectedFile))
destinationFile = copyMoveFileHandler.getDestinationFile()
Assert.assertNotEquals(
destinationFile.name,
selectedFile.name
)
Assert.assertEquals(
destinationFile.name,
"testCopyMove_1.zim"
)
kiwixMainActivity.lifecycleScope.launch {
// test fileName when there is already a file available with same name.
// it should return different name
selectedFile = File(parentFile, selectedFileName).apply {
if (!isFileExist()) createNewFile()
}
copyMoveFileHandler.setSelectedFileAndUri(null, DocumentFile.fromFile(selectedFile))
destinationFile = copyMoveFileHandler.getDestinationFile()
Assert.assertNotEquals(
destinationFile.name,
selectedFile.name
)
Assert.assertEquals(
destinationFile.name,
"testCopyMove_1.zim"
)
withContext(Dispatchers.IO) {
deleteBothPreviousFiles()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,18 @@ import io.mockk.mockk
import io.mockk.mockkStatic
import io.mockk.slot
import io.mockk.verify
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import org.junit.Before
import org.junit.jupiter.api.Test
import org.kiwix.kiwixmobile.core.R
import org.kiwix.kiwixmobile.core.extensions.toast
import org.kiwix.kiwixmobile.core.reader.ZimReaderContainer
import org.kiwix.kiwixmobile.core.utils.SharedPreferenceUtil
import org.kiwix.kiwixmobile.core.utils.dialog.AlertDialogShower
import org.kiwix.kiwixmobile.core.utils.dialog.UnsupportedMimeTypeHandler
import org.kiwix.kiwixmobile.core.utils.dialog.KiwixDialog
import org.kiwix.kiwixmobile.core.utils.dialog.UnsupportedMimeTypeHandler
import java.io.File
import java.io.InputStream

Expand All @@ -48,6 +51,7 @@ class UnsupportedMimeTypeHandlerTest {
private val savedFile: File = mockk(relaxed = true)
private val activity: Activity = mockk()
private val webResourceResponse: WebResourceResponse = mockk()
private val coroutineScope = CoroutineScope(Dispatchers.Main)
private val inputStream: InputStream = mockk()
private val unsupportedMimeTypeHandler = UnsupportedMimeTypeHandler(
activity,
Expand Down Expand Up @@ -85,13 +89,17 @@ class UnsupportedMimeTypeHandlerTest {
}

@Test
fun testOpeningFileInExternalReaderApplication() {
fun testOpeningFileInExternalReaderApplication() = runBlocking {
every {
unsupportedMimeTypeHandler.intent.resolveActivity(activity.packageManager)
} returns mockk()
every { activity.startActivity(unsupportedMimeTypeHandler.intent) } returns mockk()
val lambdaSlot = slot<() -> Unit>()
unsupportedMimeTypeHandler.showSaveOrOpenUnsupportedFilesDialog(demoUrl, "application/pdf")
unsupportedMimeTypeHandler.showSaveOrOpenUnsupportedFilesDialog(
demoUrl,
"application/pdf",
coroutineScope
)
verify {
alertDialogShower.show(
KiwixDialog.SaveOrOpenUnsupportedFiles,
Expand All @@ -116,7 +124,11 @@ class UnsupportedMimeTypeHandlerTest {
Toast.makeText(activity, R.string.no_reader_application_installed, Toast.LENGTH_LONG).show()
}
val lambdaSlot = slot<() -> Unit>()
unsupportedMimeTypeHandler.showSaveOrOpenUnsupportedFilesDialog(demoUrl, "application/pdf")
unsupportedMimeTypeHandler.showSaveOrOpenUnsupportedFilesDialog(
demoUrl,
"application/pdf",
coroutineScope
)
verify {
alertDialogShower.show(
KiwixDialog.SaveOrOpenUnsupportedFiles,
Expand All @@ -143,7 +155,8 @@ class UnsupportedMimeTypeHandlerTest {
val lambdaSlot = slot<() -> Unit>()
unsupportedMimeTypeHandler.showSaveOrOpenUnsupportedFilesDialog(
demoUrl,
"application/pdf"
"application/pdf",
coroutineScope
)
verify {
alertDialogShower.show(
Expand All @@ -160,7 +173,11 @@ class UnsupportedMimeTypeHandlerTest {
@Test
fun testUserClicksOnNoThanksButton() {
val lambdaSlot = slot<() -> Unit>()
unsupportedMimeTypeHandler.showSaveOrOpenUnsupportedFilesDialog(demoUrl, "application/pdf")
unsupportedMimeTypeHandler.showSaveOrOpenUnsupportedFilesDialog(
demoUrl,
"application/pdf",
coroutineScope
)
verify {
alertDialogShower.show(
KiwixDialog.SaveOrOpenUnsupportedFiles,
Expand All @@ -186,7 +203,11 @@ class UnsupportedMimeTypeHandlerTest {
Toast.makeText(activity, R.string.save_media_error, Toast.LENGTH_LONG).show()
}
val lambdaSlot = slot<() -> Unit>()
downloadOrOpenEpubAndPdfHandler.showSaveOrOpenUnsupportedFilesDialog(null, "application/pdf")
downloadOrOpenEpubAndPdfHandler.showSaveOrOpenUnsupportedFilesDialog(
null,
"application/pdf",
coroutineScope
)
verify {
alertDialogShower.show(
KiwixDialog.SaveOrOpenUnsupportedFiles,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ import android.os.Environment
import androidx.test.platform.app.InstrumentationRegistry
import io.mockk.every
import io.mockk.mockk
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.junit.After
import org.junit.Assert
import org.junit.Before
Expand Down Expand Up @@ -71,7 +75,7 @@ class FileUtilsInstrumentationTest {

@Test
@Throws(IOException::class)
fun testGetAllZimParts() {
fun testGetAllZimParts() = runBlocking {

// Filename ends with .zimXX and the files up till "FileName.zimer" exist
// i.e. 26 * 4 + 18 = 122 files exist
Expand Down Expand Up @@ -140,7 +144,7 @@ class FileUtilsInstrumentationTest {

@Test
@Throws(IOException::class)
fun testHasPart() {
fun testHasPart() = runBlocking {
val testId = "3yd5474g-55d1-aqw0-108z-1xp69x25260d"
val baseName = testDir?.path + "/" + testId + "testFile"

Expand Down Expand Up @@ -418,12 +422,14 @@ class FileUtilsInstrumentationTest {
)
)
context?.let { context ->
dummyUriData.forEach { dummyUrlData ->
dummyUrlData.uri?.let { uri ->
Assertions.assertEquals(
FileUtils.getLocalFilePathByUri(context, uri),
dummyUrlData.expectedFileName
)
CoroutineScope(Dispatchers.Main).launch {
dummyUriData.forEach { dummyUrlData ->
dummyUrlData.uri?.let { uri ->
Assertions.assertEquals(
FileUtils.getLocalFilePathByUri(context, uri),
dummyUrlData.expectedFileName
)
}
}
}
}
Expand Down Expand Up @@ -489,7 +495,7 @@ class FileUtilsInstrumentationTest {
}

@Test
fun testDocumentProviderContentQuery() {
fun testDocumentProviderContentQuery() = runBlocking {
// We are not running this test case on Android 13 and above. In this version,
// numerous security updates have been included, preventing us from modifying the
// default behavior of ContentResolver.
Expand Down Expand Up @@ -544,7 +550,7 @@ class FileUtilsInstrumentationTest {
}
}

private fun testWithDownloadUri(
private suspend fun testWithDownloadUri(
uri: Uri,
expectedPath: String,
documentsContractWrapper: DocumentResolverWrapper = DocumentResolverWrapper()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ class CopyMoveFileHandler @Inject constructor(
}
}

fun showMoveFileToPublicDirectoryDialog(
suspend fun showMoveFileToPublicDirectoryDialog(
uri: Uri? = null,
documentFile: DocumentFile? = null,
shouldValidateZimFile: Boolean = false,
Expand Down Expand Up @@ -155,16 +155,18 @@ class CopyMoveFileHandler @Inject constructor(
)

fun copyMoveZIMFileInSelectedStorage(storageDevice: StorageDevice) {
sharedPreferenceUtil.apply {
shouldShowStorageSelectionDialog = false
putPrefStorage(sharedPreferenceUtil.getPublicDirectoryPath(storageDevice.name))
putStoragePosition(
if (storageDevice.isInternal) INTERNAL_SELECT_POSITION
else EXTERNAL_SELECT_POSITION
)
}
if (validateZimFileCanCopyOrMove()) {
performCopyMoveOperation()
lifecycleScope?.launch {
sharedPreferenceUtil.apply {
shouldShowStorageSelectionDialog = false
putPrefStorage(sharedPreferenceUtil.getPublicDirectoryPath(storageDevice.name))
putStoragePosition(
if (storageDevice.isInternal) INTERNAL_SELECT_POSITION
else EXTERNAL_SELECT_POSITION
)
}
if (validateZimFileCanCopyOrMove()) {
performCopyMoveOperation()
}
}
}

Expand All @@ -182,7 +184,9 @@ class CopyMoveFileHandler @Inject constructor(
private fun hasNotSufficientStorageSpace(availableSpace: Long): Boolean =
availableSpace < (selectedFile?.length() ?: 0L)

fun validateZimFileCanCopyOrMove(file: File = File(sharedPreferenceUtil.prefStorage)): Boolean {
suspend fun validateZimFileCanCopyOrMove(
file: File = File(sharedPreferenceUtil.prefStorage)
): Boolean {
hidePreparingCopyMoveDialog() // hide the dialog if already showing
val availableSpace = storageCalculator.availableBytes(file)
if (hasNotSufficientStorageSpace(availableSpace)) {
Expand Down Expand Up @@ -227,19 +231,23 @@ class CopyMoveFileHandler @Inject constructor(
fileSystemDisposable = fat32Checker.fileSystemStates
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
hidePreparingCopyMoveDialog()
if (validateZimFileCanCopyOrMove()) {
performCopyMoveOperation()
lifecycleScope?.launch {
hidePreparingCopyMoveDialog()
if (validateZimFileCanCopyOrMove()) {
performCopyMoveOperation()
}
}
}
}

fun performCopyMoveOperationIfSufficientSpaceAvailable() {
val availableSpace = storageCalculator.availableBytes(File(sharedPreferenceUtil.prefStorage))
if (hasNotSufficientStorageSpace(availableSpace)) {
fileCopyMoveCallback?.insufficientSpaceInStorage(availableSpace)
} else {
performCopyMoveOperation()
lifecycleScope?.launch {
val availableSpace = storageCalculator.availableBytes(File(sharedPreferenceUtil.prefStorage))
if (hasNotSufficientStorageSpace(availableSpace)) {
fileCopyMoveCallback?.insufficientSpaceInStorage(availableSpace)
} else {
performCopyMoveOperation()
}
}
}

Expand Down Expand Up @@ -475,7 +483,7 @@ class CopyMoveFileHandler @Inject constructor(
} ?: throw FileNotFoundException("The selected file could not be opened")
}

fun getDestinationFile(): File {
suspend fun getDestinationFile(): File {
val root = File(sharedPreferenceUtil.prefStorage)
val fileName = selectedFile?.name ?: ""

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ import org.kiwix.kiwixmobile.core.extensions.ActivityExtensions.isManageExternal
import org.kiwix.kiwixmobile.core.extensions.ActivityExtensions.navigate
import org.kiwix.kiwixmobile.core.extensions.ActivityExtensions.viewModel
import org.kiwix.kiwixmobile.core.extensions.coreMainActivity
import org.kiwix.kiwixmobile.core.extensions.isFileExist
import org.kiwix.kiwixmobile.core.extensions.setBottomMarginToFragmentContainerView
import org.kiwix.kiwixmobile.core.extensions.snack
import org.kiwix.kiwixmobile.core.extensions.toast
Expand Down Expand Up @@ -412,40 +413,42 @@ class LocalLibraryFragment : BaseFragment(), CopyMoveFileHandler.FileCopyMoveCal
}

fun handleSelectedFileUri(uri: Uri) {
if (sharedPreferenceUtil.isPlayStoreBuildWithAndroid11OrAbove()) {
val documentFile = when (uri.scheme) {
"file" -> DocumentFile.fromFile(File("$uri"))
else -> {
DocumentFile.fromSingleUri(requireActivity(), uri)
lifecycleScope.launch {
if (sharedPreferenceUtil.isPlayStoreBuildWithAndroid11OrAbove()) {
val documentFile = when (uri.scheme) {
"file" -> DocumentFile.fromFile(File("$uri"))
else -> {
DocumentFile.fromSingleUri(requireActivity(), uri)
}
}
// If the file is not valid, it shows an error message and stops further processing.
// If the file name is not found, then let them to copy the file
// and we will handle this later.
val fileName = documentFile?.name
if (fileName != null && !FileUtils.isValidZimFile(fileName)) {
activity.toast(string.error_file_invalid)
return@launch
}
copyMoveFileHandler?.showMoveFileToPublicDirectoryDialog(
uri,
documentFile,
// pass if fileName is null then we will validate it after copying/moving
fileName == null,
parentFragmentManager
)
} else {
getZimFileFromUri(uri)?.let(::navigateToReaderFragment)
}
// If the file is not valid, it shows an error message and stops further processing.
// If the file name is not found, then let them to copy the file
// and we will handle this later.
val fileName = documentFile?.name
if (fileName != null && !FileUtils.isValidZimFile(fileName)) {
activity.toast(string.error_file_invalid)
return
}
copyMoveFileHandler?.showMoveFileToPublicDirectoryDialog(
uri,
documentFile,
// pass if fileName is null then we will validate it after copying/moving
fileName == null,
parentFragmentManager
)
} else {
getZimFileFromUri(uri)?.let(::navigateToReaderFragment)
}
}

private fun getZimFileFromUri(
private suspend fun getZimFileFromUri(
uri: Uri
): File? {
val filePath = FileUtils.getLocalFilePathByUri(
requireActivity().applicationContext, uri
)
if (filePath == null || !File(filePath).exists()) {
if (filePath == null || !File(filePath).isFileExist()) {
activity.toast(string.error_file_not_found)
return null
}
Expand Down
Loading

0 comments on commit bbb0122

Please sign in to comment.