diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000000..12b24cf276 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,8 @@ +root = true + +[*.{kt,kts}] +ktlint_standard_no-wildcard-imports = disabled +ktlint_standard_property-naming = disabled +ktlint_standard_value-argument-comment = disabled +ktlint_standard_kdoc-wrapping = disabled +ktlint_standard_no-consecutive-comments = disabled diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 0000000000..65ceffd6ab --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,9 @@ +# Run this command to always ignore specific commits in `git blame` +# git config blame.ignoreRevsFile .git-blame-ignore-revs + +# format all java files +94dae8259f075e4099cd92c258386dc39bfc30c1 + +# format all kotlin files +45178b3d348cd1fe768bcfc086b04b15ea5d69ea + diff --git a/spotless.license-java b/amaze.license.spotless.txt similarity index 100% rename from spotless.license-java rename to amaze.license.spotless.txt diff --git a/app/build.gradle b/app/build.gradle index 0f54e63352..df549b8049 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -153,7 +153,8 @@ dependencies { testImplementation "io.mockk:mockk:$mockkVersion" testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:$kotlinxCoroutineTestVersion" testImplementation "androidx.arch.core:core-testing:$androidXArchCoreTestVersion" - kaptTest "com.google.auto.service:auto-service:1.0-rc4" + testImplementation 'ch.qos.logback:logback-classic:1.4.14' + kaptTest "com.google.auto.service:auto-service:1.1.1" androidTestImplementation "junit:junit:$junitVersion"//tests the app logic androidTestImplementation "androidx.test.espresso:espresso-core:$espressoVersion" diff --git a/app/src/androidTest/java/com/amaze/filemanager/asynchronous/services/ftp/FtpServiceEspressoTest.kt b/app/src/androidTest/java/com/amaze/filemanager/asynchronous/services/ftp/FtpServiceEspressoTest.kt index 3b7e4952c3..5083db921f 100644 --- a/app/src/androidTest/java/com/amaze/filemanager/asynchronous/services/ftp/FtpServiceEspressoTest.kt +++ b/app/src/androidTest/java/com/amaze/filemanager/asynchronous/services/ftp/FtpServiceEspressoTest.kt @@ -62,7 +62,6 @@ import java.util.concurrent.TimeUnit @Suppress("StringLiteralDuplication") @androidx.test.filters.Suppress class FtpServiceEspressoTest { - @get:Rule var serviceTestRule = ServiceTestRule() @@ -88,10 +87,11 @@ class FtpServiceEspressoTest { .remove(FtpService.KEY_PREFERENCE_USERNAME) .remove(FtpService.KEY_PREFERENCE_PASSWORD) .commit() - service = create( - Intent(FtpService.ACTION_START_FTPSERVER) - .putExtra(FtpService.TAG_STARTED_BY_TILE, false) - ) + service = + create( + Intent(FtpService.ACTION_START_FTPSERVER) + .putExtra(FtpService.TAG_STARTED_BY_TILE, false), + ) await().atMost(10, TimeUnit.SECONDS).until { FtpService.isRunning() && isServerReady() @@ -116,10 +116,11 @@ class FtpServiceEspressoTest { .remove(FtpService.KEY_PREFERENCE_USERNAME) .remove(FtpService.KEY_PREFERENCE_PASSWORD) .commit() - service = create( - Intent(FtpService.ACTION_START_FTPSERVER) - .putExtra(FtpService.TAG_STARTED_BY_TILE, false) - ) + service = + create( + Intent(FtpService.ACTION_START_FTPSERVER) + .putExtra(FtpService.TAG_STARTED_BY_TILE, false), + ) await().atMost(10, TimeUnit.SECONDS).until { FtpService.isRunning() && isServerReady() @@ -146,14 +147,15 @@ class FtpServiceEspressoTest { FtpService.KEY_PREFERENCE_PASSWORD, PasswordUtil.encryptPassword( ApplicationProvider.getApplicationContext(), - "passw0rD" - ) + "passw0rD", + ), ) .commit() - service = create( - Intent(FtpService.ACTION_START_FTPSERVER) - .putExtra(FtpService.TAG_STARTED_BY_TILE, false) - ) + service = + create( + Intent(FtpService.ACTION_START_FTPSERVER) + .putExtra(FtpService.TAG_STARTED_BY_TILE, false), + ) await().atMost(10, TimeUnit.SECONDS).until { FtpService.isRunning() && isServerReady() @@ -176,7 +178,7 @@ class FtpServiceEspressoTest { assertTrue( "No files found on device? It is also possible that app doesn't have " + "permission to access storage, which may occur on broken Android emulators", - files.isNotEmpty() + files.isNotEmpty(), ) var downloadFolderExists = false for (f in files) { @@ -187,7 +189,7 @@ class FtpServiceEspressoTest { assertTrue( "Download folder not found on device. Either storage is not available, " + "or something is really wrong with FtpService. Check logcat.", - downloadFolderExists + downloadFolderExists, ) } @@ -289,13 +291,14 @@ class FtpServiceEspressoTest { } private fun create(intent: Intent): FtpService { - val binder = serviceTestRule - .bindService( - intent.setClass( - ApplicationProvider.getApplicationContext(), - FtpService::class.java + val binder = + serviceTestRule + .bindService( + intent.setClass( + ApplicationProvider.getApplicationContext(), + FtpService::class.java, + ), ) - ) return ((binder as ObtainableServiceBinder).service as FtpService).also { it.onStartCommand(intent, 0, 0) } diff --git a/app/src/androidTest/java/com/amaze/filemanager/asynchronous/services/ftp/FtpServiceStaticMethodsTest.kt b/app/src/androidTest/java/com/amaze/filemanager/asynchronous/services/ftp/FtpServiceStaticMethodsTest.kt index afa89840a9..85fc91332a 100644 --- a/app/src/androidTest/java/com/amaze/filemanager/asynchronous/services/ftp/FtpServiceStaticMethodsTest.kt +++ b/app/src/androidTest/java/com/amaze/filemanager/asynchronous/services/ftp/FtpServiceStaticMethodsTest.kt @@ -42,7 +42,6 @@ import org.junit.runner.RunWith @SmallTest @RunWith(AndroidJUnit4::class) class FtpServiceStaticMethodsTest { - /** To test [FtpService.getLocalInetAddress] must not return an empty string. */ @Test fun testGetLocalInetAddressMustNotBeEmpty() { diff --git a/app/src/androidTest/java/com/amaze/filemanager/database/UtilsHandlerTest.java b/app/src/androidTest/java/com/amaze/filemanager/database/UtilsHandlerTest.java index 9bc78d9883..b089ec9460 100644 --- a/app/src/androidTest/java/com/amaze/filemanager/database/UtilsHandlerTest.java +++ b/app/src/androidTest/java/com/amaze/filemanager/database/UtilsHandlerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/androidTest/java/com/amaze/filemanager/filesystem/HybridFileParcelableTest.java b/app/src/androidTest/java/com/amaze/filemanager/filesystem/HybridFileParcelableTest.java index 4317c3a4c9..be1d8aef40 100644 --- a/app/src/androidTest/java/com/amaze/filemanager/filesystem/HybridFileParcelableTest.java +++ b/app/src/androidTest/java/com/amaze/filemanager/filesystem/HybridFileParcelableTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/androidTest/java/com/amaze/filemanager/filesystem/files/CryptUtilTest.java b/app/src/androidTest/java/com/amaze/filemanager/filesystem/files/CryptUtilTest.java index 12981e7081..7b7728b0e7 100644 --- a/app/src/androidTest/java/com/amaze/filemanager/filesystem/files/CryptUtilTest.java +++ b/app/src/androidTest/java/com/amaze/filemanager/filesystem/files/CryptUtilTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/androidTest/java/com/amaze/filemanager/filesystem/files/GenericCopyUtilEspressoTest.java b/app/src/androidTest/java/com/amaze/filemanager/filesystem/files/GenericCopyUtilEspressoTest.java index 3e854bb974..5ff4562d21 100644 --- a/app/src/androidTest/java/com/amaze/filemanager/filesystem/files/GenericCopyUtilEspressoTest.java +++ b/app/src/androidTest/java/com/amaze/filemanager/filesystem/files/GenericCopyUtilEspressoTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/androidTest/java/com/amaze/filemanager/ssh/SshClientUtilTest.java b/app/src/androidTest/java/com/amaze/filemanager/ssh/SshClientUtilTest.java index fd59e1d701..42774f9380 100644 --- a/app/src/androidTest/java/com/amaze/filemanager/ssh/SshClientUtilTest.java +++ b/app/src/androidTest/java/com/amaze/filemanager/ssh/SshClientUtilTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/androidTest/java/com/amaze/filemanager/test/DummyFileGenerator.java b/app/src/androidTest/java/com/amaze/filemanager/test/DummyFileGenerator.java index df1fb60601..43f65912e4 100644 --- a/app/src/androidTest/java/com/amaze/filemanager/test/DummyFileGenerator.java +++ b/app/src/androidTest/java/com/amaze/filemanager/test/DummyFileGenerator.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/androidTest/java/com/amaze/filemanager/test/StoragePermissionHelper.kt b/app/src/androidTest/java/com/amaze/filemanager/test/StoragePermissionHelper.kt index b491fc0fde..c71d892a0b 100644 --- a/app/src/androidTest/java/com/amaze/filemanager/test/StoragePermissionHelper.kt +++ b/app/src/androidTest/java/com/amaze/filemanager/test/StoragePermissionHelper.kt @@ -34,7 +34,6 @@ package com.amaze.filemanager.test // import org.junit.Assert.assertTrue object StoragePermissionHelper { - /** * This method is intended for Android R or above devices to obtain MANAGE_EXTERNAL_STORAGE * permission via UI Automator framework when running relevant Espresso tests. diff --git a/app/src/androidTest/java/com/amaze/filemanager/ui/activities/TextEditorActivityEspressoTest.java b/app/src/androidTest/java/com/amaze/filemanager/ui/activities/TextEditorActivityEspressoTest.java index 2629676aaf..e88eab8c01 100644 --- a/app/src/androidTest/java/com/amaze/filemanager/ui/activities/TextEditorActivityEspressoTest.java +++ b/app/src/androidTest/java/com/amaze/filemanager/ui/activities/TextEditorActivityEspressoTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/androidTest/java/com/amaze/filemanager/ui/fragments/BackupPrefsFragmentTest.kt b/app/src/androidTest/java/com/amaze/filemanager/ui/fragments/BackupPrefsFragmentTest.kt index a11ebb0fad..533bbb97d9 100644 --- a/app/src/androidTest/java/com/amaze/filemanager/ui/fragments/BackupPrefsFragmentTest.kt +++ b/app/src/androidTest/java/com/amaze/filemanager/ui/fragments/BackupPrefsFragmentTest.kt @@ -46,7 +46,6 @@ import java.io.File @RunWith(AndroidJUnit4::class) class BackupPrefsFragmentTest { - var storagePath = "/storage/emulated/0" var fileName = "amaze_backup.json" @@ -63,7 +62,7 @@ class BackupPrefsFragmentTest { File( storagePath + File.separator + - fileName + fileName, ) exportFile.delete() // delete if already exists @@ -80,7 +79,7 @@ class BackupPrefsFragmentTest { File( ApplicationProvider.getApplicationContext().cacheDir.absolutePath + File.separator + - fileName + fileName, ) Assert.assertTrue(tempFile.exists()) @@ -108,7 +107,7 @@ class BackupPrefsFragmentTest { File( storagePath + File.separator + - fileName + fileName, ) activityScenario.onActivity { preferencesActivity -> @@ -116,26 +115,29 @@ class BackupPrefsFragmentTest { .add(backupPrefsFragment, null) .commitNow() - val preferences = PreferenceManager - .getDefaultSharedPreferences(preferencesActivity) + val preferences = + PreferenceManager + .getDefaultSharedPreferences(preferencesActivity) val preferenceMap: Map = preferences.all - val inputString = file - .inputStream() - .bufferedReader() - .use { - it.readText() - } + val inputString = + file + .inputStream() + .bufferedReader() + .use { + it.readText() + } val type = object : TypeToken>() {}.type - val importMap: Map = GsonBuilder() - .create() - .fromJson( - inputString, - type - ) + val importMap: Map = + GsonBuilder() + .create() + .fromJson( + inputString, + type, + ) for ((key, value) in preferenceMap) { var mapValue = importMap[key] @@ -162,7 +164,7 @@ class BackupPrefsFragmentTest { File( storagePath + File.separator + - fileName + fileName, ) exportFile.delete() // delete if already exists @@ -178,28 +180,31 @@ class BackupPrefsFragmentTest { BackupPrefsFragment.IMPORT_BACKUP_FILE, Activity.RESULT_OK, Intent().setData( - Uri.fromFile(exportFile) - ) + Uri.fromFile(exportFile), + ), ) - val inputString = exportFile - .inputStream() - .bufferedReader() - .use { - it.readText() - } + val inputString = + exportFile + .inputStream() + .bufferedReader() + .use { + it.readText() + } val type = object : TypeToken>() {}.type - val importMap: Map = GsonBuilder() - .create() - .fromJson( - inputString, - type - ) + val importMap: Map = + GsonBuilder() + .create() + .fromJson( + inputString, + type, + ) - val preferences = PreferenceManager - .getDefaultSharedPreferences(preferencesActivity) + val preferences = + PreferenceManager + .getDefaultSharedPreferences(preferencesActivity) val preferenceMap: Map = preferences.all @@ -213,13 +218,14 @@ class BackupPrefsFragmentTest { preferences: SharedPreferences, importMap: Map, key: String?, - value: Any? + value: Any?, ): Boolean { when (value!!::class.simpleName) { "Boolean" -> return importMap[key] as Boolean == preferences.getBoolean(key, false) - "Float" -> importMap[key] as Float == - preferences.getFloat(key, 0f) + "Float" -> + importMap[key] as Float == + preferences.getFloat(key, 0f) "Int" -> { // since Gson parses Integer as Double val toInt = (importMap[key] as Double).toInt() diff --git a/app/src/androidTest/java/com/amaze/filemanager/utils/CryptUtilEspressoTest.kt b/app/src/androidTest/java/com/amaze/filemanager/utils/CryptUtilEspressoTest.kt index ef67fbb2d9..77ce218f96 100644 --- a/app/src/androidTest/java/com/amaze/filemanager/utils/CryptUtilEspressoTest.kt +++ b/app/src/androidTest/java/com/amaze/filemanager/utils/CryptUtilEspressoTest.kt @@ -47,10 +47,10 @@ import kotlin.random.Random @RunWith(AndroidJUnit4::class) @Suppress("StringLiteralDuplication") class CryptUtilEspressoTest { - @Rule @JvmField - val storagePermissionRule: GrantPermissionRule = GrantPermissionRule - .grant(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) + val storagePermissionRule: GrantPermissionRule = + GrantPermissionRule + .grant(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) /** * Sanity test of CryptUtil legacy method, to ensure refactoring won't break @@ -68,23 +68,24 @@ class CryptUtilEspressoTest { ArrayList(), "test.bin${CryptUtil.CRYPT_EXTENSION}", false, - null - ) - val targetFile = File( - Environment.getExternalStorageDirectory(), - "test.bin${CryptUtil.CRYPT_EXTENSION}" + null, ) + val targetFile = + File( + Environment.getExternalStorageDirectory(), + "test.bin${CryptUtil.CRYPT_EXTENSION}", + ) assertTrue(targetFile.exists()) if (SDK_INT < JELLY_BEAN_MR2) { // Quirks for SDK < 18. File is not encrypted at all. assertTrue( "Source and target file size should be the same = ${source.size}", - source.size.toLong() == targetFile.length() + source.size.toLong() == targetFile.length(), ) } else { assertTrue( "Source size = ${source.size} target file size = ${targetFile.length()}", - targetFile.length() > source.size + targetFile.length() > source.size, ) } sourceFile.delete() @@ -96,7 +97,7 @@ class CryptUtilEspressoTest { Environment.getExternalStorageDirectory().absolutePath, ProgressHandler(), ArrayList(), - null + null, ) File(Environment.getExternalStorageDirectory(), "test.bin").run { assertTrue(this.exists()) @@ -119,16 +120,17 @@ class CryptUtilEspressoTest { ArrayList(), "test.bin${CryptUtil.AESCRYPT_EXTENSION}", true, - "12345678" - ) - val targetFile = File( - Environment.getExternalStorageDirectory(), - "test.bin${CryptUtil.AESCRYPT_EXTENSION}" + "12345678", ) + val targetFile = + File( + Environment.getExternalStorageDirectory(), + "test.bin${CryptUtil.AESCRYPT_EXTENSION}", + ) assertTrue(targetFile.exists()) assertTrue( "Source size = ${source.size} target file size = ${targetFile.length()}", - targetFile.length() > source.size + targetFile.length() > source.size, ) sourceFile.delete() CryptUtil( @@ -139,7 +141,7 @@ class CryptUtilEspressoTest { Environment.getExternalStorageDirectory().absolutePath, ProgressHandler(), ArrayList(), - "12345678" + "12345678", ) File(Environment.getExternalStorageDirectory(), "test.bin").run { assertTrue(this.exists()) diff --git a/app/src/androidTest/java/com/amaze/filemanager/utils/security/SecretKeygenEspressoTest.kt b/app/src/androidTest/java/com/amaze/filemanager/utils/security/SecretKeygenEspressoTest.kt index d91054183d..507bd8f8a6 100644 --- a/app/src/androidTest/java/com/amaze/filemanager/utils/security/SecretKeygenEspressoTest.kt +++ b/app/src/androidTest/java/com/amaze/filemanager/utils/security/SecretKeygenEspressoTest.kt @@ -37,7 +37,6 @@ import org.junit.runner.RunWith @SmallTest @RunWith(AndroidJUnit4::class) class SecretKeygenEspressoTest { - /** * Test [SecretKeygen.getSecretKey]. * diff --git a/app/src/fdroid/java/com/amaze/filemanager/asynchronous/asynctasks/CloudLoaderAsyncTask.java b/app/src/fdroid/java/com/amaze/filemanager/asynchronous/asynctasks/CloudLoaderAsyncTask.java index cbf5856349..e176ef4f38 100644 --- a/app/src/fdroid/java/com/amaze/filemanager/asynchronous/asynctasks/CloudLoaderAsyncTask.java +++ b/app/src/fdroid/java/com/amaze/filemanager/asynchronous/asynctasks/CloudLoaderAsyncTask.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2022 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/fdroid/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/RarExtractor.kt b/app/src/fdroid/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/RarExtractor.kt index 8039ef72e7..c01fa18f5d 100644 --- a/app/src/fdroid/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/RarExtractor.kt +++ b/app/src/fdroid/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/RarExtractor.kt @@ -29,7 +29,7 @@ class RarExtractor( filePath: String, outputPath: String, listener: OnUpdate, - updatePosition: UpdatePosition + updatePosition: UpdatePosition, ) : Extractor(context, filePath, outputPath, listener, updatePosition) { override fun extractWithFilter(filter: Filter) { // no-op diff --git a/app/src/fdroid/java/com/amaze/filemanager/filesystem/compressed/showcontents/helpers/RarDecompressor.kt b/app/src/fdroid/java/com/amaze/filemanager/filesystem/compressed/showcontents/helpers/RarDecompressor.kt index aceb23e1e6..e28f96590c 100644 --- a/app/src/fdroid/java/com/amaze/filemanager/filesystem/compressed/showcontents/helpers/RarDecompressor.kt +++ b/app/src/fdroid/java/com/amaze/filemanager/filesystem/compressed/showcontents/helpers/RarDecompressor.kt @@ -27,9 +27,8 @@ import com.amaze.filemanager.filesystem.compressed.showcontents.Decompressor class RarDecompressor(context: Context) : Decompressor(context) { override fun changePath( path: String, - addGoBackItem: Boolean - ) = - UnknownCompressedFileHelperCallable(filePath, addGoBackItem) + addGoBackItem: Boolean, + ) = UnknownCompressedFileHelperCallable(filePath, addGoBackItem) override fun realRelativeDirectory(dir: String): String { return "" diff --git a/app/src/fdroid/java/com/amaze/filemanager/utils/Billing.java b/app/src/fdroid/java/com/amaze/filemanager/utils/Billing.java index 69cb70d3aa..0093eefaa5 100644 --- a/app/src/fdroid/java/com/amaze/filemanager/utils/Billing.java +++ b/app/src/fdroid/java/com/amaze/filemanager/utils/Billing.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/fdroid/java/com/amaze/filemanager/utils/PackageInstallValidation.kt b/app/src/fdroid/java/com/amaze/filemanager/utils/PackageInstallValidation.kt index 838de95915..a45e25f512 100644 --- a/app/src/fdroid/java/com/amaze/filemanager/utils/PackageInstallValidation.kt +++ b/app/src/fdroid/java/com/amaze/filemanager/utils/PackageInstallValidation.kt @@ -26,7 +26,6 @@ import java.io.File * For non Google Play variant, this class does nothing. Just a stub. */ object PackageInstallValidation { - /** * Do nothing. */ diff --git a/app/src/fdroid/java/com/cloudrail/si/CloudRail.java b/app/src/fdroid/java/com/cloudrail/si/CloudRail.java index 1879a5510d..4deb9185e8 100644 --- a/app/src/fdroid/java/com/cloudrail/si/CloudRail.java +++ b/app/src/fdroid/java/com/cloudrail/si/CloudRail.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2022 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/fdroid/java/com/cloudrail/si/interfaces/CloudStorage.java b/app/src/fdroid/java/com/cloudrail/si/interfaces/CloudStorage.java index 2bd7b26e3e..853aacb113 100644 --- a/app/src/fdroid/java/com/cloudrail/si/interfaces/CloudStorage.java +++ b/app/src/fdroid/java/com/cloudrail/si/interfaces/CloudStorage.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2022 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/fdroid/java/com/cloudrail/si/services/Box.java b/app/src/fdroid/java/com/cloudrail/si/services/Box.java index 2b1fa0bc59..e1031449f8 100644 --- a/app/src/fdroid/java/com/cloudrail/si/services/Box.java +++ b/app/src/fdroid/java/com/cloudrail/si/services/Box.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2022 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/fdroid/java/com/cloudrail/si/services/Dropbox.java b/app/src/fdroid/java/com/cloudrail/si/services/Dropbox.java index 0da7ca0ce0..76d55c771e 100644 --- a/app/src/fdroid/java/com/cloudrail/si/services/Dropbox.java +++ b/app/src/fdroid/java/com/cloudrail/si/services/Dropbox.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2022 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/fdroid/java/com/cloudrail/si/services/GoogleDrive.java b/app/src/fdroid/java/com/cloudrail/si/services/GoogleDrive.java index 8796f1168f..2af786722c 100644 --- a/app/src/fdroid/java/com/cloudrail/si/services/GoogleDrive.java +++ b/app/src/fdroid/java/com/cloudrail/si/services/GoogleDrive.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2022 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/fdroid/java/com/cloudrail/si/services/OneDrive.java b/app/src/fdroid/java/com/cloudrail/si/services/OneDrive.java index 88275cecae..b94d8e8069 100644 --- a/app/src/fdroid/java/com/cloudrail/si/services/OneDrive.java +++ b/app/src/fdroid/java/com/cloudrail/si/services/OneDrive.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2022 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/fdroid/java/com/cloudrail/si/types/CloudMetaData.java b/app/src/fdroid/java/com/cloudrail/si/types/CloudMetaData.java index e6b5f6580f..4fa5b4e799 100644 --- a/app/src/fdroid/java/com/cloudrail/si/types/CloudMetaData.java +++ b/app/src/fdroid/java/com/cloudrail/si/types/CloudMetaData.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2022 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/fdroid/java/com/cloudrail/si/types/SpaceAllocation.java b/app/src/fdroid/java/com/cloudrail/si/types/SpaceAllocation.java index 798d9e25b7..54e3b78c68 100644 --- a/app/src/fdroid/java/com/cloudrail/si/types/SpaceAllocation.java +++ b/app/src/fdroid/java/com/cloudrail/si/types/SpaceAllocation.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2022 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/fdroid/java/com/github/junrar/exception/UnsupportedRarV5Exception.java b/app/src/fdroid/java/com/github/junrar/exception/UnsupportedRarV5Exception.java index 614c7e8a88..4ed70a93de 100644 --- a/app/src/fdroid/java/com/github/junrar/exception/UnsupportedRarV5Exception.java +++ b/app/src/fdroid/java/com/github/junrar/exception/UnsupportedRarV5Exception.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2022 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/AmazeFileManagerModule.java b/app/src/main/java/com/amaze/filemanager/AmazeFileManagerModule.java index 33baafd160..1250db15f1 100644 --- a/app/src/main/java/com/amaze/filemanager/AmazeFileManagerModule.java +++ b/app/src/main/java/com/amaze/filemanager/AmazeFileManagerModule.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/LogHelper.java b/app/src/main/java/com/amaze/filemanager/LogHelper.java index 786a399288..38df523ce8 100644 --- a/app/src/main/java/com/amaze/filemanager/LogHelper.java +++ b/app/src/main/java/com/amaze/filemanager/LogHelper.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/TagsHelper.java b/app/src/main/java/com/amaze/filemanager/TagsHelper.java index ce31071bdb..30d9b9e1d8 100644 --- a/app/src/main/java/com/amaze/filemanager/TagsHelper.java +++ b/app/src/main/java/com/amaze/filemanager/TagsHelper.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/adapters/AppsRecyclerAdapter.kt b/app/src/main/java/com/amaze/filemanager/adapters/AppsRecyclerAdapter.kt index 7fd03d57de..d3bf5ae753 100644 --- a/app/src/main/java/com/amaze/filemanager/adapters/AppsRecyclerAdapter.kt +++ b/app/src/main/java/com/amaze/filemanager/adapters/AppsRecyclerAdapter.kt @@ -75,9 +75,8 @@ class AppsRecyclerAdapter( private val modelProvider: AppsAdapterPreloadModel, private val isBottomSheet: Boolean, private val adjustListViewCallback: AdjustListViewForTv, - private val appDataParcelableList: MutableList + private val appDataParcelableList: MutableList, ) : RecyclerView.Adapter() { - private val myChecked = SparseBooleanArray() private var appDataListItem: MutableList = mutableListOf() set(value) { @@ -107,8 +106,9 @@ class AppsRecyclerAdapter( appDataListItem = mutableListOf() } - private val mInflater: LayoutInflater get() = fragment.requireActivity() - .getSystemService(Activity.LAYOUT_INFLATER_SERVICE) as LayoutInflater + private val mInflater: LayoutInflater get() = + fragment.requireActivity() + .getSystemService(Activity.LAYOUT_INFLATER_SERVICE) as LayoutInflater companion object { const val TYPE_ITEM = 0 @@ -117,7 +117,10 @@ class AppsRecyclerAdapter( const val EMPTY_LAST_ITEM = 3 } - override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { + override fun onCreateViewHolder( + parent: ViewGroup, + viewType: Int, + ): RecyclerView.ViewHolder { var view = View(fragment.requireContext()) when (viewType) { TYPE_ITEM -> { @@ -134,7 +137,7 @@ class AppsRecyclerAdapter( SpecialViewHolder.HEADER_SYSTEM_APP } else { SpecialViewHolder.HEADER_USER_APP - } + }, ) } EMPTY_LAST_ITEM -> { @@ -143,7 +146,7 @@ class AppsRecyclerAdapter( fragment.requireActivity().resources.getDimension(R.dimen.fab_height) + fragment.requireContext().resources .getDimension(R.dimen.fab_margin) - ).roundToInt() + ).roundToInt() return EmptyViewHolder(view) } else -> { @@ -156,7 +159,10 @@ class AppsRecyclerAdapter( return appDataListItem[position].listItemType } - override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { + override fun onBindViewHolder( + holder: RecyclerView.ViewHolder, + position: Int, + ) { if (holder is AppHolder) { appDataListItem[position].appDataParcelable?.let { rowItem -> if (isBottomSheet) { @@ -171,7 +177,7 @@ class AppsRecyclerAdapter( if (holder.about != null && !isBottomSheet) { if ((fragment.requireActivity() as MainActivity).appTheme == AppTheme.LIGHT) { holder.about.setColorFilter( - Color.parseColor("#ff666666") + Color.parseColor("#ff666666"), ) } showPopup(holder.about, rowItem) @@ -179,27 +185,24 @@ class AppsRecyclerAdapter( holder.rl.setOnFocusChangeListener { _, _ -> adjustListViewCallback.adjustListViewForTv( holder, - fragment.requireActivity() as MainActivity + fragment.requireActivity() as MainActivity, ) } holder.txtTitle.text = rowItem.label - holder.packageName.text = rowItem.packageName holder.packageName.isSelected = true // for marquee - val enableMarqueeFilename = (fragment.requireActivity() as MainActivity) .getBoolean(PreferencesConstants.PREFERENCE_ENABLE_MARQUEE_FILENAME) if (enableMarqueeFilename) { - holder.txtTitle.ellipsize = if (enableMarqueeFilename) { - TextUtils.TruncateAt.MARQUEE - } else { - TextUtils.TruncateAt.MIDDLE - } + holder.txtTitle.ellipsize = + if (enableMarqueeFilename) { + TextUtils.TruncateAt.MARQUEE + } else { + TextUtils.TruncateAt.MIDDLE + } marqueeAfterDelay(2000, holder.txtTitle) } - - // File f = new File(rowItem.getDesc()); if (!isBottomSheet) { holder.txtDesc.text = rowItem.fileSize + " |" } @@ -211,7 +214,7 @@ class AppsRecyclerAdapter( } if (myChecked[position]) { holder.rl.setBackgroundColor( - Utils.getColor(fragment.context, R.color.appsadapter_background) + Utils.getColor(fragment.context, R.color.appsadapter_background), ) } else { if ((fragment.requireActivity() as MainActivity).appTheme == AppTheme.LIGHT) { @@ -231,7 +234,10 @@ class AppsRecyclerAdapter( * Set list elements * @param showSystemApps whether to filter system apps or not */ - fun setData(data: List, showSystemApps: Boolean) { + fun setData( + data: List, + showSystemApps: Boolean, + ) { appDataParcelableList.run { clear() val list = if (!showSystemApps) data.filter { !it.isSystemApp } else data @@ -249,35 +255,37 @@ class AppsRecyclerAdapter( safeLet( openFileParcelable.uri, openFileParcelable.mimeType, - openFileParcelable.useNewStack + openFileParcelable.useNewStack, ) { uri, mimeType, useNewStack -> - val intent = buildIntent( - fragment.requireContext(), - uri, - mimeType, - useNewStack, - openFileParcelable.className, - openFileParcelable.packageName - ) + val intent = + buildIntent( + fragment.requireContext(), + uri, + mimeType, + useNewStack, + openFileParcelable.className, + openFileParcelable.packageName, + ) setLastOpenedApp( rowItem, - fragment.requireActivity() as PreferenceActivity + fragment.requireActivity() as PreferenceActivity, ) fragment.requireContext().startActivityCatchingSecurityException(intent) } } } else { - val i1 = fragment.requireContext().packageManager.getLaunchIntentForPackage( - rowItem.packageName - ) + val i1 = + fragment.requireContext().packageManager.getLaunchIntentForPackage( + rowItem.packageName, + ) if (i1 != null) { fragment.startActivity(i1) } else { Toast.makeText( fragment.context, fragment.getString(R.string.not_allowed), - Toast.LENGTH_LONG + Toast.LENGTH_LONG, ) .show() // TODO: Implement this method @@ -286,20 +294,20 @@ class AppsRecyclerAdapter( } } - private fun showPopup(v: View, rowItem: AppDataParcelable?) { + private fun showPopup( + v: View, + rowItem: AppDataParcelable?, + ) { v.setOnClickListener { view: View? -> var context = fragment.context if (( - fragment.requireActivity() - as MainActivity + fragment.requireActivity() + as MainActivity ).appTheme == AppTheme.BLACK ) { context = ContextThemeWrapper(context, R.style.overflow_black) } - val popupMenu = PopupMenu( - context, - view - ) + val popupMenu = PopupMenu(context, view) popupMenu.setOnMenuItemClickListener { item: MenuItem -> val themedActivity: MainActivity = fragment.requireActivity() as MainActivity val colorAccent = themedActivity.accent @@ -333,12 +341,9 @@ class AppsRecyclerAdapter( Intent( Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse( - String.format( - "package:%s", - rowItem!!.packageName - ) - ) - ) + String.format("package:%s", rowItem!!.packageName), + ), + ), ) return@setOnMenuItemClickListener true } @@ -357,21 +362,26 @@ class AppsRecyclerAdapter( } private fun popupOpen(appDataParcelable: AppDataParcelable) { - val i1 = fragment - .context - ?.packageManager - ?.getLaunchIntentForPackage(appDataParcelable.packageName) - if (i1 != null) fragment.startActivity(i1) else Toast.makeText( - fragment.context, - fragment.getString(R.string.not_allowed), - Toast.LENGTH_LONG - ).show() + val i1 = + fragment + .context + ?.packageManager + ?.getLaunchIntentForPackage(appDataParcelable.packageName) + if (i1 != null) { + fragment.startActivity(i1) + } else { + Toast.makeText( + fragment.context, + fragment.getString(R.string.not_allowed), + Toast.LENGTH_LONG, + ).show() + } } private fun popupShare( appDataParcelable: AppDataParcelable, themedActivity: ThemedActivity, - colorAccent: Int + colorAccent: Int, ) { val arrayList2 = ArrayList() @@ -381,21 +391,21 @@ class AppsRecyclerAdapter( arrayList2, fragment.activity, themedActivity.utilsProvider.appTheme, - colorAccent + colorAccent, ) } private fun popupUninstall( appDataParcelable: AppDataParcelable, themedActivity: ThemedActivity, - colorAccent: Int + colorAccent: Int, ) { val f1 = HybridFileParcelable(appDataParcelable.path) f1.mode = OpenMode.ROOT if (appDataParcelable.isSystemApp) { // system package if ((fragment.requireActivity() as MainActivity).getBoolean( - PreferencesConstants.PREFERENCE_ROOTMODE + PreferencesConstants.PREFERENCE_ROOTMODE, ) ) { showDeleteSystemAppDialog(themedActivity, colorAccent, f1) @@ -403,14 +413,14 @@ class AppsRecyclerAdapter( Toast.makeText( fragment.context, fragment.getString(R.string.enablerootmde), - Toast.LENGTH_SHORT + Toast.LENGTH_SHORT, ) .show() } } else { FileUtils.uninstallPackage( appDataParcelable.packageName, - fragment.context + fragment.context, ) } } @@ -419,20 +429,22 @@ class AppsRecyclerAdapter( val intent1 = Intent(Intent.ACTION_VIEW) try { - intent1.data = Uri.parse( - String.format( - "market://details?id=%s", - appDataParcelable.packageName + intent1.data = + Uri.parse( + String.format( + "market://details?id=%s", + appDataParcelable.packageName, + ), ) - ) fragment.startActivity(intent1) } catch (ifPlayStoreNotInstalled: ActivityNotFoundException) { - intent1.data = Uri.parse( - String.format( - "https://play.google.com/store/apps/details?id=%s", - appDataParcelable.packageName + intent1.data = + Uri.parse( + String.format( + "https://play.google.com/store/apps/details?id=%s", + appDataParcelable.packageName, + ), ) - ) fragment.startActivity(intent1) } } @@ -440,15 +452,17 @@ class AppsRecyclerAdapter( private fun popupBackup(appDataParcelable: AppDataParcelable) { val baseApkFile = File(appDataParcelable.path) val filesToCopyList = ArrayList() - val dst = File( - Environment.getExternalStorageDirectory() - .path + "/app_backup" - ) + val dst = + File( + Environment.getExternalStorageDirectory() + .path + "/app_backup", + ) if (!dst.exists() || !dst.isDirectory) dst.mkdirs() - val intent = Intent( - fragment.context, - CopyService::class.java - ) + val intent = + Intent( + fragment.context, + CopyService::class.java, + ) val mainApkFile = RootHelper.generateBaseFile(baseApkFile, true) val startIndex = appDataParcelable.packageName.indexOf("_") val subString = appDataParcelable.packageName.substring(startIndex + 1) @@ -478,7 +492,7 @@ class AppsRecyclerAdapter( Toast.makeText( fragment.context, fragment.getString(R.string.copyingapks, filesToCopyList.size, dst.path), - Toast.LENGTH_LONG + Toast.LENGTH_LONG, ) .show() @@ -488,13 +502,13 @@ class AppsRecyclerAdapter( private fun showDeleteSystemAppDialog( themedActivity: ThemedActivity, colorAccent: Int, - f1: HybridFileParcelable + f1: HybridFileParcelable, ) { val builder1 = MaterialDialog.Builder(fragment.requireContext()) builder1 .theme( - themedActivity.appTheme.getMaterialDialogTheme() + themedActivity.appTheme.getMaterialDialogTheme(), ) .content(fragment.getString(R.string.unin_system_apk)) .title(fragment.getString(R.string.warning)) @@ -512,12 +526,14 @@ class AppsRecyclerAdapter( if (parent != "app" && parent != "priv-app") { val baseFile = HybridFileParcelable( - f1.getParent(fragment.context) + f1.getParent(fragment.context), ) baseFile.mode = OpenMode.ROOT files.add(baseFile) - } else files.add(f1) + } else { + files.add(f1) + } } else { files.add(f1) } @@ -532,13 +548,13 @@ class AppsRecyclerAdapter( TYPE_ITEM, TYPE_HEADER_SYSTEM, TYPE_HEADER_THIRD_PARTY, - EMPTY_LAST_ITEM + EMPTY_LAST_ITEM, ) annotation class ListItemType data class ListItem( var appDataParcelable: AppDataParcelable?, - var listItemType: @ListItemType Int = TYPE_ITEM + var listItemType: @ListItemType Int = TYPE_ITEM, ) { constructor(listItemType: @ListItemType Int) : this(null, listItemType) } diff --git a/app/src/main/java/com/amaze/filemanager/adapters/ColorAdapter.java b/app/src/main/java/com/amaze/filemanager/adapters/ColorAdapter.java index ac194e5372..0c8c67fff1 100644 --- a/app/src/main/java/com/amaze/filemanager/adapters/ColorAdapter.java +++ b/app/src/main/java/com/amaze/filemanager/adapters/ColorAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/adapters/CompressedExplorerAdapter.java b/app/src/main/java/com/amaze/filemanager/adapters/CompressedExplorerAdapter.java index 73b6e2bb07..01e68b2311 100644 --- a/app/src/main/java/com/amaze/filemanager/adapters/CompressedExplorerAdapter.java +++ b/app/src/main/java/com/amaze/filemanager/adapters/CompressedExplorerAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/adapters/HiddenAdapter.kt b/app/src/main/java/com/amaze/filemanager/adapters/HiddenAdapter.kt index 468059a5fd..e718b6f186 100644 --- a/app/src/main/java/com/amaze/filemanager/adapters/HiddenAdapter.kt +++ b/app/src/main/java/com/amaze/filemanager/adapters/HiddenAdapter.kt @@ -53,22 +53,27 @@ class HiddenAdapter( private val sharedPrefs: SharedPreferences, hiddenFiles: List, var materialDialog: MaterialDialog?, - private val hide: Boolean + private val hide: Boolean, ) : RecyclerView.Adapter() { - companion object { private const val TAG = "HiddenAdapter" } private val hiddenFiles = hiddenFiles.toMutableList() - override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HiddenViewHolder { + override fun onCreateViewHolder( + parent: ViewGroup, + viewType: Int, + ): HiddenViewHolder { val mInflater = context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE) as LayoutInflater val view = mInflater.inflate(R.layout.bookmarkrow, parent, false) return HiddenViewHolder(view) } - override fun onBindViewHolder(holder: HiddenViewHolder, position: Int) { + override fun onBindViewHolder( + holder: HiddenViewHolder, + position: Int, + ) { val file = hiddenFiles[position] holder.textTitle.text = file.getName(context) holder.textDescription.text = file.getReadablePath(file.path) @@ -80,9 +85,10 @@ class HiddenAdapter( // TODO: the "hide files" feature just hide files from view in Amaze and not create // .nomedia if (!file.isSmb && file.isDirectory(context)) { - val nomediaFile = HybridFileParcelable( - hiddenFiles[position].path + "/" + FileUtils.NOMEDIA_FILE - ) + val nomediaFile = + HybridFileParcelable( + hiddenFiles[position].path + "/" + FileUtils.NOMEDIA_FILE, + ) nomediaFile.mode = OpenMode.FILE val filesToDelete = ArrayList() filesToDelete.add(nomediaFile) @@ -105,7 +111,7 @@ class HiddenAdapter( file.path, false, OpenMode.UNKNOWN, - false + false, ) } } else if (!file.isSmb) { @@ -113,7 +119,7 @@ class HiddenAdapter( FileUtils.openFile( File(file.path), (fragmentActivity as MainActivity), - sharedPrefs + sharedPrefs, ) } } diff --git a/app/src/main/java/com/amaze/filemanager/adapters/RecyclerAdapter.java b/app/src/main/java/com/amaze/filemanager/adapters/RecyclerAdapter.java index e860332277..e6e83608ee 100644 --- a/app/src/main/java/com/amaze/filemanager/adapters/RecyclerAdapter.java +++ b/app/src/main/java/com/amaze/filemanager/adapters/RecyclerAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/adapters/SearchRecyclerViewAdapter.kt b/app/src/main/java/com/amaze/filemanager/adapters/SearchRecyclerViewAdapter.kt index 7859f68a06..5c6afc3259 100644 --- a/app/src/main/java/com/amaze/filemanager/adapters/SearchRecyclerViewAdapter.kt +++ b/app/src/main/java/com/amaze/filemanager/adapters/SearchRecyclerViewAdapter.kt @@ -41,11 +41,10 @@ import java.util.Random class SearchRecyclerViewAdapter : ListAdapter( - object : DiffUtil.ItemCallback() { override fun areItemsTheSame( oldItem: SearchResult, - newItem: SearchResult + newItem: SearchResult, ): Boolean { return oldItem.file.path == newItem.file.path && oldItem.file.name == newItem.file.name @@ -53,21 +52,28 @@ class SearchRecyclerViewAdapter : override fun areContentsTheSame( oldItem: SearchResult, - newItem: SearchResult + newItem: SearchResult, ): Boolean { return oldItem.file.path == newItem.file.path && oldItem.file.name == newItem.file.name && oldItem.matchRange == newItem.matchRange } - } + }, ) { - override fun onCreateViewHolder(parent: ViewGroup, type: Int): ViewHolder { - val v: View = LayoutInflater.from(parent.context) - .inflate(R.layout.search_row_item, parent, false) + override fun onCreateViewHolder( + parent: ViewGroup, + type: Int, + ): ViewHolder { + val v: View = + LayoutInflater.from(parent.context) + .inflate(R.layout.search_row_item, parent, false) return ViewHolder(v) } - override fun onBindViewHolder(holder: SearchRecyclerViewAdapter.ViewHolder, position: Int) { + override fun onBindViewHolder( + holder: SearchRecyclerViewAdapter.ViewHolder, + position: Int, + ) { val (file, matchResult) = getItem(position) val colorPreference = @@ -78,7 +84,7 @@ class SearchRecyclerViewAdapter : ForegroundColorSpan(colorPreference.accent), matchResult.first, matchResult.last + 1, - Spannable.SPAN_EXCLUSIVE_EXCLUSIVE + Spannable.SPAN_EXCLUSIVE_EXCLUSIVE, ) holder.fileNameTV.text = fileName @@ -94,7 +100,6 @@ class SearchRecyclerViewAdapter : } inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { - val fileNameTV: AppCompatTextView val filePathTV: AppCompatTextView val colorView: View @@ -112,7 +117,7 @@ class SearchRecyclerViewAdapter : if (!file.isDirectory) { file.openFile( AppConfig.getInstance().mainActivityContext as MainActivity?, - false + false, ) } else { (AppConfig.getInstance().mainActivityContext as MainActivity?) @@ -130,9 +135,9 @@ class SearchRecyclerViewAdapter : context, ColorPreference.availableColors[ Random().nextInt( - ColorPreference.availableColors.size - 1 - ) - ] + ColorPreference.availableColors.size - 1, + ), + ], ) } } diff --git a/app/src/main/java/com/amaze/filemanager/adapters/data/AppDataParcelable.kt b/app/src/main/java/com/amaze/filemanager/adapters/data/AppDataParcelable.kt index 7f90bc8cbf..2ea826fa2d 100644 --- a/app/src/main/java/com/amaze/filemanager/adapters/data/AppDataParcelable.kt +++ b/app/src/main/java/com/amaze/filemanager/adapters/data/AppDataParcelable.kt @@ -35,5 +35,5 @@ class AppDataParcelable( var size: Long, var lastModification: Long, var isSystemApp: Boolean, - var openFileParcelable: OpenFileParcelable? + var openFileParcelable: OpenFileParcelable?, ) : Parcelable diff --git a/app/src/main/java/com/amaze/filemanager/adapters/data/AppDataSorter.kt b/app/src/main/java/com/amaze/filemanager/adapters/data/AppDataSorter.kt index 42e26b32a7..2b8ea318aa 100644 --- a/app/src/main/java/com/amaze/filemanager/adapters/data/AppDataSorter.kt +++ b/app/src/main/java/com/amaze/filemanager/adapters/data/AppDataSorter.kt @@ -31,7 +31,10 @@ class AppDataSorter(var sort: Int, isAscending: Boolean) : * Compares two elements and return negative, zero and positive integer if first argument is * less than, equal to or greater than second */ - override fun compare(file1: AppDataParcelable?, file2: AppDataParcelable?): Int { + override fun compare( + file1: AppDataParcelable?, + file2: AppDataParcelable?, + ): Int { safeLet(file1, file2) { f1, f2 -> if (f1.isSystemApp != f2.isSystemApp) { @@ -45,8 +48,9 @@ class AppDataSorter(var sort: Int, isAscending: Boolean) : } SORT_MODIF -> { // sort by last modified - return asc * java.lang.Long.valueOf(f1.lastModification) - .compareTo(f2.lastModification) + return asc * + java.lang.Long.valueOf(f1.lastModification) + .compareTo(f2.lastModification) } SORT_SIZE -> { // sort by size diff --git a/app/src/main/java/com/amaze/filemanager/adapters/data/CompressedObjectParcelable.java b/app/src/main/java/com/amaze/filemanager/adapters/data/CompressedObjectParcelable.java index b991e50b58..c9332c1944 100644 --- a/app/src/main/java/com/amaze/filemanager/adapters/data/CompressedObjectParcelable.java +++ b/app/src/main/java/com/amaze/filemanager/adapters/data/CompressedObjectParcelable.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/adapters/data/IconDataParcelable.java b/app/src/main/java/com/amaze/filemanager/adapters/data/IconDataParcelable.java index 1761b7a3aa..4a34d93e30 100644 --- a/app/src/main/java/com/amaze/filemanager/adapters/data/IconDataParcelable.java +++ b/app/src/main/java/com/amaze/filemanager/adapters/data/IconDataParcelable.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/adapters/data/LayoutElementParcelable.java b/app/src/main/java/com/amaze/filemanager/adapters/data/LayoutElementParcelable.java index c202eb9f42..82539cefb3 100644 --- a/app/src/main/java/com/amaze/filemanager/adapters/data/LayoutElementParcelable.java +++ b/app/src/main/java/com/amaze/filemanager/adapters/data/LayoutElementParcelable.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/adapters/data/OpenFileParcelable.kt b/app/src/main/java/com/amaze/filemanager/adapters/data/OpenFileParcelable.kt index 1507fef9a3..85618159eb 100644 --- a/app/src/main/java/com/amaze/filemanager/adapters/data/OpenFileParcelable.kt +++ b/app/src/main/java/com/amaze/filemanager/adapters/data/OpenFileParcelable.kt @@ -30,5 +30,5 @@ class OpenFileParcelable( var mimeType: String?, var useNewStack: Boolean?, var className: String?, - var packageName: String? + var packageName: String?, ) : Parcelable diff --git a/app/src/main/java/com/amaze/filemanager/adapters/data/StorageDirectoryParcelable.kt b/app/src/main/java/com/amaze/filemanager/adapters/data/StorageDirectoryParcelable.kt index 883d23293b..db94954518 100644 --- a/app/src/main/java/com/amaze/filemanager/adapters/data/StorageDirectoryParcelable.kt +++ b/app/src/main/java/com/amaze/filemanager/adapters/data/StorageDirectoryParcelable.kt @@ -32,18 +32,20 @@ data class StorageDirectoryParcelable( val name: String, @JvmField @DrawableRes - val iconRes: Int + val iconRes: Int, ) : Parcelable { - constructor(im: Parcel) : this( path = im.readString()!!, name = im.readString()!!, - iconRes = im.readInt() + iconRes = im.readInt(), ) override fun describeContents() = 0 - override fun writeToParcel(parcel: Parcel, i: Int) { + override fun writeToParcel( + parcel: Parcel, + i: Int, + ) { parcel.writeString(path) parcel.writeString(name) parcel.writeInt(iconRes) @@ -51,14 +53,15 @@ data class StorageDirectoryParcelable( companion object { @JvmField - val CREATOR = object : Parcelable.Creator { - override fun createFromParcel(parcel: Parcel): StorageDirectoryParcelable { - return StorageDirectoryParcelable(parcel) - } + val CREATOR = + object : Parcelable.Creator { + override fun createFromParcel(parcel: Parcel): StorageDirectoryParcelable { + return StorageDirectoryParcelable(parcel) + } - override fun newArray(size: Int): Array { - return arrayOfNulls(size) + override fun newArray(size: Int): Array { + return arrayOfNulls(size) + } } - } } } diff --git a/app/src/main/java/com/amaze/filemanager/adapters/glide/AppsAdapterPreloadModel.java b/app/src/main/java/com/amaze/filemanager/adapters/glide/AppsAdapterPreloadModel.java index c76d130cfc..11ae179524 100644 --- a/app/src/main/java/com/amaze/filemanager/adapters/glide/AppsAdapterPreloadModel.java +++ b/app/src/main/java/com/amaze/filemanager/adapters/glide/AppsAdapterPreloadModel.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/adapters/glide/RecyclerPreloadModelProvider.java b/app/src/main/java/com/amaze/filemanager/adapters/glide/RecyclerPreloadModelProvider.java index 706c65e883..961715b5d5 100644 --- a/app/src/main/java/com/amaze/filemanager/adapters/glide/RecyclerPreloadModelProvider.java +++ b/app/src/main/java/com/amaze/filemanager/adapters/glide/RecyclerPreloadModelProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/adapters/glide/RecyclerPreloadSizeProvider.java b/app/src/main/java/com/amaze/filemanager/adapters/glide/RecyclerPreloadSizeProvider.java index 21a14b2981..5bb868a8bf 100644 --- a/app/src/main/java/com/amaze/filemanager/adapters/glide/RecyclerPreloadSizeProvider.java +++ b/app/src/main/java/com/amaze/filemanager/adapters/glide/RecyclerPreloadSizeProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/adapters/glide/apkimage/ApkImageDataFetcher.java b/app/src/main/java/com/amaze/filemanager/adapters/glide/apkimage/ApkImageDataFetcher.java index 4a46251b91..1cb4ca20dc 100644 --- a/app/src/main/java/com/amaze/filemanager/adapters/glide/apkimage/ApkImageDataFetcher.java +++ b/app/src/main/java/com/amaze/filemanager/adapters/glide/apkimage/ApkImageDataFetcher.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/adapters/glide/apkimage/ApkImageModelLoader.java b/app/src/main/java/com/amaze/filemanager/adapters/glide/apkimage/ApkImageModelLoader.java index 18b66616eb..6cf0c89355 100644 --- a/app/src/main/java/com/amaze/filemanager/adapters/glide/apkimage/ApkImageModelLoader.java +++ b/app/src/main/java/com/amaze/filemanager/adapters/glide/apkimage/ApkImageModelLoader.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/adapters/glide/apkimage/ApkImageModelLoaderFactory.java b/app/src/main/java/com/amaze/filemanager/adapters/glide/apkimage/ApkImageModelLoaderFactory.java index 5efc078ecb..45c3df7732 100644 --- a/app/src/main/java/com/amaze/filemanager/adapters/glide/apkimage/ApkImageModelLoaderFactory.java +++ b/app/src/main/java/com/amaze/filemanager/adapters/glide/apkimage/ApkImageModelLoaderFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/adapters/glide/cloudicon/CloudIconDataFetcher.kt b/app/src/main/java/com/amaze/filemanager/adapters/glide/cloudicon/CloudIconDataFetcher.kt index a33715505e..8e95b1f03e 100644 --- a/app/src/main/java/com/amaze/filemanager/adapters/glide/cloudicon/CloudIconDataFetcher.kt +++ b/app/src/main/java/com/amaze/filemanager/adapters/glide/cloudicon/CloudIconDataFetcher.kt @@ -35,21 +35,24 @@ class CloudIconDataFetcher( private val context: Context, private val path: String, private val width: Int, - private val height: Int + private val height: Int, ) : DataFetcher { - companion object { private val TAG = CloudIconDataFetcher::class.java.simpleName } private var inputStream: InputStream? = null - override fun loadData(priority: Priority, callback: DataFetcher.DataCallback) { + override fun loadData( + priority: Priority, + callback: DataFetcher.DataCallback, + ) { inputStream = CloudUtil.getThumbnailInputStreamForCloud(context, path) - val options = BitmapFactory.Options().also { - it.outWidth = width - it.outHeight = height - } + val options = + BitmapFactory.Options().also { + it.outWidth = width + it.outHeight = height + } val drawable = BitmapFactory.decodeStream(inputStream, null, options) callback.onDataReady(drawable) } diff --git a/app/src/main/java/com/amaze/filemanager/adapters/glide/cloudicon/CloudIconModelFactory.java b/app/src/main/java/com/amaze/filemanager/adapters/glide/cloudicon/CloudIconModelFactory.java index e69dd3aa03..caedb7d146 100644 --- a/app/src/main/java/com/amaze/filemanager/adapters/glide/cloudicon/CloudIconModelFactory.java +++ b/app/src/main/java/com/amaze/filemanager/adapters/glide/cloudicon/CloudIconModelFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/adapters/glide/cloudicon/CloudIconModelLoader.java b/app/src/main/java/com/amaze/filemanager/adapters/glide/cloudicon/CloudIconModelLoader.java index afc9e683e7..33edfb754d 100644 --- a/app/src/main/java/com/amaze/filemanager/adapters/glide/cloudicon/CloudIconModelLoader.java +++ b/app/src/main/java/com/amaze/filemanager/adapters/glide/cloudicon/CloudIconModelLoader.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/adapters/holders/AppHolder.kt b/app/src/main/java/com/amaze/filemanager/adapters/holders/AppHolder.kt index 71edf51820..84e85ab1f0 100644 --- a/app/src/main/java/com/amaze/filemanager/adapters/holders/AppHolder.kt +++ b/app/src/main/java/com/amaze/filemanager/adapters/holders/AppHolder.kt @@ -65,7 +65,7 @@ class AppHolder(view: View) : RecyclerView.ViewHolder(view) { txtDesc.marginLeft, txtDesc.marginTop, Utils.dpToPx(view.context, 4), - txtDesc.marginBottom + txtDesc.marginBottom, ) txtDesc.layoutParams = layoutParams diff --git a/app/src/main/java/com/amaze/filemanager/adapters/holders/SpecialViewHolder.kt b/app/src/main/java/com/amaze/filemanager/adapters/holders/SpecialViewHolder.kt index 0fc7f10bb0..f329e9685a 100644 --- a/app/src/main/java/com/amaze/filemanager/adapters/holders/SpecialViewHolder.kt +++ b/app/src/main/java/com/amaze/filemanager/adapters/holders/SpecialViewHolder.kt @@ -36,7 +36,7 @@ class SpecialViewHolder( c: Context, view: View, utilsProvider: UtilitiesProvider, - val type: Int + val type: Int, ) : RecyclerView.ViewHolder(view) { // each data item is just a string in this case private val txtTitle: AppCompatTextView = view.findViewById(R.id.text) diff --git a/app/src/main/java/com/amaze/filemanager/application/AppConfig.java b/app/src/main/java/com/amaze/filemanager/application/AppConfig.java index a09fe2cfeb..06a7a2b198 100644 --- a/app/src/main/java/com/amaze/filemanager/application/AppConfig.java +++ b/app/src/main/java/com/amaze/filemanager/application/AppConfig.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/application/GlideApplication.java b/app/src/main/java/com/amaze/filemanager/application/GlideApplication.java index 32d5f2b4d6..8f234dc01c 100644 --- a/app/src/main/java/com/amaze/filemanager/application/GlideApplication.java +++ b/app/src/main/java/com/amaze/filemanager/application/GlideApplication.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/AbstractRepeatingRunnable.java b/app/src/main/java/com/amaze/filemanager/asynchronous/AbstractRepeatingRunnable.java index 8bd2230db3..0fe3a8a754 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/AbstractRepeatingRunnable.java +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/AbstractRepeatingRunnable.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/SaveOnDataUtilsChange.java b/app/src/main/java/com/amaze/filemanager/asynchronous/SaveOnDataUtilsChange.java index 25dc56f070..d19282ca35 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/SaveOnDataUtilsChange.java +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/SaveOnDataUtilsChange.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2021 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/AsyncTaskResult.java b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/AsyncTaskResult.java index a3123dddd7..a3fff01bbf 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/AsyncTaskResult.java +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/AsyncTaskResult.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/CountItemsOrAndSizeTask.java b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/CountItemsOrAndSizeTask.java index a6e63e1304..78d2d58681 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/CountItemsOrAndSizeTask.java +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/CountItemsOrAndSizeTask.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/DbViewerTask.java b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/DbViewerTask.java index a4a3d79e6e..eea2b9649e 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/DbViewerTask.java +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/DbViewerTask.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/DeleteTask.java b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/DeleteTask.java index 0b187e65f6..4f83f4bd0a 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/DeleteTask.java +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/DeleteTask.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/LoadFilesListTask.java b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/LoadFilesListTask.java index 6f031fc2b9..897b764102 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/LoadFilesListTask.java +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/LoadFilesListTask.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/LoadFolderSpaceDataTask.java b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/LoadFolderSpaceDataTask.java index 69460518a1..f0121c349b 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/LoadFolderSpaceDataTask.java +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/LoadFolderSpaceDataTask.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/SearchTextTask.kt b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/SearchTextTask.kt index ee1f0f469d..7739be49e8 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/SearchTextTask.kt +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/SearchTextTask.kt @@ -36,7 +36,7 @@ class SearchTextTask( private val textToSearch: String, private val searchedText: String, private val updateListener: OnProgressUpdate, - private val listener: OnAsyncTaskFinished> + private val listener: OnAsyncTaskFinished>, ) : AsyncTask>() { private val lineNumberReader: LineNumberReader @@ -61,11 +61,12 @@ class SearchTextTask( log.warn("failed to search text", e) } charIndex = nextPosition - val index = SearchResultIndex( - charIndex, - charIndex + searchedText.length, - lineNumberReader.lineNumber - ) + val index = + SearchResultIndex( + charIndex, + charIndex + searchedText.length, + lineNumberReader.lineNumber, + ) searchResultIndices.add(index) publishProgress(index) charIndex++ diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/StatefulAsyncTask.kt b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/StatefulAsyncTask.kt index 1e36e891f8..89b2bbd1a7 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/StatefulAsyncTask.kt +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/StatefulAsyncTask.kt @@ -24,7 +24,6 @@ package com.amaze.filemanager.asynchronous.asynctasks * Interface to define state to Asynctask */ interface StatefulAsyncTask { - /** * Set callback to current async task. To be used to attach the context on * orientation change of fragment / activity diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/AbstractCommonsArchiveHelperCallable.kt b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/AbstractCommonsArchiveHelperCallable.kt index cd82d3eace..a10d930fcc 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/AbstractCommonsArchiveHelperCallable.kt +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/AbstractCommonsArchiveHelperCallable.kt @@ -38,9 +38,8 @@ abstract class AbstractCommonsArchiveHelperCallable( context: Context, private val filePath: String, private val relativePath: String, - goBack: Boolean + goBack: Boolean, ) : CompressedHelperCallable(goBack) { - private val context: WeakReference = WeakReference(context) /** @@ -63,7 +62,7 @@ abstract class AbstractCommonsArchiveHelperCallable( if (!CompressedHelper.isEntryPathValid(name)) { AppConfig.toast( context.get(), - context.get()!!.getString(R.string.multiple_invalid_archive_entries) + context.get()!!.getString(R.string.multiple_invalid_archive_entries), ) return@run } @@ -76,15 +75,15 @@ abstract class AbstractCommonsArchiveHelperCallable( name.contains(CompressedHelper.SEPARATOR) && name.substring(0, name.lastIndexOf(CompressedHelper.SEPARATOR)) == relativePath - ) + ) if (isInBaseDir || isInRelativeDir) { elements.add( CompressedObjectParcelable( name, lastModifiedDate.time, size, - isDirectory - ) + isDirectory, + ), ) } } diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/AbstractCompressedTarArchiveHelperCallable.kt b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/AbstractCompressedTarArchiveHelperCallable.kt index bc720791bc..2ef831f663 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/AbstractCompressedTarArchiveHelperCallable.kt +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/AbstractCompressedTarArchiveHelperCallable.kt @@ -31,15 +31,15 @@ abstract class AbstractCompressedTarArchiveHelperCallable( context: Context, filePath: String, relativePath: String, - goBack: Boolean + goBack: Boolean, ) : AbstractCommonsArchiveHelperCallable(context, filePath, relativePath, goBack) { - private val compressorInputStreamConstructor: Constructor init { - compressorInputStreamConstructor = getCompressorInputStreamClass() - .getDeclaredConstructor(InputStream::class.java) + compressorInputStreamConstructor = + getCompressorInputStreamClass() + .getDeclaredConstructor(InputStream::class.java) compressorInputStreamConstructor.isAccessible = true } diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/CompressedHelperCallable.kt b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/CompressedHelperCallable.kt index d23d50ccad..fa25fe2422 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/CompressedHelperCallable.kt +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/CompressedHelperCallable.kt @@ -29,25 +29,24 @@ import java.util.* import java.util.concurrent.Callable abstract class CompressedHelperCallable internal constructor( - private val createBackItem: Boolean + private val createBackItem: Boolean, ) : Callable> { + protected val logger: Logger = LoggerFactory.getLogger(javaClass) - protected val logger: Logger = LoggerFactory.getLogger(javaClass) + @WorkerThread + @Throws(ArchiveException::class) + override fun call(): ArrayList { + val elements = ArrayList() + if (createBackItem) { + elements.add(0, CompressedObjectParcelable()) + } - @WorkerThread - @Throws(ArchiveException::class) - override fun call(): ArrayList { - val elements = ArrayList() - if (createBackItem) { - elements.add(0, CompressedObjectParcelable()) + addElements(elements) + Collections.sort(elements, CompressedObjectParcelable.Sorter()) + return elements } - addElements(elements) - Collections.sort(elements, CompressedObjectParcelable.Sorter()) - return elements + @Throws(ArchiveException::class) + protected abstract fun addElements(elements: ArrayList) } - - @Throws(ArchiveException::class) - protected abstract fun addElements(elements: ArrayList) -} diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/SevenZipHelperCallable.kt b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/SevenZipHelperCallable.kt index 11c1357fbe..45790663fb 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/SevenZipHelperCallable.kt +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/SevenZipHelperCallable.kt @@ -33,22 +33,22 @@ import java.io.IOException class SevenZipHelperCallable( private val filePath: String, private val relativePath: String, - goBack: Boolean + goBack: Boolean, ) : CompressedHelperCallable(goBack) { - @Throws(ArchiveException::class) @Suppress("Detekt.RethrowCaughtException") override fun addElements(elements: ArrayList) { try { - val sevenzFile = if (ArchivePasswordCache.getInstance().containsKey(filePath)) { - SevenZFile( - File(filePath), - ArchivePasswordCache.getInstance()[filePath]!!.toCharArray() - ) - } else { - SevenZFile(File(filePath)) - } + val sevenzFile = + if (ArchivePasswordCache.getInstance().containsKey(filePath)) { + SevenZFile( + File(filePath), + ArchivePasswordCache.getInstance()[filePath]!!.toCharArray(), + ) + } else { + SevenZFile(File(filePath)) + } val entriesMap = sevenzFile.entries.associateBy { it.name } val entries = HashSet() @@ -66,8 +66,8 @@ class SevenZipHelperCallable( 1 } else { relativePath.count { it == CompressedHelper.SEPARATOR_CHAR } + 1 - } - ) + }, + ), ) entries.forEach { path -> @@ -83,8 +83,8 @@ class SevenZipHelperCallable( 0L }, entry.size, - entry.isDirectory - ) + entry.isDirectory, + ), ) } } else { @@ -93,8 +93,8 @@ class SevenZipHelperCallable( path, 0L, 0, - true - ) + true, + ), ) } } @@ -106,7 +106,10 @@ class SevenZipHelperCallable( } } - internal fun consolidate(paths: Collection, level: Int = 0): Set { + internal fun consolidate( + paths: Collection, + level: Int = 0, + ): Set { return paths.mapNotNull { path -> when (level) { 0 -> { diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarBzip2HelperCallable.kt b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarBzip2HelperCallable.kt index 444a0f59da..b5650ae5c7 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarBzip2HelperCallable.kt +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarBzip2HelperCallable.kt @@ -28,10 +28,8 @@ class TarBzip2HelperCallable( context: Context, filePath: String, relativePath: String, - goBack: Boolean + goBack: Boolean, ) : AbstractCompressedTarArchiveHelperCallable(context, filePath, relativePath, goBack) { - - override fun getCompressorInputStreamClass(): Class = - BZip2CompressorInputStream::class.java + override fun getCompressorInputStreamClass(): Class = BZip2CompressorInputStream::class.java } diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarGzHelperCallable.kt b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarGzHelperCallable.kt index 1f19fb47a0..9de41dd6d5 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarGzHelperCallable.kt +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarGzHelperCallable.kt @@ -28,10 +28,8 @@ class TarGzHelperCallable( context: Context, filePath: String, relativePath: String, - goBack: Boolean + goBack: Boolean, ) : AbstractCompressedTarArchiveHelperCallable(context, filePath, relativePath, goBack) { - - override fun getCompressorInputStreamClass(): Class = - GzipCompressorInputStream::class.java + override fun getCompressorInputStreamClass(): Class = GzipCompressorInputStream::class.java } diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarHelperCallable.kt b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarHelperCallable.kt index 37b31265b3..9c620f3369 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarHelperCallable.kt +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarHelperCallable.kt @@ -29,10 +29,8 @@ class TarHelperCallable( context: Context, filePath: String, relativePath: String, - goBack: Boolean + goBack: Boolean, ) : AbstractCommonsArchiveHelperCallable(context, filePath, relativePath, goBack) { - - override fun createFrom(inputStream: InputStream): ArchiveInputStream = - TarArchiveInputStream(inputStream) + override fun createFrom(inputStream: InputStream): ArchiveInputStream = TarArchiveInputStream(inputStream) } diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarLzmaHelperCallable.kt b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarLzmaHelperCallable.kt index 94e947a4e1..41e302d4aa 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarLzmaHelperCallable.kt +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarLzmaHelperCallable.kt @@ -28,10 +28,8 @@ class TarLzmaHelperCallable( context: Context, filePath: String, relativePath: String, - goBack: Boolean + goBack: Boolean, ) : AbstractCompressedTarArchiveHelperCallable(context, filePath, relativePath, goBack) { - - override fun getCompressorInputStreamClass(): Class = - LZMACompressorInputStream::class.java + override fun getCompressorInputStreamClass(): Class = LZMACompressorInputStream::class.java } diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarXzHelperCallable.kt b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarXzHelperCallable.kt index 228dfea621..24fe3e3192 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarXzHelperCallable.kt +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarXzHelperCallable.kt @@ -28,10 +28,8 @@ class TarXzHelperCallable( context: Context, filePath: String, relativePath: String, - goBack: Boolean + goBack: Boolean, ) : AbstractCompressedTarArchiveHelperCallable(context, filePath, relativePath, goBack) { - - override fun getCompressorInputStreamClass(): Class = - XZCompressorInputStream::class.java + override fun getCompressorInputStreamClass(): Class = XZCompressorInputStream::class.java } diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/UnknownCompressedFileHelperCallable.kt b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/UnknownCompressedFileHelperCallable.kt index e5c90b4582..cf14ef7d28 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/UnknownCompressedFileHelperCallable.kt +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/UnknownCompressedFileHelperCallable.kt @@ -52,10 +52,9 @@ import java.util.ArrayList */ class UnknownCompressedFileHelperCallable( private val filePath: String, - goBack: Boolean + goBack: Boolean, ) : CompressedHelperCallable(goBack) { - override fun addElements(elements: ArrayList) { val entryName = filePath.substringAfterLast('/').substringBeforeLast('.') elements.add( @@ -63,8 +62,8 @@ class UnknownCompressedFileHelperCallable( entryName, 0L, 0L, - false - ) + false, + ), ) } } diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/ZipHelperCallable.kt b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/ZipHelperCallable.kt index 3ab30a333e..9ad0e63868 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/ZipHelperCallable.kt +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/ZipHelperCallable.kt @@ -38,96 +38,99 @@ class ZipHelperCallable( c: Context, realFileDirectory: String, dir: String?, - goback: Boolean + goback: Boolean, ) : CompressedHelperCallable(goback) { - private val context: WeakReference = WeakReference(c) private val fileLocation: Uri = Uri.parse(realFileDirectory) private val relativeDirectory: String? = dir @Throws(ArchiveException::class) @Suppress("ComplexMethod", "LongMethod") - public override fun addElements(elements: ArrayList) = try { - fileLocation.path?.run { - val zipfile = ZipFile(fileLocation.path) - val wholelist = filterValidEntryList(zipfile) - val strings = ArrayList() - for (entry in wholelist) { - val file = File(entry.path) - val y = entry.path.let { - if (it.startsWith("/")) { - it.substring(1, it.length) - } else { - it - } - } - if (relativeDirectory == null || relativeDirectory.trim { it <= ' ' }.isEmpty()) { - var path: String - var zipObj: CompressedObjectParcelable - if (file.parent == null || file.parent!!.isEmpty() || file.parent == "/") { - path = y - zipObj = CompressedObjectParcelable( - y, - entry.date, - entry.size, - entry.directory - ) - } else { - path = y.substring(0, y.indexOf("/") + 1) - zipObj = CompressedObjectParcelable( - path, - entry.date, - entry.size, - true - ) - } - if (!strings.contains(path)) { - elements.add(zipObj) - strings.add(path) - } - } else { - if (file.parent != null && - ( - file.parent == relativeDirectory || - file.parent == "/$relativeDirectory" - ) - ) { - if (!strings.contains(y)) { - elements.add( + public override fun addElements(elements: ArrayList) = + try { + fileLocation.path?.run { + val zipfile = ZipFile(fileLocation.path) + val wholelist = filterValidEntryList(zipfile) + val strings = ArrayList() + for (entry in wholelist) { + val file = File(entry.path) + val y = + entry.path.let { + if (it.startsWith("/")) { + it.substring(1, it.length) + } else { + it + } + } + if (relativeDirectory == null || relativeDirectory.trim { it <= ' ' }.isEmpty()) { + var path: String + var zipObj: CompressedObjectParcelable + if (file.parent == null || file.parent!!.isEmpty() || file.parent == "/") { + path = y + zipObj = CompressedObjectParcelable( y, entry.date, entry.size, - entry.directory + entry.directory, ) - ) - strings.add(y) - } - } else if (y.startsWith("$relativeDirectory/") && - y.length > relativeDirectory.length + 1 - ) { - val path1 = y.substring(relativeDirectory.length + 1, y.length) - val index = relativeDirectory.length + 1 + path1.indexOf("/") - val path = y.substring(0, index + 1) - if (!strings.contains(path)) { - elements.add( + } else { + path = y.substring(0, y.indexOf("/") + 1) + zipObj = CompressedObjectParcelable( - y.substring(0, index + 1), + path, entry.date, entry.size, - true + true, ) - ) + } + if (!strings.contains(path)) { + elements.add(zipObj) strings.add(path) } + } else { + if (file.parent != null && + ( + file.parent == relativeDirectory || + file.parent == "/$relativeDirectory" + ) + ) { + if (!strings.contains(y)) { + elements.add( + CompressedObjectParcelable( + y, + entry.date, + entry.size, + entry.directory, + ), + ) + strings.add(y) + } + } else if (y.startsWith("$relativeDirectory/") && + y.length > relativeDirectory.length + 1 + ) { + val path1 = y.substring(relativeDirectory.length + 1, y.length) + val index = relativeDirectory.length + 1 + path1.indexOf("/") + val path = y.substring(0, index + 1) + if (!strings.contains(path)) { + elements.add( + CompressedObjectParcelable( + y.substring(0, index + 1), + entry.date, + entry.size, + true, + ), + ) + strings.add(path) + } + } } } - } - } ?: throw ArchiveException(null) - } catch (e: ZipException) { - throw ArchiveException("Zip file is corrupt", e) - } + } ?: throw ArchiveException(null) + } catch (e: ZipException) { + throw ArchiveException("Zip file is corrupt", e) + } private fun filterValidEntryList(zipFile: ZipFile): List { val retval = ArrayList() @@ -137,7 +140,7 @@ class ZipHelperCallable( if (!CompressedHelper.isEntryPathValid(entry.fileName)) { AppConfig.toast( context.get(), - context.get()!!.getString(R.string.multiple_invalid_archive_entries) + context.get()!!.getString(R.string.multiple_invalid_archive_entries), ) continue } @@ -146,8 +149,8 @@ class ZipHelperCallable( entry.fileName, entry.lastModifiedTimeEpoch, entry.uncompressedSize, - entry.isDirectory - ) + entry.isDirectory, + ), ) } return retval diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ftp/AbstractGetHostInfoTask.kt b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ftp/AbstractGetHostInfoTask.kt index d8fea436bc..de2cd9f893 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ftp/AbstractGetHostInfoTask.kt +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ftp/AbstractGetHostInfoTask.kt @@ -31,9 +31,8 @@ import java.util.concurrent.Callable abstract class AbstractGetHostInfoTask>( private val hostname: String, private val port: Int, - private val callback: (V) -> Unit + private val callback: (V) -> Unit, ) : Task { - private lateinit var progressDialog: ProgressDialog /** @@ -42,11 +41,12 @@ abstract class AbstractGetHostInfoTask>( @MainThread open fun onPreExecute() { AppConfig.getInstance().run { - progressDialog = ProgressDialog.show( - this.mainActivityContext, - "", - this.resources.getString(R.string.processing) - ) + progressDialog = + ProgressDialog.show( + this.mainActivityContext, + "", + this.resources.getString(R.string.processing), + ) } } @@ -63,9 +63,9 @@ abstract class AbstractGetHostInfoTask>( R.string.ssh_connect_failed, hostname, port, - error.localizedMessage + error.localizedMessage, ), - Toast.LENGTH_LONG + Toast.LENGTH_LONG, ).show() } diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ftp/auth/FtpAuthenticationTask.kt b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ftp/auth/FtpAuthenticationTask.kt index d9132a0425..2ef16520b6 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ftp/auth/FtpAuthenticationTask.kt +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ftp/auth/FtpAuthenticationTask.kt @@ -37,16 +37,15 @@ class FtpAuthenticationTask( private val port: Int, private val certInfo: JSONObject?, private val username: String, - private val password: String? + private val password: String?, ) : Task { - override fun getTask(): FtpAuthenticationTaskCallable { return if (protocol == FTP_URI_PREFIX) { FtpAuthenticationTaskCallable( host, port, username, - password ?: "" + password ?: "", ) } else { FtpsAuthenticationTaskCallable( @@ -54,7 +53,7 @@ class FtpAuthenticationTask( port, certInfo!!, username, - password ?: "" + password ?: "", ) } } @@ -71,8 +70,8 @@ class FtpAuthenticationTask( R.string.ssh_connect_failed, host, port, - error.localizedMessage ?: error.message - ) + error.localizedMessage ?: error.message, + ), ) } } diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ftp/auth/FtpAuthenticationTaskCallable.kt b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ftp/auth/FtpAuthenticationTaskCallable.kt index 021663f89b..ae1cfe8393 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ftp/auth/FtpAuthenticationTaskCallable.kt +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ftp/auth/FtpAuthenticationTaskCallable.kt @@ -37,29 +37,29 @@ open class FtpAuthenticationTaskCallable( protected val hostname: String, protected val port: Int, protected val username: String, - protected val password: String + protected val password: String, ) : Callable { - @WorkerThread override fun call(): FTPClient { val ftpClient = createFTPClient() ftpClient.connectTimeout = CONNECT_TIMEOUT ftpClient.controlEncoding = Charsets.UTF_8.name() ftpClient.connect(hostname, port) - val loginSuccess = if (username.isBlank() && password.isBlank()) { - ftpClient.login( - FTPClientImpl.ANONYMOUS, - FTPClientImpl.generateRandomEmailAddressForLogin() - ) - } else { - ftpClient.login( - decode(username, UTF_8.name()), - decode( - PasswordUtil.decryptPassword(AppConfig.getInstance(), password), - UTF_8.name() + val loginSuccess = + if (username.isBlank() && password.isBlank()) { + ftpClient.login( + FTPClientImpl.ANONYMOUS, + FTPClientImpl.generateRandomEmailAddressForLogin(), ) - ) - } + } else { + ftpClient.login( + decode(username, UTF_8.name()), + decode( + PasswordUtil.decryptPassword(AppConfig.getInstance(), password), + UTF_8.name(), + ), + ) + } return if (loginSuccess) { ftpClient.enterLocalPassiveMode() ftpClient @@ -68,6 +68,5 @@ open class FtpAuthenticationTaskCallable( } } - protected open fun createFTPClient(): FTPClient = - NetCopyClientConnectionPool.ftpClientFactory.create(FTP_URI_PREFIX) + protected open fun createFTPClient(): FTPClient = NetCopyClientConnectionPool.ftpClientFactory.create(FTP_URI_PREFIX) } diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ftp/auth/FtpsAuthenticationTaskCallable.kt b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ftp/auth/FtpsAuthenticationTaskCallable.kt index 5d28d1d9e9..b5c71cb54b 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ftp/auth/FtpsAuthenticationTaskCallable.kt +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ftp/auth/FtpsAuthenticationTaskCallable.kt @@ -38,25 +38,25 @@ class FtpsAuthenticationTaskCallable( port: Int, private val certInfo: JSONObject, username: String, - password: String + password: String, ) : FtpAuthenticationTaskCallable(hostname, port, username, password) { - override fun call(): FTPClient { val ftpClient = createFTPClient() as FTPSClient ftpClient.connectTimeout = NetCopyClientConnectionPool.CONNECT_TIMEOUT ftpClient.controlEncoding = Charsets.UTF_8.name() ftpClient.connect(hostname, port) - val loginSuccess = if (username.isBlank() && password.isBlank()) { - ftpClient.login( - FTPClientImpl.ANONYMOUS, - FTPClientImpl.generateRandomEmailAddressForLogin() - ) - } else { - ftpClient.login( - username, - PasswordUtil.decryptPassword(AppConfig.getInstance(), password) - ) - } + val loginSuccess = + if (username.isBlank() && password.isBlank()) { + ftpClient.login( + FTPClientImpl.ANONYMOUS, + FTPClientImpl.generateRandomEmailAddressForLogin(), + ) + } else { + ftpClient.login( + username, + PasswordUtil.decryptPassword(AppConfig.getInstance(), password), + ) + } return if (loginSuccess) { // RFC 2228 set protection buffer size to 0 ftpClient.execPBSZ(0) @@ -74,16 +74,17 @@ class FtpsAuthenticationTaskCallable( return ( NetCopyClientConnectionPool.ftpClientFactory.create(FTPS_URI_PREFIX) as FTPSClient - ).apply { - this.hostnameVerifier = HostnameVerifier { _, session -> - return@HostnameVerifier if (session.peerCertificateChain.isNotEmpty()) { - X509CertificateUtil.parse( - session.peerCertificateChain.first() - )[FINGERPRINT] == certInfo.get(FINGERPRINT) - } else { - false + ).apply { + this.hostnameVerifier = + HostnameVerifier { _, session -> + return@HostnameVerifier if (session.peerCertificateChain.isNotEmpty()) { + X509CertificateUtil.parse( + session.peerCertificateChain.first(), + )[FINGERPRINT] == certInfo.get(FINGERPRINT) + } else { + false + } } - } } } } diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ftp/hostcert/FtpsGetHostCertificateTask.kt b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ftp/hostcert/FtpsGetHostCertificateTask.kt index 2fa37674f2..bba907687a 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ftp/hostcert/FtpsGetHostCertificateTask.kt +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ftp/hostcert/FtpsGetHostCertificateTask.kt @@ -29,11 +29,9 @@ class FtpsGetHostCertificateTask( private val host: String, private val port: Int, context: Context, - callback: (JSONObject) -> Unit + callback: (JSONObject) -> Unit, ) : AbstractGetHostInfoTask(host, port, callback) { - val ctx: WeakReference = WeakReference(context) - override fun getTask(): FtpsGetHostCertificateTaskCallable = - FtpsGetHostCertificateTaskCallable(host, port) + override fun getTask(): FtpsGetHostCertificateTaskCallable = FtpsGetHostCertificateTaskCallable(host, port) } diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ftp/hostcert/FtpsGetHostCertificateTaskCallable.kt b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ftp/hostcert/FtpsGetHostCertificateTaskCallable.kt index 0cc7c476c4..a541636524 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ftp/hostcert/FtpsGetHostCertificateTaskCallable.kt +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ftp/hostcert/FtpsGetHostCertificateTaskCallable.kt @@ -33,9 +33,8 @@ import javax.net.ssl.HostnameVerifier open class FtpsGetHostCertificateTaskCallable( private val hostname: String, - private val port: Int + private val port: Int, ) : Callable { - @WorkerThread override fun call(): JSONObject? { val latch = CountDownLatch(1) @@ -43,20 +42,20 @@ open class FtpsGetHostCertificateTaskCallable( val ftpClient = createFTPClient() ftpClient.connectTimeout = CONNECT_TIMEOUT ftpClient.controlEncoding = Charsets.UTF_8.name() - ftpClient.hostnameVerifier = HostnameVerifier { _, session -> - if (session.peerCertificateChain.isNotEmpty()) { - val certinfo = X509CertificateUtil.parse(session.peerCertificateChain[0]) - result = JSONObject(certinfo) + ftpClient.hostnameVerifier = + HostnameVerifier { _, session -> + if (session.peerCertificateChain.isNotEmpty()) { + val certinfo = X509CertificateUtil.parse(session.peerCertificateChain[0]) + result = JSONObject(certinfo) + } + latch.countDown() + true } - latch.countDown() - true - } ftpClient.connect(hostname, port) latch.await() ftpClient.disconnect() return result } - protected open fun createFTPClient(): FTPSClient = - NetCopyClientConnectionPool.ftpClientFactory.create(FTPS_URI_PREFIX) as FTPSClient + protected open fun createFTPClient(): FTPSClient = NetCopyClientConnectionPool.ftpClientFactory.create(FTPS_URI_PREFIX) as FTPSClient } diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/hashcalculator/CalculateHashCallback.java b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/hashcalculator/CalculateHashCallback.java index cea10c620a..67a2612054 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/hashcalculator/CalculateHashCallback.java +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/hashcalculator/CalculateHashCallback.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/hashcalculator/CalculateHashSftpCallback.java b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/hashcalculator/CalculateHashSftpCallback.java index 2430e7359f..8cd43cc9b1 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/hashcalculator/CalculateHashSftpCallback.java +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/hashcalculator/CalculateHashSftpCallback.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2021 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/hashcalculator/CalculateHashTask.kt b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/hashcalculator/CalculateHashTask.kt index 6067e9a7c5..aaac1a27de 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/hashcalculator/CalculateHashTask.kt +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/hashcalculator/CalculateHashTask.kt @@ -40,19 +40,19 @@ data class Hash(val md5: String, val sha: String) class CalculateHashTask( private val file: HybridFileParcelable, context: Context, - view: View + view: View, ) : Task> { - private val log: Logger = LoggerFactory.getLogger(CalculateHashTask::class.java) - private val task: Callable = if (file.isSftp && !file.isDirectory(context)) { - CalculateHashSftpCallback(file) - } else if (file.isFtp || file.isDirectory(context)) { - // Don't do this. Especially when FTPClient requires thread safety. - DoNothingCalculateHashCallback() - } else { - CalculateHashCallback(file, context) - } + private val task: Callable = + if (file.isSftp && !file.isDirectory(context)) { + CalculateHashSftpCallback(file) + } else if (file.isFtp || file.isDirectory(context)) { + // Don't do this. Especially when FTPClient requires thread safety. + DoNothingCalculateHashCallback() + } else { + CalculateHashCallback(file, context) + } private val context = WeakReference(context) private val view = WeakReference(view) @@ -94,7 +94,7 @@ class CalculateHashTask( context.resources.getString(R.string.md5).uppercase(Locale.getDefault()) + " " + context.resources.getString(R.string.properties_copied_clipboard), - Toast.LENGTH_SHORT + Toast.LENGTH_SHORT, ) .show() false @@ -105,7 +105,7 @@ class CalculateHashTask( context, context.resources.getString(R.string.hash_sha256) + " " + context.resources.getString(R.string.properties_copied_clipboard), - Toast.LENGTH_SHORT + Toast.LENGTH_SHORT, ) .show() false diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/movecopy/MoveFiles.java b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/movecopy/MoveFiles.java index cfcabd66b1..394a66bec3 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/movecopy/MoveFiles.java +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/movecopy/MoveFiles.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/movecopy/MoveFilesTask.kt b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/movecopy/MoveFilesTask.kt index 988cfb8bde..9d9a3b6566 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/movecopy/MoveFilesTask.kt +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/movecopy/MoveFilesTask.kt @@ -43,7 +43,7 @@ data class MoveFilesReturn( val movedCorrectly: Boolean, val invalidOperation: Boolean, val destinationSize: Long, - val totalSize: Long + val totalSize: Long, ) class MoveFilesTask( @@ -52,9 +52,8 @@ class MoveFilesTask( val currentPath: String, context: Context, val mode: OpenMode, - val paths: ArrayList + val paths: ArrayList, ) : Task { - private val log: Logger = LoggerFactory.getLogger(MoveFilesTask::class.java) private val task: MoveFiles = MoveFiles(files, isRootExplorer, context, mode, paths) @@ -88,7 +87,7 @@ class MoveFilesTask( Toast.makeText( applicationContext, R.string.some_files_failed_invalid_operation, - Toast.LENGTH_LONG + Toast.LENGTH_LONG, ) .show() } @@ -97,10 +96,11 @@ class MoveFilesTask( val targetFiles: MutableList = ArrayList() val sourcesFiles: MutableList = ArrayList() for (f in files[i]) { - val file = HybridFile( - OpenMode.FILE, - paths[i] + "/" + f.getName(applicationContext) - ) + val file = + HybridFile( + OpenMode.FILE, + paths[i] + "/" + f.getName(applicationContext), + ) targetFiles.add(file) } for (hybridFileParcelables in files) { @@ -130,13 +130,16 @@ class MoveFilesTask( } } - private fun onMovedFail(destinationSize: Long, totalBytes: Long) { + private fun onMovedFail( + destinationSize: Long, + totalBytes: Long, + ) { if (totalBytes > 0 && destinationSize < totalBytes) { // destination don't have enough space; return Toast.makeText( applicationContext, applicationContext.resources.getString(R.string.in_safe), - Toast.LENGTH_LONG + Toast.LENGTH_LONG, ) .show() return diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/movecopy/PreparePasteTask.kt b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/movecopy/PreparePasteTask.kt index 4c97e62b0e..178e36ebcc 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/movecopy/PreparePasteTask.kt +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/movecopy/PreparePasteTask.kt @@ -62,7 +62,6 @@ import java.util.LinkedList * BFS on this tree. */ class PreparePasteTask(strongRefMain: MainActivity) { - private lateinit var targetPath: String private var isMove = false private var isRootMode = false @@ -91,7 +90,7 @@ class PreparePasteTask(strongRefMain: MainActivity) { target: String, openMode: OpenMode, isMove: Boolean, - isRootMode: Boolean + isRootMode: Boolean, ) { val intent = Intent(context.get(), CopyService::class.java) intent.putParcelableArrayListExtra(CopyService.TAG_COPY_SOURCES, sourceFiles) @@ -110,7 +109,7 @@ class PreparePasteTask(strongRefMain: MainActivity) { isMove: Boolean, isRootMode: Boolean, openMode: OpenMode, - filesToCopy: ArrayList + filesToCopy: ArrayList, ) { this.targetPath = targetPath this.isMove = isMove @@ -118,12 +117,13 @@ class PreparePasteTask(strongRefMain: MainActivity) { this.openMode = openMode this.filesToCopy = filesToCopy - val isCloudOrRootMode = openMode == OpenMode.OTG || - openMode == OpenMode.GDRIVE || - openMode == OpenMode.DROPBOX || - openMode == OpenMode.BOX || - openMode == OpenMode.ONEDRIVE || - openMode == OpenMode.ROOT + val isCloudOrRootMode = + openMode == OpenMode.OTG || + openMode == OpenMode.GDRIVE || + openMode == OpenMode.DROPBOX || + openMode == OpenMode.BOX || + openMode == OpenMode.ONEDRIVE || + openMode == OpenMode.ROOT if (isCloudOrRootMode) { startService(filesToCopy, targetPath, openMode, isMove, isRootMode) @@ -142,9 +142,10 @@ class PreparePasteTask(strongRefMain: MainActivity) { return } - val isMoveSupported = isMove && - destination.mode == openMode && - MoveFiles.getOperationSupportedFileSystem().contains(openMode) + val isMoveSupported = + isMove && + destination.mode == openMode && + MoveFiles.getOperationSupportedFileSystem().contains(openMode) if (destination.usableSpace < totalBytes && !isMoveSupported @@ -153,17 +154,18 @@ class PreparePasteTask(strongRefMain: MainActivity) { return } @Suppress("DEPRECATION") - progressDialog = ProgressDialog.show( - context.get(), - "", - context.get()?.getString(R.string.checking_conflicts) - ) + progressDialog = + ProgressDialog.show( + context.get(), + "", + context.get()?.getString(R.string.checking_conflicts), + ) checkConflicts( isRootMode, filesToCopy, destination, conflictingFiles, - conflictingDirActionMap + conflictingDirActionMap, ) } @@ -172,7 +174,7 @@ class PreparePasteTask(strongRefMain: MainActivity) { filesToCopy: ArrayList, destination: HybridFile, conflictingFiles: MutableList, - conflictingDirActionMap: HashMap + conflictingDirActionMap: HashMap, ) { coroutineScope.launch { destination.forEachChildrenFile( @@ -186,7 +188,7 @@ class PreparePasteTask(strongRefMain: MainActivity) { } } } - } + }, ) withContext(Dispatchers.Main) { prepareDialog(conflictingFiles, conflictingDirActionMap) @@ -199,7 +201,7 @@ class PreparePasteTask(strongRefMain: MainActivity) { private suspend fun prepareDialog( conflictingFiles: MutableList, - conflictingDirActionMap: HashMap + conflictingDirActionMap: HashMap, ) { if (conflictingFiles.isEmpty()) return @@ -226,7 +228,7 @@ class PreparePasteTask(strongRefMain: MainActivity) { conflictingDirActionMap, copyDialogBinding, dialogBuilder, - checkBox + checkBox, ) } @@ -235,7 +237,7 @@ class PreparePasteTask(strongRefMain: MainActivity) { conflictingDirActionMap: HashMap, copyDialogBinding: CopyDialogBinding, dialogBuilder: MaterialDialog.Builder, - checkBox: AppCompatCheckBox + checkBox: AppCompatCheckBox, ) { val iterator = conflictingFiles.iterator() while (iterator.hasNext()) { @@ -287,7 +289,7 @@ class PreparePasteTask(strongRefMain: MainActivity) { private fun resolveConflict( conflictingFiles: MutableList, conflictingDirActionMap: HashMap, - filesToCopy: ArrayList + filesToCopy: ArrayList, ) = coroutineScope.launch { var index = conflictingFiles.size - 1 if (renameAll) { @@ -332,8 +334,9 @@ class PreparePasteTask(strongRefMain: MainActivity) { } if (filesToCopyPerFolder.isNotEmpty()) { @FolderState - val mode: Int = context.get()?.mainActivityHelper!! - .checkFolder(targetPath, openMode, context.get()) + val mode: Int = + context.get()?.mainActivityHelper!! + .checkFolder(targetPath, openMode, context.get()) if (mode == CAN_CREATE_FILES && !targetPath.contains("otg:/")) { // This is used because in newer devices the user has to accept a permission, // see MainActivity.onActivityResult() @@ -349,7 +352,7 @@ class PreparePasteTask(strongRefMain: MainActivity) { pathsList[foldersIndex], openMode, isMove, - isRootMode + isRootMode, ) } else { fromTask( @@ -359,8 +362,8 @@ class PreparePasteTask(strongRefMain: MainActivity) { targetPath, context.get()!!, openMode, - pathsList - ) + pathsList, + ), ) } } @@ -369,7 +372,7 @@ class PreparePasteTask(strongRefMain: MainActivity) { Toast.makeText( context.get(), context.get()!!.resources.getString(R.string.no_file_overwrite), - Toast.LENGTH_SHORT + Toast.LENGTH_SHORT, ).show() } } @@ -381,7 +384,7 @@ class PreparePasteTask(strongRefMain: MainActivity) { private inner class CopyNode( val path: String, - val filesToCopy: ArrayList + val filesToCopy: ArrayList, ) { private val nextNodes: MutableList = mutableListOf() private var queue: LinkedList? = null @@ -392,12 +395,13 @@ class PreparePasteTask(strongRefMain: MainActivity) { while (iterator.hasNext()) { val hybridFileParcelable = iterator.next() if (conflictingDirActionMap.contains(hybridFileParcelable)) { - val fileAtTarget = HybridFile( - hybridFileParcelable.mode, - path, - hybridFileParcelable.name, - hybridFileParcelable.isDirectory - ) + val fileAtTarget = + HybridFile( + hybridFileParcelable.mode, + path, + hybridFileParcelable.name, + hybridFileParcelable.isDirectory, + ) when (conflictingDirActionMap[hybridFileParcelable]) { Action.RENAME -> { if (hybridFileParcelable.isDirectory) { @@ -410,14 +414,14 @@ class PreparePasteTask(strongRefMain: MainActivity) { nextNodes.add( CopyNode( newPath, - hybridFileParcelable.listFiles(context.get(), isRootMode) - ) + hybridFileParcelable.listFiles(context.get(), isRootMode), + ), ) iterator.remove() } else { filesToCopy[filesToCopy.indexOf(hybridFileParcelable)].name = FilenameHelper.increment( - fileAtTarget + fileAtTarget, ).getName(context.get()) } } @@ -447,8 +451,9 @@ class PreparePasteTask(strongRefMain: MainActivity) { * @return The next unvisited node if available, otherwise returns null. */ fun goToNextNode(): CopyNode? = - if (queue.isNullOrEmpty()) null - else { + if (queue.isNullOrEmpty()) { + null + } else { val node = queue!!.element() val child = getUnvisitedChildNode(visited!!, node) if (child != null) { @@ -463,7 +468,7 @@ class PreparePasteTask(strongRefMain: MainActivity) { private fun getUnvisitedChildNode( visited: Set, - node: CopyNode + node: CopyNode, ): CopyNode? { for (currentNode in node.nextNodes) { if (!visited.contains(currentNode)) { diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/BasicSearch.kt b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/BasicSearch.kt index 09c568164e..46bf493d2d 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/BasicSearch.kt +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/BasicSearch.kt @@ -28,7 +28,7 @@ class BasicSearch( query: String, path: String, searchParameters: SearchParameters, - context: Context + context: Context, ) : FileSearch(query, path, searchParameters) { private val applicationContext = context.applicationContext @@ -37,7 +37,7 @@ class BasicSearch( path, SearchParameter.ROOT in searchParameters, SearchParameter.SHOW_HIDDEN_FILES in searchParameters, - { } + { }, ) { hybridFileParcelable: HybridFileParcelable -> if (SearchParameter.SHOW_HIDDEN_FILES in searchParameters || !hybridFileParcelable.isHidden diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/DeepSearch.kt b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/DeepSearch.kt index 43ba6a0259..227626b161 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/DeepSearch.kt +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/DeepSearch.kt @@ -32,7 +32,7 @@ class DeepSearch( path: String, searchParameters: SearchParameters, context: Context, - private val openMode: OpenMode + private val openMode: OpenMode, ) : FileSearch(query, path, searchParameters) { private val LOG = LoggerFactory.getLogger(DeepSearch::class.java) @@ -59,7 +59,7 @@ class DeepSearch( val nextFile = worklist.removeFirst() nextFile.forEachChildrenFile( applicationContext, - SearchParameter.ROOT in searchParameters + SearchParameter.ROOT in searchParameters, ) { file -> if (!file.isHidden || SearchParameter.SHOW_HIDDEN_FILES in searchParameters) { val resultRange = filter.searchFilter(file.getName(applicationContext)) diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/FileSearch.kt b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/FileSearch.kt index c866ce81f9..31a85e7bbc 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/FileSearch.kt +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/FileSearch.kt @@ -29,7 +29,7 @@ import java.util.regex.Pattern abstract class FileSearch( protected val query: String, protected val path: String, - protected val searchParameters: SearchParameters + protected val searchParameters: SearchParameters, ) { private val mutableFoundFilesLiveData: MutableLiveData> = MutableLiveData() @@ -66,7 +66,7 @@ abstract class FileSearch( */ protected fun publishProgress( file: HybridFileParcelable, - matchRange: MatchRange + matchRange: MatchRange, ) { foundFilesList.add(SearchResult(file, matchRange)) mutableFoundFilesLiveData.postValue(foundFilesList) @@ -75,11 +75,12 @@ abstract class FileSearch( private fun simpleFilter(query: String): SearchFilter = SearchFilter { fileName -> // check case-insensitively if query is contained in fileName - val start = fileName.lowercase(Locale.getDefault()).indexOf( - query.lowercase( - Locale.getDefault() + val start = + fileName.lowercase(Locale.getDefault()).indexOf( + query.lowercase( + Locale.getDefault(), + ), ) - ) if (start >= 0) { start until start + query.length } else { @@ -116,7 +117,7 @@ abstract class FileSearch( // compiles the given query into a Pattern Pattern.compile( bashRegexToJava(query), - Pattern.CASE_INSENSITIVE + Pattern.CASE_INSENSITIVE, ) /** diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/IndexedSearch.kt b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/IndexedSearch.kt index aac138128f..56a1cc63f3 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/IndexedSearch.kt +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/IndexedSearch.kt @@ -31,18 +31,18 @@ class IndexedSearch( query: String, path: String, searchParameters: SearchParameters, - private val cursor: Cursor + private val cursor: Cursor, ) : FileSearch(query, path, searchParameters) { override suspend fun search(filter: SearchFilter) { if (cursor.count > 0 && cursor.moveToFirst()) { do { val nextPath = cursor.getString( - cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATA) + cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATA), ) val displayName = cursor.getString( - cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DISPLAY_NAME) + cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DISPLAY_NAME), ) if (nextPath != null && displayName != null && nextPath.contains(path)) { val resultRange = filter.searchFilter(displayName) @@ -50,7 +50,7 @@ class IndexedSearch( val hybridFileParcelable = RootHelper.generateBaseFile( File(nextPath), - SearchParameter.SHOW_HIDDEN_FILES in searchParameters + SearchParameter.SHOW_HIDDEN_FILES in searchParameters, ) if (hybridFileParcelable != null) { publishProgress(hybridFileParcelable, resultRange) diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/SearchParameter.kt b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/SearchParameter.kt index 8c22765f91..ec52862e84 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/SearchParameter.kt +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/SearchParameter.kt @@ -24,7 +24,8 @@ enum class SearchParameter { ROOT, REGEX, REGEX_MATCHES, - SHOW_HIDDEN_FILES; + SHOW_HIDDEN_FILES, + ; /** * Returns [SearchParameters] containing [this] and [other] diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/SearchParameters.kt b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/SearchParameters.kt index 62104b9e69..23337c5073 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/SearchParameters.kt +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/SearchParameters.kt @@ -27,10 +27,11 @@ typealias SearchParameters = EnumSet /** * Returns [SearchParameters] extended by [other] */ -infix fun SearchParameters.and(other: SearchParameter): SearchParameters = SearchParameters.of( - other, - *this.toTypedArray() -) +infix fun SearchParameters.and(other: SearchParameter): SearchParameters = + SearchParameters.of( + other, + *this.toTypedArray(), + ) /** * Returns [SearchParameters] extended by [other] @@ -44,7 +45,7 @@ fun searchParametersFromBoolean( showHiddenFiles: Boolean = false, isRegexEnabled: Boolean = false, isRegexMatchesEnabled: Boolean = false, - isRoot: Boolean = false + isRoot: Boolean = false, ): SearchParameters { val searchParameterList = mutableListOf() diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/SearchResultListSorter.kt b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/SearchResultListSorter.kt index 517faa68fd..7dfa2b5d06 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/SearchResultListSorter.kt +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/SearchResultListSorter.kt @@ -30,50 +30,53 @@ import java.util.concurrent.TimeUnit class SearchResultListSorter( private val dirArg: DirSortBy, private val sortType: SortType, - private val searchTerm: String + private val searchTerm: String, ) : Comparator { private val fileListSorter: FileListSorter by lazy { FileListSorter(dirArg, sortType) } private val relevanceComparator: Comparator by lazy { Comparator { o1, o2 -> val currentTime = Date().time - val comparator = compareBy { (item, matchRange) -> - // the match percentage of the search term in the name - val matchPercentageScore = - matchRange.size().toDouble() / item.getParcelableName().length.toDouble() + val comparator = + compareBy { (item, matchRange) -> + // the match percentage of the search term in the name + val matchPercentageScore = + matchRange.size().toDouble() / item.getParcelableName().length.toDouble() - // if the name starts with the search term - val startScore = (matchRange.first == 0).toInt() + // if the name starts with the search term + val startScore = (matchRange.first == 0).toInt() - // if the search term is surrounded by separators - // e.g. "my-cat" more relevant than "mysterious" for search term "my" - val wordScore = item.getParcelableName().split('-', '_', '.', ' ').any { - it.contentEquals( - searchTerm, - ignoreCase = true - ) - }.toInt() + // if the search term is surrounded by separators + // e.g. "my-cat" more relevant than "mysterious" for search term "my" + val wordScore = + item.getParcelableName().split('-', '_', '.', ' ').any { + it.contentEquals( + searchTerm, + ignoreCase = true, + ) + }.toInt() - val modificationDate = item.getDate() - // the time difference as minutes - val timeDiff = - TimeUnit.MILLISECONDS.toMinutes(currentTime - modificationDate) - // 30 days as minutes - val relevantModificationPeriod = TimeUnit.DAYS.toMinutes(30) - val timeScore = if (timeDiff < relevantModificationPeriod) { - // if the file was modified within the last 30 days, the recency is normalized - (relevantModificationPeriod - timeDiff) / - relevantModificationPeriod.toDouble() - } else { - // for all older modification time, the recency doesn't change the relevancy - 0.0 - } + val modificationDate = item.getDate() + // the time difference as minutes + val timeDiff = + TimeUnit.MILLISECONDS.toMinutes(currentTime - modificationDate) + // 30 days as minutes + val relevantModificationPeriod = TimeUnit.DAYS.toMinutes(30) + val timeScore = + if (timeDiff < relevantModificationPeriod) { + // if the file was modified within the last 30 days, the recency is normalized + (relevantModificationPeriod - timeDiff) / + relevantModificationPeriod.toDouble() + } else { + // for all older modification time, the recency doesn't change the relevancy + 0.0 + } - 1.2 * matchPercentageScore + - 0.7 * startScore + - 0.7 * wordScore + - 0.6 * timeScore - } + 1.2 * matchPercentageScore + + 0.7 * startScore + + 0.7 * wordScore + + 0.6 * timeScore + } // Reverts the sorting to make most relevant first comparator.compare(o1, o2) * -1 } @@ -81,7 +84,10 @@ class SearchResultListSorter( private fun Boolean.toInt() = if (this) 1 else 0 - override fun compare(result1: SearchResult, result2: SearchResult): Int { + override fun compare( + result1: SearchResult, + result2: SearchResult, + ): Int { return when (sortType.sortBy) { SortBy.RELEVANCE -> relevanceComparator.compare(result1, result2) SortBy.SIZE, SortBy.TYPE, SortBy.LAST_MODIFIED, SortBy.NAME -> diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ssh/GetSshHostFingerprintTask.kt b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ssh/GetSshHostFingerprintTask.kt index 8f7880382c..b30834d4fc 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ssh/GetSshHostFingerprintTask.kt +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ssh/GetSshHostFingerprintTask.kt @@ -27,13 +27,11 @@ class GetSshHostFingerprintTask( private val hostname: String, private val port: Int, private val firstContact: Boolean, - callback: (PublicKey) -> Unit + callback: (PublicKey) -> Unit, ) : AbstractGetHostInfoTask( - hostname, - port, - callback -) { - - override fun getTask(): GetSshHostFingerprintTaskCallable = - GetSshHostFingerprintTaskCallable(hostname, port, firstContact) + hostname, + port, + callback, + ) { + override fun getTask(): GetSshHostFingerprintTaskCallable = GetSshHostFingerprintTaskCallable(hostname, port, firstContact) } diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ssh/GetSshHostFingerprintTaskCallable.kt b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ssh/GetSshHostFingerprintTaskCallable.kt index f2b6a806d1..4bcb09fdbc 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ssh/GetSshHostFingerprintTaskCallable.kt +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ssh/GetSshHostFingerprintTaskCallable.kt @@ -34,34 +34,42 @@ import java.util.concurrent.CountDownLatch class GetSshHostFingerprintTaskCallable( private val hostname: String, private val port: Int, - private val firstContact: Boolean = false + private val firstContact: Boolean = false, ) : Callable { - companion object { @JvmStatic - private val logger: Logger = LoggerFactory.getLogger( - GetSshHostFingerprintTaskCallable::class.java - ) + private val logger: Logger = + LoggerFactory.getLogger( + GetSshHostFingerprintTaskCallable::class.java, + ) } override fun call(): PublicKey { var holder: PublicKey? = null val latch = CountDownLatch(1) - val sshClient = NetCopyClientConnectionPool.sshClientFactory - .create(CustomSshJConfig()).also { - it.connectTimeout = NetCopyClientConnectionPool.CONNECT_TIMEOUT - it.addHostKeyVerifier(object : HostKeyVerifier { - override fun verify(hostname: String?, port: Int, key: PublicKey?): Boolean { - holder = key - latch.countDown() - return true - } - override fun findExistingAlgorithms( - hostname: String?, - port: Int - ): MutableList = Collections.emptyList() - }) - } + val sshClient = + NetCopyClientConnectionPool.sshClientFactory + .create(CustomSshJConfig()).also { + it.connectTimeout = NetCopyClientConnectionPool.CONNECT_TIMEOUT + it.addHostKeyVerifier( + object : HostKeyVerifier { + override fun verify( + hostname: String?, + port: Int, + key: PublicKey?, + ): Boolean { + holder = key + latch.countDown() + return true + } + + override fun findExistingAlgorithms( + hostname: String?, + port: Int, + ): MutableList = Collections.emptyList() + }, + ) + } return runCatching { sshClient.connect(hostname, port) latch.await() diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ssh/PemToKeyPairObservable.kt b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ssh/PemToKeyPairObservable.kt index 501be08903..b4af758b03 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ssh/PemToKeyPairObservable.kt +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ssh/PemToKeyPairObservable.kt @@ -48,13 +48,13 @@ import java.io.StringReader import java.security.KeyPair class PemToKeyPairObservable(private val pemFile: ByteArray) : ObservableOnSubscribe { - - private val converters = arrayOf( - JcaPemToKeyPairConverter(), - OpenSshPemToKeyPairConverter(), - OpenSshV1PemToKeyPairConverter(), - PuttyPrivateKeyToKeyPairConverter() - ) + private val converters = + arrayOf( + JcaPemToKeyPairConverter(), + OpenSshPemToKeyPairConverter(), + OpenSshV1PemToKeyPairConverter(), + PuttyPrivateKeyToKeyPairConverter(), + ) private var passwordFinder: PasswordFinder? = null private var errorMessage: String? = null @@ -75,13 +75,15 @@ class PemToKeyPairObservable(private val pemFile: ByteArray) : ObservableOnSubsc } } if (passwordFinder != null) { - errorMessage = AppConfig - .getInstance() - .getString(R.string.ssh_key_invalid_passphrase) + errorMessage = + AppConfig + .getInstance() + .getString(R.string.ssh_key_invalid_passphrase) } else { - errorMessage = AppConfig - .getInstance() - .getString(R.string.ssh_key_no_decoder_decrypt) + errorMessage = + AppConfig + .getInstance() + .getString(R.string.ssh_key_no_decoder_decrypt) } emitter.onError(IOException(errorMessage)) } @@ -93,14 +95,16 @@ class PemToKeyPairObservable(private val pemFile: ByteArray) : ObservableOnSubsc fun displayPassphraseDialog( exception: Throwable, positiveCallback: (() -> Unit), - negativeCallback: (() -> Unit) + negativeCallback: (() -> Unit), ) { - val builder = MaterialDialog.Builder( - AppConfig.getInstance().mainActivityContext!! - ) - val dialogLayout = DialogSingleedittextBinding.inflate( - LayoutInflater.from(AppConfig.getInstance().mainActivityContext) - ) + val builder = + MaterialDialog.Builder( + AppConfig.getInstance().mainActivityContext!!, + ) + val dialogLayout = + DialogSingleedittextBinding.inflate( + LayoutInflater.from(AppConfig.getInstance().mainActivityContext), + ) val wilTextfield: WarnableTextInputLayout = dialogLayout.singleedittextWarnabletextinputlayout val textfield = dialogLayout.singleedittextInput @@ -112,14 +116,16 @@ class PemToKeyPairObservable(private val pemFile: ByteArray) : ObservableOnSubsc .title(R.string.ssh_key_prompt_passphrase) .positiveText(R.string.ok) .onPositive { dialog: MaterialDialog, which: DialogAction? -> - passwordFinder = object : PasswordFinder { - override fun reqPassword(resource: Resource<*>?): CharArray { - return textfield.text.toString().toCharArray() - } - override fun shouldRetry(resource: Resource<*>?): Boolean { - return false + passwordFinder = + object : PasswordFinder { + override fun reqPassword(resource: Resource<*>?): CharArray { + return textfield.text.toString().toCharArray() + } + + override fun shouldRetry(resource: Resource<*>?): Boolean { + return false + } } - } dialog.dismiss() positiveCallback.invoke() } @@ -134,12 +140,12 @@ class PemToKeyPairObservable(private val pemFile: ByteArray) : ObservableOnSubsc AppConfig.getInstance().mainActivityContext, textfield, wilTextfield, - dialog.getActionButton(DialogAction.POSITIVE) + dialog.getActionButton(DialogAction.POSITIVE), ) { text: String -> if (text.isEmpty()) { WarnableTextInputValidator.ReturnState( WarnableTextInputValidator.ReturnState.STATE_ERROR, - R.string.field_empty + R.string.field_empty, ) } WarnableTextInputValidator.ReturnState() @@ -156,17 +162,18 @@ class PemToKeyPairObservable(private val pemFile: ByteArray) : ObservableOnSubsc AppConfig.getInstance() .resources .getString(R.string.ssh_pem_key_parse_error, result.localizedMessage), - Toast.LENGTH_LONG + Toast.LENGTH_LONG, ) .show() } private abstract inner class PemToKeyPairConverter { - fun convert(source: String): KeyPair? = runCatching { - throwingConvert(source) - }.onFailure { - log.warn("failed to convert pem to keypair", it) - }.getOrNull() + fun convert(source: String): KeyPair? = + runCatching { + throwingConvert(source) + }.onFailure { + log.warn("failed to convert pem to keypair", it) + }.getOrNull() protected abstract fun throwingConvert(source: String?): KeyPair? } diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ssh/SshAuthenticationTask.kt b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ssh/SshAuthenticationTask.kt index d992963289..b2a401fe1a 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ssh/SshAuthenticationTask.kt +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ssh/SshAuthenticationTask.kt @@ -39,9 +39,8 @@ class SshAuthenticationTask( private val hostKey: String, private val username: String, private val password: String? = null, - private val privateKey: KeyPair? = null + private val privateKey: KeyPair? = null, ) : Task { - override fun getTask(): SshAuthenticationTaskCallable = SshAuthenticationTaskCallable(hostname, port, hostKey, username, password, privateKey) @@ -60,11 +59,11 @@ class SshAuthenticationTask( R.string.ssh_connect_failed, hostname, port, - error.localizedMessage ?: error.message - ) + error.localizedMessage ?: error.message, + ), ) } else if (TransportException::class.java - .isAssignableFrom(error.javaClass) + .isAssignableFrom(error.javaClass) ) { val disconnectReason = TransportException::class.java.cast(error)!!.disconnectReason @@ -80,12 +79,12 @@ class SshAuthenticationTask( } else if (password != null) { AppConfig.toast( AppConfig.getInstance(), - R.string.ssh_authentication_failure_password + R.string.ssh_authentication_failure_password, ) } else if (privateKey != null) { AppConfig.toast( AppConfig.getInstance(), - R.string.ssh_authentication_failure_key + R.string.ssh_authentication_failure_key, ) } } diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ssh/SshAuthenticationTaskCallable.kt b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ssh/SshAuthenticationTaskCallable.kt index 0b35d3930c..a67c2fdb7c 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ssh/SshAuthenticationTaskCallable.kt +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ssh/SshAuthenticationTaskCallable.kt @@ -40,23 +40,23 @@ class SshAuthenticationTaskCallable( private val hostKey: String, private val username: String, private val password: String? = null, - private val privateKey: KeyPair? = null + private val privateKey: KeyPair? = null, ) : Callable { - init { require( - true == password?.isNotEmpty() || privateKey != null + true == password?.isNotEmpty() || privateKey != null, ) { "Must provide either password or privateKey" } } override fun call(): SSHClient { - val sshClient = NetCopyClientConnectionPool.sshClientFactory - .create(CustomSshJConfig()).also { - it.addHostKeyVerifier(hostKey) - it.connectTimeout = NetCopyClientConnectionPool.CONNECT_TIMEOUT - } + val sshClient = + NetCopyClientConnectionPool.sshClientFactory + .create(CustomSshJConfig()).also { + it.addHostKeyVerifier(hostKey) + it.connectTimeout = NetCopyClientConnectionPool.CONNECT_TIMEOUT + } return run { sshClient.connect(hostname, port) if (privateKey != null) { @@ -68,7 +68,7 @@ class SshAuthenticationTaskCallable( override fun getPublic(): PublicKey = privateKey.public override fun getType(): KeyType = KeyType.fromKey(public) - } + }, ) sshClient } else { @@ -77,10 +77,10 @@ class SshAuthenticationTaskCallable( decode( PasswordUtil.decryptPassword( AppConfig.getInstance(), - password!! + password!!, ), - UTF_8.name() - ) + UTF_8.name(), + ), ) sshClient } diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/texteditor/read/ReadTextFileCallable.java b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/texteditor/read/ReadTextFileCallable.java index 9090324aac..3611b68a97 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/texteditor/read/ReadTextFileCallable.java +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/texteditor/read/ReadTextFileCallable.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/texteditor/read/ReadTextFileTask.kt b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/texteditor/read/ReadTextFileTask.kt index 244214660f..d6908f036f 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/texteditor/read/ReadTextFileTask.kt +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/texteditor/read/ReadTextFileTask.kt @@ -42,21 +42,21 @@ import java.util.* class ReadTextFileTask( activity: TextEditorActivity, private val textEditorActivityWR: WeakReference, - private val appContextWR: WeakReference + private val appContextWR: WeakReference, ) : Task { - private val log: Logger = LoggerFactory.getLogger(ReadTextFileTask::class.java) private val task: ReadTextFileCallable init { val viewModel: TextEditorActivityViewModel by activity.viewModels() - task = ReadTextFileCallable( - activity.contentResolver, - viewModel.file, - activity.externalCacheDir, - activity.isRootExplorer - ) + task = + ReadTextFileCallable( + activity.contentResolver, + viewModel.file, + activity.externalCacheDir, + activity.isRootExplorer, + ) } override fun getTask(): ReadTextFileCallable = task @@ -66,20 +66,21 @@ class ReadTextFileTask( log.error("Error on text read", error) val applicationContext = appContextWR.get() ?: return - @StringRes val errorMessage: Int = when (error) { - is StreamNotFoundException -> { - R.string.error_file_not_found - } - is IOException -> { - R.string.error_io - } - is OutOfMemoryError -> { - R.string.error_file_too_large + @StringRes val errorMessage: Int = + when (error) { + is StreamNotFoundException -> { + R.string.error_file_not_found + } + is IOException -> { + R.string.error_io + } + is OutOfMemoryError -> { + R.string.error_file_too_large + } + else -> { + R.string.error + } } - else -> { - R.string.error - } - } Toast.makeText(applicationContext, errorMessage, Toast.LENGTH_SHORT).show() val textEditorActivity = textEditorActivityWR.get() ?: return textEditorActivity.dismissLoadingSnackbar() @@ -107,14 +108,15 @@ class ReadTextFileTask( if (isFileInCacheAndNotRoot) { textEditorActivity.setReadOnly() - val snackbar = Snackbar.make( - textEditorActivity.mainTextView, - R.string.file_read_only, - Snackbar.LENGTH_INDEFINITE - ) + val snackbar = + Snackbar.make( + textEditorActivity.mainTextView, + R.string.file_read_only, + Snackbar.LENGTH_INDEFINITE, + ) snackbar.setAction( textEditorActivity.resources.getString(R.string.got_it) - .uppercase(Locale.getDefault()) + .uppercase(Locale.getDefault()), ) { snackbar.dismiss() } snackbar.show() } @@ -127,15 +129,16 @@ class ReadTextFileTask( if (value.fileIsTooLong) { textEditorActivity.setReadOnly() - val snackbar = Snackbar.make( - textEditorActivity.mainTextView, - textEditorActivity.resources - .getString(R.string.file_too_long, ReadTextFileCallable.MAX_FILE_SIZE_CHARS), - Snackbar.LENGTH_INDEFINITE - ) + val snackbar = + Snackbar.make( + textEditorActivity.mainTextView, + textEditorActivity.resources + .getString(R.string.file_too_long, ReadTextFileCallable.MAX_FILE_SIZE_CHARS), + Snackbar.LENGTH_INDEFINITE, + ) snackbar.setAction( textEditorActivity.resources.getString(R.string.got_it) - .uppercase(Locale.getDefault()) + .uppercase(Locale.getDefault()), ) { snackbar.dismiss() } snackbar.show() } diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/texteditor/write/WriteTextFileCallable.java b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/texteditor/write/WriteTextFileCallable.java index e4be052993..06dcc7df03 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/texteditor/write/WriteTextFileCallable.java +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/texteditor/write/WriteTextFileCallable.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. @@ -72,7 +72,9 @@ public WriteTextFileCallable( @WorkerThread @Override public Unit call() - throws IOException, StreamNotFoundException, ShellNotRunningException, + throws IOException, + StreamNotFoundException, + ShellNotRunningException, IllegalArgumentException { OutputStream outputStream; File destFile = null; diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/texteditor/write/WriteTextFileTask.kt b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/texteditor/write/WriteTextFileTask.kt index e53f8ba57d..8345092c12 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/texteditor/write/WriteTextFileTask.kt +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/texteditor/write/WriteTextFileTask.kt @@ -40,23 +40,23 @@ class WriteTextFileTask( activity: TextEditorActivity, private val editTextString: String, private val textEditorActivityWR: WeakReference, - private val appContextWR: WeakReference + private val appContextWR: WeakReference, ) : Task { - private var log: Logger = LoggerFactory.getLogger(WriteTextFileTask::class.java) private val task: WriteTextFileCallable init { val viewModel: TextEditorActivityViewModel by activity.viewModels() - task = WriteTextFileCallable( - activity, - activity.contentResolver, - viewModel.file, - editTextString, - viewModel.cacheFile, - activity.isRootExplorer - ) + task = + WriteTextFileCallable( + activity, + activity.contentResolver, + viewModel.file, + editTextString, + viewModel.cacheFile, + activity.isRootExplorer, + ) } override fun getTask(): WriteTextFileCallable = task @@ -66,20 +66,21 @@ class WriteTextFileTask( log.error("Error on text write", error) val applicationContext = appContextWR.get() ?: return - @StringRes val errorMessage: Int = when (error) { - is StreamNotFoundException -> { - R.string.error_file_not_found - } - is IOException -> { - R.string.error_io - } - is ShellNotRunningException -> { - R.string.root_failure - } - else -> { - R.string.error + @StringRes val errorMessage: Int = + when (error) { + is StreamNotFoundException -> { + R.string.error_file_not_found + } + is IOException -> { + R.string.error_io + } + is ShellNotRunningException -> { + R.string.root_failure + } + else -> { + R.string.error + } } - } Toast.makeText(applicationContext, errorMessage, Toast.LENGTH_SHORT).show() } diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/broadcast_receivers/PackageReceiver.java b/app/src/main/java/com/amaze/filemanager/asynchronous/broadcast_receivers/PackageReceiver.java index c8cf9bf619..9128b78e2c 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/broadcast_receivers/PackageReceiver.java +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/broadcast_receivers/PackageReceiver.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/handlers/FileHandler.kt b/app/src/main/java/com/amaze/filemanager/asynchronous/handlers/FileHandler.kt index 64069eb375..f3132bff9b 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/handlers/FileHandler.kt +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/handlers/FileHandler.kt @@ -37,10 +37,10 @@ import java.lang.ref.WeakReference class FileHandler( mainFragment: MainFragment, private val listView: RecyclerView, - private val useThumbs: Boolean + private val useThumbs: Boolean, ) : Handler( - Looper.getMainLooper() -) { + Looper.getMainLooper(), + ) { private val mainFragment: WeakReference = WeakReference(mainFragment) private val log: Logger = LoggerFactory.getLogger(FileHandler::class.java) @@ -63,17 +63,19 @@ class FileHandler( log.error("Path is empty for file") return } - val fileCreated = HybridFile( - mainFragmentViewModel.openMode, - "${main.currentPath}/$path" - ) + val fileCreated = + HybridFile( + mainFragmentViewModel.openMode, + "${main.currentPath}/$path", + ) val newElement = fileCreated.generateLayoutElement(main.requireContext(), useThumbs) main.elementsList?.add(newElement) } CustomFileObserver.DELETED_ITEM -> { - val index = elementsList.withIndex().find { - File(it.value.desc).name == path - }?.index + val index = + elementsList.withIndex().find { + File(it.value.desc).name == path + }?.index if (index != null) { main.elementsList?.removeAt(index) @@ -89,7 +91,7 @@ class FileHandler( // no item left in list, recreate views main.reloadListElements( true, - !mainFragmentViewModel.isList + !mainFragmentViewModel.isList, ) } else { listView.adapter?.let { diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/loaders/AppListLoader.java b/app/src/main/java/com/amaze/filemanager/asynchronous/loaders/AppListLoader.java index 82ea7df9ae..95ce11a101 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/loaders/AppListLoader.java +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/loaders/AppListLoader.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/management/ServiceWatcherUtil.java b/app/src/main/java/com/amaze/filemanager/asynchronous/management/ServiceWatcherUtil.java index 43b264d421..165a050710 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/management/ServiceWatcherUtil.java +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/management/ServiceWatcherUtil.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/services/AbstractProgressiveService.java b/app/src/main/java/com/amaze/filemanager/asynchronous/services/AbstractProgressiveService.java index 73ec722b0e..c952fe875a 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/services/AbstractProgressiveService.java +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/services/AbstractProgressiveService.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/services/CopyService.java b/app/src/main/java/com/amaze/filemanager/asynchronous/services/CopyService.java index cf07cdb8c2..58ae8a0448 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/services/CopyService.java +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/services/CopyService.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/services/DecryptService.java b/app/src/main/java/com/amaze/filemanager/asynchronous/services/DecryptService.java index e392a607e9..494d2452f4 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/services/DecryptService.java +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/services/DecryptService.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/services/EncryptService.java b/app/src/main/java/com/amaze/filemanager/asynchronous/services/EncryptService.java index 28e1a1e128..71980ec11d 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/services/EncryptService.java +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/services/EncryptService.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/services/ExtractService.java b/app/src/main/java/com/amaze/filemanager/asynchronous/services/ExtractService.java index e836e9cb94..28d1cdca05 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/services/ExtractService.java +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/services/ExtractService.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/services/ZipService.kt b/app/src/main/java/com/amaze/filemanager/asynchronous/services/ZipService.kt index 2109d92461..f5b81d95e8 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/services/ZipService.kt +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/services/ZipService.kt @@ -63,7 +63,6 @@ import java.util.zip.ZipOutputStream @Suppress("TooManyFunctions") // Hack. class ZipService : AbstractProgressiveService() { - private val log: Logger = LoggerFactory.getLogger(ZipService::class.java) private val mBinder: IBinder = ObtainableServiceBinder(this) @@ -85,7 +84,11 @@ class ZipService : AbstractProgressiveService() { registerReceiver(receiver1, IntentFilter(KEY_COMPRESS_BROADCAST_CANCEL)) } - override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int { + override fun onStartCommand( + intent: Intent, + flags: Int, + startId: Int, + ): Int { val mZipPath = intent.getStringExtra(KEY_COMPRESS_PATH) val baseFiles: ArrayList = intent.getParcelableArrayListExtra(KEY_COMPRESS_FILES)!! @@ -99,46 +102,48 @@ class ZipService : AbstractProgressiveService() { } } sharedPreferences = PreferenceManager.getDefaultSharedPreferences(applicationContext) - accentColor = (application as AppConfig) - .utilsProvider - .colorPreference - .getCurrentUserColorPreferences(this, sharedPreferences).accent - - val notificationIntent = Intent(this, MainActivity::class.java) - .putExtra(MainActivity.KEY_INTENT_PROCESS_VIEWER, true) - val pendingIntent = PendingIntent.getActivity( - this, - 0, - notificationIntent, - getPendingIntentFlag(0) - ) - + accentColor = + (application as AppConfig) + .utilsProvider + .colorPreference + .getCurrentUserColorPreferences(this, sharedPreferences).accent + val notificationIntent = + Intent(this, MainActivity::class.java) + .putExtra(MainActivity.KEY_INTENT_PROCESS_VIEWER, true) + val pendingIntent = + PendingIntent.getActivity( + this, + 0, + notificationIntent, + getPendingIntentFlag(0), + ) customSmallContentViews = RemoteViews(packageName, R.layout.notification_service_small) customBigContentViews = RemoteViews(packageName, R.layout.notification_service_big) - val stopIntent = Intent(KEY_COMPRESS_BROADCAST_CANCEL) - val stopPendingIntent = PendingIntent.getBroadcast( - applicationContext, - 1234, - stopIntent, - getPendingIntentFlag(FLAG_UPDATE_CURRENT) - ) - val action = NotificationCompat.Action( - R.drawable.ic_zip_box_grey, - getString(R.string.stop_ftp), - stopPendingIntent - ) - mBuilder = NotificationCompat.Builder(this, NotificationConstants.CHANNEL_NORMAL_ID) - .setSmallIcon(R.drawable.ic_zip_box_grey) - .setContentIntent(pendingIntent) - .setCustomContentView(customSmallContentViews) - .setCustomBigContentView(customBigContentViews) - .setCustomHeadsUpContentView(customSmallContentViews) - .setStyle(NotificationCompat.DecoratedCustomViewStyle()) - .addAction(action) - .setOngoing(true) - .setColor(accentColor) - + val stopPendingIntent = + PendingIntent.getBroadcast( + applicationContext, + 1234, + stopIntent, + getPendingIntentFlag(FLAG_UPDATE_CURRENT), + ) + val action = + NotificationCompat.Action( + R.drawable.ic_zip_box_grey, + getString(R.string.stop_ftp), + stopPendingIntent, + ) + mBuilder = + NotificationCompat.Builder(this, NotificationConstants.CHANNEL_NORMAL_ID) + .setSmallIcon(R.drawable.ic_zip_box_grey) + .setContentIntent(pendingIntent) + .setCustomContentView(customSmallContentViews) + .setCustomBigContentView(customBigContentViews) + .setCustomHeadsUpContentView(customSmallContentViews) + .setStyle(NotificationCompat.DecoratedCustomViewStyle()) + .addAction(action) + .setOngoing(true) + .setColor(accentColor) NotificationConstants.setMetadata(this, mBuilder, NotificationConstants.TYPE_NORMAL) startForeground(NotificationConstants.ZIP_ID, mBuilder.build()) initNotificationViews() @@ -178,9 +183,8 @@ class ZipService : AbstractProgressiveService() { inner class CompressTask( private val zipService: ZipService, private val baseFiles: ArrayList, - private val zipPath: String + private val zipPath: String, ) { - private lateinit var zos: ZipOutputStream private lateinit var watcherUtil: ServiceWatcherUtil @@ -202,13 +206,13 @@ class ZipService : AbstractProgressiveService() { baseFiles[0].getName(applicationContext), baseFiles.size, totalBytes, - false + false, ) execute( emitter, zipService.applicationContext, FileUtils.hybridListToFileArrayList(baseFiles), - zipPath + zipPath, ) emitter.onComplete() @@ -218,12 +222,13 @@ class ZipService : AbstractProgressiveService() { .subscribe( { watcherUtil.stopWatch() - val intent = Intent(MainActivity.KEY_INTENT_LOAD_LIST) - .putExtra(MainActivity.KEY_INTENT_LOAD_LIST_FILE, zipPath) + val intent = + Intent(MainActivity.KEY_INTENT_LOAD_LIST) + .putExtra(MainActivity.KEY_INTENT_LOAD_LIST_FILE, zipPath) zipService.sendBroadcast(intent) zipService.stopSelf() }, - { log.error(it.message ?: "ZipService.CompressAsyncTask.compress failed") } + { log.error(it.message ?: "ZipService.CompressAsyncTask.compress failed") }, ) } @@ -243,7 +248,7 @@ class ZipService : AbstractProgressiveService() { emitter: CompletableEmitter, context: Context, baseFiles: ArrayList, - zipPath: String + zipPath: String, ) { val out: OutputStream? val zipDirectory = File(zipPath) @@ -266,7 +271,7 @@ class ZipService : AbstractProgressiveService() { zos.close() context.sendBroadcast( Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE) - .setData(Uri.fromFile(zipDirectory)) + .setData(Uri.fromFile(zipDirectory)), ) } catch (e: IOException) { log.warn("failed to close zip streams", e) @@ -275,7 +280,10 @@ class ZipService : AbstractProgressiveService() { } @Throws(IOException::class, NullPointerException::class, ZipException::class) - private fun compressFile(file: File, path: String) { + private fun compressFile( + file: File, + path: String, + ) { if (progressHandler.cancelled) return if (!file.isDirectory) { zos.putNextEntry(createZipEntry(file, path)) @@ -286,7 +294,9 @@ class ZipService : AbstractProgressiveService() { if (!progressHandler.cancelled) { zos.write(buf, 0, len) ServiceWatcherUtil.position += len.toLong() - } else break + } else { + break + } } } return @@ -304,13 +314,17 @@ class ZipService : AbstractProgressiveService() { "$path/" } - private fun createZipEntry(file: File, path: String): ZipEntry = + private fun createZipEntry( + file: File, + path: String, + ): ZipEntry = ZipEntry("${createZipEntryPrefixWith(path)}${file.name}").apply { if (SDK_INT >= O) { - val attrs = Files.readAttributes( - Paths.get(file.absolutePath), - BasicFileAttributes::class.java - ) + val attrs = + Files.readAttributes( + Paths.get(file.absolutePath), + BasicFileAttributes::class.java, + ) setCreationTime(attrs.creationTime()) .setLastAccessTime(attrs.lastAccessTime()) .lastModifiedTime = attrs.lastModifiedTime() @@ -323,11 +337,15 @@ class ZipService : AbstractProgressiveService() { * Class used for the client Binder. Because we know this service always runs in the same process * as its clients, we don't need to deal with IPC. */ - private val receiver1: BroadcastReceiver = object : BroadcastReceiver() { - override fun onReceive(context: Context, intent: Intent) { - progressHandler.cancelled = true + private val receiver1: BroadcastReceiver = + object : BroadcastReceiver() { + override fun onReceive( + context: Context, + intent: Intent, + ) { + progressHandler.cancelled = true + } } - } override fun onBind(arg0: Intent): IBinder = mBinder diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/services/ftp/CommandFactoryFactory.kt b/app/src/main/java/com/amaze/filemanager/asynchronous/services/ftp/CommandFactoryFactory.kt index 018861df7b..ef13285490 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/services/ftp/CommandFactoryFactory.kt +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/services/ftp/CommandFactoryFactory.kt @@ -31,7 +31,6 @@ import org.apache.ftpserver.command.CommandFactoryFactory * Custom [CommandFactory] factory with custom commands. */ object CommandFactoryFactory { - /** * Encapsulate custom [CommandFactory] construction logic. Append custom AVBL and PWD command, * as well as feature flag in FEAT command if not using [AndroidFtpFileSystemView]. diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/services/ftp/FtpReceiver.kt b/app/src/main/java/com/amaze/filemanager/asynchronous/services/ftp/FtpReceiver.kt index bee0985693..0903585dd1 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/services/ftp/FtpReceiver.kt +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/services/ftp/FtpReceiver.kt @@ -29,10 +29,12 @@ import com.amaze.filemanager.asynchronous.services.ftp.FtpService.Companion.isRu /** Created by yashwanthreddyg on 09-06-2016. */ class FtpReceiver : BroadcastReceiver() { - private val TAG = FtpReceiver::class.java.simpleName - override fun onReceive(context: Context, intent: Intent) { + override fun onReceive( + context: Context, + intent: Intent, + ) { if (DEBUG) { Log.v(TAG, "Received: ${intent.action}") } @@ -43,7 +45,9 @@ class FtpReceiver : BroadcastReceiver() { context.startService(service) } else if (intent.action == FtpService.ACTION_STOP_FTPSERVER) { context.stopService(service) - } else Unit + } else { + Unit + } }.onFailure { Log.e(TAG, "Failed to start/stop on intent ${it.message}") } diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/services/ftp/FtpService.kt b/app/src/main/java/com/amaze/filemanager/asynchronous/services/ftp/FtpService.kt index 37e1c68589..893dedbaa4 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/services/ftp/FtpService.kt +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/services/ftp/FtpService.kt @@ -81,7 +81,10 @@ class FtpService : Service(), Runnable { // Service will broadcast via event bus when server start/stop enum class FtpReceiverActions { - STARTED, STARTED_FROM_TILE, STOPPED, FAILED_TO_START + STARTED, + STARTED_FROM_TILE, + STOPPED, + FAILED_TO_START, } private var username: String? = null @@ -90,7 +93,11 @@ class FtpService : Service(), Runnable { private var isStartedByTile = false private lateinit var wakeLock: PowerManager.WakeLock - override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + override fun onStartCommand( + intent: Intent?, + flags: Int, + startId: Int, + ): Int { isStartedByTile = true == intent?.getBooleanExtra(TAG_STARTED_BY_TILE, false) var attempts = 10 while (serverThread != null) { @@ -140,17 +147,19 @@ class FtpService : Service(), Runnable { commandFactory = CommandFactoryFactory.create(shouldUseAndroidFileSystem) - val usernamePreference = preferences.getString( - KEY_PREFERENCE_USERNAME, - DEFAULT_USERNAME - ) + val usernamePreference = + preferences.getString( + KEY_PREFERENCE_USERNAME, + DEFAULT_USERNAME, + ) if (usernamePreference != DEFAULT_USERNAME) { username = usernamePreference runCatching { - password = PasswordUtil.decryptPassword( - applicationContext, - preferences.getString(KEY_PREFERENCE_PASSWORD, "")!! - ) + password = + PasswordUtil.decryptPassword( + applicationContext, + preferences.getString(KEY_PREFERENCE_PASSWORD, "")!!, + ) isPasswordProtected = true }.onFailure { log.warn("failed to decrypt password in ftp service", it) @@ -167,10 +176,11 @@ class FtpService : Service(), Runnable { user.name = username user.password = password } - user.homeDirectory = preferences.getString( - KEY_PREFERENCE_PATH, - defaultPath(this@FtpService) - ) + user.homeDirectory = + preferences.getString( + KEY_PREFERENCE_PATH, + defaultPath(this@FtpService), + ) if (!preferences.getBoolean(KEY_PREFERENCE_READONLY, false)) { user.authorities = listOf(WritePermission()) } @@ -184,20 +194,23 @@ class FtpService : Service(), Runnable { val keyStore = KeyStore.getInstance("BKS") val keyStorePassword = BuildConfig.FTP_SERVER_KEYSTORE_PASSWORD.toCharArray() keyStore.load(resources.openRawResource(R.raw.key), keyStorePassword) - val keyManagerFactory = KeyManagerFactory - .getInstance(KeyManagerFactory.getDefaultAlgorithm()) + val keyManagerFactory = + KeyManagerFactory + .getInstance(KeyManagerFactory.getDefaultAlgorithm()) keyManagerFactory.init(keyStore, keyStorePassword) - val trustManagerFactory = TrustManagerFactory - .getInstance(TrustManagerFactory.getDefaultAlgorithm()) + val trustManagerFactory = + TrustManagerFactory + .getInstance(TrustManagerFactory.getDefaultAlgorithm()) trustManagerFactory.init(keyStore) - fac.sslConfiguration = DefaultSslConfiguration( - keyManagerFactory, - trustManagerFactory, - ClientAuth.WANT, - "TLS", - enabledCipherSuites, - "ftpserver" - ) + fac.sslConfiguration = + DefaultSslConfiguration( + keyManagerFactory, + trustManagerFactory, + ClientAuth.WANT, + "TLS", + enabledCipherSuites, + "ftpserver", + ) fac.isImplicitSsl = true } catch (e: GeneralSecurityException) { preferences.edit().putBoolean(KEY_PREFERENCE_SECURE, false).apply() @@ -210,17 +223,18 @@ class FtpService : Service(), Runnable { addListener("default", fac.createListener()) runCatching { - server = createServer().apply { - start() - EventBus.getDefault() - .post( - if (isStartedByTile) { - FtpReceiverActions.STARTED_FROM_TILE - } else { - FtpReceiverActions.STARTED - } - ) - } + server = + createServer().apply { + start() + EventBus.getDefault() + .post( + if (isStartedByTile) { + FtpReceiverActions.STARTED_FROM_TILE + } else { + FtpReceiverActions.STARTED + }, + ) + } }.onFailure { EventBus.getDefault().post(FtpReceiverActions.FAILED_TO_START) } @@ -248,12 +262,13 @@ class FtpService : Service(), Runnable { super.onTaskRemoved(rootIntent) val restartService = Intent(applicationContext, this.javaClass).setPackage(packageName) val flag = getPendingIntentFlag(FLAG_ONE_SHOT) - val restartServicePI = PendingIntent.getService( - applicationContext, - 1, - restartService, - flag - ) + val restartServicePI = + PendingIntent.getService( + applicationContext, + 1, + restartService, + flag, + ) val alarmService = applicationContext.getSystemService(ALARM_SERVICE) as AlarmManager alarmService[AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 2000] = restartServicePI @@ -289,33 +304,34 @@ class FtpService : Service(), Runnable { private lateinit var _enabledCipherSuites: Array init { - _enabledCipherSuites = LinkedList().apply { - if (SDK_INT >= Q) { - add("TLS_AES_128_GCM_SHA256") - add("TLS_AES_256_GCM_SHA384") - add("TLS_CHACHA20_POLY1305_SHA256") - } - if (SDK_INT >= N) { - add("TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256") - add("TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256") - } - if (SDK_INT >= LOLLIPOP) { - add("TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA") - add("TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256") - add("TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA") - add("TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384") - add("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA") - add("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256") - add("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA") - add("TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384") - add("TLS_RSA_WITH_AES_128_GCM_SHA256") - add("TLS_RSA_WITH_AES_256_GCM_SHA384") - } - if (SDK_INT < LOLLIPOP) { - add("TLS_RSA_WITH_AES_128_CBC_SHA") - add("TLS_RSA_WITH_AES_256_CBC_SHA") - } - }.toTypedArray() + _enabledCipherSuites = + LinkedList().apply { + if (SDK_INT >= Q) { + add("TLS_AES_128_GCM_SHA256") + add("TLS_AES_256_GCM_SHA384") + add("TLS_CHACHA20_POLY1305_SHA256") + } + if (SDK_INT >= N) { + add("TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256") + add("TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256") + } + if (SDK_INT >= LOLLIPOP) { + add("TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA") + add("TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256") + add("TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA") + add("TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384") + add("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA") + add("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256") + add("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA") + add("TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384") + add("TLS_RSA_WITH_AES_128_GCM_SHA256") + add("TLS_RSA_WITH_AES_256_GCM_SHA384") + } + if (SDK_INT < LOLLIPOP) { + add("TLS_RSA_WITH_AES_128_CBC_SHA") + add("TLS_RSA_WITH_AES_256_CBC_SHA") + } + }.toTypedArray() } /** @@ -342,11 +358,11 @@ class FtpService : Service(), Runnable { @JvmStatic fun defaultPath(context: Context): String { return if (PreferenceManager.getDefaultSharedPreferences(context) - .getBoolean(KEY_PREFERENCE_SAF_FILESYSTEM, false) && SDK_INT > M + .getBoolean(KEY_PREFERENCE_SAF_FILESYSTEM, false) && SDK_INT > M ) { DocumentsContract.buildTreeDocumentUri( "com.android.externalstorage.documents", - "primary:" + "primary:", ).toString() } else { Environment.getExternalStorageDirectory().absolutePath diff --git a/app/src/main/java/com/amaze/filemanager/asynchronous/services/ftp/FtpTileService.java b/app/src/main/java/com/amaze/filemanager/asynchronous/services/ftp/FtpTileService.java index 01e74981b3..d0de75487b 100644 --- a/app/src/main/java/com/amaze/filemanager/asynchronous/services/ftp/FtpTileService.java +++ b/app/src/main/java/com/amaze/filemanager/asynchronous/services/ftp/FtpTileService.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/crashreport/AcraReportSender.kt b/app/src/main/java/com/amaze/filemanager/crashreport/AcraReportSender.kt index e528aa7630..0b599119b6 100644 --- a/app/src/main/java/com/amaze/filemanager/crashreport/AcraReportSender.kt +++ b/app/src/main/java/com/amaze/filemanager/crashreport/AcraReportSender.kt @@ -26,16 +26,18 @@ import org.acra.data.CrashReportData import org.acra.sender.ReportSender class AcraReportSender : ReportSender { - - override fun send(context: Context, errorContent: CrashReportData) { + override fun send( + context: Context, + errorContent: CrashReportData, + ) { ErrorActivity.reportError( context, errorContent, ErrorActivity.ErrorInfo.make( ErrorActivity.ERROR_UI_ERROR, "Application crash", - R.string.app_ui_crash - ) + R.string.app_ui_crash, + ), ) } diff --git a/app/src/main/java/com/amaze/filemanager/crashreport/AcraReportSenderFactory.kt b/app/src/main/java/com/amaze/filemanager/crashreport/AcraReportSenderFactory.kt index 56927b50ca..6fa9872961 100644 --- a/app/src/main/java/com/amaze/filemanager/crashreport/AcraReportSenderFactory.kt +++ b/app/src/main/java/com/amaze/filemanager/crashreport/AcraReportSenderFactory.kt @@ -26,7 +26,10 @@ import org.acra.sender.ReportSender import org.acra.sender.ReportSenderFactory class AcraReportSenderFactory : ReportSenderFactory { - override fun create(context: Context, config: CoreConfiguration): ReportSender { + override fun create( + context: Context, + config: CoreConfiguration, + ): ReportSender { return AcraReportSender() } diff --git a/app/src/main/java/com/amaze/filemanager/crashreport/ErrorActivity.java b/app/src/main/java/com/amaze/filemanager/crashreport/ErrorActivity.java index 7921a34c40..331a00d6d7 100644 --- a/app/src/main/java/com/amaze/filemanager/crashreport/ErrorActivity.java +++ b/app/src/main/java/com/amaze/filemanager/crashreport/ErrorActivity.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/database/CloudContract.java b/app/src/main/java/com/amaze/filemanager/database/CloudContract.java index f959fe2ab0..533f1b2e74 100644 --- a/app/src/main/java/com/amaze/filemanager/database/CloudContract.java +++ b/app/src/main/java/com/amaze/filemanager/database/CloudContract.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/database/CloudHandler.java b/app/src/main/java/com/amaze/filemanager/database/CloudHandler.java index bdedf6d706..ad826679de 100644 --- a/app/src/main/java/com/amaze/filemanager/database/CloudHandler.java +++ b/app/src/main/java/com/amaze/filemanager/database/CloudHandler.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/database/CryptHandler.kt b/app/src/main/java/com/amaze/filemanager/database/CryptHandler.kt index 1cef00b4cc..82cb9cf820 100644 --- a/app/src/main/java/com/amaze/filemanager/database/CryptHandler.kt +++ b/app/src/main/java/com/amaze/filemanager/database/CryptHandler.kt @@ -28,7 +28,6 @@ import org.slf4j.LoggerFactory /** Created by vishal on 15/4/17. */ object CryptHandler { - private val log: Logger = LoggerFactory.getLogger(CryptHandler::class.java) private val database: ExplorerDatabase = AppConfig.getInstance().explorerDatabase @@ -49,7 +48,10 @@ object CryptHandler { /** * Update specified new [EncryptedEntry] in database. */ - fun updateEntry(oldEncryptedEntry: EncryptedEntry, newEncryptedEntry: EncryptedEntry) { + fun updateEntry( + oldEncryptedEntry: EncryptedEntry, + newEncryptedEntry: EncryptedEntry, + ) { database.encryptedEntryDao().update(newEncryptedEntry).subscribeOn(Schedulers.io()) .subscribe() } diff --git a/app/src/main/java/com/amaze/filemanager/database/ExplorerDatabase.kt b/app/src/main/java/com/amaze/filemanager/database/ExplorerDatabase.kt index 65c9ec90e1..52b6fea189 100644 --- a/app/src/main/java/com/amaze/filemanager/database/ExplorerDatabase.kt +++ b/app/src/main/java/com/amaze/filemanager/database/ExplorerDatabase.kt @@ -44,11 +44,10 @@ import com.amaze.filemanager.database.models.explorer.Tab */ @Database( entities = [Tab::class, Sort::class, EncryptedEntry::class, CloudEntry::class], - version = ExplorerDatabase.DATABASE_VERSION + version = ExplorerDatabase.DATABASE_VERSION, ) @Suppress("StringLiteralDuplication", "ComplexMethod", "LongMethod") abstract class ExplorerDatabase : RoomDatabase() { - /** * Returns DAO for [Tab] objects. */ @@ -94,233 +93,243 @@ abstract class ExplorerDatabase : RoomDatabase() { private const val TEMP_TABLE_PREFIX = "temp_" // 1->2: add encrypted table (66f08f34) - internal val MIGRATION_1_2: Migration = object : Migration(1, 2) { - override fun migrate(database: SupportSQLiteDatabase) { - val CREATE_TABLE_ENCRYPTED = ( - "CREATE TABLE " + - TABLE_ENCRYPTED + - "(" + - COLUMN_ENCRYPTED_ID + - " INTEGER PRIMARY KEY," + - COLUMN_ENCRYPTED_PATH + - " TEXT," + - COLUMN_ENCRYPTED_PASSWORD + - " TEXT" + - ")" + internal val MIGRATION_1_2: Migration = + object : Migration(1, 2) { + override fun migrate(database: SupportSQLiteDatabase) { + val CREATE_TABLE_ENCRYPTED = ( + "CREATE TABLE " + + TABLE_ENCRYPTED + + "(" + + COLUMN_ENCRYPTED_ID + + " INTEGER PRIMARY KEY," + + COLUMN_ENCRYPTED_PATH + + " TEXT," + + COLUMN_ENCRYPTED_PASSWORD + + " TEXT" + + ")" ) - database.execSQL(CREATE_TABLE_ENCRYPTED) + database.execSQL(CREATE_TABLE_ENCRYPTED) + } } - } // 2->3: add cloud table (8a5ced1b) - internal val MIGRATION_2_3: Migration = object : Migration(2, 3) { - override fun migrate(database: SupportSQLiteDatabase) { - val CREATE_TABLE_CLOUD = ( - "CREATE TABLE " + - TABLE_CLOUD_PERSIST + - "(" + - COLUMN_CLOUD_ID + - " INTEGER PRIMARY KEY," + - COLUMN_CLOUD_SERVICE + - " INTEGER," + - COLUMN_CLOUD_PERSIST + - " TEXT" + - ")" + internal val MIGRATION_2_3: Migration = + object : Migration(2, 3) { + override fun migrate(database: SupportSQLiteDatabase) { + val CREATE_TABLE_CLOUD = ( + "CREATE TABLE " + + TABLE_CLOUD_PERSIST + + "(" + + COLUMN_CLOUD_ID + + " INTEGER PRIMARY KEY," + + COLUMN_CLOUD_SERVICE + + " INTEGER," + + COLUMN_CLOUD_PERSIST + + " TEXT" + + ")" ) - database.execSQL(CREATE_TABLE_CLOUD) + database.execSQL(CREATE_TABLE_CLOUD) + } } - } // 3->4: same as 2->3 (765140f6) - internal val MIGRATION_3_4: Migration = object : Migration(3, 4) { - override fun migrate(database: SupportSQLiteDatabase) = Unit - } + internal val MIGRATION_3_4: Migration = + object : Migration(3, 4) { + override fun migrate(database: SupportSQLiteDatabase) = Unit + } // 4->5: same as 3->4, same as 2->3 (37357436) - internal val MIGRATION_4_5: Migration = object : Migration(4, 5) { - override fun migrate(database: SupportSQLiteDatabase) = Unit - } + internal val MIGRATION_4_5: Migration = + object : Migration(4, 5) { + override fun migrate(database: SupportSQLiteDatabase) = Unit + } // 5->6: add sort table (fe7c0aba) - internal val MIGRATION_5_6: Migration = object : Migration(5, 6) { - override fun migrate(database: SupportSQLiteDatabase) { - database.execSQL( - "CREATE TABLE " + - TABLE_SORT + - "(" + - COLUMN_SORT_PATH + - " TEXT PRIMARY KEY," + - COLUMN_SORT_TYPE + - " INTEGER" + - ")" - ) + internal val MIGRATION_5_6: Migration = + object : Migration(5, 6) { + override fun migrate(database: SupportSQLiteDatabase) { + database.execSQL( + "CREATE TABLE " + + TABLE_SORT + + "(" + + COLUMN_SORT_PATH + + " TEXT PRIMARY KEY," + + COLUMN_SORT_TYPE + + " INTEGER" + + ")", + ) + } } - } - internal val MIGRATION_6_7: Migration = object : Migration(6, 7) { - override fun migrate(database: SupportSQLiteDatabase) { - database.execSQL( - "CREATE TABLE " + - TEMP_TABLE_PREFIX + - TABLE_TAB + - "(" + - COLUMN_TAB_NO + - " INTEGER PRIMARY KEY NOT NULL, " + - COLUMN_PATH + - " TEXT, " + - COLUMN_HOME + - " TEXT)" - ) - database.execSQL( - "INSERT INTO " + - TEMP_TABLE_PREFIX + - TABLE_TAB + - "(" + - COLUMN_TAB_NO + - "," + - COLUMN_PATH + - "," + - COLUMN_HOME + - ")" + - " SELECT " + - COLUMN_TAB_NO + - "," + - COLUMN_PATH + - "," + - COLUMN_HOME + - " FROM " + - TABLE_TAB - ) - database.execSQL("DROP TABLE $TABLE_TAB") - database.execSQL( - "ALTER TABLE $TEMP_TABLE_PREFIX$TABLE_TAB RENAME TO $TABLE_TAB" - ) - database.execSQL( - "CREATE TABLE " + - TEMP_TABLE_PREFIX + - TABLE_SORT + - "(" + - COLUMN_SORT_PATH + - " TEXT PRIMARY KEY NOT NULL, " + - COLUMN_SORT_TYPE + - " INTEGER NOT NULL)" - ) - database.execSQL( - "INSERT INTO $TEMP_TABLE_PREFIX$TABLE_SORT SELECT * FROM $TABLE_SORT" - ) - database.execSQL("DROP TABLE $TABLE_SORT") - database.execSQL( - "ALTER TABLE $TEMP_TABLE_PREFIX$TABLE_SORT RENAME TO $TABLE_SORT" - ) - database.execSQL( - "CREATE TABLE " + - TEMP_TABLE_PREFIX + - TABLE_ENCRYPTED + - "(" + - COLUMN_ENCRYPTED_ID + - " INTEGER PRIMARY KEY NOT NULL," + - COLUMN_ENCRYPTED_PATH + - " TEXT," + - COLUMN_ENCRYPTED_PASSWORD + - " TEXT)" - ) - database.execSQL( - "INSERT INTO " + - TEMP_TABLE_PREFIX + - TABLE_ENCRYPTED + - " SELECT * FROM " + - TABLE_ENCRYPTED - ) - database.execSQL("DROP TABLE $TABLE_ENCRYPTED") - database.execSQL( - "ALTER TABLE " + - TEMP_TABLE_PREFIX + - TABLE_ENCRYPTED + - " RENAME TO " + - TABLE_ENCRYPTED - ) - database.execSQL( - "CREATE TABLE " + - TEMP_TABLE_PREFIX + - TABLE_CLOUD_PERSIST + - "(" + - COLUMN_CLOUD_ID + - " INTEGER PRIMARY KEY NOT NULL," + - COLUMN_CLOUD_SERVICE + - " INTEGER," + - COLUMN_CLOUD_PERSIST + - " TEXT)" - ) - database.execSQL( - "INSERT INTO " + - TEMP_TABLE_PREFIX + - TABLE_CLOUD_PERSIST + - " SELECT * FROM " + - TABLE_CLOUD_PERSIST - ) - database.execSQL("DROP TABLE $TABLE_CLOUD_PERSIST") - database.execSQL( - "ALTER TABLE " + - TEMP_TABLE_PREFIX + - TABLE_CLOUD_PERSIST + - " RENAME TO " + - TABLE_CLOUD_PERSIST - ) + internal val MIGRATION_6_7: Migration = + object : Migration(6, 7) { + override fun migrate(database: SupportSQLiteDatabase) { + database.execSQL( + "CREATE TABLE " + + TEMP_TABLE_PREFIX + + TABLE_TAB + + "(" + + COLUMN_TAB_NO + + " INTEGER PRIMARY KEY NOT NULL, " + + COLUMN_PATH + + " TEXT, " + + COLUMN_HOME + + " TEXT)", + ) + database.execSQL( + "INSERT INTO " + + TEMP_TABLE_PREFIX + + TABLE_TAB + + "(" + + COLUMN_TAB_NO + + "," + + COLUMN_PATH + + "," + + COLUMN_HOME + + ")" + + " SELECT " + + COLUMN_TAB_NO + + "," + + COLUMN_PATH + + "," + + COLUMN_HOME + + " FROM " + + TABLE_TAB, + ) + database.execSQL("DROP TABLE $TABLE_TAB") + database.execSQL( + "ALTER TABLE $TEMP_TABLE_PREFIX$TABLE_TAB RENAME TO $TABLE_TAB", + ) + database.execSQL( + "CREATE TABLE " + + TEMP_TABLE_PREFIX + + TABLE_SORT + + "(" + + COLUMN_SORT_PATH + + " TEXT PRIMARY KEY NOT NULL, " + + COLUMN_SORT_TYPE + + " INTEGER NOT NULL)", + ) + database.execSQL( + "INSERT INTO $TEMP_TABLE_PREFIX$TABLE_SORT SELECT * FROM $TABLE_SORT", + ) + database.execSQL("DROP TABLE $TABLE_SORT") + database.execSQL( + "ALTER TABLE $TEMP_TABLE_PREFIX$TABLE_SORT RENAME TO $TABLE_SORT", + ) + database.execSQL( + "CREATE TABLE " + + TEMP_TABLE_PREFIX + + TABLE_ENCRYPTED + + "(" + + COLUMN_ENCRYPTED_ID + + " INTEGER PRIMARY KEY NOT NULL," + + COLUMN_ENCRYPTED_PATH + + " TEXT," + + COLUMN_ENCRYPTED_PASSWORD + + " TEXT)", + ) + database.execSQL( + "INSERT INTO " + + TEMP_TABLE_PREFIX + + TABLE_ENCRYPTED + + " SELECT * FROM " + + TABLE_ENCRYPTED, + ) + database.execSQL("DROP TABLE $TABLE_ENCRYPTED") + database.execSQL( + "ALTER TABLE " + + TEMP_TABLE_PREFIX + + TABLE_ENCRYPTED + + " RENAME TO " + + TABLE_ENCRYPTED, + ) + database.execSQL( + "CREATE TABLE " + + TEMP_TABLE_PREFIX + + TABLE_CLOUD_PERSIST + + "(" + + COLUMN_CLOUD_ID + + " INTEGER PRIMARY KEY NOT NULL," + + COLUMN_CLOUD_SERVICE + + " INTEGER," + + COLUMN_CLOUD_PERSIST + + " TEXT)", + ) + database.execSQL( + "INSERT INTO " + + TEMP_TABLE_PREFIX + + TABLE_CLOUD_PERSIST + + " SELECT * FROM " + + TABLE_CLOUD_PERSIST, + ) + database.execSQL("DROP TABLE $TABLE_CLOUD_PERSIST") + database.execSQL( + "ALTER TABLE " + + TEMP_TABLE_PREFIX + + TABLE_CLOUD_PERSIST + + " RENAME TO " + + TABLE_CLOUD_PERSIST, + ) + } } - } - internal val MIGRATION_7_8: Migration = object : Migration(7, 8) { - override fun migrate(database: SupportSQLiteDatabase) { - database.execSQL( - "UPDATE " + - TABLE_CLOUD_PERSIST + - " SET " + - COLUMN_CLOUD_SERVICE + - " = " + - COLUMN_CLOUD_SERVICE + - "+1" - ) + internal val MIGRATION_7_8: Migration = + object : Migration(7, 8) { + override fun migrate(database: SupportSQLiteDatabase) { + database.execSQL( + "UPDATE " + + TABLE_CLOUD_PERSIST + + " SET " + + COLUMN_CLOUD_SERVICE + + " = " + + COLUMN_CLOUD_SERVICE + + "+1", + ) + } } - } - internal val MIGRATION_8_9: Migration = object : Migration(8, 9) { - override fun migrate(database: SupportSQLiteDatabase) { - database.execSQL( - "UPDATE " + - TABLE_CLOUD_PERSIST + - " SET " + - COLUMN_CLOUD_SERVICE + - " = " + - COLUMN_CLOUD_SERVICE + - "+1" - ) + internal val MIGRATION_8_9: Migration = + object : Migration(8, 9) { + override fun migrate(database: SupportSQLiteDatabase) { + database.execSQL( + "UPDATE " + + TABLE_CLOUD_PERSIST + + " SET " + + COLUMN_CLOUD_SERVICE + + " = " + + COLUMN_CLOUD_SERVICE + + "+1", + ) + } } - } - internal val MIGRATION_9_10: Migration = object : Migration(9, 10) { - override fun migrate(database: SupportSQLiteDatabase) { - database.execSQL( - "UPDATE " + - TABLE_CLOUD_PERSIST + - " SET " + - COLUMN_CLOUD_SERVICE + - " = " + - COLUMN_CLOUD_SERVICE + - "+1" - ) + internal val MIGRATION_9_10: Migration = + object : Migration(9, 10) { + override fun migrate(database: SupportSQLiteDatabase) { + database.execSQL( + "UPDATE " + + TABLE_CLOUD_PERSIST + + " SET " + + COLUMN_CLOUD_SERVICE + + " = " + + COLUMN_CLOUD_SERVICE + + "+1", + ) + } } - } - internal val MIGRATION_10_11: Migration = object : Migration(10, DATABASE_VERSION) { - override fun migrate(database: SupportSQLiteDatabase) { - database.execSQL( - "UPDATE " + - TABLE_CLOUD_PERSIST + - " SET " + - COLUMN_CLOUD_SERVICE + - " = " + - COLUMN_CLOUD_SERVICE + - "-2" - ) + internal val MIGRATION_10_11: Migration = + object : Migration(10, DATABASE_VERSION) { + override fun migrate(database: SupportSQLiteDatabase) { + database.execSQL( + "UPDATE " + + TABLE_CLOUD_PERSIST + + " SET " + + COLUMN_CLOUD_SERVICE + + " = " + + COLUMN_CLOUD_SERVICE + + "-2", + ) + } } - } /** * Initialize the database. Optionally, may provide a custom way to create the database @@ -328,11 +337,12 @@ abstract class ExplorerDatabase : RoomDatabase() { */ @JvmStatic fun initialize(context: Context): ExplorerDatabase { - val builder = overrideDatabaseBuilder?.invoke(context) ?: Room.databaseBuilder( - context, - ExplorerDatabase::class.java, - DATABASE_NAME - ) + val builder = + overrideDatabaseBuilder?.invoke(context) ?: Room.databaseBuilder( + context, + ExplorerDatabase::class.java, + DATABASE_NAME, + ) return builder .addMigrations(MIGRATION_1_2) .addMigrations(MIGRATION_2_3) diff --git a/app/src/main/java/com/amaze/filemanager/database/SortHandler.java b/app/src/main/java/com/amaze/filemanager/database/SortHandler.java index 2e8bedfc8a..9313add374 100644 --- a/app/src/main/java/com/amaze/filemanager/database/SortHandler.java +++ b/app/src/main/java/com/amaze/filemanager/database/SortHandler.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/database/TabHandler.java b/app/src/main/java/com/amaze/filemanager/database/TabHandler.java index 12f33ab2e6..122a963977 100644 --- a/app/src/main/java/com/amaze/filemanager/database/TabHandler.java +++ b/app/src/main/java/com/amaze/filemanager/database/TabHandler.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/database/UtilitiesDatabase.kt b/app/src/main/java/com/amaze/filemanager/database/UtilitiesDatabase.kt index d61b7faad1..f2df627d27 100644 --- a/app/src/main/java/com/amaze/filemanager/database/UtilitiesDatabase.kt +++ b/app/src/main/java/com/amaze/filemanager/database/UtilitiesDatabase.kt @@ -65,14 +65,13 @@ import java.security.GeneralSecurityException History::class, com.amaze.filemanager.database.models.utilities.List::class, SmbEntry::class, - SftpEntry::class + SftpEntry::class, ], version = UtilitiesDatabase.DATABASE_VERSION, - exportSchema = false + exportSchema = false, ) @Suppress("StringLiteralDuplication", "ComplexMethod", "LongMethod") abstract class UtilitiesDatabase : RoomDatabase() { - /** * Returns DAO for [Hidden] objects. */ @@ -139,7 +138,7 @@ abstract class UtilitiesDatabase : RoomDatabase() { COLUMN_PATH + " TEXT UNIQUE" + ");" - ) + ) private const val queryHidden = ( "CREATE TABLE IF NOT EXISTS " + TABLE_HIDDEN + @@ -149,7 +148,7 @@ abstract class UtilitiesDatabase : RoomDatabase() { COLUMN_PATH + " TEXT UNIQUE" + ");" - ) + ) private const val queryList = ( "CREATE TABLE IF NOT EXISTS " + TABLE_LIST + @@ -159,7 +158,7 @@ abstract class UtilitiesDatabase : RoomDatabase() { COLUMN_PATH + " TEXT UNIQUE" + ");" - ) + ) private const val queryGrid = ( "CREATE TABLE IF NOT EXISTS " + TABLE_GRID + @@ -169,7 +168,7 @@ abstract class UtilitiesDatabase : RoomDatabase() { COLUMN_PATH + " TEXT UNIQUE" + ");" - ) + ) private const val queryBookmarks = ( "CREATE TABLE IF NOT EXISTS " + TABLE_BOOKMARKS + @@ -181,7 +180,7 @@ abstract class UtilitiesDatabase : RoomDatabase() { COLUMN_PATH + " TEXT UNIQUE" + ");" - ) + ) private const val querySmb = ( "CREATE TABLE IF NOT EXISTS " + TABLE_SMB + @@ -193,7 +192,7 @@ abstract class UtilitiesDatabase : RoomDatabase() { COLUMN_PATH + " TEXT UNIQUE" + ");" - ) + ) private const val querySftp = ( "CREATE TABLE IF NOT EXISTS " + TABLE_SFTP + @@ -211,214 +210,218 @@ abstract class UtilitiesDatabase : RoomDatabase() { COLUMN_PRIVATE_KEY + " TEXT" + ");" - ) + ) - internal val MIGRATION_1_2: Migration = object : Migration(1, 2) { - override fun migrate(database: SupportSQLiteDatabase) { - database.execSQL( - "CREATE TABLE IF NOT EXISTS " + - TABLE_SFTP + - " (" + - COLUMN_ID + - " INTEGER PRIMARY KEY," + - COLUMN_NAME + - " TEXT," + - COLUMN_PATH + - " TEXT UNIQUE," + - COLUMN_HOST_PUBKEY + - " TEXT," + - COLUMN_PRIVATE_KEY_NAME + - " TEXT," + - COLUMN_PRIVATE_KEY + - " TEXT" + - ");" - ) + internal val MIGRATION_1_2: Migration = + object : Migration(1, 2) { + override fun migrate(database: SupportSQLiteDatabase) { + database.execSQL( + "CREATE TABLE IF NOT EXISTS " + + TABLE_SFTP + + " (" + + COLUMN_ID + + " INTEGER PRIMARY KEY," + + COLUMN_NAME + + " TEXT," + + COLUMN_PATH + + " TEXT UNIQUE," + + COLUMN_HOST_PUBKEY + + " TEXT," + + COLUMN_PRIVATE_KEY_NAME + + " TEXT," + + COLUMN_PRIVATE_KEY + + " TEXT" + + ");", + ) + } } - } - internal val MIGRATION_2_3: Migration = object : Migration(2, 3) { - override fun migrate(database: SupportSQLiteDatabase) { - var backupTable = TEMP_TABLE_PREFIX + TABLE_HISTORY - database.execSQL(queryHistory.replace(TABLE_HISTORY, backupTable)) - database.execSQL( - "INSERT INTO $backupTable SELECT * FROM $TABLE_HISTORY group by path;" - ) - database.execSQL("DROP TABLE $TABLE_HISTORY;") - database.execSQL("ALTER TABLE $backupTable RENAME TO $TABLE_HISTORY;") - backupTable = TEMP_TABLE_PREFIX + TABLE_HIDDEN - database.execSQL(queryHidden.replace(TABLE_HIDDEN, backupTable)) - database.execSQL( - "INSERT INTO $backupTable SELECT * FROM $TABLE_HIDDEN group by path;" - ) - database.execSQL("DROP TABLE $TABLE_HIDDEN;") - database.execSQL("ALTER TABLE $backupTable RENAME TO $TABLE_HIDDEN;") - backupTable = TEMP_TABLE_PREFIX + TABLE_LIST - database.execSQL(queryList.replace(TABLE_LIST, backupTable)) - database.execSQL( - "INSERT INTO $backupTable SELECT * FROM $TABLE_LIST group by path;" - ) - database.execSQL("DROP TABLE $TABLE_LIST;") - database.execSQL("ALTER TABLE $backupTable RENAME TO $TABLE_LIST;") - backupTable = TEMP_TABLE_PREFIX + TABLE_GRID - database.execSQL(queryGrid.replace(TABLE_GRID, backupTable)) - database.execSQL( - "INSERT INTO $backupTable SELECT * FROM $TABLE_GRID group by path;" - ) - database.execSQL("DROP TABLE $TABLE_GRID;") - database.execSQL("ALTER TABLE $backupTable RENAME TO $TABLE_GRID;") - backupTable = TEMP_TABLE_PREFIX + TABLE_BOOKMARKS - database.execSQL(queryBookmarks.replace(TABLE_BOOKMARKS, backupTable)) - database.execSQL( - "INSERT INTO " + - backupTable + - " SELECT * FROM " + - TABLE_BOOKMARKS + - " group by path;" - ) - database.execSQL("DROP TABLE $TABLE_BOOKMARKS;") - database.execSQL("ALTER TABLE $backupTable RENAME TO $TABLE_BOOKMARKS;") - backupTable = TEMP_TABLE_PREFIX + TABLE_SMB - database.execSQL(querySmb.replace(TABLE_SMB, backupTable)) - database.execSQL( - "INSERT INTO $backupTable SELECT * FROM $TABLE_SMB group by path;" - ) - database.execSQL("DROP TABLE $TABLE_SMB;") - database.execSQL("ALTER TABLE $backupTable RENAME TO $TABLE_SMB;") - backupTable = TEMP_TABLE_PREFIX + TABLE_SFTP - database.execSQL(querySftp.replace(TABLE_SFTP, backupTable)) - database.execSQL( - "INSERT INTO $backupTable SELECT * FROM $TABLE_SFTP group by path;" - ) - database.execSQL("DROP TABLE $TABLE_SFTP;") - database.execSQL("ALTER TABLE $backupTable RENAME TO $TABLE_SFTP;") + internal val MIGRATION_2_3: Migration = + object : Migration(2, 3) { + override fun migrate(database: SupportSQLiteDatabase) { + var backupTable = TEMP_TABLE_PREFIX + TABLE_HISTORY + database.execSQL(queryHistory.replace(TABLE_HISTORY, backupTable)) + database.execSQL( + "INSERT INTO $backupTable SELECT * FROM $TABLE_HISTORY group by path;", + ) + database.execSQL("DROP TABLE $TABLE_HISTORY;") + database.execSQL("ALTER TABLE $backupTable RENAME TO $TABLE_HISTORY;") + backupTable = TEMP_TABLE_PREFIX + TABLE_HIDDEN + database.execSQL(queryHidden.replace(TABLE_HIDDEN, backupTable)) + database.execSQL( + "INSERT INTO $backupTable SELECT * FROM $TABLE_HIDDEN group by path;", + ) + database.execSQL("DROP TABLE $TABLE_HIDDEN;") + database.execSQL("ALTER TABLE $backupTable RENAME TO $TABLE_HIDDEN;") + backupTable = TEMP_TABLE_PREFIX + TABLE_LIST + database.execSQL(queryList.replace(TABLE_LIST, backupTable)) + database.execSQL( + "INSERT INTO $backupTable SELECT * FROM $TABLE_LIST group by path;", + ) + database.execSQL("DROP TABLE $TABLE_LIST;") + database.execSQL("ALTER TABLE $backupTable RENAME TO $TABLE_LIST;") + backupTable = TEMP_TABLE_PREFIX + TABLE_GRID + database.execSQL(queryGrid.replace(TABLE_GRID, backupTable)) + database.execSQL( + "INSERT INTO $backupTable SELECT * FROM $TABLE_GRID group by path;", + ) + database.execSQL("DROP TABLE $TABLE_GRID;") + database.execSQL("ALTER TABLE $backupTable RENAME TO $TABLE_GRID;") + backupTable = TEMP_TABLE_PREFIX + TABLE_BOOKMARKS + database.execSQL(queryBookmarks.replace(TABLE_BOOKMARKS, backupTable)) + database.execSQL( + "INSERT INTO " + + backupTable + + " SELECT * FROM " + + TABLE_BOOKMARKS + + " group by path;", + ) + database.execSQL("DROP TABLE $TABLE_BOOKMARKS;") + database.execSQL("ALTER TABLE $backupTable RENAME TO $TABLE_BOOKMARKS;") + backupTable = TEMP_TABLE_PREFIX + TABLE_SMB + database.execSQL(querySmb.replace(TABLE_SMB, backupTable)) + database.execSQL( + "INSERT INTO $backupTable SELECT * FROM $TABLE_SMB group by path;", + ) + database.execSQL("DROP TABLE $TABLE_SMB;") + database.execSQL("ALTER TABLE $backupTable RENAME TO $TABLE_SMB;") + backupTable = TEMP_TABLE_PREFIX + TABLE_SFTP + database.execSQL(querySftp.replace(TABLE_SFTP, backupTable)) + database.execSQL( + "INSERT INTO $backupTable SELECT * FROM $TABLE_SFTP group by path;", + ) + database.execSQL("DROP TABLE $TABLE_SFTP;") + database.execSQL("ALTER TABLE $backupTable RENAME TO $TABLE_SFTP;") + } } - } - internal val MIGRATION_3_4: Migration = object : Migration(3, 4) { - override fun migrate(database: SupportSQLiteDatabase) { - var backupTable = TEMP_TABLE_PREFIX + TABLE_HISTORY - database.execSQL( - queryHistory - .replace(TABLE_HISTORY, backupTable) - .replace("PRIMARY KEY,", "PRIMARY KEY NOT NULL,") - ) - database.execSQL( - "INSERT INTO $backupTable SELECT * FROM $TABLE_HISTORY group by path;" - ) - database.execSQL("DROP TABLE $TABLE_HISTORY;") - database.execSQL("ALTER TABLE $backupTable RENAME TO $TABLE_HISTORY;") - backupTable = TEMP_TABLE_PREFIX + TABLE_HIDDEN - database.execSQL( - queryHidden - .replace(TABLE_HIDDEN, backupTable) - .replace("PRIMARY KEY,", "PRIMARY KEY NOT NULL,") - ) - database.execSQL( - "INSERT INTO $backupTable SELECT * FROM $TABLE_HIDDEN group by path;" - ) - database.execSQL("DROP TABLE $TABLE_HIDDEN;") - database.execSQL("ALTER TABLE $backupTable RENAME TO $TABLE_HIDDEN;") - backupTable = TEMP_TABLE_PREFIX + TABLE_LIST - database.execSQL( - queryList - .replace(TABLE_LIST, backupTable) - .replace("PRIMARY KEY,", "PRIMARY KEY NOT NULL,") - ) - database.execSQL( - "INSERT INTO $backupTable SELECT * FROM $TABLE_LIST group by path;" - ) - database.execSQL("DROP TABLE $TABLE_LIST;") - database.execSQL("ALTER TABLE $backupTable RENAME TO $TABLE_LIST;") - backupTable = TEMP_TABLE_PREFIX + TABLE_GRID - database.execSQL( - queryGrid - .replace(TABLE_GRID, backupTable) - .replace("PRIMARY KEY,", "PRIMARY KEY NOT NULL,") - ) - database.execSQL( - "INSERT INTO $backupTable SELECT * FROM $TABLE_GRID group by path;" - ) - database.execSQL("DROP TABLE $TABLE_GRID;") - database.execSQL("ALTER TABLE $backupTable RENAME TO $TABLE_GRID;") - backupTable = TEMP_TABLE_PREFIX + TABLE_BOOKMARKS - database.execSQL( - queryBookmarks - .replace(TABLE_BOOKMARKS, backupTable) - .replace("PRIMARY KEY,", "PRIMARY KEY NOT NULL,") - ) - database.execSQL( - "INSERT INTO " + - backupTable + - " SELECT * FROM " + - TABLE_BOOKMARKS + - " group by path;" - ) - database.execSQL("DROP TABLE $TABLE_BOOKMARKS;") - database.execSQL("ALTER TABLE $backupTable RENAME TO $TABLE_BOOKMARKS;") - backupTable = TEMP_TABLE_PREFIX + TABLE_SMB - database.execSQL( - querySmb - .replace(TABLE_SMB, backupTable) - .replace("PRIMARY KEY,", "PRIMARY KEY NOT NULL,") - ) - database.execSQL( - "INSERT INTO $backupTable SELECT * FROM $TABLE_SMB group by path;" - ) - database.execSQL("DROP TABLE $TABLE_SMB;") - database.execSQL("ALTER TABLE $backupTable RENAME TO $TABLE_SMB;") - backupTable = TEMP_TABLE_PREFIX + TABLE_SFTP - database.execSQL( - querySftp - .replace(TABLE_SFTP, backupTable) - .replace("PRIMARY KEY,", "PRIMARY KEY NOT NULL,") - ) - database.execSQL( - "INSERT INTO $backupTable SELECT * FROM $TABLE_SFTP group by path;" - ) - database.execSQL("DROP TABLE $TABLE_SFTP;") - database.execSQL("ALTER TABLE $backupTable RENAME TO $TABLE_SFTP;") + internal val MIGRATION_3_4: Migration = + object : Migration(3, 4) { + override fun migrate(database: SupportSQLiteDatabase) { + var backupTable = TEMP_TABLE_PREFIX + TABLE_HISTORY + database.execSQL( + queryHistory + .replace(TABLE_HISTORY, backupTable) + .replace("PRIMARY KEY,", "PRIMARY KEY NOT NULL,"), + ) + database.execSQL( + "INSERT INTO $backupTable SELECT * FROM $TABLE_HISTORY group by path;", + ) + database.execSQL("DROP TABLE $TABLE_HISTORY;") + database.execSQL("ALTER TABLE $backupTable RENAME TO $TABLE_HISTORY;") + backupTable = TEMP_TABLE_PREFIX + TABLE_HIDDEN + database.execSQL( + queryHidden + .replace(TABLE_HIDDEN, backupTable) + .replace("PRIMARY KEY,", "PRIMARY KEY NOT NULL,"), + ) + database.execSQL( + "INSERT INTO $backupTable SELECT * FROM $TABLE_HIDDEN group by path;", + ) + database.execSQL("DROP TABLE $TABLE_HIDDEN;") + database.execSQL("ALTER TABLE $backupTable RENAME TO $TABLE_HIDDEN;") + backupTable = TEMP_TABLE_PREFIX + TABLE_LIST + database.execSQL( + queryList + .replace(TABLE_LIST, backupTable) + .replace("PRIMARY KEY,", "PRIMARY KEY NOT NULL,"), + ) + database.execSQL( + "INSERT INTO $backupTable SELECT * FROM $TABLE_LIST group by path;", + ) + database.execSQL("DROP TABLE $TABLE_LIST;") + database.execSQL("ALTER TABLE $backupTable RENAME TO $TABLE_LIST;") + backupTable = TEMP_TABLE_PREFIX + TABLE_GRID + database.execSQL( + queryGrid + .replace(TABLE_GRID, backupTable) + .replace("PRIMARY KEY,", "PRIMARY KEY NOT NULL,"), + ) + database.execSQL( + "INSERT INTO $backupTable SELECT * FROM $TABLE_GRID group by path;", + ) + database.execSQL("DROP TABLE $TABLE_GRID;") + database.execSQL("ALTER TABLE $backupTable RENAME TO $TABLE_GRID;") + backupTable = TEMP_TABLE_PREFIX + TABLE_BOOKMARKS + database.execSQL( + queryBookmarks + .replace(TABLE_BOOKMARKS, backupTable) + .replace("PRIMARY KEY,", "PRIMARY KEY NOT NULL,"), + ) + database.execSQL( + "INSERT INTO " + + backupTable + + " SELECT * FROM " + + TABLE_BOOKMARKS + + " group by path;", + ) + database.execSQL("DROP TABLE $TABLE_BOOKMARKS;") + database.execSQL("ALTER TABLE $backupTable RENAME TO $TABLE_BOOKMARKS;") + backupTable = TEMP_TABLE_PREFIX + TABLE_SMB + database.execSQL( + querySmb + .replace(TABLE_SMB, backupTable) + .replace("PRIMARY KEY,", "PRIMARY KEY NOT NULL,"), + ) + database.execSQL( + "INSERT INTO $backupTable SELECT * FROM $TABLE_SMB group by path;", + ) + database.execSQL("DROP TABLE $TABLE_SMB;") + database.execSQL("ALTER TABLE $backupTable RENAME TO $TABLE_SMB;") + backupTable = TEMP_TABLE_PREFIX + TABLE_SFTP + database.execSQL( + querySftp + .replace(TABLE_SFTP, backupTable) + .replace("PRIMARY KEY,", "PRIMARY KEY NOT NULL,"), + ) + database.execSQL( + "INSERT INTO $backupTable SELECT * FROM $TABLE_SFTP group by path;", + ) + database.execSQL("DROP TABLE $TABLE_SFTP;") + database.execSQL("ALTER TABLE $backupTable RENAME TO $TABLE_SFTP;") + } } - } - internal val MIGRATION_4_5: Migration = object : Migration(4, 5) { - override fun migrate(database: SupportSQLiteDatabase) { - val backupTable = TEMP_TABLE_PREFIX + TABLE_BOOKMARKS - database.execSQL( - queryBookmarks - .replace(TABLE_BOOKMARKS, backupTable) - .replace("PRIMARY KEY,", "PRIMARY KEY NOT NULL,") - ) - database.execSQL( - "INSERT INTO " + - backupTable + - "(" + - COLUMN_NAME + - "," + - COLUMN_PATH + - ") SELECT DISTINCT(" + - COLUMN_NAME + - "), " + - COLUMN_PATH + - " FROM " + - TABLE_BOOKMARKS - ) - database.execSQL("DROP TABLE $TABLE_BOOKMARKS;") - database.execSQL("ALTER TABLE $backupTable RENAME TO $TABLE_BOOKMARKS;") - database.execSQL( - "CREATE UNIQUE INDEX 'bookmarks_idx' ON " + - TABLE_BOOKMARKS + - "(" + - COLUMN_NAME + - ", " + - COLUMN_PATH + - ");" - ) + internal val MIGRATION_4_5: Migration = + object : Migration(4, 5) { + override fun migrate(database: SupportSQLiteDatabase) { + val backupTable = TEMP_TABLE_PREFIX + TABLE_BOOKMARKS + database.execSQL( + queryBookmarks + .replace(TABLE_BOOKMARKS, backupTable) + .replace("PRIMARY KEY,", "PRIMARY KEY NOT NULL,"), + ) + database.execSQL( + "INSERT INTO " + + backupTable + + "(" + + COLUMN_NAME + + "," + + COLUMN_PATH + + ") SELECT DISTINCT(" + + COLUMN_NAME + + "), " + + COLUMN_PATH + + " FROM " + + TABLE_BOOKMARKS, + ) + database.execSQL("DROP TABLE $TABLE_BOOKMARKS;") + database.execSQL("ALTER TABLE $backupTable RENAME TO $TABLE_BOOKMARKS;") + database.execSQL( + "CREATE UNIQUE INDEX 'bookmarks_idx' ON " + + TABLE_BOOKMARKS + + "(" + + COLUMN_NAME + + ", " + + COLUMN_PATH + + ");", + ) + } } - } private fun migratePasswordInUris( database: SupportSQLiteDatabase, - tableName: String + tableName: String, ): List { val updateSqls: MutableList = ArrayList() val cursor = @@ -430,21 +433,24 @@ abstract class UtilitiesDatabase : RoomDatabase() { val userCredentials = oldPath.substring(oldPath.indexOf("://") + 3, oldPath.lastIndexOf(AT)) if (userCredentials.contains(":")) { - val password = userCredentials.substring( - userCredentials.lastIndexOf(COLON) + 1 - ) + val password = + userCredentials.substring( + userCredentials.lastIndexOf(COLON) + 1, + ) if (!TextUtils.isEmpty(password)) { try { - val oldPassword = decryptPassword( - AppConfig.getInstance(), - password, - Base64.DEFAULT - ) - val newPassword = encryptPassword( - AppConfig.getInstance(), - oldPassword, - Base64.URL_SAFE - ) + val oldPassword = + decryptPassword( + AppConfig.getInstance(), + password, + Base64.DEFAULT, + ) + val newPassword = + encryptPassword( + AppConfig.getInstance(), + oldPassword, + Base64.URL_SAFE, + ) val newPath = oldPath.replace(password, newPassword!!) updateSqls.add( "UPDATE " + @@ -459,7 +465,7 @@ abstract class UtilitiesDatabase : RoomDatabase() { COLUMN_PATH + "='" + oldPath + - "'" + "'", ) } catch (e: GeneralSecurityException) { logger.error("Error migrating database records") @@ -474,16 +480,17 @@ abstract class UtilitiesDatabase : RoomDatabase() { return updateSqls } - internal val MIGRATION_5_6: Migration = object : Migration(5, DATABASE_VERSION) { - override fun migrate(database: SupportSQLiteDatabase) { - val updateSqls: MutableList = ArrayList() - updateSqls.addAll(migratePasswordInUris(database, TABLE_SMB)) - updateSqls.addAll(migratePasswordInUris(database, TABLE_SFTP)) - for (updateSql in updateSqls) { - database.execSQL(updateSql) + internal val MIGRATION_5_6: Migration = + object : Migration(5, DATABASE_VERSION) { + override fun migrate(database: SupportSQLiteDatabase) { + val updateSqls: MutableList = ArrayList() + updateSqls.addAll(migratePasswordInUris(database, TABLE_SMB)) + updateSqls.addAll(migratePasswordInUris(database, TABLE_SFTP)) + for (updateSql in updateSqls) { + database.execSQL(updateSql) + } } } - } /** * Initialize the database. Optionally, may provide a custom way to create the database @@ -495,7 +502,7 @@ abstract class UtilitiesDatabase : RoomDatabase() { overrideDatabaseBuilder?.invoke(context) ?: Room.databaseBuilder( context, UtilitiesDatabase::class.java, - DATABASE_NAME + DATABASE_NAME, ) return builder .allowMainThreadQueries() @@ -504,7 +511,7 @@ abstract class UtilitiesDatabase : RoomDatabase() { MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5, - MIGRATION_5_6 + MIGRATION_5_6, ) .build() } diff --git a/app/src/main/java/com/amaze/filemanager/database/UtilsHandler.kt b/app/src/main/java/com/amaze/filemanager/database/UtilsHandler.kt index 6a194585fb..85642e4e38 100644 --- a/app/src/main/java/com/amaze/filemanager/database/UtilsHandler.kt +++ b/app/src/main/java/com/amaze/filemanager/database/UtilsHandler.kt @@ -52,13 +52,18 @@ import java.util.* */ class UtilsHandler( private val context: Context, - private val utilitiesDatabase: UtilitiesDatabase + private val utilitiesDatabase: UtilitiesDatabase, ) { - private val log: Logger = LoggerFactory.getLogger(UtilsHandler::class.java) enum class Operation { - HISTORY, HIDDEN, LIST, GRID, BOOKMARKS, SMB, SFTP + HISTORY, + HIDDEN, + LIST, + GRID, + BOOKMARKS, + SMB, + SFTP, } /** @@ -84,7 +89,7 @@ class UtilsHandler( utilitiesDatabase .listEntryDao() .insert( - com.amaze.filemanager.database.models.utilities.List(operationData.path) + com.amaze.filemanager.database.models.utilities.List(operationData.path), ) .subscribeOn(Schedulers.io()) .subscribe() @@ -118,9 +123,9 @@ class UtilsHandler( operationData.name, operationData.hostKey, operationData.sshKeyName, - operationData.sshKey - ) - ) + operationData.sshKey, + ), + ), ) .subscribeOn(Schedulers.io()) .subscribe() @@ -171,13 +176,14 @@ class UtilsHandler( */ fun addCommonBookmarks() { val sd = Environment.getExternalStorageDirectory() - val dirs = arrayOf( - File(sd, Environment.DIRECTORY_DCIM).absolutePath, - File(sd, Environment.DIRECTORY_DOWNLOADS).absolutePath, - File(sd, Environment.DIRECTORY_MOVIES).absolutePath, - File(sd, Environment.DIRECTORY_MUSIC).absolutePath, - File(sd, Environment.DIRECTORY_PICTURES).absolutePath - ) + val dirs = + arrayOf( + File(sd, Environment.DIRECTORY_DCIM).absolutePath, + File(sd, Environment.DIRECTORY_DOWNLOADS).absolutePath, + File(sd, Environment.DIRECTORY_MOVIES).absolutePath, + File(sd, Environment.DIRECTORY_MUSIC).absolutePath, + File(sd, Environment.DIRECTORY_PICTURES).absolutePath, + ) for (dir in dirs) { saveToDatabase(OperationData(Operation.BOOKMARKS, File(dir).name, dir)) } @@ -193,7 +199,7 @@ class UtilsHandler( path: String, hostKey: String?, sshKeyName: String?, - sshKey: String? + sshKey: String?, ) { utilitiesDatabase .sftpEntryDao() @@ -222,8 +228,8 @@ class UtilsHandler( get() { val paths = LinkedList() for ( - history in utilitiesDatabase.historyEntryDao().list().subscribeOn(Schedulers.io()) - .blockingGet() + history in utilitiesDatabase.historyEntryDao().list().subscribeOn(Schedulers.io()) + .blockingGet() ) { paths.add(history.path) } @@ -237,8 +243,8 @@ class UtilsHandler( get() { val paths = ConcurrentRadixTree(DefaultCharArrayNodeFactory()) for ( - path in utilitiesDatabase.hiddenEntryDao().listPaths().subscribeOn(Schedulers.io()) - .blockingGet() + path in utilitiesDatabase.hiddenEntryDao().listPaths().subscribeOn(Schedulers.io()) + .blockingGet() ) { paths.put(path, VoidValue.SINGLETON) } @@ -249,17 +255,19 @@ class UtilsHandler( * Return list of paths using list view. */ val listViewList: ArrayList - get() = ArrayList( - utilitiesDatabase.listEntryDao().listPaths().subscribeOn(Schedulers.io()).blockingGet() - ) + get() = + ArrayList( + utilitiesDatabase.listEntryDao().listPaths().subscribeOn(Schedulers.io()).blockingGet(), + ) /** * Return list of paths using grid view. */ val gridViewList: ArrayList - get() = ArrayList( - utilitiesDatabase.gridEntryDao().listPaths().subscribeOn(Schedulers.io()).blockingGet() - ) + get() = + ArrayList( + utilitiesDatabase.gridEntryDao().listPaths().subscribeOn(Schedulers.io()).blockingGet(), + ) /** * Return list of bookmarks. @@ -268,8 +276,8 @@ class UtilsHandler( get() { val row = ArrayList>() for ( - bookmark in utilitiesDatabase.bookmarkEntryDao().list() - .subscribeOn(Schedulers.io()).blockingGet() + bookmark in utilitiesDatabase.bookmarkEntryDao().list() + .subscribeOn(Schedulers.io()).blockingGet() ) { row.add(arrayOf(bookmark.name, bookmark.path)) } @@ -283,8 +291,8 @@ class UtilsHandler( get() { val retval = ArrayList>() for ( - entry in utilitiesDatabase.smbEntryDao().list().subscribeOn(Schedulers.io()) - .blockingGet() + entry in utilitiesDatabase.smbEntryDao().list().subscribeOn(Schedulers.io()) + .blockingGet() ) { try { retval.add(arrayOf(entry.name, entry.path)) @@ -295,7 +303,7 @@ class UtilsHandler( Toast.makeText( context, context.getString(R.string.failed_smb_decrypt_path), - Toast.LENGTH_LONG + Toast.LENGTH_LONG, ) .show() removeSmbPath(entry.name, "") @@ -305,7 +313,7 @@ class UtilsHandler( Toast.makeText( context, context.getString(R.string.failed_smb_decrypt_path), - Toast.LENGTH_LONG + Toast.LENGTH_LONG, ) .show() removeSmbPath(entry.name, "") @@ -322,8 +330,8 @@ class UtilsHandler( get() { val retval = ArrayList>() for ( - entry in utilitiesDatabase.sftpEntryDao().list().subscribeOn(Schedulers.io()) - .blockingGet() + entry in utilitiesDatabase.sftpEntryDao().list().subscribeOn(Schedulers.io()) + .blockingGet() ) { val path = entry.path if (path == null) { @@ -332,7 +340,7 @@ class UtilsHandler( Toast.makeText( context, context.getString(R.string.failed_smb_decrypt_path), - Toast.LENGTH_LONG + Toast.LENGTH_LONG, ).show() } else { retval.add(arrayOf(entry.name, path)) @@ -389,7 +397,10 @@ class UtilsHandler( } }.getOrNull() - private fun removeBookmarksPath(name: String, path: String) { + private fun removeBookmarksPath( + name: String, + path: String, + ) { utilitiesDatabase .bookmarkEntryDao() .deleteByNameAndPath(name, path) @@ -403,7 +414,10 @@ class UtilsHandler( * @param path the path we get from saved runtime variables is a decrypted, to remove entry, we * must encrypt it's password fiend first first */ - private fun removeSmbPath(name: String, path: String) { + private fun removeSmbPath( + name: String, + path: String, + ) { if ("" == path) { utilitiesDatabase.smbEntryDao().deleteByName(name) .subscribeOn(Schedulers.io()).subscribe() @@ -416,7 +430,10 @@ class UtilsHandler( } } - private fun removeSftpPath(name: String, path: String) { + private fun removeSftpPath( + name: String, + path: String, + ) { if ("" == path) { utilitiesDatabase.sftpEntryDao().deleteByName(name) .subscribeOn(Schedulers.io()).subscribe() @@ -432,18 +449,24 @@ class UtilsHandler( /** * Update [Bookmark]. */ - fun renameBookmark(oldName: String, oldPath: String, newName: String, newPath: String) { - val bookmark: Bookmark = kotlin.runCatching { - utilitiesDatabase - .bookmarkEntryDao() - .findByNameAndPath(oldName, oldPath) - .subscribeOn(Schedulers.io()) - .blockingGet() - }.onFailure { - // catch error to handle Single#onError for blockingGet - log.error(it.message!!) - return - }.getOrThrow() + fun renameBookmark( + oldName: String, + oldPath: String, + newName: String, + newPath: String, + ) { + val bookmark: Bookmark = + kotlin.runCatching { + utilitiesDatabase + .bookmarkEntryDao() + .findByNameAndPath(oldName, oldPath) + .subscribeOn(Schedulers.io()) + .blockingGet() + }.onFailure { + // catch error to handle Single#onError for blockingGet + log.error(it.message!!) + return + }.getOrThrow() bookmark.name = newName bookmark.path = newPath @@ -454,7 +477,12 @@ class UtilsHandler( /** * Update [SmbEntry]. */ - fun renameSMB(oldName: String, oldPath: String, newName: String, newPath: String) { + fun renameSMB( + oldName: String, + oldPath: String, + newName: String, + newPath: String, + ) { utilitiesDatabase .smbEntryDao() .findByNameAndPath(oldName, oldPath) @@ -475,8 +503,9 @@ class UtilsHandler( */ fun clearTable(table: Operation) { when (table) { - Operation.HISTORY -> utilitiesDatabase.historyEntryDao().clear() - .subscribeOn(Schedulers.io()).subscribe() + Operation.HISTORY -> + utilitiesDatabase.historyEntryDao().clear() + .subscribeOn(Schedulers.io()).subscribe() else -> {} } } diff --git a/app/src/main/java/com/amaze/filemanager/database/daos/BookmarkEntryDao.java b/app/src/main/java/com/amaze/filemanager/database/daos/BookmarkEntryDao.java index 8dcd21be09..7b0ca71154 100644 --- a/app/src/main/java/com/amaze/filemanager/database/daos/BookmarkEntryDao.java +++ b/app/src/main/java/com/amaze/filemanager/database/daos/BookmarkEntryDao.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/database/daos/CloudEntryDao.java b/app/src/main/java/com/amaze/filemanager/database/daos/CloudEntryDao.java index 42e209f98c..62a83b211f 100644 --- a/app/src/main/java/com/amaze/filemanager/database/daos/CloudEntryDao.java +++ b/app/src/main/java/com/amaze/filemanager/database/daos/CloudEntryDao.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/database/daos/EncryptedEntryDao.java b/app/src/main/java/com/amaze/filemanager/database/daos/EncryptedEntryDao.java index 824a52cad5..e21d4e3f2b 100644 --- a/app/src/main/java/com/amaze/filemanager/database/daos/EncryptedEntryDao.java +++ b/app/src/main/java/com/amaze/filemanager/database/daos/EncryptedEntryDao.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/database/daos/GridEntryDao.java b/app/src/main/java/com/amaze/filemanager/database/daos/GridEntryDao.java index 57b753d92c..7ce356d355 100644 --- a/app/src/main/java/com/amaze/filemanager/database/daos/GridEntryDao.java +++ b/app/src/main/java/com/amaze/filemanager/database/daos/GridEntryDao.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/database/daos/HiddenEntryDao.java b/app/src/main/java/com/amaze/filemanager/database/daos/HiddenEntryDao.java index 03442cb6f8..d652155e98 100644 --- a/app/src/main/java/com/amaze/filemanager/database/daos/HiddenEntryDao.java +++ b/app/src/main/java/com/amaze/filemanager/database/daos/HiddenEntryDao.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/database/daos/HistoryEntryDao.java b/app/src/main/java/com/amaze/filemanager/database/daos/HistoryEntryDao.java index d1c791e39c..165e3adc4a 100644 --- a/app/src/main/java/com/amaze/filemanager/database/daos/HistoryEntryDao.java +++ b/app/src/main/java/com/amaze/filemanager/database/daos/HistoryEntryDao.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/database/daos/ListEntryDao.java b/app/src/main/java/com/amaze/filemanager/database/daos/ListEntryDao.java index 417360c569..f026f9d436 100644 --- a/app/src/main/java/com/amaze/filemanager/database/daos/ListEntryDao.java +++ b/app/src/main/java/com/amaze/filemanager/database/daos/ListEntryDao.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/database/daos/SftpEntryDao.java b/app/src/main/java/com/amaze/filemanager/database/daos/SftpEntryDao.java index babf1cca47..1e82e0cb6e 100644 --- a/app/src/main/java/com/amaze/filemanager/database/daos/SftpEntryDao.java +++ b/app/src/main/java/com/amaze/filemanager/database/daos/SftpEntryDao.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/database/daos/SmbEntryDao.java b/app/src/main/java/com/amaze/filemanager/database/daos/SmbEntryDao.java index adfd23dc55..b00c8df9d8 100644 --- a/app/src/main/java/com/amaze/filemanager/database/daos/SmbEntryDao.java +++ b/app/src/main/java/com/amaze/filemanager/database/daos/SmbEntryDao.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/database/daos/SortDao.java b/app/src/main/java/com/amaze/filemanager/database/daos/SortDao.java index 21f53b7813..ff09a5d551 100644 --- a/app/src/main/java/com/amaze/filemanager/database/daos/SortDao.java +++ b/app/src/main/java/com/amaze/filemanager/database/daos/SortDao.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/database/daos/TabDao.java b/app/src/main/java/com/amaze/filemanager/database/daos/TabDao.java index 2466d6c308..164d1dec1b 100644 --- a/app/src/main/java/com/amaze/filemanager/database/daos/TabDao.java +++ b/app/src/main/java/com/amaze/filemanager/database/daos/TabDao.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/database/models/OperationData.java b/app/src/main/java/com/amaze/filemanager/database/models/OperationData.java index b486238cfe..472e7b05cf 100644 --- a/app/src/main/java/com/amaze/filemanager/database/models/OperationData.java +++ b/app/src/main/java/com/amaze/filemanager/database/models/OperationData.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/database/models/StringWrapper.java b/app/src/main/java/com/amaze/filemanager/database/models/StringWrapper.java index 2195c8d6d7..6968552aee 100644 --- a/app/src/main/java/com/amaze/filemanager/database/models/StringWrapper.java +++ b/app/src/main/java/com/amaze/filemanager/database/models/StringWrapper.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/database/models/explorer/CloudEntry.java b/app/src/main/java/com/amaze/filemanager/database/models/explorer/CloudEntry.java index ec22c71edb..b161593856 100644 --- a/app/src/main/java/com/amaze/filemanager/database/models/explorer/CloudEntry.java +++ b/app/src/main/java/com/amaze/filemanager/database/models/explorer/CloudEntry.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/database/models/explorer/EncryptedEntry.java b/app/src/main/java/com/amaze/filemanager/database/models/explorer/EncryptedEntry.java index 4f38a9a454..443f2c9d53 100644 --- a/app/src/main/java/com/amaze/filemanager/database/models/explorer/EncryptedEntry.java +++ b/app/src/main/java/com/amaze/filemanager/database/models/explorer/EncryptedEntry.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/database/models/explorer/Sort.java b/app/src/main/java/com/amaze/filemanager/database/models/explorer/Sort.java index 30f82dc215..e05f6e2992 100644 --- a/app/src/main/java/com/amaze/filemanager/database/models/explorer/Sort.java +++ b/app/src/main/java/com/amaze/filemanager/database/models/explorer/Sort.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/database/models/explorer/Tab.java b/app/src/main/java/com/amaze/filemanager/database/models/explorer/Tab.java index 436e998a47..b824a0ce50 100644 --- a/app/src/main/java/com/amaze/filemanager/database/models/explorer/Tab.java +++ b/app/src/main/java/com/amaze/filemanager/database/models/explorer/Tab.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/database/models/utilities/Bookmark.java b/app/src/main/java/com/amaze/filemanager/database/models/utilities/Bookmark.java index 1fccbd0c6d..c2ab2f70e4 100644 --- a/app/src/main/java/com/amaze/filemanager/database/models/utilities/Bookmark.java +++ b/app/src/main/java/com/amaze/filemanager/database/models/utilities/Bookmark.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/database/models/utilities/Grid.java b/app/src/main/java/com/amaze/filemanager/database/models/utilities/Grid.java index 92f976dea1..dddfb2ffaf 100644 --- a/app/src/main/java/com/amaze/filemanager/database/models/utilities/Grid.java +++ b/app/src/main/java/com/amaze/filemanager/database/models/utilities/Grid.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/database/models/utilities/Hidden.java b/app/src/main/java/com/amaze/filemanager/database/models/utilities/Hidden.java index 86dfa305a7..4ae6ebb4a7 100644 --- a/app/src/main/java/com/amaze/filemanager/database/models/utilities/Hidden.java +++ b/app/src/main/java/com/amaze/filemanager/database/models/utilities/Hidden.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/database/models/utilities/History.java b/app/src/main/java/com/amaze/filemanager/database/models/utilities/History.java index 9586e4b8d9..14fb5bb13f 100644 --- a/app/src/main/java/com/amaze/filemanager/database/models/utilities/History.java +++ b/app/src/main/java/com/amaze/filemanager/database/models/utilities/History.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/database/models/utilities/List.java b/app/src/main/java/com/amaze/filemanager/database/models/utilities/List.java index 64b6f61292..0215527da1 100644 --- a/app/src/main/java/com/amaze/filemanager/database/models/utilities/List.java +++ b/app/src/main/java/com/amaze/filemanager/database/models/utilities/List.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/database/models/utilities/OperationData.java b/app/src/main/java/com/amaze/filemanager/database/models/utilities/OperationData.java index 98eb2ab8af..dee0051065 100644 --- a/app/src/main/java/com/amaze/filemanager/database/models/utilities/OperationData.java +++ b/app/src/main/java/com/amaze/filemanager/database/models/utilities/OperationData.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/database/models/utilities/OperationDataWithName.java b/app/src/main/java/com/amaze/filemanager/database/models/utilities/OperationDataWithName.java index 18314c524d..a39390c48b 100644 --- a/app/src/main/java/com/amaze/filemanager/database/models/utilities/OperationDataWithName.java +++ b/app/src/main/java/com/amaze/filemanager/database/models/utilities/OperationDataWithName.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/database/models/utilities/SftpEntry.java b/app/src/main/java/com/amaze/filemanager/database/models/utilities/SftpEntry.java index 964663b85e..d6d2e33081 100644 --- a/app/src/main/java/com/amaze/filemanager/database/models/utilities/SftpEntry.java +++ b/app/src/main/java/com/amaze/filemanager/database/models/utilities/SftpEntry.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/database/models/utilities/SmbEntry.java b/app/src/main/java/com/amaze/filemanager/database/models/utilities/SmbEntry.java index 6ae3b180f1..3910444eeb 100644 --- a/app/src/main/java/com/amaze/filemanager/database/models/utilities/SmbEntry.java +++ b/app/src/main/java/com/amaze/filemanager/database/models/utilities/SmbEntry.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/database/typeconverters/EncryptedStringTypeConverter.kt b/app/src/main/java/com/amaze/filemanager/database/typeconverters/EncryptedStringTypeConverter.kt index ccf8bd8675..9d9a1975c6 100644 --- a/app/src/main/java/com/amaze/filemanager/database/typeconverters/EncryptedStringTypeConverter.kt +++ b/app/src/main/java/com/amaze/filemanager/database/typeconverters/EncryptedStringTypeConverter.kt @@ -37,7 +37,6 @@ import com.amaze.filemanager.utils.PasswordUtil.encryptPassword * @see PasswordUtil.decryptPassword */ object EncryptedStringTypeConverter { - @JvmStatic private val TAG = EncryptedStringTypeConverter::class.java.simpleName @@ -49,7 +48,7 @@ object EncryptedStringTypeConverter { fun toPassword(encryptedStringEntryInDb: String): StringWrapper { return runCatching { StringWrapper( - decryptPassword(AppConfig.getInstance(), encryptedStringEntryInDb) + decryptPassword(AppConfig.getInstance(), encryptedStringEntryInDb), ) }.onFailure { Log.e(TAG, "Error decrypting password", it) @@ -67,7 +66,7 @@ object EncryptedStringTypeConverter { return runCatching { encryptPassword( AppConfig.getInstance(), - unencryptedPasswordString.value + unencryptedPasswordString.value, ) }.onFailure { Log.e(TAG, "Error encrypting password", it) diff --git a/app/src/main/java/com/amaze/filemanager/database/typeconverters/OpenModeTypeConverter.kt b/app/src/main/java/com/amaze/filemanager/database/typeconverters/OpenModeTypeConverter.kt index 970cf04a4d..c1ca6e5f4f 100644 --- a/app/src/main/java/com/amaze/filemanager/database/typeconverters/OpenModeTypeConverter.kt +++ b/app/src/main/java/com/amaze/filemanager/database/typeconverters/OpenModeTypeConverter.kt @@ -25,7 +25,6 @@ import com.amaze.filemanager.fileoperations.filesystem.OpenMode /** [TypeConverter] for [OpenMode] objects to database columns. */ object OpenModeTypeConverter { - /** * Convert given [OpenMode] to integer constant for database storage. */ diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/CustomFileObserver.java b/app/src/main/java/com/amaze/filemanager/filesystem/CustomFileObserver.java index 76e053feda..4792e62fd6 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/CustomFileObserver.java +++ b/app/src/main/java/com/amaze/filemanager/filesystem/CustomFileObserver.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/DeleteOperation.kt b/app/src/main/java/com/amaze/filemanager/filesystem/DeleteOperation.kt index 0799307ae1..c295a42b2e 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/DeleteOperation.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/DeleteOperation.kt @@ -37,7 +37,10 @@ object DeleteOperation { * @return true if successful. */ @JvmStatic - private fun rmdir(file: File, context: Context): Boolean { + private fun rmdir( + file: File, + context: Context, + ): Boolean { if (!file.exists()) return true val files = file.listFiles() if (files != null && files.size > 0) { @@ -70,7 +73,7 @@ object DeleteOperation { resolver.delete( MediaStore.Files.getContentUri("external"), MediaStore.MediaColumns.DATA + "=?", - arrayOf(file.absolutePath) + arrayOf(file.absolutePath), ) } return !file.exists() @@ -83,7 +86,10 @@ object DeleteOperation { * @return True if successfully deleted. */ @JvmStatic - fun deleteFile(file: File, context: Context): Boolean { + fun deleteFile( + file: File, + context: Context, + ): Boolean { // First try the normal deletion. val fileDelete = rmdir(file, context) if (file.delete() || fileDelete) return true diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/EditableFileAbstraction.java b/app/src/main/java/com/amaze/filemanager/filesystem/EditableFileAbstraction.java index a02428d303..ef4b95b48d 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/EditableFileAbstraction.java +++ b/app/src/main/java/com/amaze/filemanager/filesystem/EditableFileAbstraction.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/ExternalSdCardOperation.kt b/app/src/main/java/com/amaze/filemanager/filesystem/ExternalSdCardOperation.kt index 3826d1a922..84249465c2 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/ExternalSdCardOperation.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/ExternalSdCardOperation.kt @@ -49,7 +49,7 @@ object ExternalSdCardOperation { fun getDocumentFile( file: File, isDirectory: Boolean, - context: Context + context: Context, ): DocumentFile? { if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) return DocumentFile.fromFile(file) val baseFolder = getExtSdCardFolder(file, context) @@ -69,8 +69,9 @@ object ExternalSdCardOperation { return null } - val preferenceUri = PreferenceManager.getDefaultSharedPreferences(context) - .getString(PreferencesConstants.PREFERENCE_URI, null) + val preferenceUri = + PreferenceManager.getDefaultSharedPreferences(context) + .getString(PreferencesConstants.PREFERENCE_URI, null) var treeUri: Uri? = null if (preferenceUri != null) { treeUri = Uri.parse(preferenceUri) @@ -93,11 +94,12 @@ object ExternalSdCardOperation { var nextDocument = document.findFile(parts[i]) if (nextDocument == null) { - nextDocument = if (i < parts.size - 1 || isDirectory) { - document.createDirectory(parts[i]) - } else { - document.createFile("image", parts[i]) - } + nextDocument = + if (i < parts.size - 1 || isDirectory) { + document.createDirectory(parts[i]) + } else { + document.createFile("image", parts[i]) + } } document = nextDocument } @@ -167,7 +169,10 @@ object ExternalSdCardOperation { */ @JvmStatic @TargetApi(Build.VERSION_CODES.KITKAT) - public fun getExtSdCardFolder(file: File, context: Context): String? { + public fun getExtSdCardFolder( + file: File, + context: Context, + ): String? { val extSdPaths = getExtSdCardPaths(context) try { for (i in extSdPaths.indices) { @@ -189,7 +194,10 @@ object ExternalSdCardOperation { */ @JvmStatic @TargetApi(Build.VERSION_CODES.KITKAT) - fun isOnExtSdCard(file: File, c: Context): Boolean { + fun isOnExtSdCard( + file: File, + c: Context, + ): Boolean { return getExtSdCardFolder(file, c) != null } } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/FileProperties.kt b/app/src/main/java/com/amaze/filemanager/filesystem/FileProperties.kt index ed6f8128f5..2fbab94011 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/FileProperties.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/FileProperties.kt @@ -48,7 +48,6 @@ import java.util.regex.Pattern // TODO check if these can be done with just File methods // TODO make all of these methods File extensions object FileProperties { - private val log: Logger = LoggerFactory.getLogger(FileProperties::class.java) private const val STORAGE_PRIMARY = "primary" @@ -56,15 +55,17 @@ object FileProperties { "com.android.externalstorage.documents" @JvmField - val ANDROID_DATA_DIRS = arrayOf( - "Android/data", - "Android/obb" - ) + val ANDROID_DATA_DIRS = + arrayOf( + "Android/data", + "Android/obb", + ) @JvmField - val ANDROID_DEVICE_DATA_DIRS = ANDROID_DATA_DIRS.map { - File(Environment.getExternalStorageDirectory(), it).absolutePath - } + val ANDROID_DEVICE_DATA_DIRS = + ANDROID_DATA_DIRS.map { + File(Environment.getExternalStorageDirectory(), it).absolutePath + } /** * Check if a file is readable. @@ -122,7 +123,10 @@ object FileProperties { * @return true if it is possible to write in this directory. */ @JvmStatic - fun isWritableNormalOrSaf(folder: File?, c: Context): Boolean { + fun isWritableNormalOrSaf( + folder: File?, + c: Context, + ): Boolean { if (folder == null) { return false } @@ -158,6 +162,7 @@ object FileProperties { } // Utility methods for Kitkat + /** * Checks whether the target path exists or is writable * @@ -165,7 +170,10 @@ object FileProperties { * @return 1 if exists or writable, 0 if not writable */ @JvmStatic - fun checkFolder(f: String?, context: Context): Int { + fun checkFolder( + f: String?, + context: Context, + ): Int { if (f == null) return 0 if (f.startsWith(CifsContexts.SMB_URI_PREFIX) || f.startsWith(NetCopyClientConnectionPool.SSH_URI_PREFIX) || @@ -177,7 +185,9 @@ object FileProperties { f.startsWith(CloudHandler.CLOUD_PREFIX_DROPBOX) || f.startsWith(CloudHandler.CLOUD_PREFIX_ONE_DRIVE) || f.startsWith("content://") - ) return 1 + ) { + return 1 + } val folder = File(f) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && isOnExtSdCard(folder, context) @@ -190,15 +200,17 @@ object FileProperties { if (isWritableNormalOrSaf(folder, context)) { return 1 } - } else return if (Build.VERSION.SDK_INT == 19 && - isOnExtSdCard(folder, context) - ) { - // Assume that Kitkat workaround works - 1 - } else if (folder.canWrite()) { - 1 } else { - 0 + return if (Build.VERSION.SDK_INT == 19 && + isOnExtSdCard(folder, context) + ) { + // Assume that Kitkat workaround works + 1 + } else if (folder.canWrite()) { + 1 + } else { + 0 + } } return 0 } @@ -227,7 +239,7 @@ object FileProperties { return uri.path?.let { p -> File( Environment.getExternalStorageDirectory(), - p.substringAfter("tree/primary:") + p.substringAfter("tree/primary:"), ).absolutePath } } else { @@ -235,13 +247,23 @@ object FileProperties { } } + /** + * Remap file path + * @param path file path + * @param openDocumentTree open document tree default false + * @return remapped file path + */ @JvmStatic - fun remapPathForApi30OrAbove(path: String, openDocumentTree: Boolean = false): String { + fun remapPathForApi30OrAbove( + path: String, + openDocumentTree: Boolean = false, + ): String { return if (ANDROID_DEVICE_DATA_DIRS.containsPath(path)) { path - } else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q && ANDROID_DEVICE_DATA_DIRS.any { - path.startsWith(it) && path != it - } + } else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q && + ANDROID_DEVICE_DATA_DIRS.any { + path.startsWith(it) && path != it + } ) { val suffix = path.substringAfter(Environment.getExternalStorageDirectory().absolutePath) @@ -250,12 +272,12 @@ object FileProperties { if (openDocumentTree) { DocumentsContract.buildDocumentUri( COM_ANDROID_EXTERNALSTORAGE_DOCUMENTS, - documentId + documentId, ).toString() } else { DocumentsContract.buildTreeDocumentUri( COM_ANDROID_EXTERNALSTORAGE_DOCUMENTS, - documentId + documentId, ).toString() } } else { @@ -272,6 +294,8 @@ object FileProperties { AppConfig.getInstance().getSystemService(StorageStatsManager::class.java) .getFreeBytes(StorageManager.UUID_DEFAULT) } - } else 0L + } else { + 0L + } } } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/FileUtil.java b/app/src/main/java/com/amaze/filemanager/filesystem/FileUtil.java index 8e7012aad4..0c55808a20 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/FileUtil.java +++ b/app/src/main/java/com/amaze/filemanager/filesystem/FileUtil.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/FilenameHelper.kt b/app/src/main/java/com/amaze/filemanager/filesystem/FilenameHelper.kt index d1e97ddc4d..bab18a87f8 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/FilenameHelper.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/FilenameHelper.kt @@ -27,53 +27,57 @@ import kotlin.math.absoluteValue /** * Convenient extension to return path element of a path string = the part before the last slash. */ -fun String.pathDirname(): String = if (contains(SLASH)) { - substringBeforeLast(SLASH) -} else { - "" -} +fun String.pathDirname(): String = + if (contains(SLASH)) { + substringBeforeLast(SLASH) + } else { + "" + } /** * Convenient extension to return the name element of a path = the part after the last slash. */ -fun String.pathBasename(): String = if (contains(SLASH)) { - substringAfterLast(SLASH) -} else { - this -} +fun String.pathBasename(): String = + if (contains(SLASH)) { + substringAfterLast(SLASH) + } else { + this + } /** * Convenient extension to return the basename element of a filename = the part after the last * slash and before the extension (.). */ -fun String.pathFileBasename(): String = if (contains('.')) { - pathBasename().substringBeforeLast('.') -} else { - pathBasename() -} +fun String.pathFileBasename(): String = + if (contains('.')) { + pathBasename().substringBeforeLast('.') + } else { + pathBasename() + } /** * Convenient extension to return the extension element of a filename = the part after the last * slash and after the extension (.). Returns empty string if no extension dot exist. */ -fun String.pathFileExtension(): String = if (contains('.')) { - pathBasename().substringAfterLast('.') -} else { - "" -} +fun String.pathFileExtension(): String = + if (contains('.')) { + pathBasename().substringAfterLast('.') + } else { + "" + } enum class FilenameFormatFlag { - DARWIN, DEFAULT, WINDOWS, LINUX + DARWIN, + DEFAULT, + WINDOWS, + LINUX, } object FilenameHelper { + // Don't split complex regexs into multiple lines. - /* Don't split complex regexs into multiple lines. */ - - /* ktlint-disable max-line-length */ private const val REGEX_RAW_NUMBERS = "| [0-9]+" private const val REGEX_SOURCE = " \\((?:(another|[0-9]+(th|st|nd|rd)) )?copy\\)|copy( [0-9]+)?|\\.\\(incomplete\\)| \\([0-9]+\\)|[- ]+" - /* ktlint-enable max-line-length */ private val ordinals = arrayOf("th", "st", "nd", "rd") @@ -83,7 +87,10 @@ object FilenameHelper { * Default will not strip the raw numbers; specify removeRawNumbers = true to do so. */ @JvmStatic - fun strip(input: String, removeRawNumbers: Boolean = false): String { + fun strip( + input: String, + removeRawNumbers: Boolean = false, + ): String { val filepath = stripIncrementInternal(input, removeRawNumbers) val extension = filepath.pathFileExtension() val dirname = stripIncrementInternal(filepath.pathDirname(), removeRawNumbers) @@ -129,7 +136,7 @@ object FilenameHelper { platform: FilenameFormatFlag = FilenameFormatFlag.DEFAULT, strip: Boolean = true, removeRawNumbers: Boolean = false, - startArg: Int = 1 + startArg: Int = 1, ): HybridFile { var filename = file.getName(AppConfig.getInstance()) var dirname = file.path.pathDirname() @@ -144,46 +151,56 @@ object FilenameHelper { basename = strip(basename, removeRawNumbers) } - var retval = HybridFile( - file.mode, - dirname, - filename, - file.isDirectory(AppConfig.getInstance()) - ) - - while (retval.exists(AppConfig.getInstance())) { - filename = if (extension.isNotBlank()) { - format(platform, basename, start++) + ".$extension" - } else { - format(platform, basename, start++) - } - retval = HybridFile( + var retval = + HybridFile( file.mode, dirname, filename, - file.isDirectory(AppConfig.getInstance()) + file.isDirectory(AppConfig.getInstance()), ) + + while (retval.exists(AppConfig.getInstance())) { + filename = + if (extension.isNotBlank()) { + format(platform, basename, start++) + ".$extension" + } else { + format(platform, basename, start++) + } + retval = + HybridFile( + file.mode, + dirname, + filename, + file.isDirectory(AppConfig.getInstance()), + ) } return retval } - private fun stripIncrementInternal(input: String, removeRawNumbers: Boolean = false): String { - val source = StringBuilder().run { - append(REGEX_SOURCE) - if (removeRawNumbers) { - append(REGEX_RAW_NUMBERS) + private fun stripIncrementInternal( + input: String, + removeRawNumbers: Boolean = false, + ): String { + val source = + StringBuilder().run { + append(REGEX_SOURCE) + if (removeRawNumbers) { + append(REGEX_RAW_NUMBERS) + } + toString() } - toString() - } return Regex("($source)+$", RegexOption.IGNORE_CASE).replace(input, "") } - private fun stem(filepath: String, removeRawNumbers: Boolean = false): String { + private fun stem( + filepath: String, + removeRawNumbers: Boolean = false, + ): String { val extension = filepath.pathFileExtension() return stripIncrementInternal( filepath.pathBasename().substringBefore(".$extension"), - removeRawNumbers + removeRawNumbers, ) } @@ -199,7 +216,11 @@ object FilenameHelper { } // TODO: i18n - private fun format(flag: FilenameFormatFlag, stem: String, n: Int): String { + private fun format( + flag: FilenameFormatFlag, + stem: String, + n: Int, + ): String { return when (flag) { FilenameFormatFlag.DARWIN -> { if (n == 1) { diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/HybridFile.java b/app/src/main/java/com/amaze/filemanager/filesystem/HybridFile.java index a8bcfb18bd..ac9dc8b25d 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/HybridFile.java +++ b/app/src/main/java/com/amaze/filemanager/filesystem/HybridFile.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/HybridFileParcelable.java b/app/src/main/java/com/amaze/filemanager/filesystem/HybridFileParcelable.java index e7ad99af2d..46381a08a8 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/HybridFileParcelable.java +++ b/app/src/main/java/com/amaze/filemanager/filesystem/HybridFileParcelable.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/MakeDirectoryOperation.kt b/app/src/main/java/com/amaze/filemanager/filesystem/MakeDirectoryOperation.kt index 1765130374..0106c0ddbd 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/MakeDirectoryOperation.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/MakeDirectoryOperation.kt @@ -33,7 +33,6 @@ import java.io.IOException // This object is here to not polute the global namespace // All functions must be static object MakeDirectoryOperation { - private val log: Logger = LoggerFactory.getLogger(MakeDirectoryOperation::class.java) /** @@ -44,7 +43,10 @@ object MakeDirectoryOperation { */ @JvmStatic @Deprecated("use {@link #mkdirs(Context, HybridFile)}") - fun mkdir(file: File?, context: Context): Boolean { + fun mkdir( + file: File?, + context: Context, + ): Boolean { if (file == null) return false if (file.exists()) { // nothing to create. @@ -73,7 +75,9 @@ object MakeDirectoryOperation { } catch (e: IOException) { false } - } else false + } else { + false + } } /** @@ -83,7 +87,10 @@ object MakeDirectoryOperation { * @return true if successfully created directory, otherwise returns false. */ @JvmStatic - fun mkdirs(context: Context, file: HybridFile): Boolean { + fun mkdirs( + context: Context, + file: HybridFile, + ): Boolean { var isSuccessful = true when (file.mode) { OpenMode.SMB -> diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/MakeFileOperation.kt b/app/src/main/java/com/amaze/filemanager/filesystem/MakeFileOperation.kt index 528c5bc2d6..1e49ef1fda 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/MakeFileOperation.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/MakeFileOperation.kt @@ -43,13 +43,25 @@ object MakeFileOperation { * @return The temp file. */ @JvmStatic - fun getTempFile(file: File, context: Context): File { + fun getTempFile( + file: File, + context: Context, + ): File { val extDir = context.getExternalFilesDir(null) return File(extDir, file.name) } + /** + * Make normal file + * @param file File + * @param context Context + * @return true for success and false for failed + */ @JvmStatic - fun mkfile(file: File?, context: Context): Boolean { + fun mkfile( + file: File?, + context: Context, + ): Boolean { if (file == null) return false if (file.exists()) { // nothing to create. @@ -75,10 +87,10 @@ object MakeFileOperation { ( document?.createFile( MimeTypes.getMimeType(file.path, file.isDirectory), - file.name + file.name, ) != null - ) + ) } catch (e: UnsupportedOperationException) { log.warn("Failed to create file on sd card using document file", e) false @@ -86,15 +98,29 @@ object MakeFileOperation { } return if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) { MediaStoreHack.mkfile(context, file) - } else false + } else { + false + } } + /** + * Make text file + * @param data file data + * @param path path + * @param fileName file name + * @return true for success and false for failed + */ @JvmStatic - fun mktextfile(data: String?, path: String?, fileName: String): Boolean { - val f = File( - path, - "$fileName${AppConstants.NEW_FILE_DELIMITER}${AppConstants.NEW_FILE_EXTENSION_TXT}" - ) + fun mktextfile( + data: String?, + path: String?, + fileName: String, + ): Boolean { + val f = + File( + path, + "$fileName${AppConstants.NEW_FILE_DELIMITER}${AppConstants.NEW_FILE_EXTENSION_TXT}", + ) var out: FileOutputStream? = null var outputWriter: OutputStreamWriter? = null return try { diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/MediaStoreHack.java b/app/src/main/java/com/amaze/filemanager/filesystem/MediaStoreHack.java index 38a34472d9..5336fd6bc0 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/MediaStoreHack.java +++ b/app/src/main/java/com/amaze/filemanager/filesystem/MediaStoreHack.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/Operations.java b/app/src/main/java/com/amaze/filemanager/filesystem/Operations.java index d247ee43e2..02d46eb5ec 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/Operations.java +++ b/app/src/main/java/com/amaze/filemanager/filesystem/Operations.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/PasteHelper.java b/app/src/main/java/com/amaze/filemanager/filesystem/PasteHelper.java index 2113c1c220..74adac5fa3 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/PasteHelper.java +++ b/app/src/main/java/com/amaze/filemanager/filesystem/PasteHelper.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/RenameOperation.kt b/app/src/main/java/com/amaze/filemanager/filesystem/RenameOperation.kt index 731ebb0cc4..7fed73b3ae 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/RenameOperation.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/RenameOperation.kt @@ -40,14 +40,17 @@ object RenameOperation { * @return true if the copying was successful. */ @JvmStatic - private fun copyFile(source: File, target: File, context: Context): Boolean { + private fun copyFile( + source: File, + target: File, + context: Context, + ): Boolean { var inStream: FileInputStream? = null var outStream: OutputStream? = null var inChannel: FileChannel? = null var outChannel: FileChannel? = null try { inStream = FileInputStream(source) - // First try the normal way if (FileProperties.isWritable(target)) { // standard way @@ -56,20 +59,21 @@ object RenameOperation { outChannel = outStream.channel inChannel.transferTo(0, inChannel.size(), outChannel) } else { - outStream = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { - // Storage Access Framework - val targetDocument = - ExternalSdCardOperation.getDocumentFile(target, false, context) - targetDocument ?: throw IOException("Couldn't get DocumentFile") - context.contentResolver.openOutputStream(targetDocument.uri) - } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) { - // Workaround for Kitkat ext SD card - val uri = MediaStoreHack.getUriFromFile(target.absolutePath, context) - uri ?: return false - context.contentResolver.openOutputStream(uri) - } else { - return false - } + outStream = + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + // Storage Access Framework + val targetDocument = + ExternalSdCardOperation.getDocumentFile(target, false, context) + targetDocument ?: throw IOException("Couldn't get DocumentFile") + context.contentResolver.openOutputStream(targetDocument.uri) + } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) { + // Workaround for Kitkat ext SD card + val uri = MediaStoreHack.getUriFromFile(target.absolutePath, context) + uri ?: return false + context.contentResolver.openOutputStream(uri) + } else { + return false + } if (outStream != null) { // Both for SAF and for Kitkat, write to output stream. val buffer = ByteArray(16384) // MAGIC_NUMBER @@ -83,7 +87,7 @@ object RenameOperation { Log.e( LOG, "Error when copying file from ${source.absolutePath} to ${target.absolutePath}", - e + e, ) return false } finally { @@ -113,7 +117,11 @@ object RenameOperation { @JvmStatic @Throws(ShellNotRunningException::class) - private fun rename(f: File, name: String, root: Boolean): Boolean { + private fun rename( + f: File, + name: String, + root: Boolean, + ): Boolean { val parentName = f.parent ?: return false val parentFile = f.parentFile ?: return false @@ -140,7 +148,7 @@ object RenameOperation { fun renameFolder( source: File, target: File, - context: Context + context: Context, ): Boolean { // First try the normal rename. if (rename(source, target.name, false)) { diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/RootHelper.java b/app/src/main/java/com/amaze/filemanager/filesystem/RootHelper.java index dd9c36f25b..bead57ded7 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/RootHelper.java +++ b/app/src/main/java/com/amaze/filemanager/filesystem/RootHelper.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/cloud/CloudUtil.java b/app/src/main/java/com/amaze/filemanager/filesystem/cloud/CloudUtil.java index f83449dc50..bc7bb48d8e 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/cloud/CloudUtil.java +++ b/app/src/main/java/com/amaze/filemanager/filesystem/cloud/CloudUtil.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/CompressedHelper.java b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/CompressedHelper.java index 8dc2a80cf7..13d5135a78 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/CompressedHelper.java +++ b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/CompressedHelper.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/Extractor.java b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/Extractor.java index 4b9b8506b2..3e1a5097a4 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/Extractor.java +++ b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/Extractor.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/AbstractCommonsArchiveExtractor.kt b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/AbstractCommonsArchiveExtractor.kt index d2e0ee964d..38d2338730 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/AbstractCommonsArchiveExtractor.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/AbstractCommonsArchiveExtractor.kt @@ -38,9 +38,8 @@ abstract class AbstractCommonsArchiveExtractor( filePath: String, outputPath: String, listener: OnUpdate, - updatePosition: UpdatePosition + updatePosition: UpdatePosition, ) : Extractor(context, filePath, outputPath, listener, updatePosition) { - /** * Subclasses implement this method to create [ArchiveInputStream] instances with given archive * as [InputStream]. @@ -92,7 +91,7 @@ abstract class AbstractCommonsArchiveExtractor( context: Context, inputStream: ArchiveInputStream, entry: ArchiveEntry, - outputDir: String + outputDir: String, ) { if (entry.isDirectory) { MakeDirectoryOperation.mkdir(File(outputDir, entry.name), context) @@ -118,8 +117,8 @@ abstract class AbstractCommonsArchiveExtractor( context.getString( R.string.error_archive_cannot_extract, entry.name, - outputDir - ) + outputDir, + ), ) } } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/AbstractCommonsCompressedFileExtractor.kt b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/AbstractCommonsCompressedFileExtractor.kt index 52d9a78bab..1157b6e148 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/AbstractCommonsCompressedFileExtractor.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/AbstractCommonsCompressedFileExtractor.kt @@ -40,14 +40,14 @@ abstract class AbstractCommonsCompressedFileExtractor( filePath: String, outputPath: String, listener: OnUpdate, - updatePosition: UpdatePosition + updatePosition: UpdatePosition, ) : Extractor(context, filePath, outputPath, listener, updatePosition) { - private val compressorInputStreamConstructor: Constructor init { - compressorInputStreamConstructor = getCompressorInputStreamClass() - .getDeclaredConstructor(InputStream::class.java) + compressorInputStreamConstructor = + getCompressorInputStreamClass() + .getDeclaredConstructor(InputStream::class.java) compressorInputStreamConstructor.isAccessible = true } @@ -84,8 +84,8 @@ abstract class AbstractCommonsCompressedFileExtractor( context.getString( R.string.error_archive_cannot_extract, entryName, - outputPath - ) + outputPath, + ), ) } }.onFailure { diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/AbstractCompressedTarArchiveExtractor.kt b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/AbstractCompressedTarArchiveExtractor.kt index 160869b244..1999ed7d95 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/AbstractCompressedTarArchiveExtractor.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/AbstractCompressedTarArchiveExtractor.kt @@ -32,15 +32,15 @@ abstract class AbstractCompressedTarArchiveExtractor( filePath: String, outputPath: String, listener: OnUpdate, - updatePosition: UpdatePosition + updatePosition: UpdatePosition, ) : AbstractCommonsArchiveExtractor(context, filePath, outputPath, listener, updatePosition) { - private val compressorInputStreamConstructor: Constructor init { - compressorInputStreamConstructor = getCompressorInputStreamClass() - .getDeclaredConstructor(InputStream::class.java) + compressorInputStreamConstructor = + getCompressorInputStreamClass() + .getDeclaredConstructor(InputStream::class.java) compressorInputStreamConstructor.isAccessible = true } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/Bzip2Extractor.kt b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/Bzip2Extractor.kt index f0c8148b2f..38a05d8a56 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/Bzip2Extractor.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/Bzip2Extractor.kt @@ -30,14 +30,14 @@ class Bzip2Extractor( filePath: String, outputPath: String, listener: OnUpdate, - updatePosition: UpdatePosition + updatePosition: UpdatePosition, ) : AbstractCommonsCompressedFileExtractor( - context, - filePath, - outputPath, - listener, - updatePosition -) { + context, + filePath, + outputPath, + listener, + updatePosition, + ) { override fun getCompressorInputStreamClass(): Class { return BZip2CompressorInputStream::class.java } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/GzipExtractor.kt b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/GzipExtractor.kt index 663fff431f..b20a5072c9 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/GzipExtractor.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/GzipExtractor.kt @@ -30,14 +30,14 @@ class GzipExtractor( filePath: String, outputPath: String, listener: OnUpdate, - updatePosition: UpdatePosition + updatePosition: UpdatePosition, ) : AbstractCommonsCompressedFileExtractor( - context, - filePath, - outputPath, - listener, - updatePosition -) { + context, + filePath, + outputPath, + listener, + updatePosition, + ) { override fun getCompressorInputStreamClass(): Class { return GzipCompressorInputStream::class.java } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/LzmaExtractor.kt b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/LzmaExtractor.kt index 79c6f08b0e..fd5021d9da 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/LzmaExtractor.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/LzmaExtractor.kt @@ -30,14 +30,14 @@ class LzmaExtractor( filePath: String, outputPath: String, listener: OnUpdate, - updatePosition: UpdatePosition + updatePosition: UpdatePosition, ) : AbstractCommonsCompressedFileExtractor( - context, - filePath, - outputPath, - listener, - updatePosition -) { + context, + filePath, + outputPath, + listener, + updatePosition, + ) { override fun getCompressorInputStreamClass(): Class { return LZMACompressorInputStream::class.java } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/SevenZipExtractor.kt b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/SevenZipExtractor.kt index c5e6528d97..b39c9db054 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/SevenZipExtractor.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/SevenZipExtractor.kt @@ -44,10 +44,9 @@ class SevenZipExtractor( filePath: String, outputPath: String, listener: OnUpdate, - updatePosition: UpdatePosition + updatePosition: UpdatePosition, ) : Extractor(context, filePath, outputPath, listener, updatePosition) { - companion object { @JvmStatic private val LOG: Logger = LoggerFactory.getLogger(SevenZipExtractor::class.java) @@ -56,22 +55,23 @@ class SevenZipExtractor( @Throws(IOException::class) override fun extractWithFilter(filter: Filter) { var totalBytes: Long = 0 - val sevenzFile = runCatching { - if (ArchivePasswordCache.getInstance().containsKey(filePath)) { - SevenZFile( - File(filePath), - ArchivePasswordCache.getInstance()[filePath]!!.toCharArray() - ) - } else { - SevenZFile(File(filePath)) - } - }.getOrElse { - if (it is PasswordRequiredException || it is CorruptedInputException) { - throw it - } else { - throw BadArchiveNotice(it) + val sevenzFile = + runCatching { + if (ArchivePasswordCache.getInstance().containsKey(filePath)) { + SevenZFile( + File(filePath), + ArchivePasswordCache.getInstance()[filePath]!!.toCharArray(), + ) + } else { + SevenZFile(File(filePath)) + } + }.getOrElse { + if (it is PasswordRequiredException || it is CorruptedInputException) { + throw it + } else { + throw BadArchiveNotice(it) + } } - } val arrayList = ArrayList() // iterating archive elements to find file names that are to be extracted @@ -103,7 +103,7 @@ class SevenZipExtractor( context: Context, sevenzFile: SevenZFile, entry: SevenZArchiveEntry, - outputDir: String + outputDir: String, ) { val name = entry.name if (entry.isDirectory) { @@ -121,26 +121,28 @@ class SevenZipExtractor( while (progress < entry.size) { var length: Int val bytesLeft = java.lang.Long.valueOf(entry.size - progress).toInt() - length = sevenzFile.read( - content, - 0, - if (bytesLeft > GenericCopyUtil.DEFAULT_BUFFER_SIZE) { - GenericCopyUtil.DEFAULT_BUFFER_SIZE - } else { - bytesLeft - } - ) + length = + sevenzFile.read( + content, + 0, + if (bytesLeft > GenericCopyUtil.DEFAULT_BUFFER_SIZE) { + GenericCopyUtil.DEFAULT_BUFFER_SIZE + } else { + bytesLeft + }, + ) write(content, 0, length) updatePosition.updatePosition(length.toLong()) progress += length.toLong() } close() - val lastModifiedDate = try { - entry.lastModifiedDate.time - } catch (e: UnsupportedOperationException) { - LOG.warn("Unable to get modified date for 7zip file") - System.currentTimeMillis() - } + val lastModifiedDate = + try { + entry.lastModifiedDate.time + } catch (e: UnsupportedOperationException) { + LOG.warn("Unable to get modified date for 7zip file") + System.currentTimeMillis() + } outputFile.setLastModified(lastModifiedDate) } }?.onFailure { @@ -150,8 +152,8 @@ class SevenZipExtractor( context.getString( R.string.error_archive_cannot_extract, entry.name, - outputDir - ) + outputDir, + ), ) } } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/TarBzip2Extractor.kt b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/TarBzip2Extractor.kt index 47b148e217..fd44569377 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/TarBzip2Extractor.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/TarBzip2Extractor.kt @@ -30,15 +30,13 @@ class TarBzip2Extractor( filePath: String, outputPath: String, listener: OnUpdate, - updatePosition: UpdatePosition + updatePosition: UpdatePosition, ) : AbstractCompressedTarArchiveExtractor( - context, - filePath, - outputPath, - listener, - updatePosition -) { - - override fun getCompressorInputStreamClass(): Class = - BZip2CompressorInputStream::class.java + context, + filePath, + outputPath, + listener, + updatePosition, + ) { + override fun getCompressorInputStreamClass(): Class = BZip2CompressorInputStream::class.java } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/TarExtractor.kt b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/TarExtractor.kt index 282c6d6273..b803433459 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/TarExtractor.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/TarExtractor.kt @@ -30,15 +30,14 @@ class TarExtractor( filePath: String, outputPath: String, listener: OnUpdate, - updatePosition: UpdatePosition + updatePosition: UpdatePosition, ) : AbstractCommonsArchiveExtractor( - context, - filePath, - outputPath, - listener, - updatePosition -) { - + context, + filePath, + outputPath, + listener, + updatePosition, + ) { override fun createFrom(inputStream: InputStream): TarArchiveInputStream = runCatching { TarArchiveInputStream(inputStream) diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/TarGzExtractor.kt b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/TarGzExtractor.kt index b907f8e5d2..3cafd249a6 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/TarGzExtractor.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/TarGzExtractor.kt @@ -30,15 +30,13 @@ class TarGzExtractor( filePath: String, outputPath: String, listener: OnUpdate, - updatePosition: UpdatePosition + updatePosition: UpdatePosition, ) : AbstractCompressedTarArchiveExtractor( - context, - filePath, - outputPath, - listener, - updatePosition -) { - - override fun getCompressorInputStreamClass(): Class = - GzipCompressorInputStream::class.java + context, + filePath, + outputPath, + listener, + updatePosition, + ) { + override fun getCompressorInputStreamClass(): Class = GzipCompressorInputStream::class.java } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/TarLzmaExtractor.kt b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/TarLzmaExtractor.kt index 636a309c2b..553f0fc902 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/TarLzmaExtractor.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/TarLzmaExtractor.kt @@ -30,15 +30,13 @@ class TarLzmaExtractor( filePath: String, outputPath: String, listener: OnUpdate, - updatePosition: UpdatePosition + updatePosition: UpdatePosition, ) : AbstractCompressedTarArchiveExtractor( - context, - filePath, - outputPath, - listener, - updatePosition -) { - - override fun getCompressorInputStreamClass(): Class = - LZMACompressorInputStream::class.java + context, + filePath, + outputPath, + listener, + updatePosition, + ) { + override fun getCompressorInputStreamClass(): Class = LZMACompressorInputStream::class.java } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/TarXzExtractor.kt b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/TarXzExtractor.kt index a0c75212c6..6b701c2160 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/TarXzExtractor.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/TarXzExtractor.kt @@ -30,15 +30,13 @@ class TarXzExtractor( filePath: String, outputPath: String, listener: OnUpdate, - updatePosition: UpdatePosition + updatePosition: UpdatePosition, ) : AbstractCompressedTarArchiveExtractor( - context, - filePath, - outputPath, - listener, - updatePosition -) { - - override fun getCompressorInputStreamClass(): Class = - XZCompressorInputStream::class.java + context, + filePath, + outputPath, + listener, + updatePosition, + ) { + override fun getCompressorInputStreamClass(): Class = XZCompressorInputStream::class.java } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/XzExtractor.kt b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/XzExtractor.kt index 62a8a82f7e..0e219c1eed 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/XzExtractor.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/XzExtractor.kt @@ -30,14 +30,14 @@ class XzExtractor( filePath: String, outputPath: String, listener: OnUpdate, - updatePosition: UpdatePosition + updatePosition: UpdatePosition, ) : AbstractCommonsCompressedFileExtractor( - context, - filePath, - outputPath, - listener, - updatePosition -) { + context, + filePath, + outputPath, + listener, + updatePosition, + ) { override fun getCompressorInputStreamClass(): Class { return XZCompressorInputStream::class.java } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/ZipExtractor.kt b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/ZipExtractor.kt index 8e3535ee40..214aaefa3e 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/ZipExtractor.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/ZipExtractor.kt @@ -46,9 +46,8 @@ class ZipExtractor( filePath: String, outputPath: String, listener: OnUpdate, - updatePosition: UpdatePosition + updatePosition: UpdatePosition, ) : Extractor(context, filePath, outputPath, listener, updatePosition) { - private val isRobolectricTest = Build.HARDWARE == "robolectric" @Throws(IOException::class) @@ -109,7 +108,7 @@ class ZipExtractor( context: Context, zipFile: ZipFile, entry: FileHeader, - outputDir: String + outputDir: String, ) { val outputFile = File(outputDir, fixEntryName(entry.fileName)) if (!outputFile.canonicalPath.startsWith(outputDir) && @@ -135,7 +134,9 @@ class ZipExtractor( if (!listener.isCancelled) { write(buf, 0, len) updatePosition.updatePosition(len.toLong()) - } else break + } else { + break + } } close() outputFile.setLastModified(entry.lastModifiedTimeEpoch) @@ -145,8 +146,8 @@ class ZipExtractor( context.getString( R.string.error_archive_cannot_extract, entry.fileName, - outputDir - ) + outputDir, + ), ) } } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/showcontents/Decompressor.kt b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/showcontents/Decompressor.kt index 86824b93ac..65f9fa0464 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/showcontents/Decompressor.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/showcontents/Decompressor.kt @@ -29,7 +29,6 @@ import com.amaze.filemanager.asynchronous.services.ExtractService /** @author Emmanuel on 20/11/2017, at 17:14. */ abstract class Decompressor(protected var context: Context) { - lateinit var filePath: String /** @@ -39,16 +38,17 @@ abstract class Decompressor(protected var context: Context) { */ abstract fun changePath( path: String, - addGoBackItem: Boolean + addGoBackItem: Boolean, ): CompressedHelperCallable /** Decompress a file somewhere */ fun decompress(whereToDecompress: String) { - val intent = Intent(context, ExtractService::class.java).also { - it.putExtra(ExtractService.KEY_PATH_ZIP, filePath) - it.putExtra(ExtractService.KEY_ENTRIES_ZIP, arrayOfNulls(0)) - it.putExtra(ExtractService.KEY_PATH_EXTRACT, whereToDecompress) - } + val intent = + Intent(context, ExtractService::class.java).also { + it.putExtra(ExtractService.KEY_PATH_ZIP, filePath) + it.putExtra(ExtractService.KEY_ENTRIES_ZIP, arrayOfNulls(0)) + it.putExtra(ExtractService.KEY_PATH_EXTRACT, whereToDecompress) + } ServiceWatcherUtil.runService(context, intent) } @@ -58,15 +58,19 @@ abstract class Decompressor(protected var context: Context) { * @param subDirectories separator is "/", ended with "/" if it is a directory, does not if it's a * file */ - fun decompress(whereToDecompress: String, subDirectories: Array) { + fun decompress( + whereToDecompress: String, + subDirectories: Array, + ) { subDirectories.filterNotNull().map { realRelativeDirectory(it) }.run { - val intent = Intent(context, ExtractService::class.java).also { - it.putExtra(ExtractService.KEY_PATH_ZIP, filePath) - it.putExtra(ExtractService.KEY_ENTRIES_ZIP, subDirectories) - it.putExtra(ExtractService.KEY_PATH_EXTRACT, whereToDecompress) - } + val intent = + Intent(context, ExtractService::class.java).also { + it.putExtra(ExtractService.KEY_PATH_ZIP, filePath) + it.putExtra(ExtractService.KEY_ENTRIES_ZIP, subDirectories) + it.putExtra(ExtractService.KEY_PATH_EXTRACT, whereToDecompress) + } ServiceWatcherUtil.runService(context, intent) } } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/showcontents/helpers/SevenZipDecompressor.kt b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/showcontents/helpers/SevenZipDecompressor.kt index 0da0d7dd1a..7c8aedd351 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/showcontents/helpers/SevenZipDecompressor.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/showcontents/helpers/SevenZipDecompressor.kt @@ -27,7 +27,6 @@ import com.amaze.filemanager.filesystem.compressed.showcontents.Decompressor class SevenZipDecompressor(context: Context) : Decompressor(context) { override fun changePath( path: String, - addGoBackItem: Boolean - ) = - SevenZipHelperCallable(filePath, path, addGoBackItem) + addGoBackItem: Boolean, + ) = SevenZipHelperCallable(filePath, path, addGoBackItem) } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/showcontents/helpers/TarBzip2Decompressor.kt b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/showcontents/helpers/TarBzip2Decompressor.kt index 340af358ce..9a63002f58 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/showcontents/helpers/TarBzip2Decompressor.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/showcontents/helpers/TarBzip2Decompressor.kt @@ -27,7 +27,6 @@ import com.amaze.filemanager.filesystem.compressed.showcontents.Decompressor class TarBzip2Decompressor(context: Context) : Decompressor(context) { override fun changePath( path: String, - addGoBackItem: Boolean - ) = - TarBzip2HelperCallable(context, filePath, path, addGoBackItem) + addGoBackItem: Boolean, + ) = TarBzip2HelperCallable(context, filePath, path, addGoBackItem) } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/showcontents/helpers/TarDecompressor.kt b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/showcontents/helpers/TarDecompressor.kt index ad39d28a01..6de4cf5c38 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/showcontents/helpers/TarDecompressor.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/showcontents/helpers/TarDecompressor.kt @@ -27,7 +27,6 @@ import com.amaze.filemanager.filesystem.compressed.showcontents.Decompressor class TarDecompressor(context: Context) : Decompressor(context) { override fun changePath( path: String, - addGoBackItem: Boolean - ) = - TarHelperCallable(context, filePath, path, addGoBackItem) + addGoBackItem: Boolean, + ) = TarHelperCallable(context, filePath, path, addGoBackItem) } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/showcontents/helpers/TarGzDecompressor.kt b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/showcontents/helpers/TarGzDecompressor.kt index 03e0d8026e..870f26ab94 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/showcontents/helpers/TarGzDecompressor.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/showcontents/helpers/TarGzDecompressor.kt @@ -27,7 +27,6 @@ import com.amaze.filemanager.filesystem.compressed.showcontents.Decompressor class TarGzDecompressor(context: Context) : Decompressor(context) { override fun changePath( path: String, - addGoBackItem: Boolean - ) = - TarGzHelperCallable(context, filePath, path, addGoBackItem) + addGoBackItem: Boolean, + ) = TarGzHelperCallable(context, filePath, path, addGoBackItem) } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/showcontents/helpers/TarLzmaDecompressor.kt b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/showcontents/helpers/TarLzmaDecompressor.kt index a3697ba23b..4151224556 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/showcontents/helpers/TarLzmaDecompressor.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/showcontents/helpers/TarLzmaDecompressor.kt @@ -27,7 +27,6 @@ import com.amaze.filemanager.filesystem.compressed.showcontents.Decompressor class TarLzmaDecompressor(context: Context) : Decompressor(context) { override fun changePath( path: String, - addGoBackItem: Boolean - ) = - TarLzmaHelperCallable(context, filePath, path, addGoBackItem) + addGoBackItem: Boolean, + ) = TarLzmaHelperCallable(context, filePath, path, addGoBackItem) } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/showcontents/helpers/TarXzDecompressor.kt b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/showcontents/helpers/TarXzDecompressor.kt index adfbdd293b..ef89a5eca9 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/showcontents/helpers/TarXzDecompressor.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/showcontents/helpers/TarXzDecompressor.kt @@ -27,7 +27,6 @@ import com.amaze.filemanager.filesystem.compressed.showcontents.Decompressor class TarXzDecompressor(context: Context) : Decompressor(context) { override fun changePath( path: String, - addGoBackItem: Boolean - ) = - TarXzHelperCallable(context, filePath, path, addGoBackItem) + addGoBackItem: Boolean, + ) = TarXzHelperCallable(context, filePath, path, addGoBackItem) } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/showcontents/helpers/UnknownCompressedFileDecompressor.kt b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/showcontents/helpers/UnknownCompressedFileDecompressor.kt index 9f7120335e..a72ae8848e 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/showcontents/helpers/UnknownCompressedFileDecompressor.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/showcontents/helpers/UnknownCompressedFileDecompressor.kt @@ -30,7 +30,6 @@ import com.amaze.filemanager.filesystem.compressed.showcontents.Decompressor class UnknownCompressedFileDecompressor(context: Context) : Decompressor(context) { override fun changePath( path: String, - addGoBackItem: Boolean - ) = - UnknownCompressedFileHelperCallable(filePath, addGoBackItem) + addGoBackItem: Boolean, + ) = UnknownCompressedFileHelperCallable(filePath, addGoBackItem) } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/showcontents/helpers/ZipDecompressor.kt b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/showcontents/helpers/ZipDecompressor.kt index ab16ccd16f..f9288c24e7 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/compressed/showcontents/helpers/ZipDecompressor.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/compressed/showcontents/helpers/ZipDecompressor.kt @@ -27,7 +27,6 @@ import com.amaze.filemanager.filesystem.compressed.showcontents.Decompressor class ZipDecompressor(context: Context) : Decompressor(context) { override fun changePath( path: String, - addGoBackItem: Boolean - ) = - ZipHelperCallable(context, filePath, path, addGoBackItem) + addGoBackItem: Boolean, + ) = ZipHelperCallable(context, filePath, path, addGoBackItem) } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/files/CryptUtil.java b/app/src/main/java/com/amaze/filemanager/filesystem/files/CryptUtil.java index 859ed4375e..b6ea1a7bbe 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/files/CryptUtil.java +++ b/app/src/main/java/com/amaze/filemanager/filesystem/files/CryptUtil.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/files/EncryptDecryptUtils.java b/app/src/main/java/com/amaze/filemanager/filesystem/files/EncryptDecryptUtils.java index 8744369041..5355727bf1 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/files/EncryptDecryptUtils.java +++ b/app/src/main/java/com/amaze/filemanager/filesystem/files/EncryptDecryptUtils.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. @@ -65,6 +65,7 @@ public class EncryptDecryptUtils { public static final String DECRYPT_BROADCAST = "decrypt_broadcast"; private static final Logger LOG = LoggerFactory.getLogger(EncryptDecryptUtils.class); + /** * Queries database to map path and password. Starts the encryption process after database query * diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/files/FileListSorter.kt b/app/src/main/java/com/amaze/filemanager/filesystem/files/FileListSorter.kt index 1b57468a08..d789c38654 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/files/FileListSorter.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/files/FileListSorter.kt @@ -33,7 +33,7 @@ import java.util.Locale */ class FileListSorter( dirArg: DirSortBy, - sortType: SortType + sortType: SortType, ) : Comparator { private var dirsOnTop = dirArg private val asc: Int = sortType.sortOrder.sortFactor @@ -44,7 +44,10 @@ class FileListSorter( } /** Compares the names of [file1] and [file2] */ - private fun compareName(file1: ComparableParcelable, file2: ComparableParcelable): Int { + private fun compareName( + file1: ComparableParcelable, + file2: ComparableParcelable, + ): Int { return file1.getParcelableName().compareTo(file2.getParcelableName(), ignoreCase = true) } @@ -52,7 +55,10 @@ class FileListSorter( * Compares two elements and return negative, zero and positive integer if first argument is less * than, equal to or greater than second */ - override fun compare(file1: ComparableParcelable, file2: ComparableParcelable): Int { + override fun compare( + file1: ComparableParcelable, + file2: ComparableParcelable, + ): Int { /*File f1; if(!file1.hasSymlink()) { @@ -124,7 +130,6 @@ class FileListSorter( } companion object { - /** * Convenience method to get the file extension in given path. * diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/files/FileUtils.java b/app/src/main/java/com/amaze/filemanager/filesystem/files/FileUtils.java index 5dff098eb3..d9bdd010a7 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/files/FileUtils.java +++ b/app/src/main/java/com/amaze/filemanager/filesystem/files/FileUtils.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/files/GenericCopyUtil.java b/app/src/main/java/com/amaze/filemanager/filesystem/files/GenericCopyUtil.java index 4bed1f8397..bfc9263e12 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/files/GenericCopyUtil.java +++ b/app/src/main/java/com/amaze/filemanager/filesystem/files/GenericCopyUtil.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/files/MediaConnectionUtils.kt b/app/src/main/java/com/amaze/filemanager/filesystem/files/MediaConnectionUtils.kt index 577c33199d..e51370578c 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/files/MediaConnectionUtils.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/files/MediaConnectionUtils.kt @@ -27,7 +27,6 @@ import com.amaze.filemanager.filesystem.HybridFile import org.slf4j.LoggerFactory object MediaConnectionUtils { - private val LOG = LoggerFactory.getLogger(MediaConnectionUtils::class.java) /** @@ -37,7 +36,10 @@ object MediaConnectionUtils { * @param hybridFiles files to be scanned */ @JvmStatic - fun scanFile(context: Context, hybridFiles: Array) { + fun scanFile( + context: Context, + hybridFiles: Array, + ) { val paths = arrayOfNulls(hybridFiles.size) for (i in hybridFiles.indices) paths[i] = hybridFiles[i].path @@ -45,7 +47,7 @@ object MediaConnectionUtils { MediaScannerConnection.scanFile( context, paths, - null + null, ) { path: String, _: Uri? -> LOG.info("MediaConnectionUtils#scanFile finished scanning path$path") } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/files/sort/ComparableParcelable.kt b/app/src/main/java/com/amaze/filemanager/filesystem/files/sort/ComparableParcelable.kt index 439e9eb349..c0034cc906 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/files/sort/ComparableParcelable.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/files/sort/ComparableParcelable.kt @@ -22,7 +22,6 @@ package com.amaze.filemanager.filesystem.files.sort /** Used by [FileListSorter] to get the needed information from a `Parcelable` */ interface ComparableParcelable { - /** Returns if the parcelable represents a directory */ fun isDirectory(): Boolean diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/files/sort/DirSortBy.kt b/app/src/main/java/com/amaze/filemanager/filesystem/files/sort/DirSortBy.kt index 05e96da51b..00ffd5bb43 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/files/sort/DirSortBy.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/files/sort/DirSortBy.kt @@ -24,7 +24,8 @@ package com.amaze.filemanager.filesystem.files.sort enum class DirSortBy { DIR_ON_TOP, FILE_ON_TOP, - NONE_ON_TOP; + NONE_ON_TOP, + ; companion object { /** Returns the corresponding [DirSortBy] to [index] */ diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/files/sort/SortBy.kt b/app/src/main/java/com/amaze/filemanager/filesystem/files/sort/SortBy.kt index 8d9d6b3f39..c72836dade 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/files/sort/SortBy.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/files/sort/SortBy.kt @@ -33,7 +33,8 @@ enum class SortBy(val index: Int, val sortDirectory: Boolean) { LAST_MODIFIED(1, true), SIZE(2, true), TYPE(3, true), - RELEVANCE(4, false); + RELEVANCE(4, false), + ; /** Returns the corresponding string resource of the enum */ fun toResourceString(context: Context): String { diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/files/sort/SortOrder.kt b/app/src/main/java/com/amaze/filemanager/filesystem/files/sort/SortOrder.kt index d60d8504fd..17faafdb28 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/files/sort/SortOrder.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/files/sort/SortOrder.kt @@ -27,5 +27,5 @@ package com.amaze.filemanager.filesystem.files.sort */ enum class SortOrder(val sortFactor: Int) { ASC(1), - DESC(-1) + DESC(-1), } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/files/sort/SortType.kt b/app/src/main/java/com/amaze/filemanager/filesystem/files/sort/SortType.kt index c3042cfda0..9ac6862dab 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/files/sort/SortType.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/files/sort/SortType.kt @@ -22,7 +22,6 @@ package com.amaze.filemanager.filesystem.files.sort /** Describes how to sort with [sortBy] and which direction to use for the sort with [sortOrder] */ data class SortType(val sortBy: SortBy, val sortOrder: SortOrder) { - /** * Returns the Int corresponding to the combination of [sortBy] and [sortOrder] */ diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/ftp/Extensions.kt b/app/src/main/java/com/amaze/filemanager/filesystem/ftp/Extensions.kt index 01575e1fed..4d5ef0f108 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/ftp/Extensions.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/ftp/Extensions.kt @@ -49,13 +49,13 @@ fun FTPClient.makeDirectoryTree(dirTree: String) { if (!dirExists) { if (!makeDirectory(dir)) { throw IOException( - "Unable to create remote directory '$dir'. Error='$replyString'" + "Unable to create remote directory '$dir'. Error='$replyString'", ) } if (!changeWorkingDirectory(dir)) { throw IOException( "Unable to change into newly created remote directory '$dir'. " + - "Error='$replyString'" + "Error='$replyString'", ) } } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/ftp/FTPClientImpl.kt b/app/src/main/java/com/amaze/filemanager/filesystem/ftp/FTPClientImpl.kt index 823942c9c3..47065c3ff9 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/ftp/FTPClientImpl.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/ftp/FTPClientImpl.kt @@ -30,7 +30,6 @@ import java.io.OutputStream import kotlin.random.Random class FTPClientImpl(private val ftpClient: FTPClient) : NetCopyClient { - companion object { @JvmStatic private val logger: Logger = LoggerFactory.getLogger(FTPClientImpl::class.java) @@ -41,10 +40,11 @@ class FTPClientImpl(private val ftpClient: FTPClient) : NetCopyClient private const val ALPHABET = "abcdefghijklmnopqrstuvwxyz1234567890" @JvmStatic - private fun randomString(strlen: Int) = (1..strlen) - .map { Random.nextInt(0, ALPHABET.length) } - .map(ALPHABET::get) - .joinToString("") + private fun randomString(strlen: Int) = + (1..strlen) + .map { Random.nextInt(0, ALPHABET.length) } + .map(ALPHABET::get) + .joinToString("") /** * Generate random email address for anonymous FTP login. @@ -53,7 +53,7 @@ class FTPClientImpl(private val ftpClient: FTPClient) : NetCopyClient fun generateRandomEmailAddressForLogin( usernameLen: Int = 8, domainPrefixLen: Int = 5, - domainSuffixLen: Int = 3 + domainSuffixLen: Int = 3, ): String { val username = randomString(usernameLen) val domainPrefix = randomString(domainPrefixLen) @@ -67,34 +67,57 @@ class FTPClientImpl(private val ftpClient: FTPClient) : NetCopyClient * Most important part is to do [File.delete] when the reading is done. */ @JvmStatic - fun wrap(inputFile: File) = object : InputStream() { - private val inputStream = FileInputStream(inputFile) - override fun read() = inputStream.read() - override fun read(b: ByteArray?): Int = inputStream.read(b) - override fun read(b: ByteArray?, off: Int, len: Int): Int = - inputStream.read(b, off, len) - override fun reset() = inputStream.reset() - override fun available(): Int = inputStream.available() - override fun close() { - inputStream.close() - inputFile.delete() + fun wrap(inputFile: File) = + object : InputStream() { + private val inputStream = FileInputStream(inputFile) + + override fun read() = inputStream.read() + + override fun read(b: ByteArray?): Int = inputStream.read(b) + + override fun read( + b: ByteArray?, + off: Int, + len: Int, + ): Int = inputStream.read(b, off, len) + + override fun reset() = inputStream.reset() + + override fun available(): Int = inputStream.available() + + override fun close() { + inputStream.close() + inputFile.delete() + } + + override fun markSupported(): Boolean = inputStream.markSupported() + + override fun mark(readlimit: Int) = inputStream.mark(readlimit) + + override fun skip(n: Long): Long = inputStream.skip(n) } - override fun markSupported(): Boolean = inputStream.markSupported() - override fun mark(readlimit: Int) = inputStream.mark(readlimit) - override fun skip(n: Long): Long = inputStream.skip(n) - } /** * Wraps an [OutputStream] returned by [FTPClient.storeFileStream]. * Most important part is to do [FTPClient.completePendingCommand] on [OutputStream.close]. */ @JvmStatic - fun wrap(outputStream: OutputStream, ftpClient: FTPClient) = object : OutputStream() { + fun wrap( + outputStream: OutputStream, + ftpClient: FTPClient, + ) = object : OutputStream() { override fun write(b: Int) = outputStream.write(b) + override fun write(b: ByteArray?) = outputStream.write(b) - override fun write(b: ByteArray?, off: Int, len: Int) = - outputStream.write(b, off, len) + + override fun write( + b: ByteArray?, + off: Int, + len: Int, + ) = outputStream.write(b, off, len) + override fun flush() = outputStream.flush() + override fun close() { outputStream.close() ftpClient.completePendingCommand() diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/ftp/FtpClientTemplate.kt b/app/src/main/java/com/amaze/filemanager/filesystem/ftp/FtpClientTemplate.kt index 1aa1a01308..09cd44193f 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/ftp/FtpClientTemplate.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/ftp/FtpClientTemplate.kt @@ -29,7 +29,6 @@ import java.io.IOException */ abstract class FtpClientTemplate(url: String, closeClientOnFinish: Boolean = true) : NetCopyClientTemplate(url, closeClientOnFinish) { - @Throws(IOException::class) final override fun execute(client: NetCopyClient): T? { val ftpClient: FTPClient = client.getClientImpl() diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/ftp/NetCopyClient.kt b/app/src/main/java/com/amaze/filemanager/filesystem/ftp/NetCopyClient.kt index 4fd1dcc538..840ba7220d 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/ftp/NetCopyClient.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/ftp/NetCopyClient.kt @@ -24,7 +24,6 @@ package com.amaze.filemanager.filesystem.ftp * Base interface for defining client class that interacts with a remote server. */ interface NetCopyClient { - /** * Returns the physical client implementation. */ diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/ftp/NetCopyClientConnectionPool.kt b/app/src/main/java/com/amaze/filemanager/filesystem/ftp/NetCopyClientConnectionPool.kt index 4cee083dff..601a768229 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/ftp/NetCopyClientConnectionPool.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/ftp/NetCopyClientConnectionPool.kt @@ -47,7 +47,6 @@ import java.util.concurrent.CountDownLatch import java.util.concurrent.atomic.AtomicReference object NetCopyClientConnectionPool { - const val FTP_DEFAULT_PORT = 21 const val FTPS_DEFAULT_PORT = 990 const val SSH_DEFAULT_PORT = 22 @@ -132,27 +131,29 @@ object NetCopyClientConnectionPool { hostFingerprint: String? = null, username: String, password: String? = null, - keyPair: KeyPair? = null + keyPair: KeyPair? = null, ): NetCopyClient<*>? { - val url = NetCopyClientUtils.deriveUriFrom( - protocol, - host, - port, - "", - username, - password - ) - var client = connections[url] - if (client == null) { - client = createNetCopyClientInternal( + val url = + NetCopyClientUtils.deriveUriFrom( protocol, host, port, - hostFingerprint, + "", username, password, - keyPair ) + var client = connections[url] + if (client == null) { + client = + createNetCopyClientInternal( + protocol, + host, + port, + hostFingerprint, + username, + password, + keyPair, + ) if (client != null) connections[url] = client } else { if (!validate(client)) { @@ -181,7 +182,7 @@ object NetCopyClientConnectionPool { String?, String, String?, - KeyPair? + KeyPair?, ) -> NetCopyClient<*>? = { protocol, host, port, hostFingerprint, username, password, keyPair -> if (protocol == SSH_URI_PREFIX) { createSshClient(host, port, hostFingerprint!!, username, password, keyPair) @@ -192,7 +193,7 @@ object NetCopyClientConnectionPool { port, hostFingerprint?.let { JSONObject(it) }, username, - password + password, ) } } @@ -208,7 +209,10 @@ object NetCopyClientConnectionPool { * @param url SSH connection URI */ @SuppressLint("CheckResult") - fun removeConnection(url: String, callback: () -> Unit) { + fun removeConnection( + url: String, + callback: () -> Unit, + ) { Maybe.fromCallable(AsyncRemoveConnection(url)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) @@ -238,9 +242,10 @@ object NetCopyClientConnectionPool { }.subscribeOn(NetCopyClientUtils.getScheduler(client)).blockingGet() } - private fun expire(client: NetCopyClient<*>) = Flowable.fromCallable { - client.expire() - }.subscribeOn(NetCopyClientUtils.getScheduler(client)) + private fun expire(client: NetCopyClient<*>) = + Flowable.fromCallable { + client.expire() + }.subscribeOn(NetCopyClientUtils.getScheduler(client)) // Logic for creating SSH connection. Depends on password existence in given Uri password or // key-based authentication @@ -267,7 +272,7 @@ object NetCopyClientConnectionPool { } } } - .blockingFirst() + .blockingFirst(), ) } val hostKey = utilsHandler.getRemoteHostKey(url) ?: return null @@ -277,7 +282,7 @@ object NetCopyClientConnectionPool { hostKey, connInfo.username, connInfo.password, - keyPair.get() + keyPair.get(), ) } @@ -288,7 +293,7 @@ object NetCopyClientConnectionPool { hostKey: String, username: String, password: String?, - keyPair: KeyPair? + keyPair: KeyPair?, ): NetCopyClient? { return createSshClientInternal( host, @@ -296,7 +301,7 @@ object NetCopyClientConnectionPool { hostKey, username, password, - keyPair + keyPair, ) } @@ -307,16 +312,17 @@ object NetCopyClientConnectionPool { hostKey: String, username: String, password: String?, - keyPair: KeyPair? + keyPair: KeyPair?, ): NetCopyClient? { - val task = SshAuthenticationTask( - hostname = host, - port = port, - hostKey = hostKey, - username = username, - password = password, - privateKey = keyPair - ) + val task = + SshAuthenticationTask( + hostname = host, + port = port, + hostKey = hostKey, + username = username, + password = password, + privateKey = keyPair, + ) val latch = CountDownLatch(1) var retval: SSHClient? = null Maybe.fromCallable(task.getTask()) @@ -336,18 +342,19 @@ object NetCopyClientConnectionPool { private fun createFtpClient(url: String): NetCopyClient? { NetCopyConnectionInfo(url).run { - val certInfo = if (FTPS_URI_PREFIX == prefix) { - AppConfig.getInstance().utilsHandler.getRemoteHostKey(url) - } else { - null - } + val certInfo = + if (FTPS_URI_PREFIX == prefix) { + AppConfig.getInstance().utilsHandler.getRemoteHostKey(url) + } else { + null + } return createFtpClient( prefix, host, port, certInfo?.let { JSONObject(it) }, username, - password + password, ) } } @@ -359,16 +366,17 @@ object NetCopyClientConnectionPool { port: Int, certInfo: JSONObject?, username: String, - password: String? + password: String?, ): NetCopyClient? { - val task = FtpAuthenticationTask( - protocol, - host, - port, - certInfo, - username, - password - ) + val task = + FtpAuthenticationTask( + protocol, + host, + port, + certInfo, + username, + password, + ) val latch = CountDownLatch(1) var result: FTPClient? = null Single.fromCallable(task.getTask()) @@ -387,9 +395,8 @@ object NetCopyClientConnectionPool { } class AsyncRemoveConnection internal constructor( - private val url: String + private val url: String, ) : Callable { - override fun call() { extractBaseUriFrom(url).run { if (connections.containsKey(this)) { @@ -443,7 +450,7 @@ object NetCopyClientConnectionPool { } else { FTPClient() } - ).also { + ).also { it.addProtocolCommandListener(Slf4jPrintCommandListener()) it.connectTimeout = CONNECT_TIMEOUT it.controlEncoding = Charsets.UTF_8.name() diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/ftp/NetCopyClientTemplate.kt b/app/src/main/java/com/amaze/filemanager/filesystem/ftp/NetCopyClientTemplate.kt index af3a6660fa..82b80cc24c 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/ftp/NetCopyClientTemplate.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/ftp/NetCopyClientTemplate.kt @@ -23,25 +23,26 @@ package com.amaze.filemanager.filesystem.ftp import java.io.IOException abstract class NetCopyClientTemplate - /** - * Constructor, with closeClientOnFinish set to true (that the connection must close after ` - * execute`. - * - * @param url SSH connection URL, in the form of ` - * ssh://:@:` or ` - * ssh://@:` - */ -@JvmOverloads -constructor(@JvmField val url: String, @JvmField val closeClientOnFinish: Boolean = true) { - - /** - * Implement logic here. + * Constructor, with closeClientOnFinish set to true (that the connection must close after ` + * execute`. * - * @param client [NetCopyClient] instance, with connection opened and authenticated - * @param Requested return type - * @return Result of the execution of the type requested - **/ - @Throws(IOException::class) - abstract fun execute(client: NetCopyClient): T? -} + * @param url SSH connection URL, in the form of ` + * ssh://:@:` or ` + * ssh://@:` + */ + @JvmOverloads + constructor( + @JvmField val url: String, + @JvmField val closeClientOnFinish: Boolean = true, + ) { + /** + * Implement logic here. + * + * @param client [NetCopyClient] instance, with connection opened and authenticated + * @param Requested return type + * @return Result of the execution of the type requested + **/ + @Throws(IOException::class) + abstract fun execute(client: NetCopyClient): T? + } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/ftp/NetCopyClientUtils.kt b/app/src/main/java/com/amaze/filemanager/filesystem/ftp/NetCopyClientUtils.kt index 61f3c85f5c..92efb2bd12 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/ftp/NetCopyClientUtils.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/ftp/NetCopyClientUtils.kt @@ -54,7 +54,6 @@ import java.util.Calendar import java.util.Locale object NetCopyClientUtils { - @JvmStatic private val LOG = LoggerFactory.getLogger(NetCopyClientUtils::class.java) @@ -87,26 +86,25 @@ object NetCopyClientUtils { * @return Template execution results */ @WorkerThread - fun execute( - template: NetCopyClientTemplate - ): T? { + fun execute(template: NetCopyClientTemplate): T? { var client = getConnection(extractBaseUriFrom(template.url)) if (client == null) { client = getConnection(template.url) } var retval: T? = null if (client != null) { - retval = runCatching { - Maybe.fromCallable { - template.execute(client) - }.subscribeOn(getScheduler.invoke(client)).blockingGet() - }.onFailure { - LOG.error("Error executing template method", it) - }.also { - if (template.closeClientOnFinish) { - tryDisconnect(client) - } - }.getOrNull() + retval = + runCatching { + Maybe.fromCallable { + template.execute(client) + }.subscribeOn(getScheduler.invoke(client)).blockingGet() + }.onFailure { + LOG.error("Error executing template method", it) + }.also { + if (template.closeClientOnFinish) { + tryDisconnect(client) + } + }.getOrNull() } return retval } @@ -123,7 +121,7 @@ object NetCopyClientUtils { return if (uriWithoutProtocol.substringBefore(AT).indexOf(COLON) > 0) { SmbUtil.getSmbEncryptedPath( AppConfig.getInstance(), - fullUri + fullUri, ) } else { fullUri @@ -143,7 +141,7 @@ object NetCopyClientUtils { if (uriWithoutProtocol.lastIndexOf(COLON) > 0) { SmbUtil.getSmbDecryptedPath( AppConfig.getInstance(), - fullUri + fullUri, ) } else { fullUri @@ -232,20 +230,21 @@ object NetCopyClientUtils { defaultPath: String? = null, username: String, password: String? = null, - edit: Boolean = false + edit: Boolean = false, ): String { // FIXME: should be caller's responsibility var pathSuffix = defaultPath if (pathSuffix == null) pathSuffix = SLASH.toString() - val thisPassword = if (password == "" || password == null) { - "" - } else { - ":${if (edit) { - password + val thisPassword = + if (password == "" || password == null) { + "" } else { - password.urlEncoded() - }}" - } + ":${if (edit) { + password + } else { + password.urlEncoded() + }}" + } return if (username == "" && (true == password?.isEmpty())) { "$prefix$hostname:$port$pathSuffix" } else { @@ -258,31 +257,32 @@ object NetCopyClientUtils { */ @FolderState fun checkFolder(path: String): Int { - val template: NetCopyClientTemplate<*, Int> = if (path.startsWith(SSH_URI_PREFIX)) { - object : SFtpClientTemplate(extractBaseUriFrom(path), false) { - @FolderState - @Throws(IOException::class) - override fun execute(client: SFTPClient): Int { - return if (client.statExistence(extractRemotePathFrom(path)) == null) { - WRITABLE_ON_REMOTE - } else { - DOESNT_EXIST + val template: NetCopyClientTemplate<*, Int> = + if (path.startsWith(SSH_URI_PREFIX)) { + object : SFtpClientTemplate(extractBaseUriFrom(path), false) { + @FolderState + @Throws(IOException::class) + override fun execute(client: SFTPClient): Int { + return if (client.statExistence(extractRemotePathFrom(path)) == null) { + WRITABLE_ON_REMOTE + } else { + DOESNT_EXIST + } } } - } - } else { - object : FtpClientTemplate(extractBaseUriFrom(path), false) { - override fun executeWithFtpClient(ftpClient: FTPClient): Int { - return if (ftpClient.stat(extractRemotePathFrom(path)) - == FTPReply.DIRECTORY_STATUS - ) { - WRITABLE_ON_REMOTE - } else { - DOESNT_EXIST + } else { + object : FtpClientTemplate(extractBaseUriFrom(path), false) { + override fun executeWithFtpClient(ftpClient: FTPClient): Int { + return if (ftpClient.stat(extractRemotePathFrom(path)) + == FTPReply.DIRECTORY_STATUS + ) { + WRITABLE_ON_REMOTE + } else { + DOESNT_EXIST + } } } } - } return execute(template) ?: DOESNT_EXIST } @@ -291,13 +291,14 @@ object NetCopyClientUtils { * * Reserved for future use. */ - fun defaultPort(prefix: String) = when (prefix) { - SSH_URI_PREFIX -> SSH_DEFAULT_PORT - FTPS_URI_PREFIX -> FTPS_DEFAULT_PORT - FTP_URI_PREFIX -> FTP_DEFAULT_PORT - SMB_URI_PREFIX -> 0 // SMB never requires explicit port number at URL - else -> throw IllegalArgumentException("Cannot derive default port") - } + fun defaultPort(prefix: String) = + when (prefix) { + SSH_URI_PREFIX -> SSH_DEFAULT_PORT + FTPS_URI_PREFIX -> FTPS_DEFAULT_PORT + FTP_URI_PREFIX -> FTP_DEFAULT_PORT + SMB_URI_PREFIX -> 0 // SMB never requires explicit port number at URL + else -> throw IllegalArgumentException("Cannot derive default port") + } /** * Convenience method to format given UNIX timestamp to yyyyMMddHHmmss format. diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/ftp/NetCopyConnectionInfo.kt b/app/src/main/java/com/amaze/filemanager/filesystem/ftp/NetCopyConnectionInfo.kt index bac9fa83b7..23fafb1f4a 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/ftp/NetCopyConnectionInfo.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/ftp/NetCopyConnectionInfo.kt @@ -43,7 +43,6 @@ import com.amaze.filemanager.filesystem.smb.CifsContexts.SMB_URI_PREFIX * occur. No validation is made at this point, so proceed at your own risk. */ class NetCopyConnectionInfo(url: String) { - val prefix: String val host: String val port: Int @@ -62,11 +61,9 @@ class NetCopyConnectionInfo(url: String) { // Regex taken from https://blog.stevenlevithan.com/archives/parseuri // (No, don't break it down to lines) - /* ktlint-disable max-line-length */ + @Suppress("ktlint:standard:max-line-length") private const val URI_REGEX = "^(?:(?![^:@]+:[^:@/]*@)([^:/?#.]+):)?(?://)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:/?#]*)(?::(\\d*))?)(((/(?:[^?#](?![^?#/]*\\.[^?#/.]+(?:[?#]|$)))*/?)?([^?#/]*))(?:\\?([^#]*))?(?:#(.*))?)" - /* ktlint-enable max-line-length */ - const val MULTI_SLASH = "(?<=[^:])(//+)" const val AND = '&' @@ -80,7 +77,7 @@ class NetCopyConnectionInfo(url: String) { url.startsWith(SSH_URI_PREFIX) or url.startsWith(FTP_URI_PREFIX) or url.startsWith(FTPS_URI_PREFIX) or - url.startsWith(SMB_URI_PREFIX) + url.startsWith(SMB_URI_PREFIX), ) { "Argument is not a supported remote URI: $url" } @@ -100,43 +97,46 @@ class NetCopyConnectionInfo(url: String) { username = credential.substringBefore(COLON) password = credential.substringAfter(COLON) } - port = if (it[7].isNotEmpty()) { + port = + if (it[7].isNotEmpty()) { /* * Invalid string would have been trapped to other branches. Strings fell into * this branch must be integer */ - it[7].toInt() - } else { - 0 - } - queryString = it[12].ifEmpty { null } - arguments = if (it[12].isNotEmpty()) { - it[12].split(AND).associate { valuePair -> - val pair = valuePair.split('=') - Pair( - pair[0], - pair[1].ifEmpty { - "" - } - ) + it[7].toInt() + } else { + 0 } - } else { - null - } - defaultPath = ( - if (it[9].isEmpty()) { - null - } else if (it[9] == SLASH.toString()) { - SLASH.toString() - } else if (!it[9].endsWith(SLASH)) { - if (it[11].isEmpty()) { - it[10] - } else { - it[10].substringBeforeLast(SLASH) + queryString = it[12].ifEmpty { null } + arguments = + if (it[12].isNotEmpty()) { + it[12].split(AND).associate { valuePair -> + val pair = valuePair.split('=') + Pair( + pair[0], + pair[1].ifEmpty { + "" + }, + ) } } else { - it[9] + null } + defaultPath = + ( + if (it[9].isEmpty()) { + null + } else if (it[9] == SLASH.toString()) { + SLASH.toString() + } else if (!it[9].endsWith(SLASH)) { + if (it[11].isEmpty()) { + it[10] + } else { + it[10].substringBeforeLast(SLASH) + } + } else { + it[9] + } )?.replace(Regex(MULTI_SLASH), SLASH.toString()) filename = it[11].ifEmpty { null } } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/ftp/SSHClientImpl.kt b/app/src/main/java/com/amaze/filemanager/filesystem/ftp/SSHClientImpl.kt index ad2bf887c0..ebcf17eecd 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/ftp/SSHClientImpl.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/ftp/SSHClientImpl.kt @@ -25,7 +25,6 @@ import org.slf4j.Logger import org.slf4j.LoggerFactory class SSHClientImpl(private val sshClient: SSHClient) : NetCopyClient { - companion object { @JvmStatic private val logger: Logger = LoggerFactory.getLogger(SSHClientImpl::class.java) @@ -33,8 +32,7 @@ class SSHClientImpl(private val sshClient: SSHClient) : NetCopyClient override fun getClientImpl() = sshClient - override fun isConnectionValid(): Boolean = - sshClient.isConnected && sshClient.isAuthenticated + override fun isConnectionValid(): Boolean = sshClient.isConnected && sshClient.isAuthenticated override fun expire() { if (sshClient.isConnected) { diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/ftp/Slf4jPrintCommandListener.kt b/app/src/main/java/com/amaze/filemanager/filesystem/ftp/Slf4jPrintCommandListener.kt index 18167640fb..8ac5595a65 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/ftp/Slf4jPrintCommandListener.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/ftp/Slf4jPrintCommandListener.kt @@ -36,10 +36,9 @@ internal class Slf4jPrintCommandListener( private val nologin: Boolean = true, private val eolMarker: Char = 0.toChar(), private val directionMarker: Boolean = false, - private val loggerLevel: Level = Level.DEBUG + private val loggerLevel: Level = Level.DEBUG, ) : ProtocolCommandListener { - private val logger: Logger = LoggerFactory.getLogger(SocketClient::class.java) private val logMessage: (String) -> Unit = { msg -> @@ -72,11 +71,12 @@ internal class Slf4jPrintCommandListener( } override fun protocolReplyReceived(event: ProtocolCommandEvent) { - val msg = if (directionMarker) { - "< ${event.message}" - } else { - event.message - } + val msg = + if (directionMarker) { + "< ${event.message}" + } else { + event.message + } logMessage.invoke(msg) } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/ftpserver/AndroidFileSystemFactory.kt b/app/src/main/java/com/amaze/filemanager/filesystem/ftpserver/AndroidFileSystemFactory.kt index effc1e888a..af53162e3e 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/ftpserver/AndroidFileSystemFactory.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/ftpserver/AndroidFileSystemFactory.kt @@ -30,7 +30,6 @@ import org.apache.ftpserver.ftplet.User @RequiresApi(KITKAT) class AndroidFileSystemFactory(private val context: Context) : FileSystemFactory { - override fun createFileSystemView(user: User?): FileSystemView = AndroidFtpFileSystemView(context, user?.homeDirectory ?: FtpService.defaultPath(context)) } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/ftpserver/AndroidFtpFile.kt b/app/src/main/java/com/amaze/filemanager/filesystem/ftpserver/AndroidFtpFile.kt index 3bc7621c2a..9f10594e3c 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/ftpserver/AndroidFtpFile.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/ftpserver/AndroidFtpFile.kt @@ -41,9 +41,8 @@ class AndroidFtpFile( context: Context, private val parentDocument: DocumentFile, private val backingDocument: DocumentFile?, - private val path: String + private val path: String, ) : FtpFile { - private val _context: WeakReference = WeakReference(context) private val context: Context get() = _context.get()!! @@ -127,16 +126,18 @@ class AndroidFtpFile( */ override fun setLastModified(time: Long): Boolean { return if (doesExist()) { - val updateValues = ContentValues().also { - it.put(DocumentsContract.Document.COLUMN_LAST_MODIFIED, time) - } + val updateValues = + ContentValues().also { + it.put(DocumentsContract.Document.COLUMN_LAST_MODIFIED, time) + } val docUri: Uri = backingDocument!!.uri - val updated: Int = context.contentResolver.update( - docUri, - updateValues, - null, - null - ) + val updated: Int = + context.contentResolver.update( + docUri, + updateValues, + null, + null, + ) return updated == 1 } else { false @@ -170,46 +171,49 @@ class AndroidFtpFile( * @see FtpFile.move * @see DocumentFile.renameTo */ - override fun move(destination: FtpFile): Boolean = - backingDocument?.renameTo(destination.name) ?: false + override fun move(destination: FtpFile): Boolean = backingDocument?.renameTo(destination.name) ?: false /** * @see FtpFile.listFiles * @see DocumentFile.listFiles */ - override fun listFiles(): MutableList = if (doesExist()) { - backingDocument!!.listFiles().map { - AndroidFtpFile(context, backingDocument, it, it.name!!) - }.toMutableList() - } else { - mutableListOf() - } + override fun listFiles(): MutableList = + if (doesExist()) { + backingDocument!!.listFiles().map { + AndroidFtpFile(context, backingDocument, it, it.name!!) + }.toMutableList() + } else { + mutableListOf() + } /** * @see FtpFile.createOutputStream * @see ContentResolver.openOutputStream */ - override fun createOutputStream(offset: Long): OutputStream? = runCatching { - val uri = if (doesExist()) { - backingDocument!!.uri - } else { - val newFile = parentDocument.createFile("", name) - newFile?.uri ?: throw IOException("Cannot create file at $path") - } - context.contentResolver.openOutputStream(uri) - }.getOrThrow() + override fun createOutputStream(offset: Long): OutputStream? = + runCatching { + val uri = + if (doesExist()) { + backingDocument!!.uri + } else { + val newFile = parentDocument.createFile("", name) + newFile?.uri ?: throw IOException("Cannot create file at $path") + } + context.contentResolver.openOutputStream(uri) + }.getOrThrow() /** * @see FtpFile.createInputStream * @see ContentResolver.openInputStream */ - override fun createInputStream(offset: Long): InputStream? = runCatching { - if (doesExist()) { - context.contentResolver.openInputStream(backingDocument!!.uri).also { - it?.skip(offset) + override fun createInputStream(offset: Long): InputStream? = + runCatching { + if (doesExist()) { + context.contentResolver.openInputStream(backingDocument!!.uri).also { + it?.skip(offset) + } + } else { + throw FileNotFoundException(path) } - } else { - throw FileNotFoundException(path) - } - }.getOrThrow() + }.getOrThrow() } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/ftpserver/AndroidFtpFileSystemView.kt b/app/src/main/java/com/amaze/filemanager/filesystem/ftpserver/AndroidFtpFileSystemView.kt index b602ebc06f..1a25824733 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/ftpserver/AndroidFtpFileSystemView.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/ftpserver/AndroidFtpFileSystemView.kt @@ -34,20 +34,18 @@ import java.net.URI @RequiresApi(KITKAT) class AndroidFtpFileSystemView(private var context: Context, root: String) : FileSystemView { - private val rootPath = root private val rootDocumentFile = createDocumentFileFrom(rootPath) private var currentPath: String? = "/" - override fun getHomeDirectory(): FtpFile = - AndroidFtpFile(context, rootDocumentFile, resolveDocumentFileFromRoot("/"), "/") + override fun getHomeDirectory(): FtpFile = AndroidFtpFile(context, rootDocumentFile, resolveDocumentFileFromRoot("/"), "/") override fun getWorkingDirectory(): FtpFile { return AndroidFtpFile( context, rootDocumentFile, resolveDocumentFileFromRoot(currentPath!!), - currentPath!! + currentPath!!, ) } @@ -67,30 +65,32 @@ class AndroidFtpFileSystemView(private var context: Context, root: String) : Fil } } else -> { - currentPath = when { - currentPath.isNullOrEmpty() || currentPath == "/" -> dir - !dir.startsWith("/") -> normalizePath("$currentPath/$dir") - else -> normalizePath(dir) - } + currentPath = + when { + currentPath.isNullOrEmpty() || currentPath == "/" -> dir + !dir.startsWith("/") -> normalizePath("$currentPath/$dir") + else -> normalizePath(dir) + } resolveDocumentFileFromRoot(currentPath) != null } } } override fun getFile(file: String): FtpFile { - val path = if (currentPath.isNullOrEmpty() || currentPath == "/") { - "/$file" - } else if (file.startsWith('/')) { - file - } else { - "$currentPath/$file" - } + val path = + if (currentPath.isNullOrEmpty() || currentPath == "/") { + "/$file" + } else if (file.startsWith('/')) { + file + } else { + "$currentPath/$file" + } return normalizePath(path).let { normalizedPath -> AndroidFtpFile( context, resolveDocumentFileFromRoot(getParentFrom(normalizedPath))!!, // rootDocumentFile, resolveDocumentFileFromRoot(normalizedPath), - normalizedPath + normalizedPath, ) } } @@ -113,7 +113,7 @@ class AndroidFtpFileSystemView(private var context: Context, root: String) : Fil Uri.decode( URI(Uri.encode(path, "/")) .normalize() - .toString() + .toString(), ).replace("//", "/") } } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/ftpserver/RootFileSystemFactory.kt b/app/src/main/java/com/amaze/filemanager/filesystem/ftpserver/RootFileSystemFactory.kt index 980ac2b559..808b8dc15b 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/ftpserver/RootFileSystemFactory.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/ftpserver/RootFileSystemFactory.kt @@ -26,9 +26,7 @@ import org.apache.ftpserver.ftplet.User class RootFileSystemFactory( private val fileFactory: RootFileSystemView.SuFileFactory = - RootFileSystemView.DefaultSuFileFactory() + RootFileSystemView.DefaultSuFileFactory(), ) : FileSystemFactory { - - override fun createFileSystemView(user: User): FileSystemView = - RootFileSystemView(user, fileFactory) + override fun createFileSystemView(user: User): FileSystemView = RootFileSystemView(user, fileFactory) } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/ftpserver/RootFileSystemView.kt b/app/src/main/java/com/amaze/filemanager/filesystem/ftpserver/RootFileSystemView.kt index 83f6589d45..2e93263b4c 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/ftpserver/RootFileSystemView.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/ftpserver/RootFileSystemView.kt @@ -31,9 +31,8 @@ import java.util.* class RootFileSystemView( private val user: User, - private val fileFactory: SuFileFactory + private val fileFactory: SuFileFactory, ) : FileSystemView { - private var currDir: String private var rootDir: String @@ -51,7 +50,7 @@ class RootFileSystemView( Log.d( TAG, - "Native filesystem view created for user \"${user.name}\" with root \"${rootDir}\"" + "Native filesystem view created for user \"${user.name}\" with root \"${rootDir}\"", ) this.rootDir = rootDir @@ -122,7 +121,7 @@ class RootFileSystemView( private fun getPhysicalName( rootDir: String, currDir: String, - fileName: String + fileName: String, ): String { // normalize root dir var normalizedRootDir: String = normalizeSeparateChar(rootDir) @@ -134,13 +133,14 @@ class RootFileSystemView( // if file name is relative, set resArg to root dir + curr dir // if file name is absolute, set resArg to root dir - result = if (normalizedFileName[0] != '/') { - // file name is relative - val normalizedCurrDir = normalize(currDir) - normalizedRootDir + normalizedCurrDir.substring(1) - } else { - normalizedRootDir - } + result = + if (normalizedFileName[0] != '/') { + // file name is relative + val normalizedCurrDir = normalize(currDir) + normalizedRootDir + normalizedCurrDir.substring(1) + } else { + normalizedRootDir + } // strip last '/' result = trimTrailingSlash(result) @@ -253,12 +253,18 @@ class RootFileSystemView( /** * Create SuFile. */ - fun create(parent: String, child: String): SuFile = SuFile(parent, child) + fun create( + parent: String, + child: String, + ): SuFile = SuFile(parent, child) /** * Create SuFile. */ - fun create(parent: File, child: String): SuFile = SuFile(parent, child) + fun create( + parent: File, + child: String, + ): SuFile = SuFile(parent, child) /** * Create SuFile. diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/ftpserver/RootFtpFile.kt b/app/src/main/java/com/amaze/filemanager/filesystem/ftpserver/RootFtpFile.kt index 7a1b4994f9..0a85fac8dd 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/ftpserver/RootFtpFile.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/ftpserver/RootFtpFile.kt @@ -34,9 +34,8 @@ import java.io.OutputStream class RootFtpFile( private val fileName: String, private val backingFile: SuFile, - private val user: User + private val user: User, ) : FtpFile { - companion object { @JvmStatic private val logger: Logger = LoggerFactory.getLogger(RootFtpFile::class.java) @@ -86,18 +85,19 @@ class RootFtpFile( } // In order to maintain consistency, when possible we delete the last '/' character in the String val indexOfSlash = fullName.lastIndexOf('/') - val parentFullName: String = if (indexOfSlash == 0) { - "/" - } else { - fullName.substring(0, indexOfSlash) - } + val parentFullName: String = + if (indexOfSlash == 0) { + "/" + } else { + fullName.substring(0, indexOfSlash) + } // we check if the parent FileObject is writable. return backingFile.absoluteFile.parentFile?.run { RootFtpFile( parentFullName, this, - user + user, ).isWritable } ?: false } @@ -120,16 +120,14 @@ class RootFtpFile( override fun delete(): Boolean = backingFile.delete() - override fun move(destination: FtpFile): Boolean = - backingFile.renameTo(destination.physicalFile as SuFile) + override fun move(destination: FtpFile): Boolean = backingFile.renameTo(destination.physicalFile as SuFile) - override fun listFiles(): MutableList = backingFile.listFiles()?.map { - RootFtpFile(it.name, it, user) - }?.toMutableList() ?: emptyList().toMutableList() + override fun listFiles(): MutableList = + backingFile.listFiles()?.map { + RootFtpFile(it.name, it, user) + }?.toMutableList() ?: emptyList().toMutableList() - override fun createOutputStream(offset: Long): OutputStream = - SuFileOutputStream.open(backingFile.absolutePath) + override fun createOutputStream(offset: Long): OutputStream = SuFileOutputStream.open(backingFile.absolutePath) - override fun createInputStream(offset: Long): InputStream = - SuFileInputStream.open(backingFile.absolutePath) + override fun createInputStream(offset: Long): InputStream = SuFileInputStream.open(backingFile.absolutePath) } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/ftpserver/commands/AVBL.kt b/app/src/main/java/com/amaze/filemanager/filesystem/ftpserver/commands/AVBL.kt index 0e7334c124..8d5809b589 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/ftpserver/commands/AVBL.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/ftpserver/commands/AVBL.kt @@ -46,35 +46,39 @@ import java.io.File * See [Draft spec](https://www.ietf.org/archive/id/draft-peterson-streamlined-ftp-command-extensions-10.txt) */ class AVBL : AbstractCommand() { - companion object { private val LOG: Logger = LoggerFactory.getLogger(AVBL::class.java) } - override fun execute(session: FtpIoSession, context: FtpServerContext, request: FtpRequest) { + override fun execute( + session: FtpIoSession, + context: FtpServerContext, + request: FtpRequest, + ) { // argument check val fileName: String? = request.argument if (context.fileSystemManager is AndroidFileSystemFactory) { doWriteReply( session, REPLY_502_COMMAND_NOT_IMPLEMENTED, - "AVBL.notimplemented" + "AVBL.notimplemented", ) } else { - val ftpFile: FtpFile? = if (true == fileName?.isNotBlank()) { - runCatching { - session.fileSystemView.getFile(fileName) - }.getOrNull() - } else { - session.fileSystemView.homeDirectory - } + val ftpFile: FtpFile? = + if (true == fileName?.isNotBlank()) { + runCatching { + session.fileSystemView.getFile(fileName) + }.getOrNull() + } else { + session.fileSystemView.homeDirectory + } if (ftpFile != null) { if (session.user.authorize( if (true == fileName?.isNotBlank()) { WriteRequest(fileName) } else { WriteRequest() - } + }, ) != null || !(ftpFile.physicalFile as File).canWrite() ) { @@ -83,7 +87,7 @@ class AVBL : AbstractCommand() { runCatching { freeSpace.let { session.write( - DefaultFtpReply(REPLY_213_FILE_STATUS, it.toString()) + DefaultFtpReply(REPLY_213_FILE_STATUS, it.toString()), ) } }.onFailure { @@ -107,14 +111,14 @@ class AVBL : AbstractCommand() { private fun replyError( session: FtpIoSession, subId: String, - fileName: String? = null + fileName: String? = null, ) = doWriteReply(session, REPLY_550_REQUESTED_ACTION_NOT_TAKEN, subId, fileName) private fun doWriteReply( session: FtpIoSession, code: Int, subId: String, - fileName: String? = null + fileName: String? = null, ) { val packageName = AppConfig.getInstance().packageName val resources = AppConfig.getInstance().resources @@ -123,9 +127,9 @@ class AVBL : AbstractCommand() { code, resources.getString( resources.getIdentifier("$packageName:string/ftp_error_$subId", null, null), - fileName - ) - ) + fileName, + ), + ), ) } } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/ftpserver/commands/FEAT.kt b/app/src/main/java/com/amaze/filemanager/filesystem/ftpserver/commands/FEAT.kt index 15ef9a814a..ee284fd11e 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/ftpserver/commands/FEAT.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/ftpserver/commands/FEAT.kt @@ -33,13 +33,17 @@ import org.apache.ftpserver.impl.FtpServerContext * Custom [org.apache.ftpserver.command.impl.FEAT] to add [AVBL] command to the list. */ class FEAT : AbstractCommand() { - override fun execute(session: FtpIoSession, context: FtpServerContext, request: FtpRequest) { + override fun execute( + session: FtpIoSession, + context: FtpServerContext, + request: FtpRequest, + ) { session.resetState() session.write( DefaultFtpReply( FtpReply.REPLY_211_SYSTEM_STATUS_REPLY, - AppConfig.getInstance().getString(R.string.ftp_command_FEAT) - ) + AppConfig.getInstance().getString(R.string.ftp_command_FEAT), + ), ) } } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/ftpserver/commands/PWD.kt b/app/src/main/java/com/amaze/filemanager/filesystem/ftpserver/commands/PWD.kt index 85da3468e8..eb270d168f 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/ftpserver/commands/PWD.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/ftpserver/commands/PWD.kt @@ -33,17 +33,17 @@ import java.io.IOException * Monkey-patch [org.apache.ftpserver.command.impl.PWD] to prevent true path exposed to end user. */ class PWD : AbstractCommand() { - @Throws(IOException::class, FtpException::class) override fun execute( session: FtpIoSession, context: FtpServerContext, - request: FtpRequest + request: FtpRequest, ) { session.resetState() val fsView = session.fileSystemView - var currDir = fsView.workingDirectory.absolutePath - .substringAfter(fsView.homeDirectory.absolutePath) + var currDir = + fsView.workingDirectory.absolutePath + .substringAfter(fsView.homeDirectory.absolutePath) if (currDir.isEmpty()) { currDir = "/" } @@ -57,8 +57,8 @@ class PWD : AbstractCommand() { context, FtpReply.REPLY_257_PATHNAME_CREATED, "PWD", - currDir - ) + currDir, + ), ) } } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/root/ChangeFilePermissionsCommand.kt b/app/src/main/java/com/amaze/filemanager/filesystem/root/ChangeFilePermissionsCommand.kt index 490827774d..19715c0d56 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/root/ChangeFilePermissionsCommand.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/root/ChangeFilePermissionsCommand.kt @@ -26,7 +26,6 @@ import com.amaze.filemanager.filesystem.root.base.IRootCommand import com.topjohnwu.superuser.Shell object ChangeFilePermissionsCommand : IRootCommand() { - private const val CHMOD_COMMAND = "chmod %s %o \"%s\"" /** @@ -41,17 +40,18 @@ object ChangeFilePermissionsCommand : IRootCommand() { filePath: String, updatedPermissions: Int, isDirectory: Boolean, - onOperationPerform: (Boolean) -> Unit + onOperationPerform: (Boolean) -> Unit, ) { val mountPoint = MountPathCommand.mountPath(filePath, MountPathCommand.READ_WRITE) val options = if (isDirectory) "-R" else "" - val command = String.format( - CHMOD_COMMAND, - options, - updatedPermissions, - RootHelper.getCommandLineString(filePath) - ) + val command = + String.format( + CHMOD_COMMAND, + options, + updatedPermissions, + RootHelper.getCommandLineString(filePath), + ) runShellCommand(command).let { result: Shell.Result -> if (result.code < 0) { diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/root/ConcatenateFileCommand.kt b/app/src/main/java/com/amaze/filemanager/filesystem/root/ConcatenateFileCommand.kt index 9578ce446d..b53d8b4910 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/root/ConcatenateFileCommand.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/root/ConcatenateFileCommand.kt @@ -25,16 +25,18 @@ import com.amaze.filemanager.filesystem.RootHelper import com.amaze.filemanager.filesystem.root.base.IRootCommand object ConcatenateFileCommand : IRootCommand() { - /** * Concatenates (cat) file data to destination */ @Throws(ShellNotRunningException::class) - fun concatenateFile(sourcePath: String, destinationPath: String) { + fun concatenateFile( + sourcePath: String, + destinationPath: String, + ) { val mountPoint = MountPathCommand.mountPath(destinationPath, MountPathCommand.READ_WRITE) runShellCommand( "cat \"${RootHelper.getCommandLineString(sourcePath)}\"" + - " > \"${RootHelper.getCommandLineString(destinationPath)}\"" + " > \"${RootHelper.getCommandLineString(destinationPath)}\"", ) mountPoint?.let { MountPathCommand.mountPath(it, MountPathCommand.READ_ONLY) } } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/root/CopyFilesCommand.kt b/app/src/main/java/com/amaze/filemanager/filesystem/root/CopyFilesCommand.kt index a8598038f4..b92db336b2 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/root/CopyFilesCommand.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/root/CopyFilesCommand.kt @@ -26,20 +26,22 @@ import com.amaze.filemanager.filesystem.root.MountPathCommand.mountPath import com.amaze.filemanager.filesystem.root.base.IRootCommand object CopyFilesCommand : IRootCommand() { - /** * Copies files using root * @param source given source * @param destination given destination */ @Throws(ShellNotRunningException::class) - fun copyFiles(source: String, destination: String) { + fun copyFiles( + source: String, + destination: String, + ) { // remounting destination as rw val mountPoint = mountPath(destination, MountPathCommand.READ_WRITE) runShellCommand( "cp -r \"${RootHelper.getCommandLineString(source)}\" " + - "\"${RootHelper.getCommandLineString(destination)}\"" + "\"${RootHelper.getCommandLineString(destination)}\"", ) // we mounted the filesystem as rw, let's mount it back to ro diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/root/DeleteFileCommand.kt b/app/src/main/java/com/amaze/filemanager/filesystem/root/DeleteFileCommand.kt index 72385c02b8..228a2e54e5 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/root/DeleteFileCommand.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/root/DeleteFileCommand.kt @@ -25,7 +25,6 @@ import com.amaze.filemanager.filesystem.RootHelper import com.amaze.filemanager.filesystem.root.base.IRootCommand object DeleteFileCommand : IRootCommand() { - /** * Recursively removes a path with it's contents (if any) * @@ -34,9 +33,10 @@ object DeleteFileCommand : IRootCommand() { @Throws(ShellNotRunningException::class) fun deleteFile(path: String): Boolean { val mountPoint = MountPathCommand.mountPath(path, MountPathCommand.READ_WRITE) - val result = runShellCommandToList( - "rm -rf \"${RootHelper.getCommandLineString(path)}\"" - ) + val result = + runShellCommandToList( + "rm -rf \"${RootHelper.getCommandLineString(path)}\"", + ) mountPoint?.let { MountPathCommand.mountPath(it, MountPathCommand.READ_ONLY) } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/root/FindFileCommand.kt b/app/src/main/java/com/amaze/filemanager/filesystem/root/FindFileCommand.kt index a9baef6a64..33ad38bb71 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/root/FindFileCommand.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/root/FindFileCommand.kt @@ -25,7 +25,6 @@ import com.amaze.filemanager.filesystem.RootHelper import com.amaze.filemanager.filesystem.root.base.IRootCommand object FindFileCommand : IRootCommand() { - /** * find file at given path in root * @@ -33,9 +32,10 @@ object FindFileCommand : IRootCommand() { */ @Throws(ShellNotRunningException::class) fun findFile(path: String): Boolean { - val result = runShellCommandToList( - "find \"${RootHelper.getCommandLineString(path)}\"" - ) + val result = + runShellCommandToList( + "find \"${RootHelper.getCommandLineString(path)}\"", + ) return result.isNotEmpty() } } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/root/ListFilesCommand.kt b/app/src/main/java/com/amaze/filemanager/filesystem/root/ListFilesCommand.kt index 3b2964fc75..a3ecf77d55 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/root/ListFilesCommand.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/root/ListFilesCommand.kt @@ -37,7 +37,6 @@ import org.slf4j.LoggerFactory import java.io.File object ListFilesCommand : IRootCommand() { - private val log: Logger = LoggerFactory.getLogger(ListFilesCommand::class.java) /** @@ -48,7 +47,7 @@ object ListFilesCommand : IRootCommand() { root: Boolean, showHidden: Boolean, openModeCallback: (openMode: OpenMode) -> Unit, - onFileFoundCallback: (file: HybridFileParcelable) -> Unit + onFileFoundCallback: (file: HybridFileParcelable) -> Unit, ) { val mode: OpenMode if (root && FileUtils.isRunningAboveStorage(path)) { @@ -60,7 +59,7 @@ object ListFilesCommand : IRootCommand() { parseStringForHybridFile( rawFile = it, path = path, - isStat = !result.second + isStat = !result.second, ) ?.let(onFileFoundCallback) } @@ -84,13 +83,14 @@ object ListFilesCommand : IRootCommand() { */ fun getOpenMode( path: String, - root: Boolean + root: Boolean, ): OpenMode { - val mode: OpenMode = if (root && FileUtils.isRunningAboveStorage(path)) { - OpenMode.ROOT - } else { - OpenMode.FILE - } + val mode: OpenMode = + if (root && FileUtils.isRunningAboveStorage(path)) { + OpenMode.ROOT + } else { + OpenMode.FILE + } return mode } @@ -102,7 +102,7 @@ object ListFilesCommand : IRootCommand() { fun executeRootCommand( path: String, showHidden: Boolean, - retryWithLs: Boolean = false + retryWithLs: Boolean = false, ): Pair, Boolean> { try { /** @@ -111,18 +111,20 @@ object ListFilesCommand : IRootCommand() { */ var appendedPath = path val sanitizedPath = RootHelper.getCommandLineString(appendedPath) - appendedPath = when (path) { - "/" -> sanitizedPath.replace("/", "") - else -> sanitizedPath.plus("/") - } + appendedPath = + when (path) { + "/" -> sanitizedPath.replace("/", "") + else -> sanitizedPath.plus("/") + } - val command = "stat -c '%A %h %G %U %B %Y %N' " + - "$appendedPath*" + (if (showHidden) " $appendedPath.* " else "") + val command = + "stat -c '%A %h %G %U %B %Y %N' " + + "$appendedPath*" + (if (showHidden) " $appendedPath.* " else "") val enforceLegacyFileListing: Boolean = PreferenceManager.getDefaultSharedPreferences(AppConfig.getInstance()) .getBoolean( PreferencesConstants.PREFERENCE_ROOT_LEGACY_LISTING, - false + false, ) // #3476: Check current working dir, change back to / before proceeding runShellCommand("pwd").run { @@ -133,23 +135,26 @@ object ListFilesCommand : IRootCommand() { return if (!retryWithLs && !enforceLegacyFileListing) { log.info("Using stat for list parsing") Pair( - first = runShellCommandToList(command).map { - it.replace(appendedPath, "") - }, - second = enforceLegacyFileListing + first = + runShellCommandToList(command).map { + it.replace(appendedPath, "") + }, + second = enforceLegacyFileListing, ) } else { log.info("Using ls for list parsing") Pair( - first = runShellCommandToList( - "ls -l " + (if (showHidden) "-a " else "") + - "\"$sanitizedPath\"" - ), - second = if (retryWithLs) { - true - } else { - enforceLegacyFileListing - } + first = + runShellCommandToList( + "ls -l " + (if (showHidden) "-a " else "") + + "\"$sanitizedPath\"", + ), + second = + if (retryWithLs) { + true + } else { + enforceLegacyFileListing + }, ) } } catch (invalidCommand: ShellCommandInvalidException) { @@ -177,7 +182,7 @@ object ListFilesCommand : IRootCommand() { private fun getFilesList( path: String, showHidden: Boolean, - listener: (HybridFileParcelable) -> Unit + listener: (HybridFileParcelable) -> Unit, ): ArrayList { val pathFile = File(path) val files = ArrayList() @@ -192,7 +197,7 @@ object ListFilesCommand : IRootCommand() { RootHelper.parseFilePermission(currentFile), currentFile.lastModified(), size, - currentFile.isDirectory + currentFile.isDirectory, ).let { baseFile -> baseFile.name = currentFile.name baseFile.mode = OpenMode.FILE @@ -223,14 +228,18 @@ object ListFilesCommand : IRootCommand() { private fun parseStringForHybridFile( rawFile: String, path: String, - isStat: Boolean + isStat: Boolean, ): HybridFileParcelable? { return FileUtils.parseName( - if (isStat) rawFile.replace( - "('|`)".toRegex(), - "" - ) else rawFile, - isStat + if (isStat) { + rawFile.replace( + "('|`)".toRegex(), + "", + ) + } else { + rawFile + }, + isStat, )?.apply { this.mode = OpenMode.ROOT this.name = this.path diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/root/MakeDirectoryCommand.kt b/app/src/main/java/com/amaze/filemanager/filesystem/root/MakeDirectoryCommand.kt index d159b0ebeb..4382039b12 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/root/MakeDirectoryCommand.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/root/MakeDirectoryCommand.kt @@ -25,7 +25,6 @@ import com.amaze.filemanager.filesystem.RootHelper import com.amaze.filemanager.filesystem.root.base.IRootCommand object MakeDirectoryCommand : IRootCommand() { - /** * Creates an empty directory using root * @@ -33,7 +32,10 @@ object MakeDirectoryCommand : IRootCommand() { * @param name name of directory */ @Throws(ShellNotRunningException::class) - fun makeDirectory(path: String, name: String) { + fun makeDirectory( + path: String, + name: String, + ) { val mountPoint = MountPathCommand.mountPath(path, MountPathCommand.READ_WRITE) val filePath = "$path/$name" runShellCommand("mkdir \"${RootHelper.getCommandLineString(filePath)}\"") diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/root/MakeFileCommand.kt b/app/src/main/java/com/amaze/filemanager/filesystem/root/MakeFileCommand.kt index 2a80ce33c3..fa0efb6611 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/root/MakeFileCommand.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/root/MakeFileCommand.kt @@ -25,7 +25,6 @@ import com.amaze.filemanager.filesystem.RootHelper import com.amaze.filemanager.filesystem.root.base.IRootCommand object MakeFileCommand : IRootCommand() { - /** * Creates an empty file using root * diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/root/MountPathCommand.kt b/app/src/main/java/com/amaze/filemanager/filesystem/root/MountPathCommand.kt index 9c26ba7641..fd2e61e430 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/root/MountPathCommand.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/root/MountPathCommand.kt @@ -26,7 +26,6 @@ import com.amaze.filemanager.filesystem.RootHelper import com.amaze.filemanager.filesystem.root.base.IRootCommand object MountPathCommand : IRootCommand() { - const val READ_ONLY = "RO" const val READ_WRITE = "RW" @@ -39,7 +38,10 @@ object MountPathCommand : IRootCommand() { * @return String the root of mount point that was ro, and mounted to rw; null otherwise */ @Throws(ShellNotRunningException::class) - fun mountPath(pathArg: String, operation: String): String? { + fun mountPath( + pathArg: String, + operation: String, + ): String? { val path = RootHelper.getCommandLineString(pathArg) return when (operation) { READ_WRITE -> mountReadWrite(path) diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/root/MoveFileCommand.kt b/app/src/main/java/com/amaze/filemanager/filesystem/root/MoveFileCommand.kt index 5942486efc..b3ff0a5fc9 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/root/MoveFileCommand.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/root/MoveFileCommand.kt @@ -25,18 +25,21 @@ import com.amaze.filemanager.filesystem.RootHelper import com.amaze.filemanager.filesystem.root.base.IRootCommand object MoveFileCommand : IRootCommand() { - /** * Move files using root * @param path source path * @param destination */ @Throws(ShellNotRunningException::class) - fun moveFile(path: String, destination: String) { + fun moveFile( + path: String, + destination: String, + ) { // remounting destination as rw val mountPoint = MountPathCommand.mountPath(destination, MountPathCommand.READ_WRITE) - val command = "mv \"${RootHelper.getCommandLineString(path)}\"" + - " \"${RootHelper.getCommandLineString(destination)}\"" + val command = + "mv \"${RootHelper.getCommandLineString(path)}\"" + + " \"${RootHelper.getCommandLineString(destination)}\"" runShellCommand(command) mountPoint?.let { MountPathCommand.mountPath(it, MountPathCommand.READ_ONLY) } } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/root/RenameFileCommand.kt b/app/src/main/java/com/amaze/filemanager/filesystem/root/RenameFileCommand.kt index 7720277ed4..e3e0e4fe14 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/root/RenameFileCommand.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/root/RenameFileCommand.kt @@ -28,7 +28,6 @@ import org.slf4j.Logger import org.slf4j.LoggerFactory object RenameFileCommand : IRootCommand() { - private val log: Logger = LoggerFactory.getLogger(RenameFileCommand::class.java) /** @@ -39,10 +38,14 @@ object RenameFileCommand : IRootCommand() { * @return if rename was successful or not */ @Throws(ShellNotRunningException::class) - fun renameFile(oldPath: String, newPath: String): Boolean { + fun renameFile( + oldPath: String, + newPath: String, + ): Boolean { val mountPoint = MountPathCommand.mountPath(oldPath, MountPathCommand.READ_WRITE) - val command = "mv \"${RootHelper.getCommandLineString(oldPath)}\"" + - " \"${RootHelper.getCommandLineString(newPath)}\"" + val command = + "mv \"${RootHelper.getCommandLineString(oldPath)}\"" + + " \"${RootHelper.getCommandLineString(newPath)}\"" return try { val output = runShellCommandToList(command) mountPoint?.let { MountPathCommand.mountPath(it, MountPathCommand.READ_ONLY) } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/root/base/IRootCommand.kt b/app/src/main/java/com/amaze/filemanager/filesystem/root/base/IRootCommand.kt index ef14cd94da..5449613ba9 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/root/base/IRootCommand.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/root/base/IRootCommand.kt @@ -26,7 +26,6 @@ import com.amaze.filemanager.ui.activities.MainActivity import com.topjohnwu.superuser.Shell open class IRootCommand { - /** * Runs the command and stores output in a list. The listener is set on the handler thread [ ] * [MainActivity.handlerThread] thus any code run in callback must be thread safe. Command is run diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/smb/CifsContexts.kt b/app/src/main/java/com/amaze/filemanager/filesystem/smb/CifsContexts.kt index 229cdb38b1..08246ff1d8 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/smb/CifsContexts.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/smb/CifsContexts.kt @@ -33,17 +33,17 @@ import java.util.* import java.util.concurrent.ConcurrentHashMap object CifsContexts { - const val SMB_URI_PREFIX = "smb://" private val TAG = CifsContexts::class.java.simpleName - private val defaultProperties: Properties = Properties().apply { - setProperty("jcifs.resolveOrder", "BCAST") - setProperty("jcifs.smb.client.responseTimeout", "30000") - setProperty("jcifs.netbios.retryTimeout", "5000") - setProperty("jcifs.netbios.cachePolicy", "-1") - } + private val defaultProperties: Properties = + Properties().apply { + setProperty("jcifs.resolveOrder", "BCAST") + setProperty("jcifs.smb.client.responseTimeout", "30000") + setProperty("jcifs.netbios.retryTimeout", "5000") + setProperty("jcifs.netbios.cachePolicy", "-1") + } private val contexts: MutableMap = ConcurrentHashMap() @@ -62,7 +62,7 @@ object CifsContexts { @JvmStatic fun createWithDisableIpcSigningCheck( basePath: String, - disableIpcSigningCheck: Boolean + disableIpcSigningCheck: Boolean, ): BaseContext { return if (disableIpcSigningCheck) { val extraProperties = Properties() @@ -74,26 +74,31 @@ object CifsContexts { } @JvmStatic - fun create(basePath: String, extraProperties: Properties?): BaseContext { - val basePathKey: String = Uri.parse(basePath).run { - val prefix = "$scheme://$authority" - val suffix = if (TextUtils.isEmpty(query)) "" else "?$query" - "$prefix$suffix" - } + fun create( + basePath: String, + extraProperties: Properties?, + ): BaseContext { + val basePathKey: String = + Uri.parse(basePath).run { + val prefix = "$scheme://$authority" + val suffix = if (TextUtils.isEmpty(query)) "" else "?$query" + "$prefix$suffix" + } return if (contexts.containsKey(basePathKey)) { contexts.getValue(basePathKey) } else { - val context = Single.fromCallable { - try { - val p = Properties(defaultProperties) - if (extraProperties != null) p.putAll(extraProperties) - BaseContext(PropertyConfiguration(p)) - } catch (e: CIFSException) { - Log.e(TAG, "Error initialize jcifs BaseContext, returning default", e) - SingletonContext.getInstance() - } - }.subscribeOn(Schedulers.io()) - .blockingGet() + val context = + Single.fromCallable { + try { + val p = Properties(defaultProperties) + if (extraProperties != null) p.putAll(extraProperties) + BaseContext(PropertyConfiguration(p)) + } catch (e: CIFSException) { + Log.e(TAG, "Error initialize jcifs BaseContext, returning default", e) + SingletonContext.getInstance() + } + }.subscribeOn(Schedulers.io()) + .blockingGet() contexts[basePathKey] = context context } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/ssh/CustomSshJConfig.kt b/app/src/main/java/com/amaze/filemanager/filesystem/ssh/CustomSshJConfig.kt index 87e3849930..285dbfe778 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/ssh/CustomSshJConfig.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/ssh/CustomSshJConfig.kt @@ -36,7 +36,6 @@ import java.security.Security * @see net.schmizz.sshj.AndroidConfig */ class CustomSshJConfig : DefaultConfig() { - companion object { /** * This is where we different from the original AndroidConfig. Found it only work if we remove diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/ssh/SFTPClientExt.kt b/app/src/main/java/com/amaze/filemanager/filesystem/ssh/SFTPClientExt.kt index 4f36e35996..7241f3b444 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/ssh/SFTPClientExt.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/ssh/SFTPClientExt.kt @@ -39,13 +39,14 @@ const val READ_AHEAD_MAX_UNCONFIRMED_READS: Int = 16 fun SFTPEngine.openWithReadAheadSupport( path: String, modes: Set, - fa: FileAttributes + fa: FileAttributes, ): RemoteFile { - val handle: ByteArray = request( - newRequest(PacketType.OPEN).putString(path, subsystem.remoteCharset) - .putUInt32(OpenMode.toMask(modes).toLong()).putFileAttributes(fa) - ).retrieve(timeoutMs.toLong(), TimeUnit.MILLISECONDS) - .ensurePacketTypeIs(PacketType.HANDLE).readBytes() + val handle: ByteArray = + request( + newRequest(PacketType.OPEN).putString(path, subsystem.remoteCharset) + .putUInt32(OpenMode.toMask(modes).toLong()).putFileAttributes(fa), + ).retrieve(timeoutMs.toLong(), TimeUnit.MILLISECONDS) + .ensurePacketTypeIs(PacketType.HANDLE).readBytes() return RemoteFile(this, path, handle) } @@ -56,6 +57,6 @@ fun SFTPClient.openWithReadAheadSupport(path: String): RemoteFile { return sftpEngine.openWithReadAheadSupport( path, EnumSet.of(OpenMode.READ), - FileAttributes.EMPTY + FileAttributes.EMPTY, ) } diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/ssh/SFtpClientTemplate.kt b/app/src/main/java/com/amaze/filemanager/filesystem/ssh/SFtpClientTemplate.kt index 046929bdd1..d46d99d27f 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/ssh/SFtpClientTemplate.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/ssh/SFtpClientTemplate.kt @@ -32,7 +32,6 @@ import java.io.IOException */ abstract class SFtpClientTemplate(url: String, closeClientOnFinish: Boolean = true) : SshClientTemplate(url, closeClientOnFinish) { - private val LOG: Logger = LoggerFactory.getLogger(javaClass) override fun executeWithSSHClient(sshClient: SSHClient): T? { diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/ssh/SshClientSessionTemplate.kt b/app/src/main/java/com/amaze/filemanager/filesystem/ssh/SshClientSessionTemplate.kt index 87f78b0706..d07c7d7303 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/ssh/SshClientSessionTemplate.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/ssh/SshClientSessionTemplate.kt @@ -23,16 +23,15 @@ package com.amaze.filemanager.filesystem.ssh import net.schmizz.sshj.connection.channel.direct.Session import java.io.IOException -abstract class SshClientSessionTemplate -/** +abstract class SshClientSessionTemplate/** * Constructor. * * @param url SSH connection URL, in the form of ` * ssh://:@:` or ` * ssh://@:` - */ -(@JvmField val url: String) { - + */( + @JvmField val url: String, +) { /** * Implement logic here. * diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/ssh/SshClientTemplate.kt b/app/src/main/java/com/amaze/filemanager/filesystem/ssh/SshClientTemplate.kt index 2d56ac0be3..41d695a613 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/ssh/SshClientTemplate.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/ssh/SshClientTemplate.kt @@ -31,7 +31,6 @@ import java.io.IOException */ abstract class SshClientTemplate(url: String, closeClientOnFinish: Boolean = true) : NetCopyClientTemplate(url, closeClientOnFinish) { - @Throws(IOException::class) final override fun execute(client: NetCopyClient): T? { val sshClient: SSHClient = client.getClientImpl() diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/ssh/SshClientUtils.kt b/app/src/main/java/com/amaze/filemanager/filesystem/ssh/SshClientUtils.kt index 12c8c40094..b70ab11125 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/ssh/SshClientUtils.kt +++ b/app/src/main/java/com/amaze/filemanager/filesystem/ssh/SshClientUtils.kt @@ -42,17 +42,18 @@ import java.io.IOException import kotlin.concurrent.thread object SshClientUtils { - @JvmStatic private val LOG = LoggerFactory.getLogger(SshClientUtils::class.java) @JvmField val sftpGetSize: (String) -> Long? = { path -> - NetCopyClientUtils.execute(object : SFtpClientTemplate(path, true) { - override fun execute(client: SFTPClient): Long { - return client.size(extractRemotePathFrom(path)) - } - }) + NetCopyClientUtils.execute( + object : SFtpClientTemplate(path, true) { + override fun execute(client: SFTPClient): Long { + return client.size(extractRemotePathFrom(path)) + } + }, + ) } /** @@ -85,7 +86,7 @@ object SshClientUtils { } return retval } - } + }, ) } @@ -111,7 +112,7 @@ object SshClientUtils { @JvmStatic fun formatPlainServerPathToAuthorised( servers: ArrayList>, - path: String + path: String, ): String { for (serverEntry in servers) { val inputUri = Uri.parse(path) @@ -119,11 +120,12 @@ object SshClientUtils { if (inputUri.scheme.equals(serverUri.scheme, ignoreCase = true) && serverUri.authority!!.contains(inputUri.authority!!) ) { - val output = inputUri - .buildUpon() - .encodedAuthority(serverUri.encodedAuthority) - .build() - .toString() + val output = + inputUri + .buildUpon() + .encodedAuthority(serverUri.encodedAuthority) + .build() + .toString() LOG.info("build authorised path {} from plain path {}", output, path) return output } @@ -153,7 +155,10 @@ object SshClientUtils { */ @JvmStatic @Suppress("Detekt.TooGenericExceptionCaught") - fun launchFtp(baseFile: HybridFile, activity: MainActivity) { + fun launchFtp( + baseFile: HybridFile, + activity: MainActivity, + ) { val streamer = CloudStreamer.getInstance() thread { try { @@ -162,20 +167,21 @@ object SshClientUtils { streamer.setStreamSrc( baseFile.getInputStream(activity), baseFile.getName(activity), - fileLength + fileLength, ) activity.runOnUiThread { try { - val file = File( - extractRemotePathFrom( - baseFile.path + val file = + File( + extractRemotePathFrom( + baseFile.path, + ), ) - ) val uri = Uri.parse(CloudStreamer.URL + Uri.fromFile(file).encodedPath) val i = Intent(Intent.ACTION_VIEW) i.setDataAndType( uri, - MimeTypes.getMimeType(baseFile.path, isDirectory) + MimeTypes.getMimeType(baseFile.path, isDirectory), ) val packageManager = activity.packageManager val resInfos = packageManager.queryIntentActivities(i, 0) @@ -185,7 +191,7 @@ object SshClientUtils { Toast.makeText( activity, activity.resources.getString(R.string.smb_launch_error), - Toast.LENGTH_SHORT + Toast.LENGTH_SHORT, ) .show() } @@ -206,7 +212,10 @@ object SshClientUtils { */ @JvmStatic @Throws(IOException::class) - fun isDirectory(client: SFTPClient, info: RemoteResourceInfo): Boolean { + fun isDirectory( + client: SFTPClient, + info: RemoteResourceInfo, + ): Boolean { var isDirectory = info.isDirectory if (info.attributes.type == FileMode.Type.SYMLINK) { try { diff --git a/app/src/main/java/com/amaze/filemanager/filesystem/ssh/Statvfs.java b/app/src/main/java/com/amaze/filemanager/filesystem/ssh/Statvfs.java index a4eef976b8..3f60c32cbb 100644 --- a/app/src/main/java/com/amaze/filemanager/filesystem/ssh/Statvfs.java +++ b/app/src/main/java/com/amaze/filemanager/filesystem/ssh/Statvfs.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/ColorCircleDrawable.java b/app/src/main/java/com/amaze/filemanager/ui/ColorCircleDrawable.java index dec8bb829e..b7a23342ef 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/ColorCircleDrawable.java +++ b/app/src/main/java/com/amaze/filemanager/ui/ColorCircleDrawable.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/Extensions.kt b/app/src/main/java/com/amaze/filemanager/ui/Extensions.kt index 98d28b1d7f..eced7e276c 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/Extensions.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/Extensions.kt @@ -68,13 +68,13 @@ fun Context.updateAUAlias(shouldEnable: Boolean) { packageManager.setComponentEnabledSetting( component, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, - PackageManager.DONT_KILL_APP + PackageManager.DONT_KILL_APP, ) } else { packageManager.setComponentEnabledSetting( component, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, - PackageManager.DONT_KILL_APP + PackageManager.DONT_KILL_APP, ) } } @@ -90,10 +90,10 @@ fun AppCompatEditText.openKeyboard(context: Context) { (context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager) .showSoftInput( this, - InputMethodManager.SHOW_IMPLICIT + InputMethodManager.SHOW_IMPLICIT, ) }, - 100 + 100, ) } @@ -116,7 +116,10 @@ fun View.showFade(duration: Long) { /** * Extension function to check for activity in package manager before triggering code */ -fun Intent.runIfDocumentsUIExists(context: Context, callback: Runnable) { +fun Intent.runIfDocumentsUIExists( + context: Context, + callback: Runnable, +) { if (this.resolveActivity(context.packageManager) != null) { callback.run() } else { diff --git a/app/src/main/java/com/amaze/filemanager/ui/ItemPopupMenu.java b/app/src/main/java/com/amaze/filemanager/ui/ItemPopupMenu.java index 38ec94083e..2320ddb3c4 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/ItemPopupMenu.java +++ b/app/src/main/java/com/amaze/filemanager/ui/ItemPopupMenu.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/activities/AboutActivity.java b/app/src/main/java/com/amaze/filemanager/ui/activities/AboutActivity.java index 93c5aa2d87..e74c7f46e9 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/activities/AboutActivity.java +++ b/app/src/main/java/com/amaze/filemanager/ui/activities/AboutActivity.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/activities/DatabaseViewerActivity.java b/app/src/main/java/com/amaze/filemanager/ui/activities/DatabaseViewerActivity.java index 1ed65998a8..23c464bc02 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/activities/DatabaseViewerActivity.java +++ b/app/src/main/java/com/amaze/filemanager/ui/activities/DatabaseViewerActivity.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/activities/MainActivity.java b/app/src/main/java/com/amaze/filemanager/ui/activities/MainActivity.java index ff894315c9..691c8aa341 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/activities/MainActivity.java +++ b/app/src/main/java/com/amaze/filemanager/ui/activities/MainActivity.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. @@ -277,6 +277,7 @@ public class MainActivity extends PermissionsActivity private UtilsHandler utilsHandler; private CloudHandler cloudHandler; private CloudLoaderAsyncTask cloudLoaderAsyncTask; + /** * This is for a hack. * diff --git a/app/src/main/java/com/amaze/filemanager/ui/activities/MainActivityViewModel.kt b/app/src/main/java/com/amaze/filemanager/ui/activities/MainActivityViewModel.kt index 82c290f4f2..e9c8c83246 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/activities/MainActivityViewModel.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/activities/MainActivityViewModel.kt @@ -54,7 +54,6 @@ import java.io.File class MainActivityViewModel(val applicationContext: Application) : AndroidViewModel(applicationContext) { - var mediaCacheHash: List?> = List(5) { null } var listCache: LruCache> = LruCache(50) var trashBinFilesLiveData: MutableLiveData?>? = null @@ -78,7 +77,10 @@ class MainActivityViewModel(val applicationContext: Application) : /** * Put list for a given path in cache */ - fun putInCache(path: String, listToCache: List) { + fun putInCache( + path: String, + listToCache: List, + ) { viewModelScope.launch(Dispatchers.Default) { listCache.put(path, listToCache) } @@ -110,17 +112,20 @@ class MainActivityViewModel(val applicationContext: Application) : /** * Perform basic search: searches on the current directory */ - fun basicSearch(mainActivity: MainActivity, query: String): - LiveData> { + fun basicSearch( + mainActivity: MainActivity, + query: String, + ): LiveData> { val searchParameters = createSearchParameters(mainActivity) val path = mainActivity.currentMainFragment?.currentPath ?: "" val basicSearch = BasicSearch(query, path, searchParameters, this.applicationContext) - lastSearchJob = viewModelScope.launch(Dispatchers.IO) { - basicSearch.search() - } + lastSearchJob = + viewModelScope.launch(Dispatchers.IO) { + basicSearch.search() + } lastSearchLiveData = basicSearch.foundFilesLiveData return basicSearch.foundFilesLiveData @@ -131,16 +136,18 @@ class MainActivityViewModel(val applicationContext: Application) : */ fun indexedSearch( mainActivity: MainActivity, - query: String + query: String, ): LiveData> { - val projection = arrayOf( - MediaStore.Files.FileColumns.DATA, - MediaStore.Files.FileColumns.DISPLAY_NAME - ) - val cursor = mainActivity - .contentResolver - .query(MediaStore.Files.getContentUri("external"), projection, null, null, null) - ?: return MutableLiveData() + val projection = + arrayOf( + MediaStore.Files.FileColumns.DATA, + MediaStore.Files.FileColumns.DISPLAY_NAME, + ) + val cursor = + mainActivity + .contentResolver + .query(MediaStore.Files.getContentUri("external"), projection, null, null, null) + ?: return MutableLiveData() val searchParameters = createSearchParameters(mainActivity) @@ -148,9 +155,10 @@ class MainActivityViewModel(val applicationContext: Application) : val indexedSearch = IndexedSearch(query, path, searchParameters, cursor) - lastSearchJob = viewModelScope.launch(Dispatchers.IO) { - indexedSearch.search() - } + lastSearchJob = + viewModelScope.launch(Dispatchers.IO) { + indexedSearch.search() + } lastSearchLiveData = indexedSearch.foundFilesLiveData return indexedSearch.foundFilesLiveData @@ -161,7 +169,7 @@ class MainActivityViewModel(val applicationContext: Application) : */ fun deepSearch( mainActivity: MainActivity, - query: String + query: String, ): LiveData> { val searchParameters = createSearchParameters(mainActivity) @@ -171,17 +179,19 @@ class MainActivityViewModel(val applicationContext: Application) : val context = this.applicationContext - val deepSearch = DeepSearch( - query, - path, - searchParameters, - context, - openMode - ) + val deepSearch = + DeepSearch( + query, + path, + searchParameters, + context, + openMode, + ) - lastSearchJob = viewModelScope.launch(Dispatchers.IO) { - deepSearch.search() - } + lastSearchJob = + viewModelScope.launch(Dispatchers.IO) { + deepSearch.search() + } lastSearchLiveData = deepSearch.foundFilesLiveData return deepSearch.foundFilesLiveData @@ -193,7 +203,7 @@ class MainActivityViewModel(val applicationContext: Application) : showHiddenFiles = sharedPref.getBoolean(PREFERENCE_SHOW_HIDDENFILES, false), isRegexEnabled = sharedPref.getBoolean(PREFERENCE_REGEX, false), isRegexMatchesEnabled = sharedPref.getBoolean(PREFERENCE_REGEX_MATCHES, false), - isRoot = mainActivity.isRootExplorer + isRoot = mainActivity.isRootExplorer, ) } @@ -202,27 +212,29 @@ class MainActivityViewModel(val applicationContext: Application) : */ fun moveToBinLightWeight(mediaFileInfoList: List) { viewModelScope.launch(Dispatchers.IO) { - val trashBinFilesList = mediaFileInfoList.map { - it.generateBaseFile() - .toTrashBinFile(applicationContext) - } + val trashBinFilesList = + mediaFileInfoList.map { + it.generateBaseFile() + .toTrashBinFile(applicationContext) + } AppConfig.getInstance().trashBinInstance.moveToBin( trashBinFilesList, true, object : MoveFilesCallback { override fun invoke( originalFilePath: String, - trashBinDestination: String + trashBinDestination: String, ): Boolean { val source = File(originalFilePath) val dest = File(trashBinDestination) if (!source.renameTo(dest)) { return false } - val hybridFile = HybridFile( - OpenMode.TRASH_BIN, - originalFilePath - ) + val hybridFile = + HybridFile( + OpenMode.TRASH_BIN, + originalFilePath, + ) scanFile(applicationContext, arrayOf(hybridFile)) val intent = Intent(MainActivity.KEY_INTENT_LOAD_LIST) hybridFile.getParent(applicationContext)?.let { @@ -231,7 +243,7 @@ class MainActivityViewModel(val applicationContext: Application) : } return true } - } + }, ) } } @@ -244,8 +256,9 @@ class MainActivityViewModel(val applicationContext: Application) : LOG.info("Restoring media files from bin $mediaFileInfoList") val filesToRestore = mutableListOf() for (element in mediaFileInfoList) { - val restoreFile = element.generateBaseFile() - .toTrashBinRestoreFile(applicationContext) + val restoreFile = + element.generateBaseFile() + .toTrashBinRestoreFile(applicationContext) if (restoreFile != null) { filesToRestore.add(restoreFile) } @@ -254,13 +267,16 @@ class MainActivityViewModel(val applicationContext: Application) : filesToRestore, true, object : MoveFilesCallback { - override fun invoke(source: String, dest: String): Boolean { + override fun invoke( + source: String, + dest: String, + ): Boolean { val sourceFile = File(source) val destFile = File(dest) if (destFile.exists()) { AppConfig.toast( applicationContext, - applicationContext.getString(R.string.fileexist) + applicationContext.getString(R.string.fileexist), ) return false } @@ -270,10 +286,11 @@ class MainActivityViewModel(val applicationContext: Application) : if (!sourceFile.renameTo(destFile)) { return false } - val hybridFile = HybridFile( - OpenMode.TRASH_BIN, - source - ) + val hybridFile = + HybridFile( + OpenMode.TRASH_BIN, + source, + ) scanFile(applicationContext, arrayOf(hybridFile)) val intent = Intent(MainActivity.KEY_INTENT_LOAD_LIST) hybridFile.getParent(applicationContext)?.let { @@ -282,7 +299,7 @@ class MainActivityViewModel(val applicationContext: Application) : } return true } - } + }, ) } } @@ -302,10 +319,10 @@ class MainActivityViewModel(val applicationContext: Application) : HybridFile(OpenMode.FILE, it.path, it.fileName, it.isDirectory) .generateLayoutElement( applicationContext, - false + false, ) - } - ) + }, + ), ) } } diff --git a/app/src/main/java/com/amaze/filemanager/ui/activities/PreferencesActivity.kt b/app/src/main/java/com/amaze/filemanager/ui/activities/PreferencesActivity.kt index f54dc9848a..7566845fd7 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/activities/PreferencesActivity.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/activities/PreferencesActivity.kt @@ -96,7 +96,9 @@ class PreferencesActivity : ThemedActivity(), FolderChooserDialog.FolderCallback return if (item.itemId == android.R.id.home) { onBackPressed() true - } else false + } else { + false + } } override fun recreate() { @@ -129,14 +131,16 @@ class PreferencesActivity : ThemedActivity(), FolderChooserDialog.FolderCallback * Used to update color */ fun invalidateNavBar() { - val primaryColor = ColorPreferenceHelper - .getPrimary(currentColorPreference, MainActivity.currentTab) + val primaryColor = + ColorPreferenceHelper + .getPrimary(currentColorPreference, MainActivity.currentTab) if (Build.VERSION.SDK_INT == 20 || Build.VERSION.SDK_INT == 19) { val tintManager = SystemBarTintManager(this) tintManager.isStatusBarTintEnabled = true tintManager.setStatusBarTintColor(primaryColor) - val layoutParams = findViewById(R.id.activity_preferences).layoutParams - as ViewGroup.MarginLayoutParams + val layoutParams = + findViewById(R.id.activity_preferences).layoutParams + as ViewGroup.MarginLayoutParams val config = tintManager.config layoutParams.setMargins(0, config.statusBarHeight, 0, 0) } else if (Build.VERSION.SDK_INT >= 21) { @@ -165,7 +169,10 @@ class PreferencesActivity : ThemedActivity(), FolderChooserDialog.FolderCallback } } - override fun onFolderSelection(dialog: FolderChooserDialog, folder: File) { + override fun onFolderSelection( + dialog: FolderChooserDialog, + folder: File, + ) { supportFragmentManager.fragments.lastOrNull { it is BasePrefsFragment }?.let { (it as BasePrefsFragment).onFolderSelection(dialog, folder) } diff --git a/app/src/main/java/com/amaze/filemanager/ui/activities/UtilitiesAliasActivity.kt b/app/src/main/java/com/amaze/filemanager/ui/activities/UtilitiesAliasActivity.kt index 11bbbbc0a2..173c457b62 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/activities/UtilitiesAliasActivity.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/activities/UtilitiesAliasActivity.kt @@ -50,21 +50,23 @@ class UtilitiesAliasActivity : AppCompatActivity() { } else { AboutActivity.URL_AMAZE_UTILS }, - this + this, ) } _binding.cancelButton.setOnClickListener { finish() } - val isAUInstalled = PackageUtils.appInstalledOrNot( - AboutActivity.PACKAGE_AMAZE_UTILS, - packageManager - ) + val isAUInstalled = + PackageUtils.appInstalledOrNot( + AboutActivity.PACKAGE_AMAZE_UTILS, + packageManager, + ) if (isAUInstalled) { AppConfig.toast(this, R.string.amaze_utils_installed_alias) - val intent = packageManager.getLaunchIntentForPackage( - AboutActivity.PACKAGE_AMAZE_UTILS - ) + val intent = + packageManager.getLaunchIntentForPackage( + AboutActivity.PACKAGE_AMAZE_UTILS, + ) try { if (intent != null) { this.updateAUAlias(false) diff --git a/app/src/main/java/com/amaze/filemanager/ui/activities/superclasses/BasicActivity.java b/app/src/main/java/com/amaze/filemanager/ui/activities/superclasses/BasicActivity.java index 21de42aa06..a5ebc37afc 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/activities/superclasses/BasicActivity.java +++ b/app/src/main/java/com/amaze/filemanager/ui/activities/superclasses/BasicActivity.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/activities/superclasses/PermissionsActivity.java b/app/src/main/java/com/amaze/filemanager/ui/activities/superclasses/PermissionsActivity.java index 3a81b5ff2b..821f433420 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/activities/superclasses/PermissionsActivity.java +++ b/app/src/main/java/com/amaze/filemanager/ui/activities/superclasses/PermissionsActivity.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/activities/superclasses/PreferenceActivity.java b/app/src/main/java/com/amaze/filemanager/ui/activities/superclasses/PreferenceActivity.java index 44f83b2ae9..526264186f 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/activities/superclasses/PreferenceActivity.java +++ b/app/src/main/java/com/amaze/filemanager/ui/activities/superclasses/PreferenceActivity.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/activities/superclasses/ThemedActivity.java b/app/src/main/java/com/amaze/filemanager/ui/activities/superclasses/ThemedActivity.java index 5990be75cb..cbee76f25d 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/activities/superclasses/ThemedActivity.java +++ b/app/src/main/java/com/amaze/filemanager/ui/activities/superclasses/ThemedActivity.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/activities/texteditor/ReturnedValueOnReadFile.kt b/app/src/main/java/com/amaze/filemanager/ui/activities/texteditor/ReturnedValueOnReadFile.kt index a7dc27bbdd..99ddc3550e 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/activities/texteditor/ReturnedValueOnReadFile.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/activities/texteditor/ReturnedValueOnReadFile.kt @@ -25,5 +25,5 @@ import java.io.File data class ReturnedValueOnReadFile( val fileContents: String, val cachedFile: File?, - val fileIsTooLong: Boolean + val fileIsTooLong: Boolean, ) diff --git a/app/src/main/java/com/amaze/filemanager/ui/activities/texteditor/TextEditorActivity.java b/app/src/main/java/com/amaze/filemanager/ui/activities/texteditor/TextEditorActivity.java index 471661dea2..97b518614e 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/activities/texteditor/TextEditorActivity.java +++ b/app/src/main/java/com/amaze/filemanager/ui/activities/texteditor/TextEditorActivity.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/activities/texteditor/TextEditorActivityViewModel.kt b/app/src/main/java/com/amaze/filemanager/ui/activities/texteditor/TextEditorActivityViewModel.kt index 91b34b97d7..7057adb8b0 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/activities/texteditor/TextEditorActivityViewModel.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/activities/texteditor/TextEditorActivityViewModel.kt @@ -26,7 +26,6 @@ import java.io.File import java.util.* class TextEditorActivityViewModel : ViewModel() { - var original: String? = null /** diff --git a/app/src/main/java/com/amaze/filemanager/ui/base/BaseBottomSheetFragment.kt b/app/src/main/java/com/amaze/filemanager/ui/base/BaseBottomSheetFragment.kt index bd57be0627..aee378a9cb 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/base/BaseBottomSheetFragment.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/base/BaseBottomSheetFragment.kt @@ -30,7 +30,6 @@ import com.google.android.material.bottomsheet.BottomSheetDialog import com.google.android.material.bottomsheet.BottomSheetDialogFragment open class BaseBottomSheetFragment : BottomSheetDialogFragment() { - override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { return super.onCreateDialog(savedInstanceState) as BottomSheetDialog } @@ -43,23 +42,23 @@ open class BaseBottomSheetFragment : BottomSheetDialogFragment() { AppTheme.DARK -> { rootView.setBackgroundDrawable( context?.resources?.getDrawable( - R.drawable.shape_dialog_bottomsheet_dark - ) + R.drawable.shape_dialog_bottomsheet_dark, + ), ) } AppTheme.BLACK -> { rootView.setBackgroundDrawable( context?.resources?.getDrawable( - R.drawable.shape_dialog_bottomsheet_black - ) + R.drawable.shape_dialog_bottomsheet_black, + ), ) } AppTheme.LIGHT -> { rootView .setBackgroundDrawable( context?.resources?.getDrawable( - R.drawable.shape_dialog_bottomsheet_white - ) + R.drawable.shape_dialog_bottomsheet_white, + ), ) } } diff --git a/app/src/main/java/com/amaze/filemanager/ui/colors/ColorPreference.java b/app/src/main/java/com/amaze/filemanager/ui/colors/ColorPreference.java index 4cf8184814..988af9e4d5 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/colors/ColorPreference.java +++ b/app/src/main/java/com/amaze/filemanager/ui/colors/ColorPreference.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/colors/ColorPreferenceHelper.java b/app/src/main/java/com/amaze/filemanager/ui/colors/ColorPreferenceHelper.java index b3d5c1aa18..85066ee117 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/colors/ColorPreferenceHelper.java +++ b/app/src/main/java/com/amaze/filemanager/ui/colors/ColorPreferenceHelper.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/colors/ColorUtils.java b/app/src/main/java/com/amaze/filemanager/ui/colors/ColorUtils.java index 872e4aaa71..bd358d1c84 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/colors/ColorUtils.java +++ b/app/src/main/java/com/amaze/filemanager/ui/colors/ColorUtils.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/colors/UserColorPreferences.kt b/app/src/main/java/com/amaze/filemanager/ui/colors/UserColorPreferences.kt index b8c5e4f9dc..b8ada9589b 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/colors/UserColorPreferences.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/colors/UserColorPreferences.kt @@ -29,5 +29,5 @@ class UserColorPreferences( @ColorInt val primaryFirstTab: Int, @ColorInt val primarySecondTab: Int, @ColorInt val accent: Int, - @ColorInt val iconSkin: Int + @ColorInt val iconSkin: Int, ) : Parcelable diff --git a/app/src/main/java/com/amaze/filemanager/ui/dialogs/AlertDialog.kt b/app/src/main/java/com/amaze/filemanager/ui/dialogs/AlertDialog.kt index 63fdad04de..91e0aefeab 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/dialogs/AlertDialog.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/dialogs/AlertDialog.kt @@ -29,7 +29,6 @@ import com.amaze.filemanager.ui.activities.superclasses.ThemedActivity * Alert Dialog. */ object AlertDialog { - /** * Display an alert dialog. Optionally accepts a [MaterialDialog.SingleButtonCallback] to * provide additional behaviour when dialog button is pressed. @@ -43,20 +42,21 @@ object AlertDialog { @StringRes title: Int, @StringRes positiveButtonText: Int = android.R.string.ok, @Nullable onPositive: MaterialDialog.SingleButtonCallback? = null, - contentIsHtml: Boolean = false + contentIsHtml: Boolean = false, ) { val accentColor: Int = activity.accent - val a = MaterialDialog.Builder(activity) - .content(content, contentIsHtml) - .widgetColor(accentColor) - .theme( - activity - .appTheme - .getMaterialDialogTheme() - ) - .title(title) - .positiveText(positiveButtonText) - .positiveColor(accentColor) + val a = + MaterialDialog.Builder(activity) + .content(content, contentIsHtml) + .widgetColor(accentColor) + .theme( + activity + .appTheme + .getMaterialDialogTheme(), + ) + .title(title) + .positiveText(positiveButtonText) + .positiveColor(accentColor) if (onPositive != null) { a.onPositive(onPositive) diff --git a/app/src/main/java/com/amaze/filemanager/ui/dialogs/ColorPickerDialog.java b/app/src/main/java/com/amaze/filemanager/ui/dialogs/ColorPickerDialog.java index 6fe4b62a75..93cb5406c1 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/dialogs/ColorPickerDialog.java +++ b/app/src/main/java/com/amaze/filemanager/ui/dialogs/ColorPickerDialog.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/dialogs/DecryptFingerprintDialog.kt b/app/src/main/java/com/amaze/filemanager/ui/dialogs/DecryptFingerprintDialog.kt index 61e02827e1..f73cfec0ee 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/dialogs/DecryptFingerprintDialog.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/dialogs/DecryptFingerprintDialog.kt @@ -41,7 +41,6 @@ import java.security.GeneralSecurityException * Decrypt dialog prompt for user fingerprint. */ object DecryptFingerprintDialog { - /** * Display dialog prompting user for fingerprint in order to decrypt file. */ @@ -49,22 +48,23 @@ object DecryptFingerprintDialog { @RequiresApi(api = Build.VERSION_CODES.M) @Throws( GeneralSecurityException::class, - IOException::class + IOException::class, ) fun show( c: Context, main: MainActivity, intent: Intent, appTheme: AppTheme, - decryptButtonCallbackInterface: DecryptButtonCallbackInterface + decryptButtonCallbackInterface: DecryptButtonCallbackInterface, ) { val accentColor = main.accent val builder = MaterialDialog.Builder(c) builder.title(c.getString(R.string.crypt_decrypt)) val rootView = View.inflate(c, R.layout.dialog_decrypt_fingerprint_authentication, null) - val cancelButton = rootView.findViewById( - R.id.button_decrypt_fingerprint_cancel - ) + val cancelButton = + rootView.findViewById( + R.id.button_decrypt_fingerprint_cancel, + ) cancelButton.setTextColor(accentColor) builder.customView(rootView, true) builder.canceledOnTouchOutside(false) diff --git a/app/src/main/java/com/amaze/filemanager/ui/dialogs/DragAndDropDialog.kt b/app/src/main/java/com/amaze/filemanager/ui/dialogs/DragAndDropDialog.kt index c7b24245ae..f532ca4a7d 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/dialogs/DragAndDropDialog.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/dialogs/DragAndDropDialog.kt @@ -39,13 +39,11 @@ import org.slf4j.Logger import org.slf4j.LoggerFactory class DragAndDropDialog : DialogFragment() { - var pasteLocation: String? = null var operationFiles: ArrayList? = null var mainActivity: MainActivity? = null companion object { - private val log: Logger = LoggerFactory.getLogger(DragAndDropDialog::class.java) private const val KEY_PASTE_LOCATION = "pasteLocation" private const val KEY_FILES = "files" @@ -57,40 +55,45 @@ class DragAndDropDialog : DialogFragment() { fun showDialogOrPerformOperation( pasteLocation: String, files: ArrayList, - activity: MainActivity + activity: MainActivity, ) { - val dragAndDropPref = activity.prefs - .getInt( - PreferencesConstants.PREFERENCE_DRAG_AND_DROP_PREFERENCE, - PreferencesConstants.PREFERENCE_DRAG_DEFAULT - ) + val dragAndDropPref = + activity.prefs + .getInt( + PreferencesConstants.PREFERENCE_DRAG_AND_DROP_PREFERENCE, + PreferencesConstants.PREFERENCE_DRAG_DEFAULT, + ) if (dragAndDropPref == PreferencesConstants.PREFERENCE_DRAG_TO_MOVE_COPY) { - val dragAndDropCopy = activity.prefs - .getString(PreferencesConstants.PREFERENCE_DRAG_AND_DROP_REMEMBERED, "") + val dragAndDropCopy = + activity.prefs + .getString(PreferencesConstants.PREFERENCE_DRAG_AND_DROP_REMEMBERED, "") if (dragAndDropCopy != "") { startCopyOrMoveTask( pasteLocation, files, PreferencesConstants.PREFERENCE_DRAG_REMEMBER_MOVE .equals(dragAndDropCopy, ignoreCase = true), - activity + activity, ) } else { val dragAndDropDialog = newInstance(pasteLocation, files) dragAndDropDialog.show( activity.supportFragmentManager, - javaClass.simpleName + javaClass.simpleName, ) } } else { log.warn( "Trying to drop for copy / move while setting " + - "is drag select" + "is drag select", ) } } - private fun newInstance(pasteLocation: String, files: ArrayList): - DragAndDropDialog { + + private fun newInstance( + pasteLocation: String, + files: ArrayList, + ): DragAndDropDialog { val dragAndDropDialog = DragAndDropDialog() val args = Bundle() args.putString(KEY_PASTE_LOCATION, pasteLocation) @@ -103,7 +106,7 @@ class DragAndDropDialog : DialogFragment() { pasteLocation: String, files: ArrayList, move: Boolean, - mainActivity: MainActivity + mainActivity: MainActivity, ) { val openMode = mainActivity.currentMainFragment?.mainFragmentViewModel?.openMode ?: return @@ -113,7 +116,7 @@ class DragAndDropDialog : DialogFragment() { move, mainActivity.isRootExplorer, openMode, - files + files, ) } } @@ -135,20 +138,21 @@ class DragAndDropDialog : DialogFragment() { mainActivity?.appTheme?.getMaterialDialogTheme(), mainActivity?.accent, pasteLocation, - operationFiles + operationFiles, ) { context, dialogTheme, accent, pasteLocation, operationFiles -> - val dialog: MaterialDialog = MaterialDialog.Builder(context) - .title(getString(R.string.choose_operation)) - .customView(R.layout.dialog_drag_drop, true) - .theme(dialogTheme) - .negativeText(getString(R.string.cancel).toUpperCase()) - .negativeColor(accent) - .cancelable(false) - .onNeutral { _: MaterialDialog?, _: DialogAction? -> - dismiss() - } - .build() + val dialog: MaterialDialog = + MaterialDialog.Builder(context) + .title(getString(R.string.choose_operation)) + .customView(R.layout.dialog_drag_drop, true) + .theme(dialogTheme) + .negativeText(getString(R.string.cancel).toUpperCase()) + .negativeColor(accent) + .cancelable(false) + .onNeutral { _: MaterialDialog?, _: DialogAction? -> + dismiss() + } + .build() dialog.customView?.run { // Get views from custom layout to set text values. @@ -178,13 +182,13 @@ class DragAndDropDialog : DialogFragment() { R.drawable.ic_baseline_content_cut_24, 0, 0, - 0 + 0, ) copyButton.setCompoundDrawablesWithIntrinsicBounds( R.drawable.ic_baseline_content_copy_24, 0, 0, - 0 + 0, ) } } @@ -202,8 +206,11 @@ class DragAndDropDialog : DialogFragment() { mainActivity?.prefs?.edit() ?.putString( PreferencesConstants.PREFERENCE_DRAG_AND_DROP_REMEMBERED, - if (shouldMove) PreferencesConstants.PREFERENCE_DRAG_REMEMBER_MOVE - else PreferencesConstants.PREFERENCE_DRAG_REMEMBER_COPY + if (shouldMove) { + PreferencesConstants.PREFERENCE_DRAG_REMEMBER_MOVE + } else { + PreferencesConstants.PREFERENCE_DRAG_REMEMBER_COPY + }, )?.apply() } } diff --git a/app/src/main/java/com/amaze/filemanager/ui/dialogs/EncryptAuthenticateDialog.kt b/app/src/main/java/com/amaze/filemanager/ui/dialogs/EncryptAuthenticateDialog.kt index 925973d101..11763e598b 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/dialogs/EncryptAuthenticateDialog.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/dialogs/EncryptAuthenticateDialog.kt @@ -77,7 +77,7 @@ object EncryptAuthenticateDialog { intent: Intent, main: MainActivity, appTheme: AppTheme, - encryptButtonCallbackInterface: EncryptButtonCallbackInterface + encryptButtonCallbackInterface: EncryptButtonCallbackInterface, ) { intent.getParcelableExtra(EncryptService.TAG_SOURCE)?.run { val preferences = PreferenceManager.getDefaultSharedPreferences(c) @@ -88,16 +88,19 @@ object EncryptAuthenticateDialog { DialogEncryptAuthenticateBinding.inflate(LayoutInflater.from(c)) val rootView: View = vb.root val passwordEditText: TextInputEditText = vb.editTextDialogEncryptPassword - val passwordConfirmEditText: TextInputEditText = vb - .editTextDialogEncryptPasswordConfirm + val passwordConfirmEditText: TextInputEditText = + vb + .editTextDialogEncryptPasswordConfirm val encryptSaveAsEditText: TextInputEditText = vb.editTextEncryptSaveAs val useAzeEncrypt: AppCompatCheckBox = vb.checkboxUseAze - val usageTextInfo: AppCompatTextView = vb.textViewCryptInfo.apply { - text = HtmlCompat.fromHtml( - main.getString(R.string.encrypt_option_use_aescrypt_desc), - FROM_HTML_MODE_COMPACT - ) - } + val usageTextInfo: AppCompatTextView = + vb.textViewCryptInfo.apply { + text = + HtmlCompat.fromHtml( + main.getString(R.string.encrypt_option_use_aescrypt_desc), + FROM_HTML_MODE_COMPACT, + ) + } useAzeEncrypt.setOnCheckedChangeListener( createUseAzeEncryptCheckboxOnCheckedChangeListener( c, @@ -105,12 +108,13 @@ object EncryptAuthenticateDialog { preferences, main, encryptSaveAsEditText, - usageTextInfo - ) + usageTextInfo, + ), ) val textInputLayoutPassword: WarnableTextInputLayout = vb.tilEncryptPassword - val textInputLayoutPasswordConfirm: WarnableTextInputLayout = vb - .tilEncryptPasswordConfirm + val textInputLayoutPasswordConfirm: WarnableTextInputLayout = + vb + .tilEncryptPasswordConfirm val textInputLayoutEncryptSaveAs: WarnableTextInputLayout = vb.tilEncryptSaveAs encryptSaveAsEditText.setText(this.getName(c) + AESCRYPT_EXTENSION) textInputLayoutEncryptSaveAs.hint = @@ -135,14 +139,14 @@ object EncryptAuthenticateDialog { runCatching { encryptButtonCallbackInterface.onButtonPressed( intent, - passwordEditText.text.toString() + passwordEditText.text.toString(), ) }.onFailure { log.error("Failed to encrypt", it) Toast.makeText( c, c.getString(R.string.crypt_encryption_fail), - Toast.LENGTH_LONG + Toast.LENGTH_LONG, ).show() }.also { dialog.dismiss() @@ -159,7 +163,7 @@ object EncryptAuthenticateDialog { textInputLayoutPassword, encryptSaveAsEditText, useAzeEncrypt, - btnOK + btnOK, ) createPasswordFieldValidator( c, @@ -168,7 +172,7 @@ object EncryptAuthenticateDialog { textInputLayoutPasswordConfirm, encryptSaveAsEditText, useAzeEncrypt, - btnOK + btnOK, ) WarnableTextInputValidator( c, @@ -178,7 +182,7 @@ object EncryptAuthenticateDialog { createFilenameValidator(useAzeEncrypt, extraCondition = { true == passwordEditText.text?.isNotBlank() && passwordEditText.text.toString() == passwordConfirmEditText.text.toString() - }) + }), ) } ?: throw IllegalArgumentException("No TAG_SOURCE parameter specified") } @@ -190,12 +194,12 @@ object EncryptAuthenticateDialog { warningTextInputLayout: WarnableTextInputLayout, encryptSaveAsEditText: TextInputEditText, useAzeEncrypt: AppCompatCheckBox, - btnOK: MDButton + btnOK: MDButton, ) = WarnableTextInputValidator( c, passwordField, warningTextInputLayout, - btnOK + btnOK, ) { text: String -> if (text.isNotBlank() && text == comparingPasswordField.text.toString() && @@ -221,11 +225,12 @@ object EncryptAuthenticateDialog { preferences: SharedPreferences, main: MainActivity, encryptSaveAsEditText: TextInputEditText, - usageTextInfo: AppCompatTextView + usageTextInfo: AppCompatTextView, ) = { _: CompoundButton?, isChecked: Boolean -> - if (isChecked && !preferences.getBoolean( + if (isChecked && + !preferences.getBoolean( PREFERENCE_CRYPT_WARNING_REMEMBER, - false + false, ) ) { EncryptWarningDialog.show(main, main.appTheme) @@ -235,18 +240,19 @@ object EncryptAuthenticateDialog { CRYPT_EXTENSION } else { AESCRYPT_EXTENSION - }}" - ) - usageTextInfo.text = HtmlCompat.fromHtml( - main.getString( - if (isChecked) { - R.string.encrypt_option_use_azecrypt_desc - } else { - R.string.encrypt_option_use_aescrypt_desc - } - ), - FROM_HTML_MODE_COMPACT + }}", ) + usageTextInfo.text = + HtmlCompat.fromHtml( + main.getString( + if (isChecked) { + R.string.encrypt_option_use_azecrypt_desc + } else { + R.string.encrypt_option_use_aescrypt_desc + }, + ), + FROM_HTML_MODE_COMPACT, + ) } /** @@ -255,7 +261,7 @@ object EncryptAuthenticateDialog { @JvmStatic fun createFilenameValidator( useAzeEncrypt: AppCompatCheckBox, - extraCondition: () -> Boolean = { true } + extraCondition: () -> Boolean = { true }, ) = { text: String -> if (text.isNotBlank() && filenameIsValid(text, useAzeEncrypt) && extraCondition.invoke()) { ReturnState() @@ -280,14 +286,14 @@ object EncryptAuthenticateDialog { @JvmStatic fun filenameIsValid( filename: String?, - useAzeEncrypt: AppCompatCheckBox + useAzeEncrypt: AppCompatCheckBox, ): Boolean { return ( true == filename?.isNotBlank() && filename.endsWith(CRYPT_EXTENSION) && (useAzeEncrypt.visibility == INVISIBLE || useAzeEncrypt.isChecked) - ) || ( + ) || ( true == filename?.isNotBlank() && filename.endsWith(AESCRYPT_EXTENSION) && (useAzeEncrypt.visibility == VISIBLE && !useAzeEncrypt.isChecked) - ) + ) } } diff --git a/app/src/main/java/com/amaze/filemanager/ui/dialogs/EncryptWarningDialog.kt b/app/src/main/java/com/amaze/filemanager/ui/dialogs/EncryptWarningDialog.kt index 6db5eea3a4..6c2339b14d 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/dialogs/EncryptWarningDialog.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/dialogs/EncryptWarningDialog.kt @@ -33,14 +33,13 @@ import com.amaze.filemanager.ui.theme.AppTheme * This dialog is to warn users of the caveat of using Amaze's own encryption format. */ object EncryptWarningDialog { - /** * Display warning dialog on use of Amaze's own encryption format. */ @JvmStatic fun show( main: MainActivity, - appTheme: AppTheme + appTheme: AppTheme, ) { val accentColor: Int = main.accent val preferences = PreferenceManager.getDefaultSharedPreferences(main) diff --git a/app/src/main/java/com/amaze/filemanager/ui/dialogs/EncryptWithPresetPasswordSaveAsDialog.kt b/app/src/main/java/com/amaze/filemanager/ui/dialogs/EncryptWithPresetPasswordSaveAsDialog.kt index b1cc92d9ab..baa520724f 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/dialogs/EncryptWithPresetPasswordSaveAsDialog.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/dialogs/EncryptWithPresetPasswordSaveAsDialog.kt @@ -49,7 +49,6 @@ import com.amaze.filemanager.ui.views.WarnableTextInputValidator * Encryption save as file dialog, for us when fingerprint or master password is set. */ object EncryptWithPresetPasswordSaveAsDialog { - /** * Displays the save as dialog. */ @@ -61,37 +60,40 @@ object EncryptWithPresetPasswordSaveAsDialog { intent: Intent, main: MainActivity, password: String, - encryptButtonCallbackInterface: EncryptButtonCallbackInterface + encryptButtonCallbackInterface: EncryptButtonCallbackInterface, ) { intent.getParcelableExtra(EncryptService.TAG_SOURCE)?.run { val preferences = PreferenceManager.getDefaultSharedPreferences(c) val accentColor = main.accent val vb = DialogEncryptWithMasterPasswordBinding.inflate(LayoutInflater.from(c)) val rootView = vb.root - val encryptSaveAsEditText = vb.editTextEncryptSaveAs.also { - when (password) { - ENCRYPT_PASSWORD_FINGERPRINT -> { - // Fingerprint not supported for AESCrypt - it.setText(this.getName(c) + CryptUtil.CRYPT_EXTENSION) - } - ENCRYPT_PASSWORD_MASTER -> { - it.setText(this.getName(c) + CryptUtil.AESCRYPT_EXTENSION) - } - else -> { - throw IllegalArgumentException( - "Must be either " + - "ENCRYPT_PASSWORD_FINGERPRINT or ENCRYPT_PASSWORD_MASTER" - ) + val encryptSaveAsEditText = + vb.editTextEncryptSaveAs.also { + when (password) { + ENCRYPT_PASSWORD_FINGERPRINT -> { + // Fingerprint not supported for AESCrypt + it.setText(this.getName(c) + CryptUtil.CRYPT_EXTENSION) + } + ENCRYPT_PASSWORD_MASTER -> { + it.setText(this.getName(c) + CryptUtil.AESCRYPT_EXTENSION) + } + else -> { + throw IllegalArgumentException( + "Must be either " + + "ENCRYPT_PASSWORD_FINGERPRINT or ENCRYPT_PASSWORD_MASTER", + ) + } } } - } val useAzeEncrypt = vb.checkboxUseAze - val usageTextInfo = vb.textViewCryptInfo.apply { - text = HtmlCompat.fromHtml( - main.getString(R.string.encrypt_option_use_aescrypt_desc), - HtmlCompat.FROM_HTML_MODE_LEGACY - ) - } + val usageTextInfo = + vb.textViewCryptInfo.apply { + text = + HtmlCompat.fromHtml( + main.getString(R.string.encrypt_option_use_aescrypt_desc), + HtmlCompat.FROM_HTML_MODE_LEGACY, + ) + } if (ENCRYPT_PASSWORD_FINGERPRINT != password) { useAzeEncrypt.setOnCheckedChangeListener( createUseAzeEncryptCheckboxOnCheckedChangeListener( @@ -100,47 +102,48 @@ object EncryptWithPresetPasswordSaveAsDialog { preferences, main, encryptSaveAsEditText, - usageTextInfo - ) + usageTextInfo, + ), ) } else { useAzeEncrypt.visibility = View.INVISIBLE usageTextInfo.visibility = View.INVISIBLE } - val saveAsDialog = MaterialDialog.Builder(c) - .title( - if (isDirectory) { - R.string.encrypt_folder_save_as - } else { - R.string.encrypt_file_save_as - } - ).customView(rootView, true) - .positiveColor(accentColor) - .negativeColor(accentColor) - .positiveText(android.R.string.ok) - .negativeText(android.R.string.cancel) - .onPositive { dialog, _ -> - intent.putExtra(TAG_ENCRYPT_TARGET, encryptSaveAsEditText.text.toString()) - intent.putExtra(TAG_PASSWORD, password) - runCatching { - encryptButtonCallbackInterface.onButtonPressed(intent, password) - }.onFailure { - Toast.makeText( - c, - c.getString(R.string.crypt_encryption_fail), - Toast.LENGTH_LONG - ).show() - }.also { - dialog.dismiss() - } - }.build() + val saveAsDialog = + MaterialDialog.Builder(c) + .title( + if (isDirectory) { + R.string.encrypt_folder_save_as + } else { + R.string.encrypt_file_save_as + }, + ).customView(rootView, true) + .positiveColor(accentColor) + .negativeColor(accentColor) + .positiveText(android.R.string.ok) + .negativeText(android.R.string.cancel) + .onPositive { dialog, _ -> + intent.putExtra(TAG_ENCRYPT_TARGET, encryptSaveAsEditText.text.toString()) + intent.putExtra(TAG_PASSWORD, password) + runCatching { + encryptButtonCallbackInterface.onButtonPressed(intent, password) + }.onFailure { + Toast.makeText( + c, + c.getString(R.string.crypt_encryption_fail), + Toast.LENGTH_LONG, + ).show() + }.also { + dialog.dismiss() + } + }.build() WarnableTextInputValidator( c, encryptSaveAsEditText, vb.tilEncryptSaveAs, saveAsDialog.getActionButton(DialogAction.POSITIVE), - createFilenameValidator(useAzeEncrypt) + createFilenameValidator(useAzeEncrypt), ) saveAsDialog.show() saveAsDialog.getActionButton(DialogAction.POSITIVE).isEnabled = true diff --git a/app/src/main/java/com/amaze/filemanager/ui/dialogs/GeneralDialogCreation.java b/app/src/main/java/com/amaze/filemanager/ui/dialogs/GeneralDialogCreation.java index f20e9d1f3e..0c7a553e25 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/dialogs/GeneralDialogCreation.java +++ b/app/src/main/java/com/amaze/filemanager/ui/dialogs/GeneralDialogCreation.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/dialogs/HiddenFilesDialog.kt b/app/src/main/java/com/amaze/filemanager/ui/dialogs/HiddenFilesDialog.kt index 0330b6a442..269bd437e9 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/dialogs/HiddenFilesDialog.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/dialogs/HiddenFilesDialog.kt @@ -35,28 +35,33 @@ object HiddenFilesDialog { * Create hidden files dialog, it shows the files hidden from the context view when selecting */ @JvmStatic - fun showHiddenDialog(mainActivity: MainActivity, mainFragment: MainFragment) { + fun showHiddenDialog( + mainActivity: MainActivity, + mainFragment: MainFragment, + ) { val sharedPrefs = mainActivity.prefs val appTheme = mainActivity.appTheme - val adapter = HiddenAdapter( - mainActivity, - mainFragment, - sharedPrefs, - FileUtils.toHybridFileConcurrentRadixTree(DataUtils.getInstance().hiddenFiles), - null, - false - ) + val adapter = + HiddenAdapter( + mainActivity, + mainFragment, + sharedPrefs, + FileUtils.toHybridFileConcurrentRadixTree(DataUtils.getInstance().hiddenFiles), + null, + false, + ) - val materialDialog = MaterialDialog.Builder(mainActivity).also { builder -> - builder.positiveText(R.string.close) - builder.positiveColor(mainActivity.accent) - builder.title(R.string.hiddenfiles) - builder.theme(appTheme.getMaterialDialogTheme()) - builder.autoDismiss(true) - builder.adapter(adapter, null) - builder.dividerColor(Color.GRAY) - }.build() + val materialDialog = + MaterialDialog.Builder(mainActivity).also { builder -> + builder.positiveText(R.string.close) + builder.positiveColor(mainActivity.accent) + builder.title(R.string.hiddenfiles) + builder.theme(appTheme.getMaterialDialogTheme()) + builder.autoDismiss(true) + builder.adapter(adapter, null) + builder.dividerColor(Color.GRAY) + }.build() adapter.materialDialog = materialDialog materialDialog.setOnDismissListener { diff --git a/app/src/main/java/com/amaze/filemanager/ui/dialogs/HistoryDialog.kt b/app/src/main/java/com/amaze/filemanager/ui/dialogs/HistoryDialog.kt index 591080f792..cb1e6f793a 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/dialogs/HistoryDialog.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/dialogs/HistoryDialog.kt @@ -34,31 +34,36 @@ object HistoryDialog { * Create history dialog, it shows the accessed folders from last accessed to first accessed */ @JvmStatic - fun showHistoryDialog(mainActivity: MainActivity, mainFragment: MainFragment) { + fun showHistoryDialog( + mainActivity: MainActivity, + mainFragment: MainFragment, + ) { val sharedPrefs = mainActivity.prefs val appTheme = mainActivity.appTheme - val adapter = HiddenAdapter( - mainActivity, - mainFragment, - sharedPrefs, - FileUtils.toHybridFileArrayList(DataUtils.getInstance().history), - null, - true - ) + val adapter = + HiddenAdapter( + mainActivity, + mainFragment, + sharedPrefs, + FileUtils.toHybridFileArrayList(DataUtils.getInstance().history), + null, + true, + ) - val materialDialog = MaterialDialog.Builder(mainActivity).also { builder -> - builder.positiveText(R.string.cancel) - builder.positiveColor(mainActivity.accent) - builder.negativeText(R.string.clear) - builder.negativeColor(mainActivity.accent) - builder.title(R.string.history) - builder.onNegative { _: MaterialDialog?, _: DialogAction? -> - DataUtils.getInstance().clearHistory() - } - builder.theme(appTheme.getMaterialDialogTheme()) - builder.adapter(adapter, null) - }.build() + val materialDialog = + MaterialDialog.Builder(mainActivity).also { builder -> + builder.positiveText(R.string.cancel) + builder.positiveColor(mainActivity.accent) + builder.negativeText(R.string.clear) + builder.negativeColor(mainActivity.accent) + builder.title(R.string.history) + builder.onNegative { _: MaterialDialog?, _: DialogAction? -> + DataUtils.getInstance().clearHistory() + } + builder.theme(appTheme.getMaterialDialogTheme()) + builder.adapter(adapter, null) + }.build() adapter.materialDialog = materialDialog materialDialog.show() } diff --git a/app/src/main/java/com/amaze/filemanager/ui/dialogs/OpenFileDialogFragment.kt b/app/src/main/java/com/amaze/filemanager/ui/dialogs/OpenFileDialogFragment.kt index e0b5746617..87dab6230d 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/dialogs/OpenFileDialogFragment.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/dialogs/OpenFileDialogFragment.kt @@ -61,7 +61,6 @@ import org.slf4j.Logger import org.slf4j.LoggerFactory class OpenFileDialogFragment : BaseBottomSheetFragment(), AdjustListViewForTv { - private var uri: Uri? = null private var mimeType: String? = null private var useNewStack: Boolean? = null @@ -73,7 +72,6 @@ class OpenFileDialogFragment : BaseBottomSheetFragment(), AdjustListViewForTv= Build.VERSION_CODES.LOLLIPOP) { @@ -171,7 +175,7 @@ class OpenFileDialogFragment : BaseBottomSheetFragment(), AdjustListViewForTv() - var preloader = RecyclerViewPreloader( - GlideApp.with(this), - modelProvider, - sizeProvider, - GlideConstants.MAX_PRELOAD_FILES - ) + var preloader = + RecyclerViewPreloader( + GlideApp.with(this), + modelProvider, + sizeProvider, + GlideConstants.MAX_PRELOAD_FILES, + ) sharedPreferences = PreferenceManager.getDefaultSharedPreferences(requireContext()) - val intent = buildIntent( - requireContext(), - uri!!, - mimeType!!, - useNewStack!!, - null, - null - ) + val intent = + buildIntent( + requireContext(), + uri!!, + mimeType!!, + useNewStack!!, + null, + null, + ) val appDataParcelableList = initAppDataParcelableList(intent) - val lastClassAndPackageRaw = sharedPreferences - .getString(mimeType.plus(KEY_PREFERENCES_LAST), null) + val lastClassAndPackageRaw = + sharedPreferences + .getString(mimeType.plus(KEY_PREFERENCES_LAST), null) val lastClassAndPackage = lastClassAndPackageRaw?.split(" ") - val lastAppData: AppDataParcelable = initLastAppData( - lastClassAndPackage, - appDataParcelableList - ) ?: return - - adapter = AppsRecyclerAdapter( - this, - modelProvider, - true, - this, - appDataParcelableList - ) + val lastAppData: AppDataParcelable = + initLastAppData( + lastClassAndPackage, + appDataParcelableList, + ) ?: return + + adapter = + AppsRecyclerAdapter( + this, + modelProvider, + true, + this, + appDataParcelableList, + ) loadViews(lastAppData) viewBinding.appsRecyclerView.addOnScrollListener(preloader) @@ -354,21 +368,22 @@ class OpenFileDialogFragment : BaseBottomSheetFragment(), AdjustListViewForTv @@ -394,13 +409,14 @@ class OpenFileDialogFragment : BaseBottomSheetFragment(), AdjustListViewForTv = ArrayList() packageManager.queryIntentActivities(intent, PackageManager.MATCH_ALL).forEach { - val openFileParcelable = OpenFileParcelable( - uri, - mimeType, - useNewStack, - it.activityInfo.name, - it.activityInfo.packageName - ) + val openFileParcelable = + OpenFileParcelable( + uri, + mimeType, + useNewStack, + it.activityInfo.name, + it.activityInfo.packageName, + ) val label = it.loadLabel(packageManager).toString() val appDataParcelable = AppDataParcelable( @@ -412,7 +428,7 @@ class OpenFileDialogFragment : BaseBottomSheetFragment(), AdjustListViewForTv?, - appDataParcelableList: MutableList + appDataParcelableList: MutableList, ): AppDataParcelable? { if (appDataParcelableList.size == 0) { AppConfig.toast(requireContext(), requireContext().getString(R.string.no_app_found)) @@ -438,27 +454,31 @@ class OpenFileDialogFragment : BaseBottomSheetFragment(), AdjustListViewForTv, Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/dialogs/SftpConnectDialog.kt b/app/src/main/java/com/amaze/filemanager/ui/dialogs/SftpConnectDialog.kt index c6446bf3b7..bd956ac854 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/dialogs/SftpConnectDialog.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/dialogs/SftpConnectDialog.kt @@ -87,9 +87,7 @@ import java.util.concurrent.Callable /** SSH/SFTP connection setup dialog. */ class SftpConnectDialog : DialogFragment() { - companion object { - @JvmStatic private val log: Logger = LoggerFactory.getLogger(SftpConnectDialog::class.java) @@ -142,27 +140,29 @@ class SftpConnectDialog : DialogFragment() { // Use system provided action to get Uri to PEM. binding.selectPemBTN.setOnClickListener { - val intent = Intent() - .setType(MimeTypes.ALL_MIME_TYPES) - .setAction(Intent.ACTION_GET_CONTENT) + val intent = + Intent() + .setType(MimeTypes.ALL_MIME_TYPES) + .setAction(Intent.ACTION_GET_CONTENT) activityResultHandlerForPemSelection.launch(intent) } // Define action for buttons - val dialogBuilder = MaterialDialog.Builder(ctx.get()!!) - .title(R.string.scp_connection) - .autoDismiss(false) - .customView(binding.root, true) - .theme(utilsProvider.appTheme.getMaterialDialogTheme()) - .negativeText(R.string.cancel) - .positiveText(if (edit) R.string.update else R.string.create) - .positiveColor(accentColor) - .negativeColor(accentColor) - .neutralColor(accentColor) - .onPositive(handleOnPositiveButton(edit)) - .onNegative { dialog: MaterialDialog, _: DialogAction? -> - dialog.dismiss() - } + val dialogBuilder = + MaterialDialog.Builder(ctx.get()!!) + .title(R.string.scp_connection) + .autoDismiss(false) + .customView(binding.root, true) + .theme(utilsProvider.appTheme.getMaterialDialogTheme()) + .negativeText(R.string.cancel) + .positiveText(if (edit) R.string.update else R.string.create) + .positiveColor(accentColor) + .negativeColor(accentColor) + .neutralColor(accentColor) + .onPositive(handleOnPositiveButton(edit)) + .onNegative { dialog: MaterialDialog, _: DialogAction? -> + dialog.dismiss() + } // If we are editing connection settings, give new actions for neutral and negative buttons if (edit) { @@ -182,113 +182,121 @@ class SftpConnectDialog : DialogFragment() { return dialog } - private fun initForm(edit: Boolean) = binding.run { - portET.apply { - filters = arrayOf(MinMaxInputFilter(VALID_PORT_RANGE)) - // For convenience, so I don't need to press backspace all the time - onFocusChangeListener = View.OnFocusChangeListener { _: View?, hasFocus: Boolean -> - if (hasFocus) { - selectAll() - } - } - } - protocolDropDown.adapter = ArrayAdapter( - requireContext(), - android.R.layout.simple_spinner_dropdown_item, - requireContext().resources.getStringArray(R.array.ftpProtocols) - ) - chkFtpAnonymous.setOnCheckedChangeListener { _, isChecked -> - usernameET.isEnabled = !isChecked - passwordET.isEnabled = !isChecked - if (isChecked) { - usernameET.setText("") - passwordET.setText("") - } - } - defaultPathET.filters = arrayOf(defaultPathCharFilter) - // If it's new connection setup, set some default values - // Otherwise, use given Bundle instance for filling in the blanks - if (!edit) { - connectionET.setText(R.string.scp_connection) - portET.setText(NetCopyClientConnectionPool.SSH_DEFAULT_PORT.toString()) - protocolDropDown.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { - override fun onItemSelected( - parent: AdapterView<*>?, - view: View?, - position: Int, - id: Long - ) { - portET.setText( - when (position) { - 1 -> NetCopyClientConnectionPool.FTP_DEFAULT_PORT.toString() - 2 -> NetCopyClientConnectionPool.FTPS_DEFAULT_PORT.toString() - else -> NetCopyClientConnectionPool.SSH_DEFAULT_PORT.toString() + private fun initForm(edit: Boolean) = + binding.run { + portET.apply { + filters = arrayOf(MinMaxInputFilter(VALID_PORT_RANGE)) + // For convenience, so I don't need to press backspace all the time + onFocusChangeListener = + View.OnFocusChangeListener { _: View?, hasFocus: Boolean -> + if (hasFocus) { + selectAll() } - ) - chkFtpAnonymous.visibility = when (position) { - 0 -> View.GONE - else -> View.VISIBLE - } - if (position == 0) { - chkFtpAnonymous.isChecked = false } - selectPemBTN.visibility = when (position) { - 0 -> View.VISIBLE - else -> View.GONE - } - } - override fun onNothingSelected(parent: AdapterView<*>?) = Unit } - } else { - protocolDropDown.setSelection( - when (requireArguments().getString(ARG_PROTOCOL)) { - FTP_URI_PREFIX -> 1 - FTPS_URI_PREFIX -> 2 - else -> 0 + protocolDropDown.adapter = + ArrayAdapter( + requireContext(), + android.R.layout.simple_spinner_dropdown_item, + requireContext().resources.getStringArray(R.array.ftpProtocols), + ) + chkFtpAnonymous.setOnCheckedChangeListener { _, isChecked -> + usernameET.isEnabled = !isChecked + passwordET.isEnabled = !isChecked + if (isChecked) { + usernameET.setText("") + passwordET.setText("") } - ) - connectionET.setText(requireArguments().getString(ARG_NAME)) - ipET.setText(requireArguments().getString(ARG_ADDRESS)) - portET.setText(requireArguments().getInt(ARG_PORT).toString()) - defaultPathET.setText(requireArguments().getString(ARG_DEFAULT_PATH)) - usernameET.setText(requireArguments().getString(ARG_USERNAME)) - if (requireArguments().getBoolean(ARG_HAS_PASSWORD)) { - passwordET.setHint(R.string.password_unchanged) + } + defaultPathET.filters = arrayOf(defaultPathCharFilter) + // If it's new connection setup, set some default values + // Otherwise, use given Bundle instance for filling in the blanks + if (!edit) { + connectionET.setText(R.string.scp_connection) + portET.setText(NetCopyClientConnectionPool.SSH_DEFAULT_PORT.toString()) + protocolDropDown.onItemSelectedListener = + object : AdapterView.OnItemSelectedListener { + override fun onItemSelected( + parent: AdapterView<*>?, + view: View?, + position: Int, + id: Long, + ) { + portET.setText( + when (position) { + 1 -> NetCopyClientConnectionPool.FTP_DEFAULT_PORT.toString() + 2 -> NetCopyClientConnectionPool.FTPS_DEFAULT_PORT.toString() + else -> NetCopyClientConnectionPool.SSH_DEFAULT_PORT.toString() + }, + ) + chkFtpAnonymous.visibility = + when (position) { + 0 -> View.GONE + else -> View.VISIBLE + } + if (position == 0) { + chkFtpAnonymous.isChecked = false + } + selectPemBTN.visibility = + when (position) { + 0 -> View.VISIBLE + else -> View.GONE + } + } + + override fun onNothingSelected(parent: AdapterView<*>?) = Unit + } } else { - selectedParsedKeyPairName = requireArguments().getString(ARG_KEYPAIR_NAME) - selectPemBTN.text = selectedParsedKeyPairName + protocolDropDown.setSelection( + when (requireArguments().getString(ARG_PROTOCOL)) { + FTP_URI_PREFIX -> 1 + FTPS_URI_PREFIX -> 2 + else -> 0 + }, + ) + connectionET.setText(requireArguments().getString(ARG_NAME)) + ipET.setText(requireArguments().getString(ARG_ADDRESS)) + portET.setText(requireArguments().getInt(ARG_PORT).toString()) + defaultPathET.setText(requireArguments().getString(ARG_DEFAULT_PATH)) + usernameET.setText(requireArguments().getString(ARG_USERNAME)) + if (requireArguments().getBoolean(ARG_HAS_PASSWORD)) { + passwordET.setHint(R.string.password_unchanged) + } else { + selectedParsedKeyPairName = requireArguments().getString(ARG_KEYPAIR_NAME) + selectPemBTN.text = selectedParsedKeyPairName + } + oldPath = + NetCopyClientUtils.deriveUriFrom( + requireArguments().getString(ARG_PROTOCOL)!!, + requireArguments().getString(ARG_ADDRESS)!!, + requireArguments().getInt(ARG_PORT), + requireArguments().getString(ARG_DEFAULT_PATH, ""), + requireArguments().getString(ARG_USERNAME)!!, + requireArguments().getString(ARG_PASSWORD), + edit, + ) } - oldPath = NetCopyClientUtils.deriveUriFrom( - requireArguments().getString(ARG_PROTOCOL)!!, - requireArguments().getString(ARG_ADDRESS)!!, - requireArguments().getInt(ARG_PORT), - requireArguments().getString(ARG_DEFAULT_PATH, ""), - requireArguments().getString(ARG_USERNAME)!!, - requireArguments().getString(ARG_PASSWORD), - edit - ) } - } - private fun appendButtonListenersForEdit( - dialogBuilder: MaterialDialog.Builder - ) { + private fun appendButtonListenersForEdit(dialogBuilder: MaterialDialog.Builder) { createConnectionSettings(edit = true).run { dialogBuilder .negativeText(R.string.delete) .onNegative { dialog: MaterialDialog, _: DialogAction? -> - val path = NetCopyClientUtils.deriveUriFrom( - getProtocolPrefixFromDropdownSelection(), - hostname, - port, - defaultPath, - username, - requireArguments().getString(ARG_PASSWORD, null), - edit = true - ) - val i = DataUtils.getInstance().containsServer( - arrayOf(connectionName, path) - ) + val path = + NetCopyClientUtils.deriveUriFrom( + getProtocolPrefixFromDropdownSelection(), + hostname, + port, + defaultPath, + username, + requireArguments().getString(ARG_PASSWORD, null), + edit = true, + ) + val i = + DataUtils.getInstance().containsServer( + arrayOf(connectionName, path), + ) if (i > -1) { DataUtils.getInstance().removeServer(i) AppConfig.getInstance() @@ -300,8 +308,8 @@ class SftpConnectDialog : DialogFragment() { connectionName, null, null, - null - ) + null, + ), ) } (activity as MainActivity).drawer.refreshDrawer() @@ -312,42 +320,46 @@ class SftpConnectDialog : DialogFragment() { } } - private fun createValidator(edit: Boolean, okBTN: MDButton): SimpleTextWatcher { + private fun createValidator( + edit: Boolean, + okBTN: MDButton, + ): SimpleTextWatcher { return object : SimpleTextWatcher() { override fun afterTextChanged(s: Editable) { val portETValue = binding.portET.text.toString() - val port = if (portETValue.isDigitsOnly() && (portETValue.length in 1..5)) { - portETValue.toInt() - } else { - -1 - } - val hasCredential: Boolean = if (edit) { - if (true == binding.passwordET.text?.isNotEmpty() || - !TextUtils.isEmpty(requireArguments().getString(ARG_PASSWORD)) - ) { - true + val port = + if (portETValue.isDigitsOnly() && (portETValue.length in 1..5)) { + portETValue.toInt() } else { - true == selectedParsedKeyPairName?.isNotEmpty() + -1 + } + val hasCredential: Boolean = + if (edit) { + if (true == binding.passwordET.text?.isNotEmpty() || + !TextUtils.isEmpty(requireArguments().getString(ARG_PASSWORD)) + ) { + true + } else { + true == selectedParsedKeyPairName?.isNotEmpty() + } + } else { + true == binding.passwordET.text?.isNotEmpty() || selectedParsedKeyPair != null } - } else { - true == binding.passwordET.text?.isNotEmpty() || selectedParsedKeyPair != null - } okBTN.isEnabled = ( true == binding.connectionET.text?.isNotEmpty() && true == binding.ipET.text?.isNotEmpty() && port in VALID_PORT_RANGE && true == binding.usernameET.text?.isNotEmpty() && hasCredential - ) || ( + ) || ( binding.chkFtpAnonymous.isChecked && binding.protocolDropDown.selectedItemPosition > 0 - ) + ) } } } - private fun handleOnPositiveButton(edit: Boolean): - MaterialDialog.SingleButtonCallback = + private fun handleOnPositiveButton(edit: Boolean): MaterialDialog.SingleButtonCallback = MaterialDialog.SingleButtonCallback { _, _ -> createConnectionSettings(edit).run { when (prefix) { @@ -357,7 +369,10 @@ class SftpConnectDialog : DialogFragment() { } } - private fun positiveButtonForFtp(connectionSettings: ConnectionSettings, edit: Boolean) { + private fun positiveButtonForFtp( + connectionSettings: ConnectionSettings, + edit: Boolean, + ) { connectionSettings.run { authenticateAndSaveSetup(connectionSettings = connectionSettings, isEdit = edit) } @@ -366,7 +381,10 @@ class SftpConnectDialog : DialogFragment() { /* * for SSH and FTPS, get host's cert/public key fingerprint. */ - private fun positiveButtonForSftp(connectionSettings: ConnectionSettings, edit: Boolean) { + private fun positiveButtonForSftp( + connectionSettings: ConnectionSettings, + edit: Boolean, + ) { connectionSettings.run { // Get original SSH host key AppConfig.getInstance().utilsHandler.getRemoteHostKey( @@ -377,17 +395,17 @@ class SftpConnectDialog : DialogFragment() { defaultPath, username, requireArguments().getString(ARG_PASSWORD, null), - edit - ) + edit, + ), )?.let { sshHostKey -> NetCopyClientConnectionPool.removeConnection( - this.toUriString() + this.toUriString(), ) { if (prefix == FTPS_URI_PREFIX) { reconnectToFtpsServerToVerifyHostFingerprint( this, JSONObject(sshHostKey), - edit + edit, ) } else { reconnectToSshServerToVerifyHostFingerprint(this, sshHostKey, edit) @@ -413,7 +431,8 @@ class SftpConnectDialog : DialogFragment() { hostAndPort, hostKeyAlgorithm, hostKeyFingerprint, - hostInfo -> + hostInfo, + -> AlertDialog.Builder(ctx.get()) .setTitle(R.string.ssh_host_key_verification_prompt_title) .setMessage( @@ -421,8 +440,8 @@ class SftpConnectDialog : DialogFragment() { R.string.ssh_host_key_verification_prompt, hostAndPort, hostKeyAlgorithm, - hostKeyFingerprint - ) + hostKeyFingerprint, + ), ).setCancelable(true) .setPositiveButton(R.string.yes) { dialog1: DialogInterface, _: Int -> @@ -431,7 +450,7 @@ class SftpConnectDialog : DialogFragment() { if (authenticateAndSaveSetup( connectionSettings, hostInfo?.toString() ?: hostKeyFingerprint, - edit + edit, ) ) { dialog1.dismiss() @@ -446,13 +465,13 @@ class SftpConnectDialog : DialogFragment() { private fun firstConnectToFtpsServer( connectionSettings: ConnectionSettings, - edit: Boolean + edit: Boolean, ) = connectionSettings.run { connectToSecureServerInternal( FtpsGetHostCertificateTask( hostname, port, - requireContext() + requireContext(), ) { hostInfo -> createFirstConnectCallback.invoke( edit, @@ -464,21 +483,21 @@ class SftpConnectDialog : DialogFragment() { }.toString(), "SHA-256", hostInfo.getString(FINGERPRINT), - hostInfo + hostInfo, ) - } + }, ) } private fun firstConnectToSftpServer( connectionSettings: ConnectionSettings, - edit: Boolean + edit: Boolean, ) = connectionSettings.run { connectToSecureServerInternal( GetSshHostFingerprintTask( hostname, port, - true + true, ) { hostKey: PublicKey -> createFirstConnectCallback.invoke( edit, @@ -490,9 +509,9 @@ class SftpConnectDialog : DialogFragment() { }.toString(), hostKey.algorithm, SecurityUtils.getFingerprint(hostKey), - null + null, ) - } + }, ) } @@ -503,21 +522,21 @@ class SftpConnectDialog : DialogFragment() { authenticateAndSaveSetup( connectionSettings, oldHostIdentity, - edit + edit, ) } else { AlertDialog.Builder(ctx.get()) .setTitle( - R.string.ssh_connect_failed_host_key_changed_title + R.string.ssh_connect_failed_host_key_changed_title, ).setMessage( - R.string.ssh_connect_failed_host_key_changed_prompt + R.string.ssh_connect_failed_host_key_changed_prompt, ).setPositiveButton( - R.string.update_host_key + R.string.update_host_key, ) { _: DialogInterface?, _: Int -> authenticateAndSaveSetup( connectionSettings, newHostIdentity, - edit + edit, ) }.setNegativeButton(R.string.cancel_recommended) { dialog1: DialogInterface, _: Int -> @@ -529,7 +548,7 @@ class SftpConnectDialog : DialogFragment() { private fun reconnectToSshServerToVerifyHostFingerprint( connectionSettings: ConnectionSettings, sshHostKey: String, - edit: Boolean + edit: Boolean, ) { connectionSettings.run { connectToSecureServerInternal( @@ -542,10 +561,10 @@ class SftpConnectDialog : DialogFragment() { sshHostKey, currentHostKeyFingerprint, { currentHostKeyFingerprint == sshHostKey }, - edit + edit, ) } - } + }, ) } } @@ -553,30 +572,28 @@ class SftpConnectDialog : DialogFragment() { private fun reconnectToFtpsServerToVerifyHostFingerprint( connectionSettings: ConnectionSettings, ftpsHostInfo: JSONObject, - edit: Boolean + edit: Boolean, ) { connectionSettings.run { connectToSecureServerInternal( FtpsGetHostCertificateTask( hostname, port, - requireContext() + requireContext(), ) { hostInfo: JSONObject -> createReconnectSecureServerCallback( connectionSettings, ftpsHostInfo.toString(), hostInfo.toString(), { ftpsHostInfo.getString(FINGERPRINT) == hostInfo.getString(FINGERPRINT) }, - edit + edit, ) - } + }, ) } } - private fun > connectToSecureServerInternal( - task: AbstractGetHostInfoTask - ) { + private fun > connectToSecureServerInternal(task: AbstractGetHostInfoTask) { Single.fromCallable(task.getTask()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) @@ -585,73 +602,77 @@ class SftpConnectDialog : DialogFragment() { } @Suppress("LabeledExpression") - private val activityResultHandlerForPemSelection = registerForActivityResult( - ActivityResultContracts.StartActivityForResult() - ) { - if (Activity.RESULT_OK == it.resultCode) { - it.data?.data?.run { - selectedPem = this - runCatching { - requireContext().contentResolver.openInputStream(this)?.let { - selectedKeyContent -> - val observable = PemToKeyPairObservable(selectedKeyContent) - create(observable).subscribeOn(Schedulers.io()) - .observeOn(AndroidSchedulers.mainThread()) - .retryWhen { exceptions -> - exceptions.flatMap { exception -> - create { subscriber -> - observable.displayPassphraseDialog(exception, { - subscriber.onNext(Unit) - }, { - subscriber.onError(exception) - }) + private val activityResultHandlerForPemSelection = + registerForActivityResult( + ActivityResultContracts.StartActivityForResult(), + ) { + if (Activity.RESULT_OK == it.resultCode) { + it.data?.data?.run { + selectedPem = this + runCatching { + requireContext().contentResolver.openInputStream(this)?.let { + selectedKeyContent -> + val observable = PemToKeyPairObservable(selectedKeyContent) + create(observable).subscribeOn(Schedulers.io()) + .observeOn(AndroidSchedulers.mainThread()) + .retryWhen { exceptions -> + exceptions.flatMap { exception -> + create { subscriber -> + observable.displayPassphraseDialog(exception, { + subscriber.onNext(Unit) + }, { + subscriber.onError(exception) + }) + } } } - } - .subscribe({ result -> - selectedParsedKeyPair = result - selectedParsedKeyPairName = this - .lastPathSegment!! - .substring( - this.lastPathSegment!! - .indexOf('/') + 1 - ) - val okBTN = (dialog as MaterialDialog) - .getActionButton(DialogAction.POSITIVE) - okBTN.isEnabled = okBTN.isEnabled || true - binding.selectPemBTN.text = selectedParsedKeyPairName - }, {}) + .subscribe({ result -> + selectedParsedKeyPair = result + selectedParsedKeyPairName = + this + .lastPathSegment!! + .substring( + this.lastPathSegment!! + .indexOf('/') + 1, + ) + val okBTN = + (dialog as MaterialDialog) + .getActionButton(DialogAction.POSITIVE) + okBTN.isEnabled = okBTN.isEnabled || true + binding.selectPemBTN.text = selectedParsedKeyPairName + }, {}) + } + }.onFailure { + log.error("Error reading PEM key", it) } - }.onFailure { - log.error("Error reading PEM key", it) } } } - } private fun authenticateAndSaveSetup( connectionSettings: ConnectionSettings, hostKeyFingerprint: String? = null, - isEdit: Boolean - ): Boolean = connectionSettings.run { - val path = this.toUriString() - val encryptedPath = NetCopyClientUtils.encryptFtpPathAsNecessary(path) - return if (!isEdit) { - saveFtpConnectionAndLoadlist( - connectionSettings, - hostKeyFingerprint, - encryptedPath, - selectedParsedKeyPairName, - selectedParsedKeyPair - ) - } else { - updateFtpConnection( - connectionName, - hostKeyFingerprint, - encryptedPath - ) + isEdit: Boolean, + ): Boolean = + connectionSettings.run { + val path = this.toUriString() + val encryptedPath = NetCopyClientUtils.encryptFtpPathAsNecessary(path) + return if (!isEdit) { + saveFtpConnectionAndLoadlist( + connectionSettings, + hostKeyFingerprint, + encryptedPath, + selectedParsedKeyPairName, + selectedParsedKeyPair, + ) + } else { + updateFtpConnection( + connectionName, + hostKeyFingerprint, + encryptedPath, + ) + } } - } @Suppress("LongParameterList") private fun saveFtpConnectionAndLoadlist( @@ -659,7 +680,7 @@ class SftpConnectDialog : DialogFragment() { hostKeyFingerprint: String?, encryptedPath: String, selectedParsedKeyPairName: String?, - selectedParsedKeyPair: KeyPair? + selectedParsedKeyPair: KeyPair?, ): Boolean { connectionSettings.run { return runCatching { @@ -674,7 +695,7 @@ class SftpConnectDialog : DialogFragment() { } else { password }, - selectedParsedKeyPair + selectedParsedKeyPair, )?.run { if (DataUtils.getInstance().containsServer(encryptedPath) == -1) { DataUtils.getInstance().addServer(arrayOf(connectionName, encryptedPath)) @@ -686,8 +707,8 @@ class SftpConnectDialog : DialogFragment() { connectionName, hostKeyFingerprint, selectedParsedKeyPairName, - getPemContents() - ) + getPemContents(), + ), ) val ma = (activity as MainActivity).currentMainFragment ma?.loadlist( @@ -698,14 +719,14 @@ class SftpConnectDialog : DialogFragment() { } else { OpenMode.FTP }, - false + false, ) dismiss() } else { Snackbar.make( requireActivity().findViewById(R.id.content_frame), getString(R.string.connection_exists), - Snackbar.LENGTH_SHORT + Snackbar.LENGTH_SHORT, ).show() dismiss() } @@ -721,7 +742,7 @@ class SftpConnectDialog : DialogFragment() { private fun updateFtpConnection( connectionName: String, hostKeyFingerprint: String?, - encryptedPath: String + encryptedPath: String, ): Boolean { val i = DataUtils.getInstance().containsServer(oldPath) @@ -739,7 +760,7 @@ class SftpConnectDialog : DialogFragment() { encryptedPath, hostKeyFingerprint, selectedParsedKeyPairName, - getPemContents() + getPemContents(), ) } dismiss() @@ -747,13 +768,14 @@ class SftpConnectDialog : DialogFragment() { } // Read the PEM content from InputStream to String. - private fun getPemContents(): String? = selectedPem?.run { - runCatching { - requireContext().contentResolver.openInputStream(this) - ?.bufferedReader() - ?.use(BufferedReader::readText) - }.getOrNull() - } + private fun getPemContents(): String? = + selectedPem?.run { + runCatching { + requireContext().contentResolver.openInputStream(this) + ?.bufferedReader() + ?.use(BufferedReader::readText) + }.getOrNull() + } private fun getProtocolPrefixFromDropdownSelection(): String { return when (binding.protocolDropDown.selectedItem.toString()) { @@ -772,16 +794,17 @@ class SftpConnectDialog : DialogFragment() { val username: String, val password: String? = null, val selectedParsedKeyPairName: String? = null, - val selectedParsedKeyPair: KeyPair? = null + val selectedParsedKeyPair: KeyPair? = null, ) { - fun toUriString() = NetCopyClientUtils.deriveUriFrom( - prefix, - hostname, - port, - defaultPath, - username, - password - ) + fun toUriString() = + NetCopyClientUtils.deriveUriFrom( + prefix, + hostname, + port, + defaultPath, + username, + password, + ) } // FIXME: username/password may not need urlEncoded during edit mode @@ -793,18 +816,19 @@ class SftpConnectDialog : DialogFragment() { port = binding.portET.text.toString().toInt(), defaultPath = binding.defaultPathET.text.toString(), username = binding.usernameET.text.toString().urlEncoded(), - password = if (true == binding.passwordET.text?.isEmpty()) { - if (edit) { - requireArguments().getString(ARG_PASSWORD, null)?.run { - PasswordUtil.decryptPassword(AppConfig.getInstance(), this) + password = + if (true == binding.passwordET.text?.isEmpty()) { + if (edit) { + requireArguments().getString(ARG_PASSWORD, null)?.run { + PasswordUtil.decryptPassword(AppConfig.getInstance(), this) + } + } else { + requireArguments().getString(ARG_PASSWORD, null) } } else { - requireArguments().getString(ARG_PASSWORD, null) - } - } else { - binding.passwordET.text.toString().urlEncoded() - }, + binding.passwordET.text.toString().urlEncoded() + }, selectedParsedKeyPairName = this.selectedParsedKeyPairName, - selectedParsedKeyPair = selectedParsedKeyPair + selectedParsedKeyPair = selectedParsedKeyPair, ) } diff --git a/app/src/main/java/com/amaze/filemanager/ui/dialogs/SmbConnectDialog.java b/app/src/main/java/com/amaze/filemanager/ui/dialogs/SmbConnectDialog.java index 488bda1412..a1f4dcad60 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/dialogs/SmbConnectDialog.java +++ b/app/src/main/java/com/amaze/filemanager/ui/dialogs/SmbConnectDialog.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/dialogs/SmbSearchDialog.kt b/app/src/main/java/com/amaze/filemanager/ui/dialogs/SmbSearchDialog.kt index 87ebaf7b18..0cd1a20f64 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/dialogs/SmbSearchDialog.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/dialogs/SmbSearchDialog.kt @@ -52,7 +52,6 @@ import org.slf4j.LoggerFactory /** Created by arpitkh996 on 16-01-2016 edited by Emmanuel Messulam @gmail.com> */ class SmbSearchDialog : DialogFragment() { - private lateinit var utilsProvider: UtilitiesProvider private lateinit var listViewAdapter: ListViewAdapter private val viewModel = ComputerParcelableViewModel() @@ -99,38 +98,39 @@ class SmbSearchDialog : DialogFragment() { viewModel.valHolder.postValue(ComputerParcelable("-1", "-1")) listViewAdapter = ListViewAdapter(requireActivity()) val observable = SmbDeviceScannerObservable() - subnetScannerObserver = observable - .subscribeOn(Schedulers.io()) - .observeOn(AndroidSchedulers.mainThread()) - .doOnDispose { - observable.stop() - } - .subscribe( - { computer: ComputerParcelable -> - if (!listViewAdapter.contains(computer)) { - viewModel.valHolder.postValue(computer) - } - }, - { err: Throwable -> - LOG.error("Error searching for devices", err) + subnetScannerObserver = + observable + .subscribeOn(Schedulers.io()) + .observeOn(AndroidSchedulers.mainThread()) + .doOnDispose { + observable.stop() } - ) { - subnetScannerObserver.dispose() - activity?.runOnUiThread { - if (listViewAdapter.dummyOnly()) { - dismiss() - Toast.makeText( - activity, - getString(R.string.no_device_found), - Toast.LENGTH_SHORT - ).show() - val mainActivity = activity as MainActivity - mainActivity.showSMBDialog("", "", false) - return@runOnUiThread + .subscribe( + { computer: ComputerParcelable -> + if (!listViewAdapter.contains(computer)) { + viewModel.valHolder.postValue(computer) + } + }, + { err: Throwable -> + LOG.error("Error searching for devices", err) + }, + ) { + subnetScannerObserver.dispose() + activity?.runOnUiThread { + if (listViewAdapter.dummyOnly()) { + dismiss() + Toast.makeText( + activity, + getString(R.string.no_device_found), + Toast.LENGTH_SHORT, + ).show() + val mainActivity = activity as MainActivity + mainActivity.showSMBDialog("", "", false) + return@runOnUiThread + } + listViewAdapter.removeDummy() } - listViewAdapter.removeDummy() } - } builder.adapter(listViewAdapter, null) viewModel.valHolder.observe(this) { listViewAdapter.add(it) @@ -139,7 +139,7 @@ class SmbSearchDialog : DialogFragment() { } private inner class ListViewAdapter( - context: Context + context: Context, ) : RecyclerView.Adapter() { private val items: MutableList = ArrayList() private val mInflater: LayoutInflater @@ -168,7 +168,7 @@ class SmbSearchDialog : DialogFragment() { items.remove( items.find { it.addr == "-1" && it.name == "-1" - } + }, ) notifyDataSetChanged() } @@ -187,7 +187,10 @@ class SmbSearchDialog : DialogFragment() { return items.size == 1 && items.last().addr == "-1" } - override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { + override fun onCreateViewHolder( + parent: ViewGroup, + viewType: Int, + ): ViewHolder { val view: View return when (viewType) { VIEW_PROGRESSBAR -> { @@ -202,7 +205,10 @@ class SmbSearchDialog : DialogFragment() { } } - override fun onBindViewHolder(holder: ViewHolder, position: Int) { + override fun onBindViewHolder( + holder: ViewHolder, + position: Int, + ) { val viewType = getItemViewType(position) if (viewType == Companion.VIEW_PROGRESSBAR) { return @@ -215,7 +221,7 @@ class SmbSearchDialog : DialogFragment() { mainActivity.showSMBDialog( listViewAdapter.items[position].name, listViewAdapter.items[position].addr, - false + false, ) } } diff --git a/app/src/main/java/com/amaze/filemanager/ui/dialogs/share/ShareAdapter.java b/app/src/main/java/com/amaze/filemanager/ui/dialogs/share/ShareAdapter.java index b907cc63d9..d6b7f0236e 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/dialogs/share/ShareAdapter.java +++ b/app/src/main/java/com/amaze/filemanager/ui/dialogs/share/ShareAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/dialogs/share/ShareTask.java b/app/src/main/java/com/amaze/filemanager/ui/dialogs/share/ShareTask.java index c27520a8be..8f7c44102e 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/dialogs/share/ShareTask.java +++ b/app/src/main/java/com/amaze/filemanager/ui/dialogs/share/ShareTask.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/drag/DragToTrashListener.kt b/app/src/main/java/com/amaze/filemanager/ui/drag/DragToTrashListener.kt index 7a40c9ec44..d588b017c3 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/drag/DragToTrashListener.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/drag/DragToTrashListener.kt @@ -25,9 +25,12 @@ import android.view.View class DragToTrashListener( private val dragEventCallback: () -> Unit, - private val dragEnteredCallback: () -> Unit + private val dragEnteredCallback: () -> Unit, ) : View.OnDragListener { - override fun onDrag(p0: View?, p1: DragEvent?): Boolean { + override fun onDrag( + p0: View?, + p1: DragEvent?, + ): Boolean { return when (p1?.action) { DragEvent.ACTION_DRAG_ENDED -> { true diff --git a/app/src/main/java/com/amaze/filemanager/ui/drag/RecyclerAdapterDragListener.kt b/app/src/main/java/com/amaze/filemanager/ui/drag/RecyclerAdapterDragListener.kt index 9705abd126..eda7e37e83 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/drag/RecyclerAdapterDragListener.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/drag/RecyclerAdapterDragListener.kt @@ -40,19 +40,21 @@ class RecyclerAdapterDragListener( private val adapter: RecyclerAdapter, private val holder: ItemViewHolder?, private val dragAndDropPref: Int, - private val mainFragment: MainFragment + private val mainFragment: MainFragment, ) : View.OnDragListener { - private val TAG = javaClass.simpleName - override fun onDrag(p0: View?, p1: DragEvent?): Boolean { + override fun onDrag( + p0: View?, + p1: DragEvent?, + ): Boolean { return when (p1?.action) { DragEvent.ACTION_DRAG_ENDED -> { Log.d(TAG, "ENDING DRAG, DISABLE CORNERS") mainFragment.requireMainActivity().initCornersDragListener( true, dragAndDropPref - != PreferencesConstants.PREFERENCE_DRAG_TO_SELECT + != PreferencesConstants.PREFERENCE_DRAG_TO_SELECT, ) if (dragAndDropPref != PreferencesConstants.PREFERENCE_DRAG_TO_SELECT @@ -82,7 +84,7 @@ class RecyclerAdapterDragListener( holder.checkImageView } else { holder.checkImageViewGrid - } + }, ) } } else { @@ -148,39 +150,42 @@ class RecyclerAdapterDragListener( var currentFileParcelable: HybridFileParcelable? = null var isCurrentElementDirectory: Boolean? = null var isEmptyArea: Boolean? = null - var pasteLocation: String? = if (adapter.itemsDigested?.size == 0) { - mainFragment.currentPath - } else { - if (holder == null || holder.adapterPosition == RecyclerView.NO_POSITION) { - Log.d(TAG, "Trying to drop into empty area") - isEmptyArea = true + var pasteLocation: String? = + if (adapter.itemsDigested?.size == 0) { mainFragment.currentPath } else { - adapter.itemsDigested?.let { - itemsDigested -> - if (itemsDigested[holder.adapterPosition].specialType - == RecyclerAdapter.TYPE_BACK - ) { - // dropping in goback button - // hack to get the parent path - val hybridFileParcelable = mainFragment - .elementsList!![1].generateBaseFile() - val hybridFile = HybridFile( - hybridFileParcelable.mode, - hybridFileParcelable.getParent(mainFragment.context) - ) - hybridFile.getParent(mainFragment.context) - } else { - val currentElement = - itemsDigested[holder.adapterPosition] - .layoutElementParcelable - currentFileParcelable = currentElement?.generateBaseFile() - isCurrentElementDirectory = currentElement?.isDirectory - currentElement?.desc + if (holder == null || holder.adapterPosition == RecyclerView.NO_POSITION) { + Log.d(TAG, "Trying to drop into empty area") + isEmptyArea = true + mainFragment.currentPath + } else { + adapter.itemsDigested?.let { + itemsDigested -> + if (itemsDigested[holder.adapterPosition].specialType + == RecyclerAdapter.TYPE_BACK + ) { + // dropping in goback button + // hack to get the parent path + val hybridFileParcelable = + mainFragment + .elementsList!![1].generateBaseFile() + val hybridFile = + HybridFile( + hybridFileParcelable.mode, + hybridFileParcelable.getParent(mainFragment.context), + ) + hybridFile.getParent(mainFragment.context) + } else { + val currentElement = + itemsDigested[holder.adapterPosition] + .layoutElementParcelable + currentFileParcelable = currentElement?.generateBaseFile() + isCurrentElementDirectory = currentElement?.isDirectory + currentElement?.desc + } } } } - } if (checkedItems?.size == 0) { // probably because we switched tabs and // this adapter doesn't have any checked items, get from data utils @@ -189,7 +194,7 @@ class RecyclerAdapterDragListener( TAG, "Didn't find checked items in adapter, " + "checking dataUtils size ${ - dataUtils.checkedItemsList?.size ?: "null"}" + dataUtils.checkedItemsList?.size ?: "null"}", ) checkedItems = dataUtils.checkedItemsList } @@ -202,19 +207,20 @@ class RecyclerAdapterDragListener( isCurrentElementDirectory == false && currentFileParcelable?.getParent(mainFragment.context) .equals(file.getParent(mainFragment.context)) - ) || + ) || ( - isEmptyArea == true && mainFragment.currentPath - .equals(file.getParent(mainFragment.context)) - ) - ) + isEmptyArea == true && + mainFragment.currentPath + .equals(file.getParent(mainFragment.context)) + ) + ) ) { Log.d( TAG, ( "Trying to drop into one of checked items or current " + "location, not allowed ${it.desc}" - ) + ), ) holder?.baseItemView?.run { isFocusable = false @@ -233,12 +239,12 @@ class RecyclerAdapterDragListener( ( "Trying to drop into one of checked items " + "%s" - ).format(pasteLocation) + ).format(pasteLocation), ) DragAndDropDialog.showDialogOrPerformOperation( pasteLocation!!, arrayList, - mainFragment.requireMainActivity() + mainFragment.requireMainActivity(), ) adapter.toggleChecked(false) holder?.baseItemView?.run { diff --git a/app/src/main/java/com/amaze/filemanager/ui/drag/TabFragmentBottomDragListener.kt b/app/src/main/java/com/amaze/filemanager/ui/drag/TabFragmentBottomDragListener.kt index 881146cfac..4df629170b 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/drag/TabFragmentBottomDragListener.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/drag/TabFragmentBottomDragListener.kt @@ -25,10 +25,12 @@ import android.view.View class TabFragmentBottomDragListener( private val dragEnterCallBack: () -> Unit, - private val dragExitCallBack: () -> Unit + private val dragExitCallBack: () -> Unit, ) : View.OnDragListener { - - override fun onDrag(p0: View?, p1: DragEvent?): Boolean { + override fun onDrag( + p0: View?, + p1: DragEvent?, + ): Boolean { return when (p1?.action) { DragEvent.ACTION_DRAG_ENDED -> { true diff --git a/app/src/main/java/com/amaze/filemanager/ui/drag/TabFragmentSideDragListener.kt b/app/src/main/java/com/amaze/filemanager/ui/drag/TabFragmentSideDragListener.kt index ae7ad2cd4d..c67373067f 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/drag/TabFragmentSideDragListener.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/drag/TabFragmentSideDragListener.kt @@ -24,7 +24,10 @@ import android.view.DragEvent import android.view.View class TabFragmentSideDragListener(private val dragEventCallback: () -> Unit) : View.OnDragListener { - override fun onDrag(p0: View?, p1: DragEvent?): Boolean { + override fun onDrag( + p0: View?, + p1: DragEvent?, + ): Boolean { return when (p1?.action) { DragEvent.ACTION_DRAG_ENDED -> { true diff --git a/app/src/main/java/com/amaze/filemanager/ui/fragments/AdjustListViewForTv.kt b/app/src/main/java/com/amaze/filemanager/ui/fragments/AdjustListViewForTv.kt index 29e7977646..fba387de90 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/fragments/AdjustListViewForTv.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/fragments/AdjustListViewForTv.kt @@ -28,5 +28,8 @@ interface AdjustListViewForTv { * Adjust list view focus scroll when using dpad. * Scroll few more elements up / down so that it's easier for user to see list */ - fun adjustListViewForTv(viewHolder: T, mainActivity: MainActivity) + fun adjustListViewForTv( + viewHolder: T, + mainActivity: MainActivity, + ) } diff --git a/app/src/main/java/com/amaze/filemanager/ui/fragments/AppsListFragment.java b/app/src/main/java/com/amaze/filemanager/ui/fragments/AppsListFragment.java index da887dc805..9cd9e6a3b3 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/fragments/AppsListFragment.java +++ b/app/src/main/java/com/amaze/filemanager/ui/fragments/AppsListFragment.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/fragments/CloudSheetFragment.java b/app/src/main/java/com/amaze/filemanager/ui/fragments/CloudSheetFragment.java index 0037e97a49..3a976e0f32 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/fragments/CloudSheetFragment.java +++ b/app/src/main/java/com/amaze/filemanager/ui/fragments/CloudSheetFragment.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/fragments/CompressedExplorerFragment.kt b/app/src/main/java/com/amaze/filemanager/ui/fragments/CompressedExplorerFragment.kt index 975e1f52de..dacea24693 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/fragments/CompressedExplorerFragment.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/fragments/CompressedExplorerFragment.kt @@ -92,7 +92,6 @@ import java.io.IOException @Suppress("TooManyFunctions") class CompressedExplorerFragment : Fragment(), BottomBarButtonPath { - lateinit var compressedFile: File private val viewModel: CompressedExplorerFragmentViewModel by viewModels() @@ -155,27 +154,29 @@ class CompressedExplorerFragment : Fragment(), BottomBarButtonPath { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, - savedInstanceState: Bundle? + savedInstanceState: Bundle?, ): View { val rootView: View = MainFragBinding.inflate(inflater).root - listView = rootView.findViewById(R.id.listView).also { - it.setOnTouchListener { _: View?, _: MotionEvent? -> - compressedExplorerAdapter?.apply { - if (stopAnims && !this.stoppedAnimation) { - stopAnim() + listView = + rootView.findViewById(R.id.listView).also { + it.setOnTouchListener { _: View?, _: MotionEvent? -> + compressedExplorerAdapter?.apply { + if (stopAnims && !this.stoppedAnimation) { + stopAnim() + } + this.stoppedAnimation = true + stopAnims = false } - this.stoppedAnimation = true - stopAnims = false + false } - false } - } - swipeRefreshLayout = rootView - .findViewById(R.id.activity_main_swipe_refresh_layout).also { - it.setOnRefreshListener { refresh() } - it.isRefreshing = true - } + swipeRefreshLayout = + rootView + .findViewById(R.id.activity_main_swipe_refresh_layout).also { + it.setOnRefreshListener { refresh() } + it.isRefreshing = true + } viewModel.elements.observe( viewLifecycleOwner, { elements -> @@ -184,7 +185,7 @@ class CompressedExplorerFragment : Fragment(), BottomBarButtonPath { swipeRefreshLayout.isRefreshing = false updateBottomBar() } - } + }, ) return rootView } @@ -198,22 +199,26 @@ class CompressedExplorerFragment : Fragment(), BottomBarButtonPath { } } - override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + override fun onViewCreated( + view: View, + savedInstanceState: Bundle?, + ) { super.onViewCreated(view, savedInstanceState) val sp = PreferenceManager.getDefaultSharedPreferences(requireActivity()) val fileName = prepareCompressedFile(requireArguments().getString(KEY_PATH, "/")) - mToolbarContainer = requireMainActivity().appbar.appbarLayout.also { - it.setOnTouchListener { _: View?, _: MotionEvent? -> - if (stopAnims) { - if (false == compressedExplorerAdapter?.stoppedAnimation) { - stopAnim() + mToolbarContainer = + requireMainActivity().appbar.appbarLayout.also { + it.setOnTouchListener { _: View?, _: MotionEvent? -> + if (stopAnims) { + if (false == compressedExplorerAdapter?.stoppedAnimation) { + stopAnim() + } + compressedExplorerAdapter?.stoppedAnimation = true } - compressedExplorerAdapter?.stoppedAnimation = true + stopAnims = false + false } - stopAnims = false - false } - } listView?.visibility = View.VISIBLE listView?.layoutManager = LinearLayoutManager(activity) val utilsProvider = AppConfig.getInstance().utilsProvider @@ -227,8 +232,8 @@ class CompressedExplorerFragment : Fragment(), BottomBarButtonPath { listView?.setBackgroundColor( Utils.getColor( context, - android.R.color.background_light - ) + android.R.color.background_light, + ), ) } gobackitem = sp.getBoolean(PreferencesConstants.PREFERENCE_SHOW_GOBACK_BUTTON, false) @@ -257,7 +262,7 @@ class CompressedExplorerFragment : Fragment(), BottomBarButtonPath { Toast.makeText( requireContext(), R.string.error_cant_decompress_that_file, - Toast.LENGTH_LONG + Toast.LENGTH_LONG, ).show() parentFragmentManager.beginTransaction() .remove(this@CompressedExplorerFragment).commit() @@ -283,22 +288,23 @@ class CompressedExplorerFragment : Fragment(), BottomBarButtonPath { arrayOf(MediaStore.MediaColumns.DISPLAY_NAME), null, null, - null + null, )?.run { try { if (moveToFirst()) { - fileName = getString(0).let { + fileName = + getString(0).let { /* * Strip any slashes to prevent possibility to access files outside * cache dir if malicious ContentProvider gives malicious value * of MediaStore.MediaColumns.DISPLAY_NAME when querying */ - if (it.contains(File.pathSeparator)) { - it.substringAfterLast(File.pathSeparatorChar) - } else { - it + if (it.contains(File.pathSeparator)) { + it.substringAfterLast(File.pathSeparatorChar) + } else { + it + } } - } compressedFile = File(requireContext().cacheDir, fileName) } else { // At this point, we know nothing the file the URI represents, we are doing everything @@ -307,7 +313,7 @@ class CompressedExplorerFragment : Fragment(), BottomBarButtonPath { File.createTempFile( "compressed", null, - requireContext().cacheDir + requireContext().cacheDir, ) .also { fileName = it.name @@ -326,8 +332,8 @@ class CompressedExplorerFragment : Fragment(), BottomBarButtonPath { requireContext() .getString( R.string.compressed_explorer_fragment_error_open_uri, - pathUri.toString() - ) + pathUri.toString(), + ), ) requireActivity().onBackPressed() } finally { @@ -336,9 +342,10 @@ class CompressedExplorerFragment : Fragment(), BottomBarButtonPath { } } else { pathUri.path?.let { path -> - compressedFile = File(path).also { - fileName = it.name.substring(0, it.name.lastIndexOf(".")) - } + compressedFile = + File(path).also { + fileName = it.name.substring(0, it.name.lastIndexOf(".")) + } } } @@ -368,7 +375,7 @@ class CompressedExplorerFragment : Fragment(), BottomBarButtonPath { Toast.makeText( requireContext(), R.string.error_cant_decompress_that_file, - Toast.LENGTH_LONG + Toast.LENGTH_LONG, ).show() return } @@ -379,144 +386,162 @@ class CompressedExplorerFragment : Fragment(), BottomBarButtonPath { } @JvmField - var mActionModeCallback: ActionMode.Callback = object : ActionMode.Callback { - private fun hideOption(id: Int, menu: Menu) { - val item = menu.findItem(id) - item.isVisible = false - } + var mActionModeCallback: ActionMode.Callback = + object : ActionMode.Callback { + private fun hideOption( + id: Int, + menu: Menu, + ) { + val item = menu.findItem(id) + item.isVisible = false + } - private fun showOption(id: Int, menu: Menu) { - val item = menu.findItem(id) - item.isVisible = true - } + private fun showOption( + id: Int, + menu: Menu, + ) { + val item = menu.findItem(id) + item.isVisible = true + } - // called when the action mode is created; startActionMode() was called - override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean { - // Inflate a menu resource providing context menu items - val v = ActionmodeBinding.inflate(LayoutInflater.from(requireContext())).root - mode.customView = v - // assumes that you have "contexual.xml" menu resources - mode.menuInflater.inflate(R.menu.contextual, menu) - hideOption(R.id.cpy, menu) - hideOption(R.id.cut, menu) - hideOption(R.id.delete, menu) - hideOption(R.id.addshortcut, menu) - hideOption(R.id.share, menu) - hideOption(R.id.openwith, menu) - showOption(R.id.all, menu) - hideOption(R.id.compress, menu) - hideOption(R.id.hide, menu) - showOption(R.id.ex, menu) - mode.title = getString(R.string.select) - requireMainActivity().updateViews( - ColorDrawable( - Utils.getColor( - context, - R.color.holo_dark_action_mode - ) + // called when the action mode is created; startActionMode() was called + override fun onCreateActionMode( + mode: ActionMode, + menu: Menu, + ): Boolean { + // Inflate a menu resource providing context menu items + val v = ActionmodeBinding.inflate(LayoutInflater.from(requireContext())).root + mode.customView = v + // assumes that you have "contexual.xml" menu resources + mode.menuInflater.inflate(R.menu.contextual, menu) + hideOption(R.id.cpy, menu) + hideOption(R.id.cut, menu) + hideOption(R.id.delete, menu) + hideOption(R.id.addshortcut, menu) + hideOption(R.id.share, menu) + hideOption(R.id.openwith, menu) + showOption(R.id.all, menu) + hideOption(R.id.compress, menu) + hideOption(R.id.hide, menu) + showOption(R.id.ex, menu) + mode.title = getString(R.string.select) + requireMainActivity().updateViews( + ColorDrawable( + Utils.getColor( + context, + R.color.holo_dark_action_mode, + ), + ), ) - ) - if (SDK_INT >= LOLLIPOP) { - val window = requireActivity().window - if (requireMainActivity() - .getBoolean(PreferencesConstants.PREFERENCE_COLORED_NAVIGATION) - ) { - window.navigationBarColor = - Utils.getColor(context, android.R.color.black) + if (SDK_INT >= LOLLIPOP) { + val window = requireActivity().window + if (requireMainActivity() + .getBoolean(PreferencesConstants.PREFERENCE_COLORED_NAVIGATION) + ) { + window.navigationBarColor = + Utils.getColor(context, android.R.color.black) + } } + if (SDK_INT < KITKAT) { + requireMainActivity().appbar.toolbar.visibility = View.GONE + } + return true } - if (SDK_INT < KITKAT) { - requireMainActivity().appbar.toolbar.visibility = View.GONE - } - return true - } - // the following method is called each time - // the action mode is shown. Always called after - // onCreateActionMode, but - // may be called multiple times if the mode is invalidated. - override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean { - compressedExplorerAdapter?.checkedItemPositions?.let { positions -> - (mode.customView.findViewById(R.id.item_count) as AppCompatTextView).text = - positions.size.toString() - menu.findItem(R.id.all) - .setTitle( - if (positions.size == folder + file) { - R.string.deselect_all - } else { - R.string.select_all - } - ) - } - return false // Return false if nothing is done - } - - // called when the user selects a contextual menu item - override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean { - return compressedExplorerAdapter?.let { - when (item.itemId) { - R.id.all -> { - val positions = it.checkedItemPositions - val shouldDeselectAll = positions.size != folder + file - it.toggleChecked(shouldDeselectAll) - mode.invalidate() - item.setTitle( - if (shouldDeselectAll) { + // the following method is called each time + // the action mode is shown. Always called after + // onCreateActionMode, but + // may be called multiple times if the mode is invalidated. + override fun onPrepareActionMode( + mode: ActionMode, + menu: Menu, + ): Boolean { + compressedExplorerAdapter?.checkedItemPositions?.let { positions -> + (mode.customView.findViewById(R.id.item_count) as AppCompatTextView).text = + positions.size.toString() + menu.findItem(R.id.all) + .setTitle( + if (positions.size == folder + file) { R.string.deselect_all } else { R.string.select_all - } + }, ) - if (!shouldDeselectAll) { - selection = false - mActionMode?.finish() - mActionMode = null + } + return false // Return false if nothing is done + } + + // called when the user selects a contextual menu item + override fun onActionItemClicked( + mode: ActionMode, + item: MenuItem, + ): Boolean { + return compressedExplorerAdapter?.let { + when (item.itemId) { + R.id.all -> { + val positions = it.checkedItemPositions + val shouldDeselectAll = positions.size != folder + file + it.toggleChecked(shouldDeselectAll) + mode.invalidate() + item.setTitle( + if (shouldDeselectAll) { + R.string.deselect_all + } else { + R.string.select_all + }, + ) + if (!shouldDeselectAll) { + selection = false + mActionMode?.finish() + mActionMode = null + } + return true } - return true - } - R.id.ex -> { - Toast.makeText(activity, getString(R.string.extracting), Toast.LENGTH_SHORT) - .show() - val dirs = arrayOfNulls( - it.checkedItemPositions.size - ) - var i = 0 - while (i < dirs.size) { - dirs[i] = - viewModel - .elements - .value!![it.checkedItemPositions[i]].path - i++ + R.id.ex -> { + Toast.makeText(activity, getString(R.string.extracting), Toast.LENGTH_SHORT) + .show() + val dirs = + arrayOfNulls( + it.checkedItemPositions.size, + ) + var i = 0 + while (i < dirs.size) { + dirs[i] = + viewModel + .elements + .value!![it.checkedItemPositions[i]].path + i++ + } + decompressor.decompress(compressedFile.path, dirs) + mode.finish() + return true } - decompressor.decompress(compressedFile.path, dirs) - mode.finish() - return true + else -> false } - else -> false - } - } ?: false - } + } ?: false + } - override fun onDestroyActionMode(actionMode: ActionMode) { - compressedExplorerAdapter?.toggleChecked(false) - @ColorInt val primaryColor = ColorPreferenceHelper.getPrimary( - requireMainActivity().currentColorPreference, - MainActivity.currentTab - ) - selection = false - requireMainActivity().updateViews(ColorDrawable(primaryColor)) - if (SDK_INT >= LOLLIPOP) { - val window = requireActivity().window - if (requireMainActivity() - .getBoolean(PreferencesConstants.PREFERENCE_COLORED_NAVIGATION) - ) { - window.navigationBarColor = - requireMainActivity().skinStatusBar + override fun onDestroyActionMode(actionMode: ActionMode) { + compressedExplorerAdapter?.toggleChecked(false) + @ColorInt val primaryColor = + ColorPreferenceHelper.getPrimary( + requireMainActivity().currentColorPreference, + MainActivity.currentTab, + ) + selection = false + requireMainActivity().updateViews(ColorDrawable(primaryColor)) + if (SDK_INT >= LOLLIPOP) { + val window = requireActivity().window + if (requireMainActivity() + .getBoolean(PreferencesConstants.PREFERENCE_COLORED_NAVIGATION) + ) { + window.navigationBarColor = + requireMainActivity().skinStatusBar + } } + mActionMode = null } - mActionMode = null } - } override fun onDestroyView() { super.onDestroyView() @@ -525,7 +550,7 @@ class CompressedExplorerFragment : Fragment(), BottomBarButtonPath { // be cleaned after it is destroyed, preventing leaks mToolbarContainer?.setOnTouchListener(null) (mToolbarContainer as AppBarLayout?)?.removeOnOffsetChangedListener( - offsetListenerForToolbar + offsetListenerForToolbar, ) requireMainActivity().supportInvalidateOptionsMenu() @@ -551,28 +576,33 @@ class CompressedExplorerFragment : Fragment(), BottomBarButtonPath { requireActivity().unbindService(mServiceConnection) } - private val mServiceConnection: ServiceConnection = object : ServiceConnection { - override fun onServiceConnected(name: ComponentName, service: IBinder) = Unit - override fun onServiceDisconnected(name: ComponentName) { - // open file if pending - if (isOpen) { - files?.let { cachedFiles -> - // open most recent entry added to files to be deleted from cache - val cacheFile = File(cachedFiles[cachedFiles.size - 1].path) - if (cacheFile.exists()) { - FileUtils.openFile( - cacheFile, - requireMainActivity(), - requireMainActivity().prefs - ) + private val mServiceConnection: ServiceConnection = + object : ServiceConnection { + override fun onServiceConnected( + name: ComponentName, + service: IBinder, + ) = Unit + + override fun onServiceDisconnected(name: ComponentName) { + // open file if pending + if (isOpen) { + files?.let { cachedFiles -> + // open most recent entry added to files to be deleted from cache + val cacheFile = File(cachedFiles[cachedFiles.size - 1].path) + if (cacheFile.exists()) { + FileUtils.openFile( + cacheFile, + requireMainActivity(), + requireMainActivity().prefs, + ) + } + // reset the flag and cache file, as it's root is already in the list for deletion + isOpen = false + cachedFiles.removeAt(cachedFiles.size - 1) } - // reset the flag and cache file, as it's root is already in the list for deletion - isOpen = false - cachedFiles.removeAt(cachedFiles.size - 1) } } } - } override fun changePath(path: String) { var folder = path @@ -593,7 +623,7 @@ class CompressedExplorerFragment : Fragment(), BottomBarButtonPath { } else { archiveCorruptOrUnsupportedToast(error) } - } + }, ) swipeRefreshLayout.isRefreshing = true updateBottomBar() @@ -603,9 +633,10 @@ class CompressedExplorerFragment : Fragment(), BottomBarButtonPath { private fun dialogGetPasswordFromUser(filePath: String) { val positiveCallback = SingleButtonCallback { dialog: MaterialDialog, _: DialogAction? -> - val editText = dialog.view.findViewById( - R.id.singleedittext_input - ) + val editText = + dialog.view.findViewById( + R.id.singleedittext_input, + ) val password: String = editText.text.toString() ArchivePasswordCache.getInstance()[filePath] = password dialog.dismiss() @@ -619,7 +650,7 @@ class CompressedExplorerFragment : Fragment(), BottomBarButtonPath { R.string.archive_password_prompt, R.string.authenticate_password, positiveCallback, - null + null, ) } @@ -633,17 +664,18 @@ class CompressedExplorerFragment : Fragment(), BottomBarButtonPath { Toast.makeText( activity, requireContext().getString(msg, compressedFile.absolutePath), - Toast.LENGTH_LONG + Toast.LENGTH_LONG, ).show() requireActivity().supportFragmentManager.beginTransaction().remove(this).commit() } override val path: String - get() = if (!isRootRelativePath) { - CompressedHelper.SEPARATOR + relativeDirectory - } else { - "" - } + get() = + if (!isRootRelativePath) { + CompressedHelper.SEPARATOR + relativeDirectory + } else { + "" + } override val rootDrawable: Int get() = R.drawable.ic_compressed_white_24dp @@ -667,16 +699,20 @@ class CompressedExplorerFragment : Fragment(), BottomBarButtonPath { } } - private fun createViews(items: List?, dir: String) { + private fun createViews( + items: List?, + dir: String, + ) { if (compressedExplorerAdapter == null) { - compressedExplorerAdapter = CompressedExplorerAdapter( - activity, - AppConfig.getInstance().utilsProvider, - items, - this, - decompressor, - PreferenceManager.getDefaultSharedPreferences(requireMainActivity()) - ) + compressedExplorerAdapter = + CompressedExplorerAdapter( + activity, + AppConfig.getInstance().utilsProvider, + items, + this, + decompressor, + PreferenceManager.getDefaultSharedPreferences(requireMainActivity()), + ) listView?.adapter = compressedExplorerAdapter } else { compressedExplorerAdapter?.generateZip(items) @@ -695,21 +731,23 @@ class CompressedExplorerFragment : Fragment(), BottomBarButtonPath { // listView.removeItemDecoration(headersDecor); addheader = true } else { - dividerItemDecoration = DividerItemDecoration( - activity, - true, - showDividers - ).also { - listView?.addItemDecoration(it) - } + dividerItemDecoration = + DividerItemDecoration( + activity, + true, + showDividers, + ).also { + listView?.addItemDecoration(it) + } // headersDecor = new StickyRecyclerHeadersDecoration(compressedExplorerAdapter); // listView.addItemDecoration(headersDecor); addheader = false } - fastScroller = requireView().findViewById(R.id.fastscroll).also { - it.setRecyclerView(listView!!, 1) - it.setPressedHandleColor(requireMainActivity().accent) - } + fastScroller = + requireView().findViewById(R.id.fastscroll).also { + it.setRecyclerView(listView!!, 1) + it.setPressedHandleColor(requireMainActivity().accent) + } (mToolbarContainer as AppBarLayout?)?.addOnOffsetChangedListener(offsetListenerForToolbar) listView?.stopScroll() relativeDirectory = dir diff --git a/app/src/main/java/com/amaze/filemanager/ui/fragments/DbViewerFragment.java b/app/src/main/java/com/amaze/filemanager/ui/fragments/DbViewerFragment.java index fadbe32733..b0f44fac7e 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/fragments/DbViewerFragment.java +++ b/app/src/main/java/com/amaze/filemanager/ui/fragments/DbViewerFragment.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/fragments/FtpServerFragment.kt b/app/src/main/java/com/amaze/filemanager/ui/fragments/FtpServerFragment.kt index 41de2a8ec9..4cba8f6b73 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/fragments/FtpServerFragment.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/fragments/FtpServerFragment.kt @@ -99,7 +99,6 @@ import java.security.GeneralSecurityException */ @Suppress("TooManyFunctions") class FtpServerFragment : Fragment(R.layout.fragment_ftp) { - private val log: Logger = LoggerFactory.getLogger(FtpServerFragment::class.java) private val statusText: AppCompatTextView get() = binding.textViewFtpStatus @@ -123,11 +122,12 @@ class FtpServerFragment : Fragment(R.layout.fragment_ftp) { private val mainActivity: MainActivity get() = requireActivity() as MainActivity - private val activityResultHandlerOnFtpServerPathUpdate = createOpenDocumentTreeIntentCallback { - directoryUri -> - changeFTPServerPath(directoryUri.toString()) - updatePathText() - } + private val activityResultHandlerOnFtpServerPathUpdate = + createOpenDocumentTreeIntentCallback { + directoryUri -> + changeFTPServerPath(directoryUri.toString()) + updatePathText() + } private val activityResultHandlerOnFtpServerPathGrantedSafAccess = createOpenDocumentTreeIntentCallback { @@ -150,7 +150,7 @@ class FtpServerFragment : Fragment(R.layout.fragment_ftp) { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, - savedInstanceState: Bundle? + savedInstanceState: Bundle?, ): View { _binding = FragmentFtpBinding.inflate(inflater) accentColor = mainActivity.accent @@ -191,7 +191,7 @@ class FtpServerFragment : Fragment(R.layout.fragment_ftp) { .input( getString(R.string.ftp_port_edit_menu_title), currentFtpPort.toString(), - true + true, ) { _: MaterialDialog?, _: CharSequence? -> } .inputType(InputType.TYPE_CLASS_NUMBER) .onPositive { dialog: MaterialDialog, _: DialogAction? -> @@ -203,7 +203,7 @@ class FtpServerFragment : Fragment(R.layout.fragment_ftp) { Toast.makeText( activity, R.string.ftp_port_change_error_invalid, - Toast.LENGTH_SHORT + Toast.LENGTH_SHORT, ) .show() } else { @@ -211,7 +211,7 @@ class FtpServerFragment : Fragment(R.layout.fragment_ftp) { Toast.makeText( activity, R.string.ftp_port_change_success, - Toast.LENGTH_SHORT + Toast.LENGTH_SHORT, ) .show() } @@ -229,7 +229,7 @@ class FtpServerFragment : Fragment(R.layout.fragment_ftp) { intent.runIfDocumentsUIExists(mainActivity) { activityResultHandlerOnFtpServerPathUpdate.launch( - intent + intent, ) } } else { @@ -263,11 +263,12 @@ class FtpServerFragment : Fragment(R.layout.fragment_ftp) { } } } - val dialog = loginDialogBuilder.customView(loginDialogView.root, true) - .title(getString(R.string.ftp_login)) - .positiveText(getString(R.string.set).uppercase()) - .negativeText(getString(R.string.cancel)) - .build() + val dialog = + loginDialogBuilder.customView(loginDialogView.root, true) + .title(getString(R.string.ftp_login)) + .positiveText(getString(R.string.set).uppercase()) + .negativeText(getString(R.string.cancel)) + .build() // TextWatcher for port number was deliberately removed. It didn't work anyway, so // no reason to keep here. Pending reimplementation when material-dialogs lib is @@ -304,29 +305,31 @@ class FtpServerFragment : Fragment(R.layout.fragment_ftp) { getString(R.string.ftp_timeout) + " (" + resources.getString(R.string.ftp_seconds) + - ")" + ")", ) timeoutBuilder.input( ( FtpService.DEFAULT_TIMEOUT.toString() + " " + resources.getString(R.string.ftp_seconds) - ), + ), ftpTimeout.toString(), - true + true, ) { _: MaterialDialog?, input: CharSequence -> - val isInputInteger: Boolean = try { - // try parsing for integer check - input.toString().toInt() - true - } catch (e: NumberFormatException) { - false - } - ftpTimeout = if (input.isEmpty() || !isInputInteger) { - FtpService.DEFAULT_TIMEOUT - } else { - Integer.valueOf(input.toString()) - } + val isInputInteger: Boolean = + try { + // try parsing for integer check + input.toString().toInt() + true + } catch (e: NumberFormatException) { + false + } + ftpTimeout = + if (input.isEmpty() || !isInputInteger) { + FtpService.DEFAULT_TIMEOUT + } else { + Integer.valueOf(input.toString()) + } } timeoutBuilder .positiveText(resources.getString(R.string.set).uppercase()) @@ -343,7 +346,10 @@ class FtpServerFragment : Fragment(R.layout.fragment_ftp) { return false } - override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { + override fun onCreateOptionsMenu( + menu: Menu, + inflater: MenuInflater, + ) { mainActivity.menuInflater.inflate(R.menu.ftp_server_menu, menu) menu.findItem(R.id.checkbox_ftp_readonly).isChecked = readonlyPreference menu.findItem(R.id.checkbox_ftp_secure).isChecked = securePreference @@ -354,27 +360,31 @@ class FtpServerFragment : Fragment(R.layout.fragment_ftp) { private fun shouldUseSafFileSystem(): Boolean { return mainActivity.prefs.getBoolean( FtpService.KEY_PREFERENCE_SAF_FILESYSTEM, - false + false, ) && SDK_INT >= M } - private val mWifiReceiver: BroadcastReceiver = object : BroadcastReceiver() { - override fun onReceive(context: Context, intent: Intent) { - // connected to Wi-Fi or eth - if (isConnectedToLocalNetwork(context)) { - ftpBtn.isEnabled = true - dismissSnackbar() - } else { - // Wi-Fi or eth connection lost - stopServer() - statusText.text = spannedStatusNoConnection - ftpBtn.isEnabled = false - ftpBtn.text = resources.getString(R.string.start_ftp).uppercase() - promptUserToEnableWireless() + private val mWifiReceiver: BroadcastReceiver = + object : BroadcastReceiver() { + override fun onReceive( + context: Context, + intent: Intent, + ) { + // connected to Wi-Fi or eth + if (isConnectedToLocalNetwork(context)) { + ftpBtn.isEnabled = true + dismissSnackbar() + } else { + // Wi-Fi or eth connection lost + stopServer() + statusText.text = spannedStatusNoConnection + ftpBtn.isEnabled = false + ftpBtn.text = resources.getString(R.string.start_ftp).uppercase() + promptUserToEnableWireless() + } } } - } /** * Handles messages sent from [EventBus]. @@ -387,14 +397,18 @@ class FtpServerFragment : Fragment(R.layout.fragment_ftp) { updateSpans() when (signal) { FtpReceiverActions.STARTED, FtpReceiverActions.STARTED_FROM_TILE -> { - statusText.text = if (securePreference) spannedStatusSecure - else spannedStatusConnected + statusText.text = + if (securePreference) { + spannedStatusSecure + } else { + spannedStatusConnected + } url.text = spannedStatusUrl ftpBtn.text = resources.getString(R.string.stop_ftp).uppercase() FtpNotification.updateNotification( context, - FtpReceiverActions.STARTED_FROM_TILE == signal + FtpReceiverActions.STARTED_FROM_TILE == signal, ) } FtpReceiverActions.FAILED_TO_START -> { @@ -413,16 +427,15 @@ class FtpServerFragment : Fragment(R.layout.fragment_ftp) { } @Suppress("LabeledExpression") - private fun createOpenDocumentTreeIntentCallback(callback: (directoryUri: Uri) -> Unit): - ActivityResultLauncher { + private fun createOpenDocumentTreeIntentCallback(callback: (directoryUri: Uri) -> Unit): ActivityResultLauncher { return registerForActivityResult( - ActivityResultContracts.StartActivityForResult() + ActivityResultContracts.StartActivityForResult(), ) { if (it.resultCode == RESULT_OK && SDK_INT >= LOLLIPOP) { val directoryUri = it.data?.data ?: return@registerForActivityResult requireContext().contentResolver.takePersistableUriPermission( directoryUri, - GRANT_URI_RW_PERMISSION + GRANT_URI_RW_PERMISSION, ) callback.invoke(directoryUri) } @@ -431,15 +444,16 @@ class FtpServerFragment : Fragment(R.layout.fragment_ftp) { /** Check URI access. Prompt user to DocumentsUI if necessary */ private fun checkUriAccessIfNecessary(callback: () -> Unit) { - val directoryUri: String = mainActivity.prefs - .getString(KEY_PREFERENCE_PATH, defaultPathFromPreferences)!! + val directoryUri: String = + mainActivity.prefs + .getString(KEY_PREFERENCE_PATH, defaultPathFromPreferences)!! if (shouldUseSafFileSystem()) { Uri.parse(directoryUri).run { if (requireContext().checkUriPermission( this, Process.myPid(), Process.myUid(), - GRANT_URI_RW_PERMISSION + GRANT_URI_RW_PERMISSION, ) == PackageManager.PERMISSION_DENIED ) { mainActivity.accent.run { @@ -454,33 +468,38 @@ class FtpServerFragment : Fragment(R.layout.fragment_ftp) { .positiveColor(accentColor) .negativeText(R.string.cancel) .negativeColor(accentColor) - .onPositive(fun(dialog: MaterialDialog, _: DialogAction) { - val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE) - - intent.runIfDocumentsUIExists(mainActivity) { - activityResultHandlerOnFtpServerPathGrantedSafAccess.launch( - intent.also { - if (SDK_INT >= O && - directoryUri.startsWith(defaultPathFromPreferences) - ) { - it.putExtra( - EXTRA_INITIAL_URI, - DocumentsContract.buildDocumentUri( - "com.android.externalstorage.documents", - "primary:" + - directoryUri - .substringAfter( - defaultPathFromPreferences - ) + .onPositive( + fun( + dialog: MaterialDialog, + _: DialogAction, + ) { + val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE) + + intent.runIfDocumentsUIExists(mainActivity) { + activityResultHandlerOnFtpServerPathGrantedSafAccess.launch( + intent.also { + if (SDK_INT >= O && + directoryUri.startsWith(defaultPathFromPreferences) + ) { + it.putExtra( + EXTRA_INITIAL_URI, + DocumentsContract.buildDocumentUri( + "com.android.externalstorage.documents", + "primary:" + + directoryUri + .substringAfter( + defaultPathFromPreferences, + ), + ), ) - ) - } - } - ) - } - - dialog.dismiss() - }).build().show() + } + }, + ) + } + + dialog.dismiss() + }, + ).build().show() } } else { callback.invoke() @@ -490,7 +509,7 @@ class FtpServerFragment : Fragment(R.layout.fragment_ftp) { if (directoryUri.startsWith(ContentResolver.SCHEME_CONTENT)) { AppConfig.toast( mainActivity, - getString(R.string.ftp_server_fallback_path_reset_prompt) + getString(R.string.ftp_server_fallback_path_reset_prompt), ) resetFTPPath() } @@ -509,14 +528,15 @@ class FtpServerFragment : Fragment(R.layout.fragment_ftp) { private fun stopServer() { requireContext().sendBroadcast( Intent(FtpService.ACTION_STOP_FTPSERVER) - .setPackage(requireContext().packageName) + .setPackage(requireContext().packageName), ) } - private fun doStartServer() = requireContext().sendBroadcast( - Intent(FtpService.ACTION_START_FTPSERVER) - .setPackage(requireContext().packageName) - ) + private fun doStartServer() = + requireContext().sendBroadcast( + Intent(FtpService.ACTION_START_FTPSERVER) + .setPackage(requireContext().packageName), + ) override fun onResume() { super.onResume() @@ -556,32 +576,34 @@ class FtpServerFragment : Fragment(R.layout.fragment_ftp) { ftpBtn.text = resources.getString(R.string.stop_ftp).uppercase() } val passwordDecrypted = passwordFromPreferences - val passwordBulleted: CharSequence = OneCharacterCharSequence( - '\u25CF', - passwordDecrypted?.length ?: 0 - ) + val passwordBulleted: CharSequence = + OneCharacterCharSequence( + '\u25CF', + passwordDecrypted?.length ?: 0, + ) username.text = "${resources.getString(R.string.username)}: $usernameFromPreferences" password.text = "${resources.getString(R.string.password)}: $passwordBulleted" ftpPasswordVisibleButton.setImageDrawable( - resources.getDrawable(R.drawable.ic_eye_grey600_24dp) + resources.getDrawable(R.drawable.ic_eye_grey600_24dp), ) - ftpPasswordVisibleButton.visibility = if (passwordDecrypted?.isEmpty() == true) { - View.GONE - } else { - View.VISIBLE - } + ftpPasswordVisibleButton.visibility = + if (passwordDecrypted?.isEmpty() == true) { + View.GONE + } else { + View.VISIBLE + } ftpPasswordVisibleButton.setOnClickListener { if (password.text.toString().contains("\u25CF")) { // password was not visible, let's make it visible password.text = resources.getString(R.string.password) + ": " + passwordDecrypted ftpPasswordVisibleButton.setImageDrawable( - resources.getDrawable(R.drawable.ic_eye_off_grey600_24dp) + resources.getDrawable(R.drawable.ic_eye_off_grey600_24dp), ) } else { // password was visible, let's hide it password.text = resources.getString(R.string.password) + ": " + passwordBulleted ftpPasswordVisibleButton.setImageDrawable( - resources.getDrawable(R.drawable.ic_eye_grey600_24dp) + resources.getDrawable(R.drawable.ic_eye_grey600_24dp), ) } } @@ -596,9 +618,10 @@ class FtpServerFragment : Fragment(R.layout.fragment_ftp) { } private fun updatePathText() { - val sb = StringBuilder(resources.getString(R.string.ftp_path)) - .append(": ") - .append(pathToDisplayString(defaultPathFromPreferences)) + val sb = + StringBuilder(resources.getString(R.string.ftp_path)) + .append(": ") + .append(pathToDisplayString(defaultPathFromPreferences)) if (readonlyPreference) sb.append(" \uD83D\uDD12") sharedPath.text = sb.toString() setListener() @@ -614,7 +637,7 @@ class FtpServerFragment : Fragment(R.layout.fragment_ftp) { AppConfig.toast( mainActivity, - getString(R.string.ftp_server_reset_notify) + getString(R.string.ftp_server_reset_notify), ) } } @@ -638,43 +661,49 @@ class FtpServerFragment : Fragment(R.layout.fragment_ftp) { Toast.makeText( context, resources.getString(R.string.local_inet_addr_error), - Toast.LENGTH_SHORT + Toast.LENGTH_SHORT, ) .show() } val statusHead = "${resources.getString(R.string.ftp_status_title)}: " - spannedStatusConnected = HtmlCompat.fromHtml( - "$statusHead  " + - "${resources.getString(R.string.ftp_status_running)}", - FROM_HTML_MODE_COMPACT - ) - spannedStatusUrl = HtmlCompat.fromHtml( - "URL: $ftpAddress", - FROM_HTML_MODE_COMPACT - ) - spannedStatusNoConnection = HtmlCompat.fromHtml( - "$statusHead    " + - "" + - "${resources.getString(R.string.ftp_status_no_connection)}", - FROM_HTML_MODE_COMPACT - ) - spannedStatusNotRunning = HtmlCompat.fromHtml( - "$statusHead    " + - "${resources.getString(R.string.ftp_status_not_running)}", - FROM_HTML_MODE_COMPACT - ) - spannedStatusSecure = HtmlCompat.fromHtml( - "$statusHead    " + - "${resources.getString(R.string.ftp_status_secure_connection)}", - FROM_HTML_MODE_COMPACT - ) - spannedStatusUrl = HtmlCompat.fromHtml( - "URL: $ftpAddress", - FROM_HTML_MODE_COMPACT - ) + spannedStatusConnected = + HtmlCompat.fromHtml( + "$statusHead  " + + "${resources.getString(R.string.ftp_status_running)}", + FROM_HTML_MODE_COMPACT, + ) + spannedStatusUrl = + HtmlCompat.fromHtml( + "URL: $ftpAddress", + FROM_HTML_MODE_COMPACT, + ) + spannedStatusNoConnection = + HtmlCompat.fromHtml( + "$statusHead    " + + "" + + "${resources.getString(R.string.ftp_status_no_connection)}", + FROM_HTML_MODE_COMPACT, + ) + spannedStatusNotRunning = + HtmlCompat.fromHtml( + "$statusHead    " + + "${resources.getString(R.string.ftp_status_not_running)}", + FROM_HTML_MODE_COMPACT, + ) + spannedStatusSecure = + HtmlCompat.fromHtml( + "$statusHead    " + + "${resources.getString(R.string.ftp_status_secure_connection)}", + FROM_HTML_MODE_COMPACT, + ) + spannedStatusUrl = + HtmlCompat.fromHtml( + "URL: $ftpAddress", + FROM_HTML_MODE_COMPACT, + ) } private fun initLoginDialogViews(loginDialogView: DialogFtpLoginBinding) { @@ -695,7 +724,10 @@ class FtpServerFragment : Fragment(R.layout.fragment_ftp) { } } - private fun updateViews(mainActivity: MainActivity, binding: FragmentFtpBinding) { + private fun updateViews( + mainActivity: MainActivity, + binding: FragmentFtpBinding, + ) { mainActivity.appbar.setTitle(R.string.ftp) mainActivity.hideFab() mainActivity.appbar.bottomBar.setVisibility(View.GONE) @@ -711,10 +743,10 @@ class FtpServerFragment : Fragment(R.layout.fragment_ftp) { } AppTheme.DARK, AppTheme.BLACK -> { startDividerView.setBackgroundColor( - Utils.getColor(context, R.color.divider_dark_card) + Utils.getColor(context, R.color.divider_dark_card), ) statusDividerView.setBackgroundColor( - Utils.getColor(context, R.color.divider_dark_card) + Utils.getColor(context, R.color.divider_dark_card), ) } else -> { @@ -723,7 +755,7 @@ class FtpServerFragment : Fragment(R.layout.fragment_ftp) { val skin_color = mainActivity.currentColorPreference.primaryFirstTab val skinTwoColor = mainActivity.currentColorPreference.primarySecondTab mainActivity.updateViews( - ColorDrawable(if (MainActivity.currentTab == 1) skinTwoColor else skin_color) + ColorDrawable(if (MainActivity.currentTab == 1) skinTwoColor else skin_color), ) ftpBtn.setOnKeyListener( @@ -746,7 +778,7 @@ class FtpServerFragment : Fragment(R.layout.fragment_ftp) { } } true - } + }, ) } @@ -761,37 +793,41 @@ class FtpServerFragment : Fragment(R.layout.fragment_ftp) { } else { FtpService.INITIALS_HOST_FTP } - ) + + ) + ia.hostAddress + ":" + defaultPortFromPreferences - ) + ) } private val defaultPortFromPreferences: Int - get() = mainActivity.prefs - .getInt(FtpService.PORT_PREFERENCE_KEY, FtpService.DEFAULT_PORT) + get() = + mainActivity.prefs + .getInt(FtpService.PORT_PREFERENCE_KEY, FtpService.DEFAULT_PORT) private val usernameFromPreferences: String - get() = mainActivity.prefs - .getString(FtpService.KEY_PREFERENCE_USERNAME, FtpService.DEFAULT_USERNAME)!! + get() = + mainActivity.prefs + .getString(FtpService.KEY_PREFERENCE_USERNAME, FtpService.DEFAULT_USERNAME)!! // can't decrypt the password saved in preferences, remove the preference altogether private val passwordFromPreferences: String? - get() = runCatching { - val encryptedPassword: String = mainActivity.prefs.getString( - FtpService.KEY_PREFERENCE_PASSWORD, - "" - )!! - if (encryptedPassword == "") { - "" - } else { - PasswordUtil.decryptPassword(requireContext(), encryptedPassword) - } - }.onFailure { - log.warn("failed to decrypt ftp server password", it) - Toast.makeText(requireContext(), R.string.error, Toast.LENGTH_SHORT).show() - mainActivity.prefs.edit().putString(FtpService.KEY_PREFERENCE_PASSWORD, "").apply() - }.getOrNull() + get() = + runCatching { + val encryptedPassword: String = + mainActivity.prefs.getString( + FtpService.KEY_PREFERENCE_PASSWORD, + "", + )!! + if (encryptedPassword == "") { + "" + } else { + PasswordUtil.decryptPassword(requireContext(), encryptedPassword) + } + }.onFailure { + log.warn("failed to decrypt ftp server password", it) + Toast.makeText(requireContext(), R.string.error, Toast.LENGTH_SHORT).show() + mainActivity.prefs.edit().putString(FtpService.KEY_PREFERENCE_PASSWORD, "").apply() + }.getOrNull() private val defaultPathFromPreferences: String get() { @@ -856,7 +892,7 @@ class FtpServerFragment : Fragment(R.layout.fragment_ftp) { .edit() .putString( FtpService.KEY_PREFERENCE_PASSWORD, - PasswordUtil.encryptPassword(this, password) + PasswordUtil.encryptPassword(this, password), ) .apply() } @@ -874,17 +910,19 @@ class FtpServerFragment : Fragment(R.layout.fragment_ftp) { // Returns timeout from preferences, in seconds private var ftpTimeout: Int - get() = mainActivity - .prefs - .getInt(FtpService.KEY_PREFERENCE_TIMEOUT, FtpService.DEFAULT_TIMEOUT) + get() = + mainActivity + .prefs + .getInt(FtpService.KEY_PREFERENCE_TIMEOUT, FtpService.DEFAULT_TIMEOUT) private set(seconds) { mainActivity.prefs.edit().putInt(FtpService.KEY_PREFERENCE_TIMEOUT, seconds).apply() } private var securePreference: Boolean - get() = mainActivity - .prefs - .getBoolean(FtpService.KEY_PREFERENCE_SECURE, FtpService.DEFAULT_SECURE) + get() = + mainActivity + .prefs + .getBoolean(FtpService.KEY_PREFERENCE_SECURE, FtpService.DEFAULT_SECURE) private set(isSecureEnabled) { mainActivity .prefs @@ -919,12 +957,13 @@ class FtpServerFragment : Fragment(R.layout.fragment_ftp) { private fun promptUserToEnableWireless() { // No wifi, no data, no connection at all - snackbar = Utils.showThemedSnackbar( - activity as MainActivity?, - getString(R.string.ftp_server_prompt_connect_to_network), - BaseTransientBottomBar.LENGTH_INDEFINITE, - R.string.ftp_server_open_settings - ) { startActivity(Intent(Settings.ACTION_WIFI_SETTINGS)) } + snackbar = + Utils.showThemedSnackbar( + activity as MainActivity?, + getString(R.string.ftp_server_prompt_connect_to_network), + BaseTransientBottomBar.LENGTH_INDEFINITE, + R.string.ftp_server_open_settings, + ) { startActivity(Intent(Settings.ACTION_WIFI_SETTINGS)) } snackbar!!.show() } diff --git a/app/src/main/java/com/amaze/filemanager/ui/fragments/MainFragment.java b/app/src/main/java/com/amaze/filemanager/ui/fragments/MainFragment.java index 24ad0250e5..29c2a3393b 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/fragments/MainFragment.java +++ b/app/src/main/java/com/amaze/filemanager/ui/fragments/MainFragment.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/fragments/ProcessViewerFragment.java b/app/src/main/java/com/amaze/filemanager/ui/fragments/ProcessViewerFragment.java index c9f4a181c2..1507198595 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/fragments/ProcessViewerFragment.java +++ b/app/src/main/java/com/amaze/filemanager/ui/fragments/ProcessViewerFragment.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. @@ -85,6 +85,7 @@ public class ProcessViewerFragment extends Fragment { private int accentColor; private final LineData lineData = new LineData(); private ProcessparentBinding binding = null; + /** Time in seconds just for showing to the user. No guarantees. */ private long looseTimeInSeconds = 0L; diff --git a/app/src/main/java/com/amaze/filemanager/ui/fragments/TabFragment.java b/app/src/main/java/com/amaze/filemanager/ui/fragments/TabFragment.java index 5c8a2950dc..9cfe88053c 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/fragments/TabFragment.java +++ b/app/src/main/java/com/amaze/filemanager/ui/fragments/TabFragment.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/fragments/data/AppListViewModel.kt b/app/src/main/java/com/amaze/filemanager/ui/fragments/data/AppListViewModel.kt index d377633822..103ce85f0e 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/fragments/data/AppListViewModel.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/fragments/data/AppListViewModel.kt @@ -26,7 +26,6 @@ import androidx.lifecycle.ViewModel import com.amaze.filemanager.adapters.data.AppDataParcelable class AppListViewModel : ViewModel() { - var recyclerViewState: Parcelable? = null val isAscending = false val sortby = 0 diff --git a/app/src/main/java/com/amaze/filemanager/ui/fragments/data/CompressedExplorerFragmentViewModel.kt b/app/src/main/java/com/amaze/filemanager/ui/fragments/data/CompressedExplorerFragmentViewModel.kt index 6021258fee..8f208a023e 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/fragments/data/CompressedExplorerFragmentViewModel.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/fragments/data/CompressedExplorerFragmentViewModel.kt @@ -25,7 +25,6 @@ import androidx.lifecycle.ViewModel import com.amaze.filemanager.adapters.data.CompressedObjectParcelable class CompressedExplorerFragmentViewModel : ViewModel() { - val elements: MutableLiveData> by lazy { MutableLiveData() } diff --git a/app/src/main/java/com/amaze/filemanager/ui/fragments/data/MainFragmentViewModel.kt b/app/src/main/java/com/amaze/filemanager/ui/fragments/data/MainFragmentViewModel.kt index b99139943d..69b61e42cb 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/fragments/data/MainFragmentViewModel.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/fragments/data/MainFragmentViewModel.kt @@ -44,7 +44,6 @@ import kotlinx.coroutines.launch import java.util.Objects class MainFragmentViewModel : ViewModel() { - var currentPath: String? = null /** This is not an exact copy of the elements in the adapter */ @@ -115,11 +114,12 @@ class MainFragmentViewModel : ViewModel() { } } if (!::openMode.isInitialized) { - openMode = if (getInt("openmode", -1) !== -1) { - OpenMode.getOpenMode(getInt("openmode", -1)) - } else { - OpenMode.FILE - } + openMode = + if (getInt("openmode", -1) !== -1) { + OpenMode.getOpenMode(getInt("openmode", -1)) + } else { + OpenMode.FILE + } } } } @@ -128,10 +128,11 @@ class MainFragmentViewModel : ViewModel() { * Initialize drag drop preference */ fun initDragAndDropPreference(sharedPreferences: SharedPreferences) { - dragAndDropPreference = sharedPreferences.getInt( - PreferencesConstants.PREFERENCE_DRAG_AND_DROP_PREFERENCE, - PreferencesConstants.PREFERENCE_DRAG_DEFAULT - ) + dragAndDropPreference = + sharedPreferences.getInt( + PreferencesConstants.PREFERENCE_DRAG_AND_DROP_PREFERENCE, + PreferencesConstants.PREFERENCE_DRAG_DEFAULT, + ) } /** @@ -140,7 +141,7 @@ class MainFragmentViewModel : ViewModel() { fun initIsList() { isList = DataUtils.getInstance().getListOrGridForPath( currentPath, - DataUtils.LIST + DataUtils.LIST, ) == DataUtils.LIST } @@ -148,10 +149,11 @@ class MainFragmentViewModel : ViewModel() { * Initialize column number from preference */ fun initColumns(sharedPreferences: SharedPreferences) { - val columnPreference = sharedPreferences.getString( - PREFERENCE_GRID_COLUMNS, - PREFERENCE_GRID_COLUMNS_DEFAULT - ) + val columnPreference = + sharedPreferences.getString( + PREFERENCE_GRID_COLUMNS, + PREFERENCE_GRID_COLUMNS_DEFAULT, + ) Objects.requireNonNull(columnPreference) columns = columnPreference?.toInt() } @@ -164,11 +166,14 @@ class MainFragmentViewModel : ViewModel() { * * Final value of [.sortby] varies from 0 to 3 */ - fun initSortModes(sortType: SortType, sharedPref: SharedPreferences) { + fun initSortModes( + sortType: SortType, + sharedPref: SharedPreferences, + ) { this.sortType = sortType sharedPref.getString( PreferencesConstants.PREFERENCE_DIRECTORY_SORT_MODE, - "0" + "0", )?.run { dsort = DirSortBy.getDirSortBy(Integer.parseInt(this)) } diff --git a/app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/AppearancePrefsFragment.kt b/app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/AppearancePrefsFragment.kt index 6ce08c8d97..cbde160735 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/AppearancePrefsFragment.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/AppearancePrefsFragment.kt @@ -35,99 +35,111 @@ class AppearancePrefsFragment : BasePrefsFragment() { /** * The actual value saved for the preference, to see the localized strings see [R.array.columns] */ - private val savedPreferenceValues = listOf( - PREFERENCE_GRID_COLUMNS_DEFAULT, - "2", - "3", - "4", - "5", - "6" - ) + private val savedPreferenceValues = + listOf( + PREFERENCE_GRID_COLUMNS_DEFAULT, + "2", + "3", + "4", + "5", + "6", + ) private var currentTheme = 0 private var gridColumnPref: Preference? = null - private val onClickTheme = Preference.OnPreferenceClickListener { - val builder = MaterialDialog.Builder(activity) - builder.items(R.array.theme) - .itemsCallbackSingleChoice(currentTheme) { dialog, _, which, _ -> - val editor = activity.prefs.edit() - editor.putString(PreferencesConstants.FRAGMENT_THEME, which.toString()) - editor.apply() - - activity.utilsProvider.themeManager.setAppThemePreference( - AppThemePreference.getTheme(which) - ) - activity.recreate() - - dialog.dismiss() - true - } - .title(R.string.theme) - .build() - .show() - - true - } - - private val onClickGridColumn = Preference.OnPreferenceClickListener { - val dialog = MaterialDialog.Builder(activity).also { builder -> - builder.theme(activity.utilsProvider.appTheme.getMaterialDialogTheme()) - builder.title(R.string.gridcolumnno) - val columnsPreference = activity - .prefs - .getString(PREFERENCE_GRID_COLUMNS, PREFERENCE_GRID_COLUMNS_DEFAULT) - - Objects.requireNonNull(columnsPreference) - val current = when (columnsPreference) { - null -> { - PREFERENCE_GRID_COLUMNS_DEFAULT.toInt() - } - else -> { - columnsPreference.toInt() - 1 - } - } - - builder - .items(R.array.columns) - .itemsCallbackSingleChoice(current) { dialog, _, which, _ -> + private val onClickTheme = + Preference.OnPreferenceClickListener { + val builder = MaterialDialog.Builder(activity) + builder.items(R.array.theme) + .itemsCallbackSingleChoice(currentTheme) { dialog, _, which, _ -> val editor = activity.prefs.edit() - editor.putString( - PREFERENCE_GRID_COLUMNS, - savedPreferenceValues[which] - ) + editor.putString(PreferencesConstants.FRAGMENT_THEME, which.toString()) editor.apply() + + activity.utilsProvider.themeManager.setAppThemePreference( + AppThemePreference.getTheme(which), + ) + activity.recreate() + dialog.dismiss() - updateGridColumnSummary() true } - }.build() - dialog.show() + .title(R.string.theme) + .build() + .show() - true - } + true + } - private val onClickFollowBatterySaver = Preference.OnPreferenceClickListener { - // recreate the activity since the theme could have changed with this preference change - activity.recreate() - true - } + private val onClickGridColumn = + Preference.OnPreferenceClickListener { + val dialog = + MaterialDialog.Builder(activity).also { builder -> + builder.theme(activity.utilsProvider.appTheme.getMaterialDialogTheme()) + builder.title(R.string.gridcolumnno) + val columnsPreference = + activity + .prefs + .getString(PREFERENCE_GRID_COLUMNS, PREFERENCE_GRID_COLUMNS_DEFAULT) + + Objects.requireNonNull(columnsPreference) + val current = + when (columnsPreference) { + null -> { + PREFERENCE_GRID_COLUMNS_DEFAULT.toInt() + } + else -> { + columnsPreference.toInt() - 1 + } + } + + builder + .items(R.array.columns) + .itemsCallbackSingleChoice(current) { dialog, _, which, _ -> + val editor = activity.prefs.edit() + editor.putString( + PREFERENCE_GRID_COLUMNS, + savedPreferenceValues[which], + ) + editor.apply() + dialog.dismiss() + updateGridColumnSummary() + true + } + }.build() + dialog.show() + + true + } + + private val onClickFollowBatterySaver = + Preference.OnPreferenceClickListener { + // recreate the activity since the theme could have changed with this preference change + activity.recreate() + true + } - override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { + override fun onCreatePreferences( + savedInstanceState: Bundle?, + rootKey: String?, + ) { setPreferencesFromResource(R.xml.appearance_prefs, rootKey) val themePref = findPreference(PreferencesConstants.FRAGMENT_THEME) val themes = resources.getStringArray(R.array.theme) - currentTheme = activity - .prefs - .getString(PreferencesConstants.FRAGMENT_THEME, "4")!! - .toInt() + currentTheme = + activity + .prefs + .getString(PreferencesConstants.FRAGMENT_THEME, "4")!! + .toInt() themePref?.summary = themes[currentTheme] themePref?.onPreferenceClickListener = onClickTheme - val batterySaverPref = findPreference( - PreferencesConstants.FRAGMENT_FOLLOW_BATTERY_SAVER - ) + val batterySaverPref = + findPreference( + PreferencesConstants.FRAGMENT_FOLLOW_BATTERY_SAVER, + ) val currentThemeEnum = AppThemePreference.getTheme(currentTheme) batterySaverPref?.isVisible = currentThemeEnum.canBeLight @@ -136,20 +148,22 @@ class AppearancePrefsFragment : BasePrefsFragment() { findPreference(PreferencesConstants.PREFERENCE_COLORED_NAVIGATION) ?.let { it.isEnabled = true - it.onPreferenceClickListener = Preference.OnPreferenceClickListener { - activity.invalidateNavBar() + it.onPreferenceClickListener = + Preference.OnPreferenceClickListener { + activity.invalidateNavBar() - true - } + true + } } findPreference( - PreferencesConstants.PREFERENCE_SELECT_COLOR_CONFIG - )?.onPreferenceClickListener = Preference.OnPreferenceClickListener { - activity.pushFragment(ColorPrefsFragment()) + PreferencesConstants.PREFERENCE_SELECT_COLOR_CONFIG, + )?.onPreferenceClickListener = + Preference.OnPreferenceClickListener { + activity.pushFragment(ColorPrefsFragment()) - true - } + true + } gridColumnPref = findPreference(PREFERENCE_GRID_COLUMNS) updateGridColumnSummary() @@ -157,10 +171,11 @@ class AppearancePrefsFragment : BasePrefsFragment() { } private fun updateGridColumnSummary() { - val preferenceColumns = activity.prefs.getString( - PREFERENCE_GRID_COLUMNS, - PREFERENCE_GRID_COLUMNS_DEFAULT - ) + val preferenceColumns = + activity.prefs.getString( + PREFERENCE_GRID_COLUMNS, + PREFERENCE_GRID_COLUMNS_DEFAULT, + ) gridColumnPref?.summary = preferenceColumns } } diff --git a/app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/BackupPrefsFragment.kt b/app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/BackupPrefsFragment.kt index e727e1d922..dd13c279b1 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/BackupPrefsFragment.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/BackupPrefsFragment.kt @@ -41,7 +41,6 @@ import org.slf4j.LoggerFactory import java.io.* class BackupPrefsFragment : BasePrefsFragment() { - private val TAG: String = TagsHelper.getTag(BasePrefsFragment::class.java) private val log: Logger = LoggerFactory.getLogger(BackupPrefsFragment::class.java) @@ -53,8 +52,9 @@ class BackupPrefsFragment : BasePrefsFragment() { /** Export app settings to a JSON file */ fun exportPrefs() { - val map: Map = PreferenceManager - .getDefaultSharedPreferences(requireActivity()).all + val map: Map = + PreferenceManager + .getDefaultSharedPreferences(requireActivity()).all val gsonString: String = Gson().toJson(map) @@ -73,7 +73,7 @@ class BackupPrefsFragment : BasePrefsFragment() { Toast.makeText( context, getString(R.string.select_save_location), - Toast.LENGTH_SHORT + Toast.LENGTH_SHORT, ).show() val intent = Intent(context, MainActivity::class.java) @@ -99,23 +99,27 @@ class BackupPrefsFragment : BasePrefsFragment() { .setType("*/*") .putExtra( Intent.EXTRA_MIME_TYPES, - arrayOf("application/json") + arrayOf("application/json"), ), - IMPORT_BACKUP_FILE + IMPORT_BACKUP_FILE, ) } else { startActivityForResult( Intent.createChooser( Intent(Intent.ACTION_GET_CONTENT) .setType("application/json"), - "Choose backup file" + "Choose backup file", ), - IMPORT_BACKUP_FILE + IMPORT_BACKUP_FILE, ) } } - override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { + override fun onActivityResult( + requestCode: Int, + resultCode: Int, + data: Intent?, + ) { super.onActivityResult(requestCode, resultCode, data) val nonNull = data != null && data.data != null @@ -129,9 +133,10 @@ class BackupPrefsFragment : BasePrefsFragment() { Log.i(TAG, "read import file: $uri") try { - val inputStream = uri?.let { - context?.contentResolver?.openInputStream(it) - } + val inputStream = + uri?.let { + context?.contentResolver?.openInputStream(it) + } val bufferedReader = BufferedReader(InputStreamReader(inputStream)) val stringBuilder = StringBuilder() @@ -142,10 +147,11 @@ class BackupPrefsFragment : BasePrefsFragment() { val type = object : TypeToken>() {}.type - val map: Map = Gson().fromJson( - stringBuilder.toString(), - type - ) + val map: Map = + Gson().fromJson( + stringBuilder.toString(), + type, + ) val editor: SharedPreferences.Editor? = PreferenceManager.getDefaultSharedPreferences(requireActivity()).edit() @@ -158,20 +164,20 @@ class BackupPrefsFragment : BasePrefsFragment() { Toast.makeText( context, getString(R.string.importing_completed), - Toast.LENGTH_SHORT + Toast.LENGTH_SHORT, ).show() startActivity( Intent( context, - MainActivity::class.java - ) + MainActivity::class.java, + ), ) // restart Amaze for changes to take effect } catch (e: IOException) { Toast.makeText( context, getString(R.string.importing_failed), - Toast.LENGTH_SHORT + Toast.LENGTH_SHORT, ).show() log.error(getString(R.string.importing_failed), e) } @@ -181,7 +187,11 @@ class BackupPrefsFragment : BasePrefsFragment() { } @Suppress("UNCHECKED_CAST") - private fun storePreference(editor: SharedPreferences.Editor?, key: String?, value: Any) { + private fun storePreference( + editor: SharedPreferences.Editor?, + key: String?, + value: Any, + ) { try { when (value::class.simpleName) { "Boolean" -> editor?.putBoolean(key, value as Boolean) @@ -195,27 +205,32 @@ class BackupPrefsFragment : BasePrefsFragment() { Toast.makeText( context, "${getString(R.string.import_failed_for)} $key", - Toast.LENGTH_SHORT + Toast.LENGTH_SHORT, ).show() log.error("${getString(R.string.import_failed_for)} $key", e) } } - override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { + override fun onCreatePreferences( + savedInstanceState: Bundle?, + rootKey: String?, + ) { setPreferencesFromResource(R.xml.backup_prefs, rootKey) findPreference( - PreferencesConstants.PREFERENCE_EXPORT_SETTINGS - )?.onPreferenceClickListener = OnPreferenceClickListener { - exportPrefs() - true - } + PreferencesConstants.PREFERENCE_EXPORT_SETTINGS, + )?.onPreferenceClickListener = + OnPreferenceClickListener { + exportPrefs() + true + } findPreference( - PreferencesConstants.PREFERENCE_IMPORT_SETTINGS - )?.onPreferenceClickListener = OnPreferenceClickListener { - importPrefs() - true - } + PreferencesConstants.PREFERENCE_IMPORT_SETTINGS, + )?.onPreferenceClickListener = + OnPreferenceClickListener { + importPrefs() + true + } } } diff --git a/app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/BasePrefsFragment.kt b/app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/BasePrefsFragment.kt index 4d416055a9..24afba6b64 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/BasePrefsFragment.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/BasePrefsFragment.kt @@ -37,7 +37,10 @@ abstract class BasePrefsFragment : PreferenceFragmentCompat(), FolderChooserDial activity.supportActionBar?.title = getString(title) } - override fun onFolderSelection(dialog: FolderChooserDialog, folder: File) { + override fun onFolderSelection( + dialog: FolderChooserDialog, + folder: File, + ) { dialog.dismiss() } diff --git a/app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/BehaviorPrefsFragment.kt b/app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/BehaviorPrefsFragment.kt index 5e19ac7b12..189b77b104 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/BehaviorPrefsFragment.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/BehaviorPrefsFragment.kt @@ -36,7 +36,10 @@ import java.io.File class BehaviorPrefsFragment : BasePrefsFragment(), FolderChooserDialog.FolderCallback { override val title = R.string.behavior - override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { + override fun onCreatePreferences( + savedInstanceState: Bundle?, + rootKey: String?, + ) { setPreferencesFromResource(R.xml.behavior_prefs, rootKey) findPreference("clear_open_file")?.onPreferenceClickListener = @@ -47,45 +50,53 @@ class BehaviorPrefsFragment : BasePrefsFragment(), FolderChooserDialog.FolderCal } findPreference(PreferencesConstants.PREFERENCE_ZIP_EXTRACT_PATH) - ?.onPreferenceClickListener = Preference.OnPreferenceClickListener { - FolderChooserDialog.Builder(activity) - .tag(PreferencesConstants.PREFERENCE_ZIP_EXTRACT_PATH) - .goUpLabel(getString(R.string.folder_go_up_one_level)) - .chooseButton(R.string.choose_folder) - .cancelButton(R.string.cancel) - .initialPath( - activity.prefs.getString( - PreferencesConstants.PREFERENCE_ZIP_EXTRACT_PATH, - Environment.getExternalStorageDirectory().path + ?.onPreferenceClickListener = + Preference.OnPreferenceClickListener { + FolderChooserDialog.Builder(activity) + .tag(PreferencesConstants.PREFERENCE_ZIP_EXTRACT_PATH) + .goUpLabel(getString(R.string.folder_go_up_one_level)) + .chooseButton(R.string.choose_folder) + .cancelButton(R.string.cancel) + .initialPath( + activity.prefs.getString( + PreferencesConstants.PREFERENCE_ZIP_EXTRACT_PATH, + Environment.getExternalStorageDirectory().path, + ), ) - ) - .build() - .show(activity) - true - } + .build() + .show(activity) + true + } findPreference(PreferencesConstants.PREFERENCE_TRASH_BIN_RETENTION_NUM_OF_FILES) - ?.onPreferenceClickListener = Preference.OnPreferenceClickListener { - trashBinRetentionNumOfFiles() - true - } + ?.onPreferenceClickListener = + Preference.OnPreferenceClickListener { + trashBinRetentionNumOfFiles() + true + } findPreference(PreferencesConstants.PREFERENCE_TRASH_BIN_RETENTION_DAYS) - ?.onPreferenceClickListener = Preference.OnPreferenceClickListener { - trashBinRetentionDays() - true - } + ?.onPreferenceClickListener = + Preference.OnPreferenceClickListener { + trashBinRetentionDays() + true + } findPreference(PreferencesConstants.PREFERENCE_TRASH_BIN_RETENTION_BYTES) - ?.onPreferenceClickListener = Preference.OnPreferenceClickListener { - trashBinRetentionBytes() - true - } + ?.onPreferenceClickListener = + Preference.OnPreferenceClickListener { + trashBinRetentionBytes() + true + } findPreference(PreferencesConstants.PREFERENCE_TRASH_BIN_CLEANUP_INTERVAL) - ?.onPreferenceClickListener = Preference.OnPreferenceClickListener { - trashBinCleanupInterval() - true - } + ?.onPreferenceClickListener = + Preference.OnPreferenceClickListener { + trashBinCleanupInterval() + true + } } - override fun onFolderSelection(dialog: FolderChooserDialog, folder: File) { + override fun onFolderSelection( + dialog: FolderChooserDialog, + folder: File, + ) { // Just to be safe if (folder.exists() && folder.isDirectory) { // Write settings to preferences @@ -99,21 +110,22 @@ class BehaviorPrefsFragment : BasePrefsFragment(), FolderChooserDialog.FolderCal private fun trashBinRetentionNumOfFiles() { val dialogBuilder = MaterialDialog.Builder(activity) dialogBuilder.title( - resources.getString(R.string.trash_bin_retention_num_of_files_title) + resources.getString(R.string.trash_bin_retention_num_of_files_title), ) val sharedPrefs = PreferenceManager.getDefaultSharedPreferences(requireContext()) - val numOfFiles = sharedPrefs.getInt( - PreferencesConstants.KEY_TRASH_BIN_RETENTION_NUM_OF_FILES, - TrashBinConfig.RETENTION_NUM_OF_FILES - ) + val numOfFiles = + sharedPrefs.getInt( + PreferencesConstants.KEY_TRASH_BIN_RETENTION_NUM_OF_FILES, + TrashBinConfig.RETENTION_NUM_OF_FILES, + ) dialogBuilder.inputType(InputType.TYPE_CLASS_NUMBER) dialogBuilder.input( "", "$numOfFiles", - true + true, ) { _, _ -> } dialogBuilder.theme( - activity.utilsProvider.appTheme.materialDialogTheme + activity.utilsProvider.appTheme.materialDialogTheme, ) dialogBuilder.positiveText(resources.getString(R.string.ok)) dialogBuilder.negativeText(resources.getString(R.string.cancel)) @@ -125,13 +137,13 @@ class BehaviorPrefsFragment : BasePrefsFragment(), FolderChooserDialog.FolderCal val inputText = dialog.inputEditText?.text.toString() sharedPrefs.edit().putInt( PreferencesConstants.KEY_TRASH_BIN_RETENTION_NUM_OF_FILES, - inputText.toInt() + inputText.toInt(), ).apply() } dialogBuilder.onNeutral { _, _ -> sharedPrefs.edit().putInt( PreferencesConstants.KEY_TRASH_BIN_RETENTION_NUM_OF_FILES, - TrashBinConfig.RETENTION_NUM_OF_FILES + TrashBinConfig.RETENTION_NUM_OF_FILES, ).apply() } dialogBuilder.onNegative { dialog, _ -> dialog.cancel() } @@ -141,21 +153,22 @@ class BehaviorPrefsFragment : BasePrefsFragment(), FolderChooserDialog.FolderCal private fun trashBinRetentionDays() { val dialogBuilder = MaterialDialog.Builder(activity) dialogBuilder.title( - resources.getString(R.string.trash_bin_retention_days_title) + resources.getString(R.string.trash_bin_retention_days_title), ) val sharedPrefs = PreferenceManager.getDefaultSharedPreferences(requireContext()) - val days = sharedPrefs.getInt( - PreferencesConstants.KEY_TRASH_BIN_RETENTION_DAYS, - TrashBinConfig.RETENTION_DAYS_INFINITE - ) + val days = + sharedPrefs.getInt( + PreferencesConstants.KEY_TRASH_BIN_RETENTION_DAYS, + TrashBinConfig.RETENTION_DAYS_INFINITE, + ) dialogBuilder.inputType(InputType.TYPE_CLASS_NUMBER) dialogBuilder.input( "", "$days", - true + true, ) { _, _ -> } dialogBuilder.theme( - activity.utilsProvider.appTheme.materialDialogTheme + activity.utilsProvider.appTheme.materialDialogTheme, ) dialogBuilder.positiveText(resources.getString(R.string.ok)) dialogBuilder.negativeText(resources.getString(R.string.cancel)) @@ -167,13 +180,13 @@ class BehaviorPrefsFragment : BasePrefsFragment(), FolderChooserDialog.FolderCal val inputText = dialog.inputEditText?.text.toString() sharedPrefs.edit().putInt( PreferencesConstants.KEY_TRASH_BIN_RETENTION_DAYS, - inputText.toInt() + inputText.toInt(), ).apply() } dialogBuilder.onNeutral { _, _ -> sharedPrefs.edit().putInt( PreferencesConstants.KEY_TRASH_BIN_RETENTION_DAYS, - TrashBinConfig.RETENTION_DAYS_INFINITE + TrashBinConfig.RETENTION_DAYS_INFINITE, ).apply() } dialogBuilder.onNegative { dialog, _ -> dialog.cancel() } @@ -183,21 +196,22 @@ class BehaviorPrefsFragment : BasePrefsFragment(), FolderChooserDialog.FolderCal private fun trashBinRetentionBytes() { val dialogBuilder = MaterialDialog.Builder(activity) dialogBuilder.title( - resources.getString(R.string.trash_bin_retention_bytes_title) + resources.getString(R.string.trash_bin_retention_bytes_title), ) val sharedPrefs = PreferenceManager.getDefaultSharedPreferences(requireContext()) - val bytes = sharedPrefs.getLong( - PreferencesConstants.KEY_TRASH_BIN_RETENTION_BYTES, - TrashBinConfig.RETENTION_BYTES_INFINITE - ) + val bytes = + sharedPrefs.getLong( + PreferencesConstants.KEY_TRASH_BIN_RETENTION_BYTES, + TrashBinConfig.RETENTION_BYTES_INFINITE, + ) dialogBuilder.inputType(InputType.TYPE_CLASS_NUMBER) dialogBuilder.input( "", "$bytes", - true + true, ) { _, _ -> } dialogBuilder.theme( - activity.utilsProvider.appTheme.materialDialogTheme + activity.utilsProvider.appTheme.materialDialogTheme, ) dialogBuilder.positiveText(resources.getString(R.string.ok)) dialogBuilder.negativeText(resources.getString(R.string.cancel)) @@ -209,13 +223,13 @@ class BehaviorPrefsFragment : BasePrefsFragment(), FolderChooserDialog.FolderCal val inputText = dialog.inputEditText?.text.toString() sharedPrefs.edit().putLong( PreferencesConstants.KEY_TRASH_BIN_RETENTION_BYTES, - inputText.toLong() + inputText.toLong(), ).apply() } dialogBuilder.onNeutral { _, _ -> sharedPrefs.edit().putLong( PreferencesConstants.KEY_TRASH_BIN_RETENTION_BYTES, - TrashBinConfig.RETENTION_BYTES_INFINITE + TrashBinConfig.RETENTION_BYTES_INFINITE, ).apply() } dialogBuilder.onNegative { dialog, _ -> dialog.cancel() } @@ -225,21 +239,22 @@ class BehaviorPrefsFragment : BasePrefsFragment(), FolderChooserDialog.FolderCal private fun trashBinCleanupInterval() { val dialogBuilder = MaterialDialog.Builder(activity) dialogBuilder.title( - resources.getString(R.string.trash_bin_cleanup_interval_title) + resources.getString(R.string.trash_bin_cleanup_interval_title), ) val sharedPrefs = PreferenceManager.getDefaultSharedPreferences(requireContext()) - val intervalHours = sharedPrefs.getInt( - PreferencesConstants.KEY_TRASH_BIN_CLEANUP_INTERVAL_HOURS, - TrashBinConfig.INTERVAL_CLEANUP_HOURS - ) + val intervalHours = + sharedPrefs.getInt( + PreferencesConstants.KEY_TRASH_BIN_CLEANUP_INTERVAL_HOURS, + TrashBinConfig.INTERVAL_CLEANUP_HOURS, + ) dialogBuilder.inputType(InputType.TYPE_CLASS_NUMBER) dialogBuilder.input( "", "$intervalHours", - true + true, ) { _, _ -> } dialogBuilder.theme( - activity.utilsProvider.appTheme.materialDialogTheme + activity.utilsProvider.appTheme.materialDialogTheme, ) dialogBuilder.positiveText(resources.getString(R.string.ok)) dialogBuilder.negativeText(resources.getString(R.string.cancel)) @@ -251,13 +266,13 @@ class BehaviorPrefsFragment : BasePrefsFragment(), FolderChooserDialog.FolderCal val inputText = dialog.inputEditText?.text.toString() sharedPrefs.edit().putInt( PreferencesConstants.KEY_TRASH_BIN_CLEANUP_INTERVAL_HOURS, - inputText.toInt() + inputText.toInt(), ).apply() } dialogBuilder.onNeutral { _, _ -> sharedPrefs.edit().putInt( PreferencesConstants.KEY_TRASH_BIN_CLEANUP_INTERVAL_HOURS, - TrashBinConfig.INTERVAL_CLEANUP_HOURS + TrashBinConfig.INTERVAL_CLEANUP_HOURS, ).apply() } dialogBuilder.onNegative { dialog, _ -> dialog.cancel() } diff --git a/app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/BookmarksPrefsFragment.kt b/app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/BookmarksPrefsFragment.kt index 334a58abf0..45fbfc86d9 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/BookmarksPrefsFragment.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/BookmarksPrefsFragment.kt @@ -56,7 +56,10 @@ class BookmarksPrefsFragment : BasePrefsFragment() { showDeleteDialog(it) } - override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { + override fun onCreatePreferences( + savedInstanceState: Bundle?, + rootKey: String?, + ) { setPreferencesFromResource(R.xml.bookmarks_prefs, rootKey) findPreference("add_bookmarks")?.onPreferenceClickListener = @@ -96,15 +99,16 @@ class BookmarksPrefsFragment : BasePrefsFragment() { val txtShortcutName = dialogBinding.text1 val txtShortcutPath = dialogBinding.text2 - val dialog = MaterialDialog.Builder(requireActivity()) - .title(R.string.create_bookmark) - .theme(activity.appTheme.getMaterialDialogTheme()) - .positiveColor(fabSkin) - .positiveText(R.string.create) - .negativeColor(fabSkin) - .negativeText(android.R.string.cancel) - .customView(v, false) - .build() + val dialog = + MaterialDialog.Builder(requireActivity()) + .title(R.string.create_bookmark) + .theme(activity.appTheme.getMaterialDialogTheme()) + .positiveColor(fabSkin) + .positiveText(R.string.create) + .negativeColor(fabSkin) + .negativeText(android.R.string.cancel) + .customView(v, false) + .build() dialog.getActionButton(DialogAction.POSITIVE).isEnabled = false disableButtonIfTitleEmpty(txtShortcutName, dialog) disableButtonIfNotPath(txtShortcutPath, dialog) @@ -115,17 +119,18 @@ class BookmarksPrefsFragment : BasePrefsFragment() { p.summary = txtShortcutPath.text position[p] = dataUtils.books.size bookmarksList?.addPreference(p) - val values = arrayOf( - txtShortcutName.text.toString(), - txtShortcutPath.text.toString() - ) + val values = + arrayOf( + txtShortcutName.text.toString(), + txtShortcutPath.text.toString(), + ) dataUtils.addBook(values) utilsHandler.saveToDatabase( OperationData( UtilsHandler.Operation.BOOKMARKS, txtShortcutName.text.toString(), - txtShortcutPath.text.toString() - ) + txtShortcutPath.text.toString(), + ), ) dialog.dismiss() } @@ -145,15 +150,16 @@ class BookmarksPrefsFragment : BasePrefsFragment() { editText1.setText(p.title) editText2.setText(p.summary) - val dialog = MaterialDialog.Builder(activity) - .title(R.string.edit_bookmark) - .theme(activity.appTheme.getMaterialDialogTheme()) - .positiveColor(fabSkin) - .positiveText(getString(R.string.edit).uppercase()) // TODO: 29/4/2017 don't use toUpperCase() - .negativeColor(fabSkin) - .negativeText(android.R.string.cancel) - .customView(v, false) - .build() + val dialog = + MaterialDialog.Builder(activity) + .title(R.string.edit_bookmark) + .theme(activity.appTheme.getMaterialDialogTheme()) + .positiveColor(fabSkin) + .positiveText(getString(R.string.edit).uppercase()) // TODO: 29/4/2017 don't use toUpperCase() + .negativeColor(fabSkin) + .negativeText(android.R.string.cancel) + .customView(v, false) + .build() dialog.getActionButton(DialogAction.POSITIVE).isEnabled = FileUtils.isPathAccessible(editText2.text.toString(), activity.prefs) disableButtonIfTitleEmpty(editText1, dialog) @@ -177,7 +183,7 @@ class BookmarksPrefsFragment : BasePrefsFragment() { oldName, oldPath, editText1.text.toString(), - editText2.text.toString() + editText2.text.toString(), ) } dialog.dismiss() @@ -189,14 +195,15 @@ class BookmarksPrefsFragment : BasePrefsFragment() { val fabSkin = activity.accent val utilsHandler = AppConfig.getInstance().utilsHandler - val dialog = MaterialDialog.Builder(activity) - .title(R.string.question_delete_bookmark) - .theme(activity.appTheme.getMaterialDialogTheme()) - .positiveColor(fabSkin) - .positiveText(getString(R.string.delete).uppercase()) // TODO: 29/4/2017 don't use toUpperCase(), 20/9,2017 why not? - .negativeColor(fabSkin) - .negativeText(android.R.string.cancel) - .build() + val dialog = + MaterialDialog.Builder(activity) + .title(R.string.question_delete_bookmark) + .theme(activity.appTheme.getMaterialDialogTheme()) + .positiveColor(fabSkin) + .positiveText(getString(R.string.delete).uppercase()) // TODO: 29/4/2017 don't use toUpperCase(), 20/9,2017 why not? + .negativeColor(fabSkin) + .negativeText(android.R.string.cancel) + .build() dialog.getActionButton(DialogAction.POSITIVE) .setOnClickListener { dataUtils.removeBook(position[p]!!) @@ -204,8 +211,8 @@ class BookmarksPrefsFragment : BasePrefsFragment() { OperationData( UtilsHandler.Operation.BOOKMARKS, p.title.toString(), - p.summary.toString() - ) + p.summary.toString(), + ), ) bookmarksList?.removePreference(p) position.remove(p) @@ -214,24 +221,30 @@ class BookmarksPrefsFragment : BasePrefsFragment() { dialog.show() } - private fun disableButtonIfNotPath(path: AppCompatEditText, dialog: MaterialDialog) { + private fun disableButtonIfNotPath( + path: AppCompatEditText, + dialog: MaterialDialog, + ) { path.addTextChangedListener( object : SimpleTextWatcher() { override fun afterTextChanged(s: Editable) { dialog.getActionButton(DialogAction.POSITIVE).isEnabled = FileUtils.isPathAccessible(s.toString(), activity.prefs) } - } + }, ) } - private fun disableButtonIfTitleEmpty(title: AppCompatEditText, dialog: MaterialDialog) { + private fun disableButtonIfTitleEmpty( + title: AppCompatEditText, + dialog: MaterialDialog, + ) { title.addTextChangedListener( object : SimpleTextWatcher() { override fun afterTextChanged(s: Editable) { dialog.getActionButton(DialogAction.POSITIVE).isEnabled = title.length() > 0 } - } + }, ) } } diff --git a/app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/ColorPrefsFragment.kt b/app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/ColorPrefsFragment.kt index 7c6eb8b98c..e9b7119e9b 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/ColorPrefsFragment.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/ColorPrefsFragment.kt @@ -38,19 +38,24 @@ class ColorPrefsFragment : BasePrefsFragment() { private var dialog: MaterialDialog? = null - override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { + override fun onCreatePreferences( + savedInstanceState: Bundle?, + rootKey: String?, + ) { setPreferencesFromResource(R.xml.color_prefs, rootKey) - val showColorChangeDialogListener = Preference.OnPreferenceClickListener { - showColorChangeDialog(it.key) + val showColorChangeDialogListener = + Preference.OnPreferenceClickListener { + showColorChangeDialog(it.key) - true - } + true + } - val colorPickerPref = activity.prefs.getInt( - PreferencesConstants.PREFERENCE_COLOR_CONFIG, - ColorPickerDialog.NO_DATA - ) + val colorPickerPref = + activity.prefs.getInt( + PreferencesConstants.PREFERENCE_COLOR_CONFIG, + ColorPickerDialog.NO_DATA, + ) val skin = findPreference(PreferencesConstants.PREFERENCE_SKIN) val skinTwo = findPreference(PreferencesConstants.PREFERENCE_SKIN_TWO) @@ -79,16 +84,18 @@ class ColorPrefsFragment : BasePrefsFragment() { } private fun showPreselectedColorsConfigDialog() { - val newDialog = ColorPickerDialog.newInstance( - PreferencesConstants.PRESELECTED_CONFIGS, - activity.currentColorPreference, - activity.appTheme - ) - newDialog.setListener { - val colorPickerPref = activity.prefs.getInt( - PreferencesConstants.PREFERENCE_COLOR_CONFIG, - ColorPickerDialog.NO_DATA + val newDialog = + ColorPickerDialog.newInstance( + PreferencesConstants.PRESELECTED_CONFIGS, + activity.currentColorPreference, + activity.appTheme, ) + newDialog.setListener { + val colorPickerPref = + activity.prefs.getInt( + PreferencesConstants.PREFERENCE_COLOR_CONFIG, + ColorPickerDialog.NO_DATA, + ) if (colorPickerPref == ColorPickerDialog.RANDOM_INDEX) { AppConfig.toast(getActivity(), R.string.set_random) } @@ -102,63 +109,67 @@ class ColorPrefsFragment : BasePrefsFragment() { private fun showColorChangeDialog(colorPrefKey: String) { val currentColorPreference = activity.currentColorPreference ?: return - @ColorInt val currentColor = when (colorPrefKey) { - PreferencesConstants.PREFERENCE_SKIN -> currentColorPreference.primaryFirstTab - PreferencesConstants.PREFERENCE_SKIN_TWO -> currentColorPreference.primarySecondTab - PreferencesConstants.PREFERENCE_ACCENT -> currentColorPreference.accent - PreferencesConstants.PREFERENCE_ICON_SKIN -> currentColorPreference.iconSkin - else -> 0 - } - - val adapter = ColorAdapter( - activity, - ColorPreference.availableColors, - currentColor - ) { selectedColor: Int -> - @ColorInt var primaryFirst = currentColorPreference.primaryFirstTab - - @ColorInt var primarySecond = currentColorPreference.primarySecondTab - - @ColorInt var accent = currentColorPreference.accent - - @ColorInt var iconSkin = currentColorPreference.iconSkin + @ColorInt val currentColor = when (colorPrefKey) { - PreferencesConstants.PREFERENCE_SKIN -> primaryFirst = selectedColor - PreferencesConstants.PREFERENCE_SKIN_TWO -> primarySecond = selectedColor - PreferencesConstants.PREFERENCE_ACCENT -> accent = selectedColor - PreferencesConstants.PREFERENCE_ICON_SKIN -> iconSkin = selectedColor + PreferencesConstants.PREFERENCE_SKIN -> currentColorPreference.primaryFirstTab + PreferencesConstants.PREFERENCE_SKIN_TWO -> currentColorPreference.primarySecondTab + PreferencesConstants.PREFERENCE_ACCENT -> currentColorPreference.accent + PreferencesConstants.PREFERENCE_ICON_SKIN -> currentColorPreference.iconSkin + else -> 0 } - activity - .colorPreference - .saveColorPreferences( - activity.prefs, - UserColorPreferences(primaryFirst, primarySecond, accent, iconSkin) - ) - dialog?.dismiss() - activity.recreate() - } - - val v = DialogGridBinding.inflate(LayoutInflater.from(requireContext())).root.also { - it.adapter = adapter - it.onItemClickListener = adapter - } - - val fabSkin = activity.accent - dialog = MaterialDialog.Builder(activity) - .positiveText(com.amaze.filemanager.R.string.cancel) - .title(com.amaze.filemanager.R.string.choose_color) - .theme(activity.appTheme.getMaterialDialogTheme()) - .autoDismiss(true) - .positiveColor(fabSkin) - .neutralColor(fabSkin) - .neutralText(com.amaze.filemanager.R.string.default_string) - .onNeutral { _, _ -> + val adapter = + ColorAdapter( + activity, + ColorPreference.availableColors, + currentColor, + ) { selectedColor: Int -> + @ColorInt var primaryFirst = currentColorPreference.primaryFirstTab + + @ColorInt var primarySecond = currentColorPreference.primarySecondTab + + @ColorInt var accent = currentColorPreference.accent + + @ColorInt var iconSkin = currentColorPreference.iconSkin + when (colorPrefKey) { + PreferencesConstants.PREFERENCE_SKIN -> primaryFirst = selectedColor + PreferencesConstants.PREFERENCE_SKIN_TWO -> primarySecond = selectedColor + PreferencesConstants.PREFERENCE_ACCENT -> accent = selectedColor + PreferencesConstants.PREFERENCE_ICON_SKIN -> iconSkin = selectedColor + } activity .colorPreference - .saveColorPreferences(activity.prefs, currentColorPreference) + .saveColorPreferences( + activity.prefs, + UserColorPreferences(primaryFirst, primarySecond, accent, iconSkin), + ) + dialog?.dismiss() activity.recreate() - }.customView(v, false) - .show() + } + + val v = + DialogGridBinding.inflate(LayoutInflater.from(requireContext())).root.also { + it.adapter = adapter + it.onItemClickListener = adapter + } + + val fabSkin = activity.accent + + dialog = + MaterialDialog.Builder(activity) + .positiveText(com.amaze.filemanager.R.string.cancel) + .title(com.amaze.filemanager.R.string.choose_color) + .theme(activity.appTheme.getMaterialDialogTheme()) + .autoDismiss(true) + .positiveColor(fabSkin) + .neutralColor(fabSkin) + .neutralText(com.amaze.filemanager.R.string.default_string) + .onNeutral { _, _ -> + activity + .colorPreference + .saveColorPreferences(activity.prefs, currentColorPreference) + activity.recreate() + }.customView(v, false) + .show() } } diff --git a/app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/PrefsFragment.kt b/app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/PrefsFragment.kt index 049b8f59e2..74a7e81cee 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/PrefsFragment.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/PrefsFragment.kt @@ -32,7 +32,10 @@ import com.amaze.filemanager.utils.Utils class PrefsFragment : BasePrefsFragment() { override val title = R.string.setting - override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { + override fun onCreatePreferences( + savedInstanceState: Bundle?, + rootKey: String?, + ) { setPreferencesFromResource(R.xml.preferences, rootKey) findPreference("appearance")?.onPreferenceClickListener = @@ -72,31 +75,33 @@ class PrefsFragment : BasePrefsFragment() { } findPreference("feedback") - ?.onPreferenceClickListener = Preference.OnPreferenceClickListener { - val emailIntent = Utils.buildEmailIntent(requireContext(), null, Utils.EMAIL_SUPPORT) - - val activities = activity.packageManager.queryIntentActivities( - emailIntent, - PackageManager.MATCH_DEFAULT_ONLY - ) + ?.onPreferenceClickListener = + Preference.OnPreferenceClickListener { + val emailIntent = Utils.buildEmailIntent(requireContext(), null, Utils.EMAIL_SUPPORT) - if (activities.isNotEmpty()) { - startActivity( - Intent.createChooser( + val activities = + activity.packageManager.queryIntentActivities( emailIntent, - resources.getString(R.string.feedback) + PackageManager.MATCH_DEFAULT_ONLY, ) - ) - } else { - Toast.makeText( - getActivity(), - resources.getString(R.string.send_email_to) + " " + Utils.EMAIL_SUPPORT, - Toast.LENGTH_LONG - ) - .show() - } - false - } + if (activities.isNotEmpty()) { + startActivity( + Intent.createChooser( + emailIntent, + resources.getString(R.string.feedback), + ), + ) + } else { + Toast.makeText( + getActivity(), + resources.getString(R.string.send_email_to) + " " + Utils.EMAIL_SUPPORT, + Toast.LENGTH_LONG, + ) + .show() + } + + false + } } } diff --git a/app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/QuickAccessesPrefsFragment.kt b/app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/QuickAccessesPrefsFragment.kt index ebcee4e92a..b58d85b16e 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/QuickAccessesPrefsFragment.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/QuickAccessesPrefsFragment.kt @@ -31,35 +31,41 @@ class QuickAccessesPrefsFragment : BasePrefsFragment() { companion object { const val KEY = "quick access array" - val KEYS = arrayOf( - "fastaccess", - "recent", - "image", - "video", - "audio", - "documents", - "apks" - ) + val KEYS = + arrayOf( + "fastaccess", + "recent", + "image", + "video", + "audio", + "documents", + "apks", + ) val DEFAULT = arrayOf(true, true, true, true, true, true, true) - val prefPos: Map = KEYS.withIndex().associate { - Pair(it.value, it.index) - } + val prefPos: Map = + KEYS.withIndex().associate { + Pair(it.value, it.index) + } } - override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { + override fun onCreatePreferences( + savedInstanceState: Bundle?, + rootKey: String?, + ) { setPreferencesFromResource(R.xml.quickaccess_prefs, rootKey) val currentValue = TinyDB.getBooleanArray(activity.prefs, KEY, DEFAULT)!! - val onChange = Preference.OnPreferenceClickListener { preference -> - prefPos[preference.key]?.let { - currentValue[it] = (preference as SwitchPreference).isChecked - TinyDB.putBooleanArray(activity.prefs, KEY, currentValue) - } + val onChange = + Preference.OnPreferenceClickListener { preference -> + prefPos[preference.key]?.let { + currentValue[it] = (preference as SwitchPreference).isChecked + TinyDB.putBooleanArray(activity.prefs, KEY, currentValue) + } - true - } + true + } for (key in KEYS) { findPreference(key)?.onPreferenceClickListener = onChange diff --git a/app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/SecurityPrefsFragment.kt b/app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/SecurityPrefsFragment.kt index fd2839e654..74381bfcf8 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/SecurityPrefsFragment.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/SecurityPrefsFragment.kt @@ -40,7 +40,6 @@ import java.io.IOException import java.security.GeneralSecurityException class SecurityPrefsFragment : BasePrefsFragment() { - private val log: Logger = LoggerFactory.getLogger(SecurityPrefsFragment::class.java) override val title = R.string.security @@ -48,148 +47,157 @@ class SecurityPrefsFragment : BasePrefsFragment() { private var masterPasswordPreference: Preference? = null private var keyguardManager: KeyguardManager? = null private var fingerprintManager: FingerprintManager? = null - private val onClickFingerprint = Preference.OnPreferenceChangeListener { _, _ -> - if (ActivityCompat.checkSelfPermission( - activity, - Manifest.permission.USE_FINGERPRINT - ) - != PackageManager.PERMISSION_GRANTED - ) { - Toast.makeText( - activity, - resources.getString(R.string.crypt_fingerprint_no_permission), - Toast.LENGTH_LONG - ) - .show() - false - } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && - fingerprintManager?.hasEnrolledFingerprints() == false - ) { - Toast.makeText( - activity, - resources.getString(R.string.crypt_fingerprint_not_enrolled), - Toast.LENGTH_LONG - ) - .show() - false - } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && - keyguardManager?.isKeyguardSecure == false - ) { - Toast.makeText( - activity, - resources.getString(R.string.crypt_fingerprint_no_security), - Toast.LENGTH_LONG - ) - .show() - false - } else { - masterPasswordPreference?.isEnabled = false - true - } - } - private val onClickMasterPassword = Preference.OnPreferenceClickListener { - val masterPasswordDialogBuilder = MaterialDialog.Builder(activity) - masterPasswordDialogBuilder.title( - resources.getString(R.string.crypt_pref_master_password_title) - ) - - var decryptedPassword: String? = null - try { - val preferencePassword = activity.prefs.getString( - PreferencesConstants.PREFERENCE_CRYPT_MASTER_PASSWORD, - PreferencesConstants.PREFERENCE_CRYPT_MASTER_PASSWORD_DEFAULT - )!! - decryptedPassword = if ( - preferencePassword != - PreferencesConstants.PREFERENCE_CRYPT_MASTER_PASSWORD_DEFAULT + private val onClickFingerprint = + Preference.OnPreferenceChangeListener { _, _ -> + if (ActivityCompat.checkSelfPermission( + activity, + Manifest.permission.USE_FINGERPRINT, + ) + != PackageManager.PERMISSION_GRANTED ) { - - // password is set, try to decrypt - PasswordUtil.decryptPassword(activity, preferencePassword) + Toast.makeText( + activity, + resources.getString(R.string.crypt_fingerprint_no_permission), + Toast.LENGTH_LONG, + ) + .show() + false + } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && + fingerprintManager?.hasEnrolledFingerprints() == false + ) { + Toast.makeText( + activity, + resources.getString(R.string.crypt_fingerprint_not_enrolled), + Toast.LENGTH_LONG, + ) + .show() + false + } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && + keyguardManager?.isKeyguardSecure == false + ) { + Toast.makeText( + activity, + resources.getString(R.string.crypt_fingerprint_no_security), + Toast.LENGTH_LONG, + ) + .show() + false } else { - // no password set in preferences, just leave the field empty - "" + masterPasswordPreference?.isEnabled = false + true } - } catch (e: GeneralSecurityException) { - log.warn("failed to decrypt master password", e) - } catch (e: IOException) { - log.warn("failed to decrypt master password", e) } + private val onClickMasterPassword = + Preference.OnPreferenceClickListener { + val masterPasswordDialogBuilder = MaterialDialog.Builder(activity) + masterPasswordDialogBuilder.title( + resources.getString(R.string.crypt_pref_master_password_title), + ) - masterPasswordDialogBuilder.input( - resources.getString(R.string.authenticate_password), - decryptedPassword, - true - ) { _, _ -> } - masterPasswordDialogBuilder.theme( - activity.utilsProvider.appTheme.getMaterialDialogTheme() - ) - masterPasswordDialogBuilder.positiveText(resources.getString(R.string.ok)) - masterPasswordDialogBuilder.negativeText(resources.getString(R.string.cancel)) - masterPasswordDialogBuilder.positiveColor(activity.accent) - masterPasswordDialogBuilder.negativeColor(activity.accent) - - masterPasswordDialogBuilder.onPositive { dialog, _ -> + var decryptedPassword: String? = null try { - val inputText = dialog.inputEditText!!.text.toString() - if (inputText != - PreferencesConstants.PREFERENCE_CRYPT_MASTER_PASSWORD_DEFAULT - ) { + val preferencePassword = + activity.prefs.getString( + PreferencesConstants.PREFERENCE_CRYPT_MASTER_PASSWORD, + PreferencesConstants.PREFERENCE_CRYPT_MASTER_PASSWORD_DEFAULT, + )!! + decryptedPassword = + if ( + preferencePassword != + PreferencesConstants.PREFERENCE_CRYPT_MASTER_PASSWORD_DEFAULT + ) { + + // password is set, try to decrypt + PasswordUtil.decryptPassword(activity, preferencePassword) + } else { + // no password set in preferences, just leave the field empty + "" + } + } catch (e: GeneralSecurityException) { + log.warn("failed to decrypt master password", e) + } catch (e: IOException) { + log.warn("failed to decrypt master password", e) + } + + masterPasswordDialogBuilder.input( + resources.getString(R.string.authenticate_password), + decryptedPassword, + true, + ) { _, _ -> } + masterPasswordDialogBuilder.theme( + activity.utilsProvider.appTheme.getMaterialDialogTheme(), + ) + masterPasswordDialogBuilder.positiveText(resources.getString(R.string.ok)) + masterPasswordDialogBuilder.negativeText(resources.getString(R.string.cancel)) + masterPasswordDialogBuilder.positiveColor(activity.accent) + masterPasswordDialogBuilder.negativeColor(activity.accent) + + masterPasswordDialogBuilder.onPositive { dialog, _ -> + try { + val inputText = dialog.inputEditText!!.text.toString() + if (inputText != + PreferencesConstants.PREFERENCE_CRYPT_MASTER_PASSWORD_DEFAULT + ) { + val editor = activity.prefs.edit() + editor.putString( + PreferencesConstants.PREFERENCE_CRYPT_MASTER_PASSWORD, + PasswordUtil.encryptPassword( + activity, + dialog.inputEditText!!.text.toString(), + ), + ) + editor.apply() + } else { + val editor = activity.prefs.edit() + editor.putString(PreferencesConstants.PREFERENCE_CRYPT_MASTER_PASSWORD, "") + editor.apply() + } + } catch (e: GeneralSecurityException) { + log.warn("failed to encrypt master password", e) val editor = activity.prefs.edit() editor.putString( PreferencesConstants.PREFERENCE_CRYPT_MASTER_PASSWORD, - PasswordUtil.encryptPassword( - activity, - dialog.inputEditText!!.text.toString() - ) + PreferencesConstants.PREFERENCE_CRYPT_MASTER_PASSWORD_DEFAULT, ) editor.apply() - } else { + } catch (e: IOException) { + log.warn("failed to encrypt master password", e) val editor = activity.prefs.edit() - editor.putString(PreferencesConstants.PREFERENCE_CRYPT_MASTER_PASSWORD, "") + editor.putString( + PreferencesConstants.PREFERENCE_CRYPT_MASTER_PASSWORD, + PreferencesConstants.PREFERENCE_CRYPT_MASTER_PASSWORD_DEFAULT, + ) editor.apply() } - } catch (e: GeneralSecurityException) { - log.warn("failed to encrypt master password", e) - val editor = activity.prefs.edit() - editor.putString( - PreferencesConstants.PREFERENCE_CRYPT_MASTER_PASSWORD, - PreferencesConstants.PREFERENCE_CRYPT_MASTER_PASSWORD_DEFAULT - ) - editor.apply() - } catch (e: IOException) { - log.warn("failed to encrypt master password", e) - val editor = activity.prefs.edit() - editor.putString( - PreferencesConstants.PREFERENCE_CRYPT_MASTER_PASSWORD, - PreferencesConstants.PREFERENCE_CRYPT_MASTER_PASSWORD_DEFAULT - ) - editor.apply() } - } - masterPasswordDialogBuilder.onNegative { dialog, _ -> dialog.cancel() } + masterPasswordDialogBuilder.onNegative { dialog, _ -> dialog.cancel() } - masterPasswordDialogBuilder.build().show() + masterPasswordDialogBuilder.build().show() - true - } + true + } - override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { + override fun onCreatePreferences( + savedInstanceState: Bundle?, + rootKey: String?, + ) { setPreferencesFromResource(R.xml.security_prefs, rootKey) - masterPasswordPreference = findPreference( - PreferencesConstants.PREFERENCE_CRYPT_MASTER_PASSWORD - ) - val checkBoxFingerprint = findPreference( - PreferencesConstants.PREFERENCE_CRYPT_FINGERPRINT - ) + masterPasswordPreference = + findPreference( + PreferencesConstants.PREFERENCE_CRYPT_MASTER_PASSWORD, + ) + val checkBoxFingerprint = + findPreference( + PreferencesConstants.PREFERENCE_CRYPT_FINGERPRINT, + ) if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2 || activity.prefs.getBoolean( - PreferencesConstants.PREFERENCE_CRYPT_FINGERPRINT, - false - ) + PreferencesConstants.PREFERENCE_CRYPT_FINGERPRINT, + false, + ) ) { // encryption feature not available masterPasswordPreference?.isEnabled = false @@ -197,11 +205,13 @@ class SecurityPrefsFragment : BasePrefsFragment() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // finger print sensor - keyguardManager = activity.getSystemService(Context.KEYGUARD_SERVICE) - as KeyguardManager? + keyguardManager = + activity.getSystemService(Context.KEYGUARD_SERVICE) + as KeyguardManager? if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { - fingerprintManager = activity.getSystemService(Context.FINGERPRINT_SERVICE) - as FingerprintManager? + fingerprintManager = + activity.getSystemService(Context.FINGERPRINT_SERVICE) + as FingerprintManager? if (fingerprintManager?.isHardwareDetected == true) { checkBoxFingerprint?.isEnabled = true } diff --git a/app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/UiPrefsFragment.kt b/app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/UiPrefsFragment.kt index d87b52ac61..50d8ffb2b5 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/UiPrefsFragment.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/UiPrefsFragment.kt @@ -29,12 +29,14 @@ import com.amaze.filemanager.R import com.amaze.filemanager.utils.getLangPreferenceDropdownEntries class UiPrefsFragment : BasePrefsFragment() { - override val title = R.string.ui private var dragAndDropPref: Preference? = null - override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { + override fun onCreatePreferences( + savedInstanceState: Bundle?, + rootKey: String?, + ) { setPreferencesFromResource(R.xml.ui_prefs, rootKey) findPreference("sidebar_bookmarks")?.onPreferenceClickListener = @@ -51,92 +53,98 @@ class UiPrefsFragment : BasePrefsFragment() { findPreference(PreferencesConstants.PREFERENCE_LANGUAGE)?.apply { val availableLocales = requireContext().getLangPreferenceDropdownEntries() - val currentLanguagePreference = AppCompatDelegate.getApplicationLocales().let { - if (AppCompatDelegate.getApplicationLocales() == - LocaleListCompat.getEmptyLocaleList() - ) { - 0 + val currentLanguagePreference = + AppCompatDelegate.getApplicationLocales().let { + if (AppCompatDelegate.getApplicationLocales() == + LocaleListCompat.getEmptyLocaleList() + ) { + 0 + } else { + availableLocales.values.indexOf( + AppCompatDelegate.getApplicationLocales()[0], + ) + 1 + } + } + this.summary = + if (currentLanguagePreference == 0) { + getString(R.string.preference_language_system_default) } else { - availableLocales.values.indexOf( - AppCompatDelegate.getApplicationLocales()[0] - ) + 1 + availableLocales.entries.find { + it.value == AppCompatDelegate.getApplicationLocales()[0] + }?.key } - } - this.summary = if (currentLanguagePreference == 0) { - getString(R.string.preference_language_system_default) - } else { - availableLocales.entries.find { - it.value == AppCompatDelegate.getApplicationLocales()[0] - }?.key - } - onPreferenceClickListener = Preference.OnPreferenceClickListener { - MaterialDialog.Builder(activity).apply { - theme(activity.utilsProvider.appTheme.materialDialogTheme) - title(R.string.preference_language_dialog_title) - items( - arrayOf(getString(R.string.preference_language_system_default)) - .plus(availableLocales.keys.toTypedArray()) - .toSet() - ) - itemsCallbackSingleChoice(currentLanguagePreference) { - dialog, _, _, textLabel -> - if (textLabel == getString(R.string.preference_language_system_default)) { - AppCompatDelegate.setApplicationLocales( - LocaleListCompat.getEmptyLocaleList() - ) - } else { - AppCompatDelegate.setApplicationLocales( - LocaleListCompat.create(availableLocales[textLabel]) - ) + onPreferenceClickListener = + Preference.OnPreferenceClickListener { + MaterialDialog.Builder(activity).apply { + theme(activity.utilsProvider.appTheme.materialDialogTheme) + title(R.string.preference_language_dialog_title) + items( + arrayOf(getString(R.string.preference_language_system_default)) + .plus(availableLocales.keys.toTypedArray()) + .toSet(), + ) + itemsCallbackSingleChoice(currentLanguagePreference) { + dialog, _, _, textLabel -> + if (textLabel == getString(R.string.preference_language_system_default)) { + AppCompatDelegate.setApplicationLocales( + LocaleListCompat.getEmptyLocaleList(), + ) + } else { + AppCompatDelegate.setApplicationLocales( + LocaleListCompat.create(availableLocales[textLabel]), + ) + } + dialog.dismiss() + true } - dialog.dismiss() - true - } - }.show() - true - } + }.show() + true + } } val dragToMoveArray = resources.getStringArray(R.array.dragAndDropPreference) dragAndDropPref = findPreference(PreferencesConstants.PREFERENCE_DRAG_AND_DROP_PREFERENCE) updateDragAndDropPreferenceSummary() - dragAndDropPref?.onPreferenceClickListener = Preference.OnPreferenceClickListener { - val dragDialogBuilder = MaterialDialog.Builder(activity) - dragDialogBuilder.theme( - activity.utilsProvider.appTheme.getMaterialDialogTheme() - ) - dragDialogBuilder.title(R.string.drag_and_drop_preference) - val currentDragPreference: Int = activity.prefs.getInt( - PreferencesConstants.PREFERENCE_DRAG_AND_DROP_PREFERENCE, - PreferencesConstants.PREFERENCE_DRAG_DEFAULT - ) - dragDialogBuilder - .items(R.array.dragAndDropPreference) - .itemsCallbackSingleChoice(currentDragPreference) { dialog, _, which, _ -> - val editor = activity.prefs.edit() - editor.putInt( + dragAndDropPref?.onPreferenceClickListener = + Preference.OnPreferenceClickListener { + val dragDialogBuilder = MaterialDialog.Builder(activity) + dragDialogBuilder.theme( + activity.utilsProvider.appTheme.getMaterialDialogTheme(), + ) + dragDialogBuilder.title(R.string.drag_and_drop_preference) + val currentDragPreference: Int = + activity.prefs.getInt( PreferencesConstants.PREFERENCE_DRAG_AND_DROP_PREFERENCE, - which - ) - editor.putString( - PreferencesConstants.PREFERENCE_DRAG_AND_DROP_REMEMBERED, - null + PreferencesConstants.PREFERENCE_DRAG_DEFAULT, ) - editor.apply() - dialog.dismiss() - updateDragAndDropPreferenceSummary() - true - } - dragDialogBuilder.build().show() - true - } + dragDialogBuilder + .items(R.array.dragAndDropPreference) + .itemsCallbackSingleChoice(currentDragPreference) { dialog, _, which, _ -> + val editor = activity.prefs.edit() + editor.putInt( + PreferencesConstants.PREFERENCE_DRAG_AND_DROP_PREFERENCE, + which, + ) + editor.putString( + PreferencesConstants.PREFERENCE_DRAG_AND_DROP_REMEMBERED, + null, + ) + editor.apply() + dialog.dismiss() + updateDragAndDropPreferenceSummary() + true + } + dragDialogBuilder.build().show() + true + } } private fun updateDragAndDropPreferenceSummary() { - val value = activity.prefs.getInt( - PreferencesConstants.PREFERENCE_DRAG_AND_DROP_PREFERENCE, - PreferencesConstants.PREFERENCE_DRAG_DEFAULT - ) + val value = + activity.prefs.getInt( + PreferencesConstants.PREFERENCE_DRAG_AND_DROP_PREFERENCE, + PreferencesConstants.PREFERENCE_DRAG_DEFAULT, + ) val dragToMoveArray = resources.getStringArray(R.array.dragAndDropPreference) dragAndDropPref?.summary = dragToMoveArray[value] } diff --git a/app/src/main/java/com/amaze/filemanager/ui/icons/Icons.java b/app/src/main/java/com/amaze/filemanager/ui/icons/Icons.java index 60587ab12c..9cf5861eb4 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/icons/Icons.java +++ b/app/src/main/java/com/amaze/filemanager/ui/icons/Icons.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/icons/MimeTypes.java b/app/src/main/java/com/amaze/filemanager/ui/icons/MimeTypes.java index 49b982e333..1f203d3c37 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/icons/MimeTypes.java +++ b/app/src/main/java/com/amaze/filemanager/ui/icons/MimeTypes.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/notifications/FtpNotification.java b/app/src/main/java/com/amaze/filemanager/ui/notifications/FtpNotification.java index 7117f551d5..fa51a92332 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/notifications/FtpNotification.java +++ b/app/src/main/java/com/amaze/filemanager/ui/notifications/FtpNotification.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/notifications/NotificationConstants.java b/app/src/main/java/com/amaze/filemanager/ui/notifications/NotificationConstants.java index 6f9e15127c..673efc6a68 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/notifications/NotificationConstants.java +++ b/app/src/main/java/com/amaze/filemanager/ui/notifications/NotificationConstants.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/provider/UtilitiesProvider.java b/app/src/main/java/com/amaze/filemanager/ui/provider/UtilitiesProvider.java index 11834b5f22..7e5ec553ee 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/provider/UtilitiesProvider.java +++ b/app/src/main/java/com/amaze/filemanager/ui/provider/UtilitiesProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/selection/SelectionPopupMenu.kt b/app/src/main/java/com/amaze/filemanager/ui/selection/SelectionPopupMenu.kt index 43ab7d8333..403bf9d73e 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/selection/SelectionPopupMenu.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/selection/SelectionPopupMenu.kt @@ -35,12 +35,10 @@ class SelectionPopupMenu( private val recyclerAdapter: RecyclerAdapter, private val actionModeView: View, private val currentPath: String, - context: Context + context: Context, ) : PopupMenu(context, actionModeView), PopupMenu.OnMenuItemClickListener { - companion object { - private const val SIMILARITY_THRESHOLD = 500 const val FUZZYNESS_FACTOR = 4 @@ -48,22 +46,24 @@ class SelectionPopupMenu( recyclerAdapter: RecyclerAdapter, actionModeView: View, currentPath: String, - mainActivity: MainActivity? + mainActivity: MainActivity?, ) { mainActivity?.also { var currentContext: Context = mainActivity.applicationContext if (mainActivity.appTheme == AppTheme.BLACK) { - currentContext = ContextThemeWrapper( - mainActivity.applicationContext, - R.style.overflow_black - ) + currentContext = + ContextThemeWrapper( + mainActivity.applicationContext, + R.style.overflow_black, + ) } - val popupMenu = SelectionPopupMenu( - recyclerAdapter, - actionModeView, - currentPath, - currentContext - ) + val popupMenu = + SelectionPopupMenu( + recyclerAdapter, + actionModeView, + currentPath, + currentContext, + ) popupMenu.inflate(R.menu.selection_criteria) recyclerAdapter.itemsDigested?.let { itemsDigested -> @@ -87,7 +87,7 @@ class SelectionPopupMenu( recyclerAdapter.toggleChecked( !recyclerAdapter .areAllChecked(currentPath), - currentPath + currentPath, ) } R.id.select_inverse -> { @@ -107,8 +107,9 @@ class SelectionPopupMenu( } } actionModeView.invalidate() - actionModeView.findViewById(R.id.item_count).text = recyclerAdapter - .checkedItems.size.toString() + actionModeView.findViewById(R.id.item_count).text = + recyclerAdapter + .checkedItems.size.toString() return true } } diff --git a/app/src/main/java/com/amaze/filemanager/ui/strings/StorageNamingHelper.java b/app/src/main/java/com/amaze/filemanager/ui/strings/StorageNamingHelper.java index 358d92dcfd..b09a7d0872 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/strings/StorageNamingHelper.java +++ b/app/src/main/java/com/amaze/filemanager/ui/strings/StorageNamingHelper.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/theme/AppTheme.java b/app/src/main/java/com/amaze/filemanager/ui/theme/AppTheme.java index 2856cc6e42..dd58d95f1d 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/theme/AppTheme.java +++ b/app/src/main/java/com/amaze/filemanager/ui/theme/AppTheme.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/theme/AppThemeManager.java b/app/src/main/java/com/amaze/filemanager/ui/theme/AppThemeManager.java index 9c79c32cf3..12cfcfc5ff 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/theme/AppThemeManager.java +++ b/app/src/main/java/com/amaze/filemanager/ui/theme/AppThemeManager.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/theme/AppThemePreference.kt b/app/src/main/java/com/amaze/filemanager/ui/theme/AppThemePreference.kt index e33aabfe03..54c2890f80 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/theme/AppThemePreference.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/theme/AppThemePreference.kt @@ -42,7 +42,8 @@ enum class AppThemePreference(val id: Int, val canBeLight: Boolean) { DARK(1, false), TIMED(2, true), BLACK(3, false), - SYSTEM(4, true); + SYSTEM(4, true), + ; /** * Returns the correct [Theme] associated with this [AppThemePreference] based on [context]. @@ -58,20 +59,24 @@ enum class AppThemePreference(val id: Int, val canBeLight: Boolean) { */ fun getSimpleTheme(context: Context): AppTheme { val preferences = PreferenceManager.getDefaultSharedPreferences(context) - val followBatterySaver = preferences.getBoolean( - PreferencesConstants.FRAGMENT_FOLLOW_BATTERY_SAVER, - false - ) + val followBatterySaver = + preferences.getBoolean( + PreferencesConstants.FRAGMENT_FOLLOW_BATTERY_SAVER, + false, + ) return getSimpleTheme( isNightMode(context), - followBatterySaver && isBatterySaverMode(context) + followBatterySaver && isBatterySaverMode(context), ) } /** * Returns the correct [AppTheme] based on [isNightMode] and [isBatterySaver]. */ - fun getSimpleTheme(isNightMode: Boolean, isBatterySaver: Boolean): AppTheme { + fun getSimpleTheme( + isNightMode: Boolean, + isBatterySaver: Boolean, + ): AppTheme { return if (canBeLight && isBatterySaver) { AppTheme.DARK } else { @@ -100,7 +105,7 @@ enum class AppThemePreference(val id: Int, val canBeLight: Boolean) { return ( context.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES - ) + ) } /** diff --git a/app/src/main/java/com/amaze/filemanager/ui/views/CheckableCircleView.java b/app/src/main/java/com/amaze/filemanager/ui/views/CheckableCircleView.java index 65fc46ac03..7584668651 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/views/CheckableCircleView.java +++ b/app/src/main/java/com/amaze/filemanager/ui/views/CheckableCircleView.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/views/CircleGradientDrawable.java b/app/src/main/java/com/amaze/filemanager/ui/views/CircleGradientDrawable.java index b02b73bd27..ce6b2bdc37 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/views/CircleGradientDrawable.java +++ b/app/src/main/java/com/amaze/filemanager/ui/views/CircleGradientDrawable.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/views/CircularColorsView.java b/app/src/main/java/com/amaze/filemanager/ui/views/CircularColorsView.java index d946db5d36..928d87f5df 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/views/CircularColorsView.java +++ b/app/src/main/java/com/amaze/filemanager/ui/views/CircularColorsView.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/views/CustomLinearSmoothScroller.java b/app/src/main/java/com/amaze/filemanager/ui/views/CustomLinearSmoothScroller.java index 4952ccd82f..4c346316b4 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/views/CustomLinearSmoothScroller.java +++ b/app/src/main/java/com/amaze/filemanager/ui/views/CustomLinearSmoothScroller.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2021 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/views/CustomScrollGridLayoutManager.kt b/app/src/main/java/com/amaze/filemanager/ui/views/CustomScrollGridLayoutManager.kt index c73db2c642..f7681d3688 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/views/CustomScrollGridLayoutManager.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/views/CustomScrollGridLayoutManager.kt @@ -29,7 +29,7 @@ class CustomScrollGridLayoutManager(context: Context?, spanCount: Int) : override fun smoothScrollToPosition( recyclerView: RecyclerView?, state: RecyclerView.State?, - position: Int + position: Int, ) { val linearSmoothScroller = CustomLinearSmoothScroller(recyclerView!!.context, false) linearSmoothScroller.targetPosition = position diff --git a/app/src/main/java/com/amaze/filemanager/ui/views/CustomScrollLinearLayoutManager.kt b/app/src/main/java/com/amaze/filemanager/ui/views/CustomScrollLinearLayoutManager.kt index 88a0d14c8a..b25b8fc455 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/views/CustomScrollLinearLayoutManager.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/views/CustomScrollLinearLayoutManager.kt @@ -25,11 +25,10 @@ import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView class CustomScrollLinearLayoutManager(context: Context?) : LinearLayoutManager(context) { - override fun smoothScrollToPosition( recyclerView: RecyclerView?, state: RecyclerView.State?, - position: Int + position: Int, ) { val linearSmoothScroller = CustomLinearSmoothScroller(recyclerView!!.context, true) linearSmoothScroller.targetPosition = position diff --git a/app/src/main/java/com/amaze/filemanager/ui/views/CustomZoomFocusChange.java b/app/src/main/java/com/amaze/filemanager/ui/views/CustomZoomFocusChange.java index a14ab426b9..890878b636 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/views/CustomZoomFocusChange.java +++ b/app/src/main/java/com/amaze/filemanager/ui/views/CustomZoomFocusChange.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2021 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/views/DividerItemDecoration.java b/app/src/main/java/com/amaze/filemanager/ui/views/DividerItemDecoration.java index 0cef27db7f..8c0f2b168c 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/views/DividerItemDecoration.java +++ b/app/src/main/java/com/amaze/filemanager/ui/views/DividerItemDecoration.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/views/FastScroller.java b/app/src/main/java/com/amaze/filemanager/ui/views/FastScroller.java index 2f89d1a683..c3bd60b368 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/views/FastScroller.java +++ b/app/src/main/java/com/amaze/filemanager/ui/views/FastScroller.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/views/Indicator.java b/app/src/main/java/com/amaze/filemanager/ui/views/Indicator.java index d740f74657..8631ae961f 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/views/Indicator.java +++ b/app/src/main/java/com/amaze/filemanager/ui/views/Indicator.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/views/ScrimInsetsRelativeLayout.java b/app/src/main/java/com/amaze/filemanager/ui/views/ScrimInsetsRelativeLayout.java index 864f1d0a20..9ff35469aa 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/views/ScrimInsetsRelativeLayout.java +++ b/app/src/main/java/com/amaze/filemanager/ui/views/ScrimInsetsRelativeLayout.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/views/ThemedImageButton.java b/app/src/main/java/com/amaze/filemanager/ui/views/ThemedImageButton.java index 9f462a47ae..f5ac31fbac 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/views/ThemedImageButton.java +++ b/app/src/main/java/com/amaze/filemanager/ui/views/ThemedImageButton.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/views/ThemedImageView.java b/app/src/main/java/com/amaze/filemanager/ui/views/ThemedImageView.java index 2e5da7f75c..a8dcf913e1 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/views/ThemedImageView.java +++ b/app/src/main/java/com/amaze/filemanager/ui/views/ThemedImageView.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/views/ThemedTextView.java b/app/src/main/java/com/amaze/filemanager/ui/views/ThemedTextView.java index fe725f78e6..eb72dc47ef 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/views/ThemedTextView.java +++ b/app/src/main/java/com/amaze/filemanager/ui/views/ThemedTextView.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/views/WarnableTextInputLayout.java b/app/src/main/java/com/amaze/filemanager/ui/views/WarnableTextInputLayout.java index 8ce05ca583..887e938a93 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/views/WarnableTextInputLayout.java +++ b/app/src/main/java/com/amaze/filemanager/ui/views/WarnableTextInputLayout.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/views/WarnableTextInputValidator.java b/app/src/main/java/com/amaze/filemanager/ui/views/WarnableTextInputValidator.java index f75479a4da..ac474a240c 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/views/WarnableTextInputValidator.java +++ b/app/src/main/java/com/amaze/filemanager/ui/views/WarnableTextInputValidator.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/views/appbar/AppBar.java b/app/src/main/java/com/amaze/filemanager/ui/views/appbar/AppBar.java index 12c17004d2..d0edd12c63 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/views/appbar/AppBar.java +++ b/app/src/main/java/com/amaze/filemanager/ui/views/appbar/AppBar.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/views/appbar/BottomBar.java b/app/src/main/java/com/amaze/filemanager/ui/views/appbar/BottomBar.java index fe127201db..4385a620e6 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/views/appbar/BottomBar.java +++ b/app/src/main/java/com/amaze/filemanager/ui/views/appbar/BottomBar.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/views/appbar/SearchView.java b/app/src/main/java/com/amaze/filemanager/ui/views/appbar/SearchView.java index 126779a069..1397fcaee0 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/views/appbar/SearchView.java +++ b/app/src/main/java/com/amaze/filemanager/ui/views/appbar/SearchView.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/views/drawer/ActionViewStateManager.java b/app/src/main/java/com/amaze/filemanager/ui/views/drawer/ActionViewStateManager.java index 4e273f2217..98fe9e8a7b 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/views/drawer/ActionViewStateManager.java +++ b/app/src/main/java/com/amaze/filemanager/ui/views/drawer/ActionViewStateManager.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/views/drawer/CustomNavigationView.java b/app/src/main/java/com/amaze/filemanager/ui/views/drawer/CustomNavigationView.java index 4d804fffb1..f09724f563 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/views/drawer/CustomNavigationView.java +++ b/app/src/main/java/com/amaze/filemanager/ui/views/drawer/CustomNavigationView.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/views/drawer/Drawer.java b/app/src/main/java/com/amaze/filemanager/ui/views/drawer/Drawer.java index 2f1f604bc8..358bfeb869 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/views/drawer/Drawer.java +++ b/app/src/main/java/com/amaze/filemanager/ui/views/drawer/Drawer.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/views/drawer/DrawerViewModel.kt b/app/src/main/java/com/amaze/filemanager/ui/views/drawer/DrawerViewModel.kt index ddca4e58fb..3742688814 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/views/drawer/DrawerViewModel.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/views/drawer/DrawerViewModel.kt @@ -31,7 +31,15 @@ class DrawerViewModel : ViewModel() { return requireNotNull(menuMetadataMap[item.toNonLeaking()]) } - fun putDrawerMetadata(item: MenuItem, metadata: MenuMetadata) { + /** + * Put drawer meta data + * @param item menu item + * @param metadata menu meta data + */ + fun putDrawerMetadata( + item: MenuItem, + metadata: MenuMetadata, + ) { menuMetadataMap[item.toNonLeaking()] = metadata } } diff --git a/app/src/main/java/com/amaze/filemanager/ui/views/drawer/GestureExclusionView.kt b/app/src/main/java/com/amaze/filemanager/ui/views/drawer/GestureExclusionView.kt index 1c446bc194..32e8ce37de 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/views/drawer/GestureExclusionView.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/views/drawer/GestureExclusionView.kt @@ -29,11 +29,17 @@ import android.view.View class GestureExclusionView( context: Context, - attrs: AttributeSet? = null + attrs: AttributeSet? = null, ) : View(context, attrs) { private val gestureExclusionRects = mutableListOf() - override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { + override fun onLayout( + changed: Boolean, + left: Int, + top: Int, + right: Int, + bottom: Int, + ) { super.onLayout(changed, left, top, right, bottom) if (changed) { diff --git a/app/src/main/java/com/amaze/filemanager/ui/views/drawer/HasherOfMenuItem.kt b/app/src/main/java/com/amaze/filemanager/ui/views/drawer/HasherOfMenuItem.kt index bbf04494d1..5fb3a2c312 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/views/drawer/HasherOfMenuItem.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/views/drawer/HasherOfMenuItem.kt @@ -29,7 +29,7 @@ data class HasherOfMenuItem( val groupId: Int, val itemId: Int, val title: CharSequence?, - val ordering: Int + val ordering: Int, ) fun MenuItem.toNonLeaking(): HasherOfMenuItem { diff --git a/app/src/main/java/com/amaze/filemanager/ui/views/drawer/MenuMetadata.java b/app/src/main/java/com/amaze/filemanager/ui/views/drawer/MenuMetadata.java index bfcc7ee4e4..b5f1bf208a 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/views/drawer/MenuMetadata.java +++ b/app/src/main/java/com/amaze/filemanager/ui/views/drawer/MenuMetadata.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/ui/views/preference/CheckBox.kt b/app/src/main/java/com/amaze/filemanager/ui/views/preference/CheckBox.kt index f718b43f84..40a50c5395 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/views/preference/CheckBox.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/views/preference/CheckBox.kt @@ -29,7 +29,6 @@ import androidx.preference.SwitchPreference /** Created by Arpit on 10/18/2015 edited by Emmanuel Messulam @gmail.com> */ class CheckBox(context: Context, attrs: AttributeSet) : SwitchPreference(context, attrs) { - override fun onBindViewHolder(holder: PreferenceViewHolder) { clearListenerInViewGroup(holder.itemView as ViewGroup) super.onBindViewHolder(holder) diff --git a/app/src/main/java/com/amaze/filemanager/ui/views/preference/PathSwitchPreference.kt b/app/src/main/java/com/amaze/filemanager/ui/views/preference/PathSwitchPreference.kt index 61482c6499..bbf218f9a8 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/views/preference/PathSwitchPreference.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/views/preference/PathSwitchPreference.kt @@ -31,7 +31,7 @@ import com.amaze.filemanager.R class PathSwitchPreference( context: Context, private val onEdit: (PathSwitchPreference) -> Unit, - private val onDelete: (PathSwitchPreference) -> Unit + private val onDelete: (PathSwitchPreference) -> Unit, ) : Preference(context) { var lastItemClicked = -1 private set diff --git a/app/src/main/java/com/amaze/filemanager/ui/views/preference/SelectedColorsPreference.kt b/app/src/main/java/com/amaze/filemanager/ui/views/preference/SelectedColorsPreference.kt index c79d0322a5..9ad24d9059 100644 --- a/app/src/main/java/com/amaze/filemanager/ui/views/preference/SelectedColorsPreference.kt +++ b/app/src/main/java/com/amaze/filemanager/ui/views/preference/SelectedColorsPreference.kt @@ -40,12 +40,13 @@ import com.amaze.filemanager.ui.views.CircularColorsView */ class SelectedColorsPreference(context: Context, attrs: AttributeSet) : DialogPreference(context, attrs) { - private var colors = intArrayOf( - Color.TRANSPARENT, - Color.TRANSPARENT, - Color.TRANSPARENT, - Color.TRANSPARENT - ) + private var colors = + intArrayOf( + Color.TRANSPARENT, + Color.TRANSPARENT, + Color.TRANSPARENT, + Color.TRANSPARENT, + ) private var backgroundColor = 0 private var visibility = View.VISIBLE private var selectedIndex = -1 @@ -68,14 +69,18 @@ class SelectedColorsPreference(context: Context, attrs: AttributeSet) : } override fun getSummary(): CharSequence { - val colorPickerPref = sharedPreferences?.getInt( - PreferencesConstants.PREFERENCE_COLOR_CONFIG, - ColorPickerDialog.NO_DATA - ) ?: ColorPickerDialog.NO_DATA + val colorPickerPref = + sharedPreferences?.getInt( + PreferencesConstants.PREFERENCE_COLOR_CONFIG, + ColorPickerDialog.NO_DATA, + ) ?: ColorPickerDialog.NO_DATA return context.getString(ColorPickerDialog.getTitle(colorPickerPref)) } - override fun onGetDefaultValue(a: TypedArray, index: Int): Any { + override fun onGetDefaultValue( + a: TypedArray, + index: Int, + ): Any { return a.getString(index)!! } @@ -116,7 +121,12 @@ class SelectedColorsPreference(context: Context, attrs: AttributeSet) : /** * set colours to specified and notify colour changed. */ - fun setColors(color: Int, color1: Int, color2: Int, color3: Int) { + fun setColors( + color: Int, + color1: Int, + color2: Int, + color3: Int, + ) { colors = intArrayOf(color, color1, color2, color3) notifyChanged() } diff --git a/app/src/main/java/com/amaze/filemanager/utils/AESCrypt.kt b/app/src/main/java/com/amaze/filemanager/utils/AESCrypt.kt index 429625642b..bba0806336 100644 --- a/app/src/main/java/com/amaze/filemanager/utils/AESCrypt.kt +++ b/app/src/main/java/com/amaze/filemanager/utils/AESCrypt.kt @@ -74,7 +74,6 @@ import kotlin.text.Charsets.UTF_8 * */ class AESCrypt(password: String) { - private lateinit var password: ByteArray private val cipher: Cipher private val hmac: Mac @@ -88,6 +87,7 @@ class AESCrypt(password: String) { /******************* * PRIVATE METHODS * */ + /** * Generates a pseudo-random byte array. * @return pseudo-random byte array of len bytes. @@ -106,7 +106,10 @@ class AESCrypt(password: String) { * The generated hash is saved back to the original byte array.

* Maximum array size is [.SHA_SIZE] bytes. */ - private fun digestRandomBytes(bytes: ByteArray, num: Int) { + private fun digestRandomBytes( + bytes: ByteArray, + num: Int, + ) { require(bytes.size <= SHA_SIZE) digest.reset() digest.update(bytes) @@ -152,7 +155,10 @@ class AESCrypt(password: String) { * This AES key is used to crypt IV 2 and AES key 2. * @return AES key of [.KEY_SIZE] bytes. */ - private fun generateAESKey1(iv: ByteArray, password: ByteArray): ByteArray { + private fun generateAESKey1( + iv: ByteArray, + password: ByteArray, + ): ByteArray { var aesKey = ByteArray(KEY_SIZE) iv.copyInto(aesKey, endIndex = iv.size) for (i in 0..8191) { @@ -211,7 +217,7 @@ class AESCrypt(password: String) { version: Int = AESCRYPT_SPEC_VERSION, `in`: InputStream, out: OutputStream, - progressHandler: ProgressHandler + progressHandler: ProgressHandler, ) { var text: ByteArray? ivSpec1 = IvParameterSpec(generateIv1()) @@ -285,7 +291,11 @@ class AESCrypt(password: String) { */ @Suppress("LongMethod", "ComplexMethod") @Throws(GeneralSecurityException::class) - fun decrypt(inSize: Long, `in`: InputStream, out: OutputStream) { + fun decrypt( + inSize: Long, + `in`: InputStream, + out: OutputStream, + ) { var text: ByteArray var total = (3 + 1 + 1 + BLOCK_SIZE + BLOCK_SIZE + KEY_SIZE + SHA_SIZE + 1 + SHA_SIZE).toLong() @@ -339,7 +349,7 @@ class AESCrypt(password: String) { total = inSize - total // Payload size. if (total % BLOCK_SIZE != 0L) { throw DecryptFailureException( - "Input file is corrupt. BLOCK_SIZE = $BLOCK_SIZE, total was $total" + "Input file is corrupt. BLOCK_SIZE = $BLOCK_SIZE, total was $total", ) } if (total == 0L) { // Hack: empty files won't enter block-processing for-loop below. diff --git a/app/src/main/java/com/amaze/filemanager/utils/AnimUtils.kt b/app/src/main/java/com/amaze/filemanager/utils/AnimUtils.kt index 812b92dcc3..89f4356642 100644 --- a/app/src/main/java/com/amaze/filemanager/utils/AnimUtils.kt +++ b/app/src/main/java/com/amaze/filemanager/utils/AnimUtils.kt @@ -44,14 +44,17 @@ object AnimUtils { * Animates filenames textview to marquee after a delay. Make sure to set [ ][TextView.setSelected] to false in order to stop the marquee later */ @JvmStatic - fun marqueeAfterDelay(delayInMillis: Int, marqueeView: ThemedTextView) { + fun marqueeAfterDelay( + delayInMillis: Int, + marqueeView: ThemedTextView, + ) { Handler() .postDelayed( { // marquee works only when text view has focus marqueeView.isSelected = true }, - delayInMillis.toLong() + delayInMillis.toLong(), ) } } diff --git a/app/src/main/java/com/amaze/filemanager/utils/BookSorter.kt b/app/src/main/java/com/amaze/filemanager/utils/BookSorter.kt index fca5312b6c..ab5a638571 100644 --- a/app/src/main/java/com/amaze/filemanager/utils/BookSorter.kt +++ b/app/src/main/java/com/amaze/filemanager/utils/BookSorter.kt @@ -24,7 +24,10 @@ import java.util.* /** Created by Arpit on 20-11-2015. */ class BookSorter : Comparator> { - override fun compare(lhs: Array, rhs: Array): Int { + override fun compare( + lhs: Array, + rhs: Array, + ): Int { var result = lhs[0].compareTo(rhs[0], ignoreCase = true) if (result == 0) { // the title is same, compare their paths diff --git a/app/src/main/java/com/amaze/filemanager/utils/BottomBarButtonPath.kt b/app/src/main/java/com/amaze/filemanager/utils/BottomBarButtonPath.kt index 2e8f21c368..ca91daae92 100644 --- a/app/src/main/java/com/amaze/filemanager/utils/BottomBarButtonPath.kt +++ b/app/src/main/java/com/amaze/filemanager/utils/BottomBarButtonPath.kt @@ -30,6 +30,7 @@ interface BottomBarButtonPath { * This allows the fragment to change the path represented in the BottomBar directly */ fun changePath(path: String) + val path: String? @get:DrawableRes diff --git a/app/src/main/java/com/amaze/filemanager/utils/ComputerParcelable.kt b/app/src/main/java/com/amaze/filemanager/utils/ComputerParcelable.kt index 4b8a6eeac6..6de6cbbce8 100644 --- a/app/src/main/java/com/amaze/filemanager/utils/ComputerParcelable.kt +++ b/app/src/main/java/com/amaze/filemanager/utils/ComputerParcelable.kt @@ -26,7 +26,8 @@ import kotlinx.parcelize.Parcelize @Parcelize data class ComputerParcelable(val addr: String, val name: String) : Parcelable { override fun toString(): String = "$name [$addr]" + override fun hashCode(): Int = addr.hashCode() - override fun equals(other: Any?): Boolean = - other is ComputerParcelable && other.addr == this.addr + + override fun equals(other: Any?): Boolean = other is ComputerParcelable && other.addr == this.addr } diff --git a/app/src/main/java/com/amaze/filemanager/utils/ContextLocaleExt.kt b/app/src/main/java/com/amaze/filemanager/utils/ContextLocaleExt.kt index 5ef6bdf387..6cd1f381a5 100644 --- a/app/src/main/java/com/amaze/filemanager/utils/ContextLocaleExt.kt +++ b/app/src/main/java/com/amaze/filemanager/utils/ContextLocaleExt.kt @@ -60,35 +60,37 @@ fun Context.getLocaleListFromXml(): LocaleListCompat { */ fun Context.getLangPreferenceDropdownEntries(): Map { val localeList = getLocaleListFromXml() - val currentLocaleList: List = ( - if (!AppCompatDelegate.getApplicationLocales().isEmpty) { - AppCompatDelegate.getApplicationLocales() - } else { - LocaleListCompat.getDefault() - } + val currentLocaleList: List = + ( + if (!AppCompatDelegate.getApplicationLocales().isEmpty) { + AppCompatDelegate.getApplicationLocales() + } else { + LocaleListCompat.getDefault() + } ).let { appLocales -> - ArrayList().apply { - for (x in 0 until appLocales.size()) { - appLocales.get(x)?.let { - this.add(it) + ArrayList().apply { + for (x in 0 until appLocales.size()) { + appLocales.get(x)?.let { + this.add(it) + } } } } - } val map = mutableMapOf() for (a in 0 until localeList.size()) { localeList[a].let { it?.run { - val displayName: String = if (currentLocaleList.isEmpty()) { - this.getDisplayName(Locale.getDefault()) - } else { - this.getDisplayName( - currentLocaleList.first { locale -> - this.getDisplayName(locale).isNotEmpty() - } - ) - } + val displayName: String = + if (currentLocaleList.isEmpty()) { + this.getDisplayName(Locale.getDefault()) + } else { + this.getDisplayName( + currentLocaleList.first { locale -> + this.getDisplayName(locale).isNotEmpty() + }, + ) + } map.put(displayName, this) } } diff --git a/app/src/main/java/com/amaze/filemanager/utils/DataUtils.java b/app/src/main/java/com/amaze/filemanager/utils/DataUtils.java index 8203132dc5..8e090417d4 100644 --- a/app/src/main/java/com/amaze/filemanager/utils/DataUtils.java +++ b/app/src/main/java/com/amaze/filemanager/utils/DataUtils.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/utils/DatapointParcelable.kt b/app/src/main/java/com/amaze/filemanager/utils/DatapointParcelable.kt index 8ef97de93a..017633f99b 100644 --- a/app/src/main/java/com/amaze/filemanager/utils/DatapointParcelable.kt +++ b/app/src/main/java/com/amaze/filemanager/utils/DatapointParcelable.kt @@ -45,9 +45,8 @@ data class DatapointParcelable( val byteProgress: Long, val speedRaw: Long, val move: Boolean, - val completed: Boolean + val completed: Boolean, ) : Parcelable { - companion object { /** * For the first datapoint, everything is 0 or false except the params. Allows move boolean to @@ -62,7 +61,7 @@ data class DatapointParcelable( name: String?, amountOfSourceFiles: Int, totalSize: Long, - move: Boolean + move: Boolean, ): DatapointParcelable = DatapointParcelable( name, @@ -72,7 +71,7 @@ data class DatapointParcelable( 0, 0, move, - false + false, ) } } diff --git a/app/src/main/java/com/amaze/filemanager/utils/EditTextColorStateUtil.java b/app/src/main/java/com/amaze/filemanager/utils/EditTextColorStateUtil.java index 8590ec520d..1a992542d0 100644 --- a/app/src/main/java/com/amaze/filemanager/utils/EditTextColorStateUtil.java +++ b/app/src/main/java/com/amaze/filemanager/utils/EditTextColorStateUtil.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/utils/FingerprintHandler.java b/app/src/main/java/com/amaze/filemanager/utils/FingerprintHandler.java index 824a945629..4e7e6d580b 100644 --- a/app/src/main/java/com/amaze/filemanager/utils/FingerprintHandler.java +++ b/app/src/main/java/com/amaze/filemanager/utils/FingerprintHandler.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/utils/GenericExt.kt b/app/src/main/java/com/amaze/filemanager/utils/GenericExt.kt index c54a5d9f73..02f93d5f55 100644 --- a/app/src/main/java/com/amaze/filemanager/utils/GenericExt.kt +++ b/app/src/main/java/com/amaze/filemanager/utils/GenericExt.kt @@ -34,15 +34,19 @@ inline fun safeLet( p3: T3?, p4: T4?, p5: T5?, - block: (T1, T2, T3, T4, T5) -> R? + block: (T1, T2, T3, T4, T5) -> R?, ): R? { - return if (p1 != null && p2 != null && p3 != null && p4 != null && p5 != null) block( - p1, - p2, - p3, - p4, - p5 - ) else null + return if (p1 != null && p2 != null && p3 != null && p4 != null && p5 != null) { + block( + p1, + p2, + p3, + p4, + p5, + ) + } else { + null + } } /** @@ -53,13 +57,17 @@ inline fun safeLet( p1: T1?, p2: T2?, p3: T3?, - block: (T1, T2, T3) -> R? + block: (T1, T2, T3) -> R?, ): R? { - return if (p1 != null && p2 != null && p3 != null) block( - p1, - p2, - p3 - ) else null + return if (p1 != null && p2 != null && p3 != null) { + block( + p1, + p2, + p3, + ) + } else { + null + } } /** @@ -69,12 +77,16 @@ inline fun safeLet( inline fun safeLet( p1: T1?, p2: T2?, - block: (T1, T2) -> R? + block: (T1, T2) -> R?, ): R? { - return if (p1 != null && p2 != null) block( - p1, - p2 - ) else null + return if (p1 != null && p2 != null) { + block( + p1, + p2, + ) + } else { + null + } } /** diff --git a/app/src/main/java/com/amaze/filemanager/utils/GlideConstants.java b/app/src/main/java/com/amaze/filemanager/utils/GlideConstants.java index 12db9e78e8..c8ec849dbc 100644 --- a/app/src/main/java/com/amaze/filemanager/utils/GlideConstants.java +++ b/app/src/main/java/com/amaze/filemanager/utils/GlideConstants.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/utils/ImmutableEntry.java b/app/src/main/java/com/amaze/filemanager/utils/ImmutableEntry.java index 88f28e6c8f..8d51ff7ffa 100644 --- a/app/src/main/java/com/amaze/filemanager/utils/ImmutableEntry.java +++ b/app/src/main/java/com/amaze/filemanager/utils/ImmutableEntry.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/utils/InterestingConfigChange.java b/app/src/main/java/com/amaze/filemanager/utils/InterestingConfigChange.java index 2f5cb41978..f9100fd5f4 100644 --- a/app/src/main/java/com/amaze/filemanager/utils/InterestingConfigChange.java +++ b/app/src/main/java/com/amaze/filemanager/utils/InterestingConfigChange.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/utils/MainActivityActionMode.kt b/app/src/main/java/com/amaze/filemanager/utils/MainActivityActionMode.kt index 2c50641a14..4af20b454a 100644 --- a/app/src/main/java/com/amaze/filemanager/utils/MainActivityActionMode.kt +++ b/app/src/main/java/com/amaze/filemanager/utils/MainActivityActionMode.kt @@ -44,23 +44,31 @@ import java.lang.ref.WeakReference class MainActivityActionMode(private val mainActivityReference: WeakReference) : ActionMode.Callback { - var actionModeView: View? = null var actionMode: ActionMode? = null var pasteHelper: PasteHelper? = null - private fun hideOption(id: Int, menu: Menu) { + private fun hideOption( + id: Int, + menu: Menu, + ) { val item = menu.findItem(id) item.isVisible = false } - private fun showOption(id: Int, menu: Menu) { + private fun showOption( + id: Int, + menu: Menu, + ) { val item = menu.findItem(id) item.isVisible = true } // called when the action mode is created; startActionMode() was called - override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean { + override fun onCreateActionMode( + mode: ActionMode, + menu: Menu, + ): Boolean { // Inflate a menu resource providing context menu items val inflater = mode.menuInflater mainActivityReference.get()?.let { @@ -89,8 +97,8 @@ class MainActivityActionMode(private val mainActivityReference: WeakReference val checkedItems: ArrayList = @@ -119,15 +130,16 @@ class MainActivityActionMode(private val mainActivityReference: WeakReference return when (item.itemId) { @@ -211,7 +230,7 @@ class MainActivityActionMode(private val mainActivityReference: WeakReference { - if (checkedItems.size > 100) Toast.makeText( - mainActivity, - mainActivity.resources.getString(R.string.share_limit), - Toast.LENGTH_SHORT - ) - .show() else { + if (checkedItems.size > 100) { + Toast.makeText( + mainActivity, + mainActivity.resources.getString(R.string.share_limit), + Toast.LENGTH_SHORT, + ) + .show() + } else { mainActivity.currentMainFragment?.mainFragmentViewModel?.also { mainFragmentViewModel -> when (checkedItems[0].mode) { OpenMode.DROPBOX, OpenMode.BOX, OpenMode.GDRIVE, - OpenMode.ONEDRIVE -> + OpenMode.ONEDRIVE, + -> FileUtils.shareCloudFiles( checkedItems, checkedItems[0].mode, - mainActivity + mainActivity, ) else -> { val arrayList = ArrayList() @@ -261,7 +283,7 @@ class MainActivityActionMode(private val mainActivityReference: WeakReference { safeLet( mainActivity.currentMainFragment?.mainFragmentViewModel, - mainActivity.currentMainFragment?.adapter + mainActivity.currentMainFragment?.adapter, ) { mainFragmentViewModel, adapter -> if (adapter.areAllChecked(mainFragmentViewModel.currentPath)) { adapter.toggleChecked( false, - mainFragmentViewModel.currentPath + mainFragmentViewModel.currentPath, ) item.setTitle(R.string.select_all) } else { adapter.toggleChecked( true, - mainFragmentViewModel.currentPath + mainFragmentViewModel.currentPath, ) item.setTitle(R.string.deselect_all) } @@ -331,8 +353,11 @@ class MainActivityActionMode(private val mainActivityReference: WeakReference adapter.toggleChecked(false, mainFragmentViewModel.currentPath) @@ -404,8 +429,10 @@ class MainActivityActionMode(private val mainActivityReference: WeakReference, Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/utils/MinMaxInputFilter.kt b/app/src/main/java/com/amaze/filemanager/utils/MinMaxInputFilter.kt index e9290b6c54..c38a7d9280 100644 --- a/app/src/main/java/com/amaze/filemanager/utils/MinMaxInputFilter.kt +++ b/app/src/main/java/com/amaze/filemanager/utils/MinMaxInputFilter.kt @@ -24,7 +24,6 @@ import android.text.InputFilter import android.text.Spanned class MinMaxInputFilter(private val min: Int, private val max: Int) : InputFilter { - constructor(range: IntRange) : this(range.first, range.last) override fun filter( @@ -33,7 +32,7 @@ class MinMaxInputFilter(private val min: Int, private val max: Int) : InputFilte end: Int, dest: Spanned?, dstart: Int, - dend: Int + dend: Int, ): CharSequence? { runCatching { val input = (dest.toString() + source.toString()).toInt() @@ -44,7 +43,11 @@ class MinMaxInputFilter(private val min: Int, private val max: Int) : InputFilte return "" } - private fun isInRange(minValue: Int, maxValue: Int, input: Int): Boolean { + private fun isInRange( + minValue: Int, + maxValue: Int, + input: Int, + ): Boolean { return if (maxValue > minValue) { input in minValue..maxValue } else { diff --git a/app/src/main/java/com/amaze/filemanager/utils/NetworkUtil.kt b/app/src/main/java/com/amaze/filemanager/utils/NetworkUtil.kt index ea501ea752..c6c7bc9af7 100644 --- a/app/src/main/java/com/amaze/filemanager/utils/NetworkUtil.kt +++ b/app/src/main/java/com/amaze/filemanager/utils/NetworkUtil.kt @@ -34,7 +34,6 @@ import java.net.NetworkInterface import java.net.UnknownHostException object NetworkUtil { - private val log: Logger = LoggerFactory.getLogger(NetworkUtil::class.java) private fun getConnectivityManager(context: Context) = @@ -61,8 +60,8 @@ object NetworkUtil { ni.type and ( ConnectivityManager.TYPE_WIFI or ConnectivityManager.TYPE_ETHERNET - ) != 0 - ) + ) != 0 + ) } ?: false } @@ -106,8 +105,9 @@ object NetworkUtil { return null } if (isConnectedToWifi(context)) { - val wm = context.applicationContext.getSystemService(Service.WIFI_SERVICE) - as WifiManager + val wm = + context.applicationContext.getSystemService(Service.WIFI_SERVICE) + as WifiManager val ipAddress = wm.connectionInfo.ipAddress return if (ipAddress == 0) null else intToInet(ipAddress) } @@ -146,7 +146,10 @@ object NetworkUtil { } } - private fun byteOfInt(value: Int, which: Int): Byte { + private fun byteOfInt( + value: Int, + which: Int, + ): Byte { val shift = which * 8 return (value shr shift).toByte() } diff --git a/app/src/main/java/com/amaze/filemanager/utils/OTGUtil.kt b/app/src/main/java/com/amaze/filemanager/utils/OTGUtil.kt index 4b38b58162..cad7ae00d1 100644 --- a/app/src/main/java/com/amaze/filemanager/utils/OTGUtil.kt +++ b/app/src/main/java/com/amaze/filemanager/utils/OTGUtil.kt @@ -41,7 +41,6 @@ import java.net.URLDecoder /** Created by Vishal on 27-04-2017. */ object OTGUtil { - const val PREFIX_OTG = "otg:/" private const val PREFIX_DOCUMENT_FILE = "content:/" const val PREFIX_MEDIA_REMOVABLE = "/mnt/media_rw" @@ -63,7 +62,10 @@ object OTGUtil { */ @Deprecated("use getDocumentFiles()") @JvmStatic - fun getDocumentFilesList(path: String, context: Context): ArrayList { + fun getDocumentFilesList( + path: String, + context: Context, + ): ArrayList { val files = ArrayList() getDocumentFiles( path, @@ -72,7 +74,7 @@ object OTGUtil { override fun onFileFound(file: HybridFileParcelable) { files.add(file) } - } + }, ) return files } @@ -85,9 +87,14 @@ object OTGUtil { * @param context context for loading */ @JvmStatic - fun getDocumentFiles(path: String, context: Context, fileFound: OnFileFound) { - val rootUriString = SingletonUsbOtg.getInstance().usbOtgRoot - ?: throw NullPointerException("USB OTG root not set!") + fun getDocumentFiles( + path: String, + context: Context, + fileFound: OnFileFound, + ) { + val rootUriString = + SingletonUsbOtg.getInstance().usbOtgRoot + ?: throw NullPointerException("USB OTG root not set!") return getDocumentFiles(rootUriString, path, context, OpenMode.OTG, fileFound) } @@ -97,16 +104,17 @@ object OTGUtil { path: String, context: Context, openMode: OpenMode, - fileFound: OnFileFound + fileFound: OnFileFound, ) { var rootUri = DocumentFile.fromTreeUri(context, rootUriString) - val parts: Array = if (openMode == OpenMode.DOCUMENT_FILE) { - path.substringAfter(rootUriString.toString()) - .split("/", PATH_SEPARATOR_ENCODED).toTypedArray() - } else { - path.split("/").toTypedArray() - } + val parts: Array = + if (openMode == OpenMode.DOCUMENT_FILE) { + path.substringAfter(rootUriString.toString()) + .split("/", PATH_SEPARATOR_ENCODED).toTypedArray() + } else { + path.split("/").toTypedArray() + } for (part in parts.filterNot { it.isEmpty() or it.isBlank() }) { // first omit 'otg:/' before iterating through DocumentFile if (path == "$PREFIX_OTG/" || path == "$PREFIX_DOCUMENT_FILE/") break @@ -126,13 +134,14 @@ object OTGUtil { var size: Long = 0 if (!file.isDirectory) size = file.length() Log.d(context.javaClass.simpleName, "Found file: ${file.name}") - val baseFile = HybridFileParcelable( - path + "/" + file.name, - RootHelper.parseDocumentFilePermission(file), - file.lastModified(), - size, - file.isDirectory - ) + val baseFile = + HybridFileParcelable( + path + "/" + file.name, + RootHelper.parseDocumentFilePermission(file), + file.lastModified(), + size, + file.isDirectory, + ) baseFile.name = file.name baseFile.mode = openMode baseFile.fullUri = file.uri @@ -151,10 +160,11 @@ object OTGUtil { fun getDocumentFile( path: String, context: Context, - createRecursive: Boolean + createRecursive: Boolean, ): DocumentFile? { - val rootUriString = SingletonUsbOtg.getInstance().usbOtgRoot - ?: throw NullPointerException("USB OTG root not set!") + val rootUriString = + SingletonUsbOtg.getInstance().usbOtgRoot + ?: throw NullPointerException("USB OTG root not set!") return getDocumentFile(path, rootUriString, context, OpenMode.OTG, createRecursive) } @@ -165,19 +175,21 @@ object OTGUtil { rootUri: Uri, context: Context, openMode: OpenMode, - createRecursive: Boolean + createRecursive: Boolean, ): DocumentFile? { // start with root of SD card and then parse through document tree. - var retval: DocumentFile? = DocumentFile.fromTreeUri(context, rootUri) - ?: throw DocumentFileNotFoundException(rootUri, path) - val parts: Array = if (openMode == OpenMode.DOCUMENT_FILE) { - URLDecoder.decode(path, Charsets.UTF_8.name()).substringAfter( - URLDecoder.decode(rootUri.toString(), Charsets.UTF_8.name()) - ) - .split("/", PATH_SEPARATOR_ENCODED).toTypedArray() - } else { - path.split("/").toTypedArray() - } + var retval: DocumentFile? = + DocumentFile.fromTreeUri(context, rootUri) + ?: throw DocumentFileNotFoundException(rootUri, path) + val parts: Array = + if (openMode == OpenMode.DOCUMENT_FILE) { + URLDecoder.decode(path, Charsets.UTF_8.name()).substringAfter( + URLDecoder.decode(rootUri.toString(), Charsets.UTF_8.name()), + ) + .split("/", PATH_SEPARATOR_ENCODED).toTypedArray() + } else { + path.split("/").toTypedArray() + } for (part in parts.filterNot { it.isEmpty() or it.isBlank() }) { if (path == "otg:/" || path == "content:/") break if (part == "otg:" || part == "" || part == "content:") continue @@ -202,13 +214,11 @@ object OTGUtil { /** Checks if there is at least one USB device connected with class MASS STORAGE. */ @JvmStatic - fun getMassStorageDevicesConnected( - context: Context - ): List { + fun getMassStorageDevicesConnected(context: Context): List { val usbManager = context.getSystemService(Context.USB_SERVICE) as? UsbManager val devices = usbManager?.deviceList ?: mapOf() return devices.mapNotNullTo( - ArrayList() + ArrayList(), ) { entry -> val device = entry.value var retval: UsbOtgRepresentation? = null @@ -226,7 +236,7 @@ object OTGUtil { TAG, "Permission denied reading serial number of device " + "${device.vendorId}:${device.productId}", - ifPermissionDenied + ifPermissionDenied, ) } } diff --git a/app/src/main/java/com/amaze/filemanager/utils/ObtainableServiceBinder.java b/app/src/main/java/com/amaze/filemanager/utils/ObtainableServiceBinder.java index ae6b9b2a56..6eee3c686f 100644 --- a/app/src/main/java/com/amaze/filemanager/utils/ObtainableServiceBinder.java +++ b/app/src/main/java/com/amaze/filemanager/utils/ObtainableServiceBinder.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/utils/OneCharacterCharSequence.kt b/app/src/main/java/com/amaze/filemanager/utils/OneCharacterCharSequence.kt index fb31ebe799..9746c576f6 100644 --- a/app/src/main/java/com/amaze/filemanager/utils/OneCharacterCharSequence.kt +++ b/app/src/main/java/com/amaze/filemanager/utils/OneCharacterCharSequence.kt @@ -24,11 +24,16 @@ import java.util.* class OneCharacterCharSequence(private val value: Char, override val length: Int) : CharSequence { override fun get(index: Int): Char = - if (index < length) value - else throw IndexOutOfBoundsException() + if (index < length) { + value + } else { + throw IndexOutOfBoundsException() + } - override fun subSequence(startIndex: Int, endIndex: Int): CharSequence = - OneCharacterCharSequence(value, endIndex - startIndex) + override fun subSequence( + startIndex: Int, + endIndex: Int, + ): CharSequence = OneCharacterCharSequence(value, endIndex - startIndex) override fun toString(): String { val array = CharArray(length) diff --git a/app/src/main/java/com/amaze/filemanager/utils/PackageUtils.kt b/app/src/main/java/com/amaze/filemanager/utils/PackageUtils.kt index aae981e953..3bba3c4ce8 100644 --- a/app/src/main/java/com/amaze/filemanager/utils/PackageUtils.kt +++ b/app/src/main/java/com/amaze/filemanager/utils/PackageUtils.kt @@ -23,13 +23,14 @@ package com.amaze.filemanager.utils import android.content.pm.PackageManager class PackageUtils { - companion object { - /** * Checks whether a package name is installed or not */ - fun appInstalledOrNot(uri: String, pm: PackageManager): Boolean { + fun appInstalledOrNot( + uri: String, + pm: PackageManager, + ): Boolean { return try { pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES) true diff --git a/app/src/main/java/com/amaze/filemanager/utils/PasswordUtil.kt b/app/src/main/java/com/amaze/filemanager/utils/PasswordUtil.kt index 54b53158f7..0dc123973f 100644 --- a/app/src/main/java/com/amaze/filemanager/utils/PasswordUtil.kt +++ b/app/src/main/java/com/amaze/filemanager/utils/PasswordUtil.kt @@ -34,7 +34,6 @@ import javax.crypto.spec.GCMParameterSpec import javax.crypto.spec.IvParameterSpec object PasswordUtil { - // 12 byte long IV supported by android for GCM private const val IV = BuildConfig.CRYPTO_IV @@ -42,9 +41,12 @@ object PasswordUtil { @RequiresApi(api = Build.VERSION_CODES.M) @Throws( GeneralSecurityException::class, - IOException::class + IOException::class, ) - private fun aesEncryptPassword(plainTextPassword: String, base64Options: Int): String? { + private fun aesEncryptPassword( + plainTextPassword: String, + base64Options: Int, + ): String? { val cipher = Cipher.getInstance(CryptUtil.ALGO_AES) val gcmParameterSpec = GCMParameterSpec(128, IV.toByteArray()) cipher.init(Cipher.ENCRYPT_MODE, SecretKeygen.getSecretKey(), gcmParameterSpec) @@ -56,9 +58,12 @@ object PasswordUtil { @RequiresApi(api = Build.VERSION_CODES.M) @Throws( GeneralSecurityException::class, - IOException::class + IOException::class, ) - private fun aesDecryptPassword(cipherPassword: String, base64Options: Int): String { + private fun aesDecryptPassword( + cipherPassword: String, + base64Options: Int, + ): String { val cipher = Cipher.getInstance(CryptUtil.ALGO_AES) val gcmParameterSpec = GCMParameterSpec(128, IV.toByteArray()) cipher.init(Cipher.DECRYPT_MODE, SecretKeygen.getSecretKey(), gcmParameterSpec) @@ -69,12 +74,12 @@ object PasswordUtil { @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2) @Throws( GeneralSecurityException::class, - IOException::class + IOException::class, ) private fun rsaEncryptPassword( context: Context, password: String, - base64Options: Int + base64Options: Int, ): String? { val cipher = Cipher.getInstance(CryptUtil.ALGO_AES) val ivParameterSpec = IvParameterSpec(IV.toByteArray()) @@ -85,12 +90,12 @@ object PasswordUtil { @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2) @Throws( GeneralSecurityException::class, - IOException::class + IOException::class, ) private fun rsaDecryptPassword( context: Context, cipherText: String, - base64Options: Int + base64Options: Int, ): String { val cipher = Cipher.getInstance(CryptUtil.ALGO_AES) val ivParameterSpec = IvParameterSpec(IV.toByteArray()) @@ -104,13 +109,15 @@ object PasswordUtil { fun encryptPassword( context: Context, plainText: String, - base64Options: Int = Base64.URL_SAFE + base64Options: Int = Base64.URL_SAFE, ): String? { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { aesEncryptPassword(plainText, base64Options) } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { rsaEncryptPassword(context, plainText, base64Options) - } else plainText + } else { + plainText + } } /** Method handles decryption of cipher text on various APIs */ @@ -118,12 +125,14 @@ object PasswordUtil { fun decryptPassword( context: Context, cipherText: String, - base64Options: Int = Base64.URL_SAFE + base64Options: Int = Base64.URL_SAFE, ): String { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { aesDecryptPassword(cipherText, base64Options) } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { rsaDecryptPassword(context, cipherText, base64Options) - } else cipherText + } else { + cipherText + } } } diff --git a/app/src/main/java/com/amaze/filemanager/utils/PreferenceUtils.kt b/app/src/main/java/com/amaze/filemanager/utils/PreferenceUtils.kt index 688e568df2..660cf45026 100644 --- a/app/src/main/java/com/amaze/filemanager/utils/PreferenceUtils.kt +++ b/app/src/main/java/com/amaze/filemanager/utils/PreferenceUtils.kt @@ -33,6 +33,6 @@ object PreferenceUtils { Color.alpha(color), (Color.red(color) * 0.6f).toInt().coerceAtLeast(0), (Color.green(color) * 0.6f).toInt().coerceAtLeast(0), - (Color.blue(color) * 0.6f).toInt().coerceAtLeast(0) + (Color.blue(color) * 0.6f).toInt().coerceAtLeast(0), ) } diff --git a/app/src/main/java/com/amaze/filemanager/utils/ProgressHandler.java b/app/src/main/java/com/amaze/filemanager/utils/ProgressHandler.java index 58267ba44c..86a76029c8 100644 --- a/app/src/main/java/com/amaze/filemanager/utils/ProgressHandler.java +++ b/app/src/main/java/com/amaze/filemanager/utils/ProgressHandler.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. @@ -41,11 +41,13 @@ public class ProgressHandler { * (see Java Language Specification 17.7) */ private volatile long writtenSize = 0L; + /** total number of source files to be processed */ private volatile int sourceFiles = 0; /** number of source files processed so far */ private volatile int sourceFilesProcessed = 0; + /** file name currently being processed */ private volatile String fileName; diff --git a/app/src/main/java/com/amaze/filemanager/utils/ScreenUtils.kt b/app/src/main/java/com/amaze/filemanager/utils/ScreenUtils.kt index d6eef12a09..0f073f2ca0 100644 --- a/app/src/main/java/com/amaze/filemanager/utils/ScreenUtils.kt +++ b/app/src/main/java/com/amaze/filemanager/utils/ScreenUtils.kt @@ -26,7 +26,6 @@ import java.lang.ref.WeakReference import kotlin.math.roundToInt class ScreenUtils(act: Activity) { - private val _activity: WeakReference = WeakReference(act) private val activity: Activity? get() = _activity.get() diff --git a/app/src/main/java/com/amaze/filemanager/utils/SimpleTextWatcher.kt b/app/src/main/java/com/amaze/filemanager/utils/SimpleTextWatcher.kt index e1be55c069..acd8395f41 100644 --- a/app/src/main/java/com/amaze/filemanager/utils/SimpleTextWatcher.kt +++ b/app/src/main/java/com/amaze/filemanager/utils/SimpleTextWatcher.kt @@ -24,7 +24,19 @@ import android.text.Editable import android.text.TextWatcher open class SimpleTextWatcher : TextWatcher { - override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) = Unit - override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) = Unit + override fun beforeTextChanged( + s: CharSequence, + start: Int, + count: Int, + after: Int, + ) = Unit + + override fun onTextChanged( + s: CharSequence, + start: Int, + before: Int, + count: Int, + ) = Unit + override fun afterTextChanged(s: Editable) = Unit } diff --git a/app/src/main/java/com/amaze/filemanager/utils/TinyDB.kt b/app/src/main/java/com/amaze/filemanager/utils/TinyDB.kt index 057ac30ad3..c02c9d4df4 100644 --- a/app/src/main/java/com/amaze/filemanager/utils/TinyDB.kt +++ b/app/src/main/java/com/amaze/filemanager/utils/TinyDB.kt @@ -29,9 +29,9 @@ import android.text.TextUtils */ object TinyDB { /* - * The "‚" character is not a comma, it is the SINGLE LOW-9 QUOTATION MARK. U-201A - * + U-2017 + U-201A are used for separating the items in a list. - */ + * The "‚" character is not a comma, it is the SINGLE LOW-9 QUOTATION MARK. U-201A + * + U-2017 + U-201A are used for separating the items in a list. + */ private const val DIVIDER = "‚‗‚" /** @@ -41,7 +41,11 @@ object TinyDB { * @param array array of Booleans to be added */ @JvmStatic - fun putBooleanArray(preferences: SharedPreferences, key: String?, array: Array) { + fun putBooleanArray( + preferences: SharedPreferences, + key: String?, + array: Array, + ) { preferences.edit().putString(key, TextUtils.join(DIVIDER, array)).apply() } @@ -55,7 +59,7 @@ object TinyDB { fun getBooleanArray( preferences: SharedPreferences, key: String?, - defaultValue: Array? + defaultValue: Array?, ): Array? { val prefValue = preferences.getString(key, "") if (prefValue == "") { diff --git a/app/src/main/java/com/amaze/filemanager/utils/UUIDv5.kt b/app/src/main/java/com/amaze/filemanager/utils/UUIDv5.kt index 344482d034..20882cb55e 100644 --- a/app/src/main/java/com/amaze/filemanager/utils/UUIDv5.kt +++ b/app/src/main/java/com/amaze/filemanager/utils/UUIDv5.kt @@ -29,7 +29,6 @@ import java.util.* * https://gist.github.com/icedraco/00118b4d3c91d96d8c58e837a448f1b8 */ object UUIDv5 { - // Constants defined in RFC4122 https://www.ietf.org/rfc/rfc4122.txt @JvmStatic val DNS: UUID = UUID.fromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8") @@ -50,7 +49,10 @@ object UUIDv5 { */ @JvmStatic @Suppress("TooGenericExceptionThrown") - fun fromString(namespaceUUID: UUID, name: String): UUID { + fun fromString( + namespaceUUID: UUID, + name: String, + ): UUID { val md: MessageDigest try { md = MessageDigest.getInstance("SHA-1") @@ -61,9 +63,9 @@ object UUIDv5 { md.update(toBytes(namespaceUUID)) md.update(name.toByteArray()) val bytes = md.digest() - /* clear version; set to version 5 */ + // clear version; set to version 5 bytes[6] = ((bytes[6].toInt() and 0x0F) or 0x50).toByte() - /* clear variant; set to IETF variant */ + // clear variant; set to IETF variant bytes[8] = ((bytes[8].toInt() and 0x3F) or 0x80).toByte() return fromBytes(bytes) } diff --git a/app/src/main/java/com/amaze/filemanager/utils/Utils.java b/app/src/main/java/com/amaze/filemanager/utils/Utils.java index bc50b16de3..c7484391db 100644 --- a/app/src/main/java/com/amaze/filemanager/utils/Utils.java +++ b/app/src/main/java/com/amaze/filemanager/utils/Utils.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/main/java/com/amaze/filemanager/utils/X509CertificateUtil.kt b/app/src/main/java/com/amaze/filemanager/utils/X509CertificateUtil.kt index e2d14e9eb0..e41d73459b 100644 --- a/app/src/main/java/com/amaze/filemanager/utils/X509CertificateUtil.kt +++ b/app/src/main/java/com/amaze/filemanager/utils/X509CertificateUtil.kt @@ -26,14 +26,12 @@ import java.security.MessageDigest import java.util.* object X509CertificateUtil { - const val SUBJECT = "subject" const val ISSUER = "issuer" const val SERIAL = "serial" const val FINGERPRINT = "sha256Fingerprint" - private fun colonSeparatedHex(array: ByteArray) = - ByteArrayUtils.toHex(array).chunked(2).joinToString(":") + private fun colonSeparatedHex(array: ByteArray) = ByteArrayUtils.toHex(array).chunked(2).joinToString(":") /** * Parse a [javax.security.cert.X509Certificate] and return part of its information in a JSON object. @@ -48,9 +46,10 @@ object X509CertificateUtil { retval[SUBJECT] = certificate.subjectDN.name retval[ISSUER] = certificate.issuerDN.name retval[SERIAL] = colonSeparatedHex(certificate.serialNumber.toByteArray()) - retval[FINGERPRINT] = MessageDigest.getInstance("sha-256").run { - colonSeparatedHex(digest(certificate.encoded)) - } + retval[FINGERPRINT] = + MessageDigest.getInstance("sha-256").run { + colonSeparatedHex(digest(certificate.encoded)) + } return retval } @@ -67,9 +66,10 @@ object X509CertificateUtil { retval[SUBJECT] = certificate.subjectDN.name retval[ISSUER] = certificate.issuerDN.name retval[SERIAL] = colonSeparatedHex(certificate.serialNumber.toByteArray()) - retval[FINGERPRINT] = MessageDigest.getInstance("sha-256").run { - colonSeparatedHex(digest(certificate.encoded)) - } + retval[FINGERPRINT] = + MessageDigest.getInstance("sha-256").run { + colonSeparatedHex(digest(certificate.encoded)) + } return retval } } diff --git a/app/src/main/java/com/amaze/filemanager/utils/security/SecretKeygen.kt b/app/src/main/java/com/amaze/filemanager/utils/security/SecretKeygen.kt index 4189ff41f7..7f363c3743 100644 --- a/app/src/main/java/com/amaze/filemanager/utils/security/SecretKeygen.kt +++ b/app/src/main/java/com/amaze/filemanager/utils/security/SecretKeygen.kt @@ -50,7 +50,6 @@ import javax.crypto.spec.SecretKeySpec import javax.security.auth.x500.X500Principal object SecretKeygen { - private const val PREFERENCE_KEY = "aes_key" private const val ALGO_RSA = "RSA/ECB/PKCS1Padding" @@ -76,20 +75,22 @@ object SecretKeygen { @RequiresApi(api = M) @Throws( GeneralSecurityException::class, - IOException::class + IOException::class, ) private fun getAesSecretKey(): Key { val keyStore = KeyStore.getInstance(CryptUtil.KEY_STORE_ANDROID) keyStore.load(null) return if (!keyStore.containsAlias(CryptUtil.KEY_ALIAS_AMAZE)) { - val keyGenerator = KeyGenerator.getInstance( - KeyProperties.KEY_ALGORITHM_AES, - CryptUtil.KEY_STORE_ANDROID - ) - val builder = KeyGenParameterSpec.Builder( - CryptUtil.KEY_ALIAS_AMAZE, - KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT - ) + val keyGenerator = + KeyGenerator.getInstance( + KeyProperties.KEY_ALGORITHM_AES, + CryptUtil.KEY_STORE_ANDROID, + ) + val builder = + KeyGenParameterSpec.Builder( + CryptUtil.KEY_ALIAS_AMAZE, + KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT, + ) builder.setBlockModes(KeyProperties.BLOCK_MODE_GCM) builder.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) builder.setRandomizedEncryptionRequired(false) @@ -108,7 +109,7 @@ object SecretKeygen { return if (encodedString != null) { SecretKeySpec( decryptAESKey(Base64.decode(encodedString, Base64.DEFAULT)), - "AES" + "AES", ) } else { generateRsaKeyPair(AppConfig.getInstance()) @@ -128,13 +129,14 @@ object SecretKeygen { val end = Calendar.getInstance() end.add(Calendar.YEAR, 30) val keyPairGenerator = KeyPairGenerator.getInstance("RSA", CryptUtil.KEY_STORE_ANDROID) - val spec = KeyPairGeneratorSpec.Builder(context) - .setAlias(CryptUtil.KEY_ALIAS_AMAZE) - .setSubject(X500Principal("CN=" + CryptUtil.KEY_ALIAS_AMAZE)) - .setSerialNumber(BigInteger.TEN) - .setStartDate(start.time) - .setEndDate(end.time) - .build() + val spec = + KeyPairGeneratorSpec.Builder(context) + .setAlias(CryptUtil.KEY_ALIAS_AMAZE) + .setSubject(X500Principal("CN=" + CryptUtil.KEY_ALIAS_AMAZE)) + .setSerialNumber(BigInteger.TEN) + .setStartDate(start.time) + .setEndDate(end.time) + .build() keyPairGenerator.initialize(spec) keyPairGenerator.generateKeyPair() } diff --git a/app/src/main/java/com/amaze/filemanager/utils/smb/SameSubnetDiscoverDeviceStrategy.kt b/app/src/main/java/com/amaze/filemanager/utils/smb/SameSubnetDiscoverDeviceStrategy.kt index d4385fe95a..66e4739d9c 100644 --- a/app/src/main/java/com/amaze/filemanager/utils/smb/SameSubnetDiscoverDeviceStrategy.kt +++ b/app/src/main/java/com/amaze/filemanager/utils/smb/SameSubnetDiscoverDeviceStrategy.kt @@ -40,7 +40,6 @@ import java.net.InetAddress * TODO: if we can get the gateway using __legit__ API, may swarm the network in broader netmasks */ class SameSubnetDiscoverDeviceStrategy : SmbDeviceScannerObservable.DiscoverDeviceStrategy { - private lateinit var worker: Disposable companion object { @@ -60,37 +59,39 @@ class SameSubnetDiscoverDeviceStrategy : SmbDeviceScannerObservable.DiscoverDevi override fun discoverDevices(callback: (ComputerParcelable) -> Unit) { val neighbourhoods = getNeighbourhoodHosts() - worker = Flowable.fromIterable(neighbourhoods) - .parallel(PARALLELISM) - .runOn(Schedulers.io()) - .map { addr -> - if (addr.isReachable(HOST_UP_TIMEOUT)) { - val portsReachable = listOf( - PortScan.onAddress(addr).setPorts(TCP_PORTS).setMethodTCP().doScan() - ).flatten() - if (portsReachable.isNotEmpty()) { - addr + worker = + Flowable.fromIterable(neighbourhoods) + .parallel(PARALLELISM) + .runOn(Schedulers.io()) + .map { addr -> + if (addr.isReachable(HOST_UP_TIMEOUT)) { + val portsReachable = + listOf( + PortScan.onAddress(addr).setPorts(TCP_PORTS).setMethodTCP().doScan(), + ).flatten() + if (portsReachable.isNotEmpty()) { + addr + } else { + false + } } else { false } - } else { - false - } - }.filter { - it is InetAddress - }.doOnNext { addr -> - addr as InetAddress - callback.invoke( - ComputerParcelable( - addr.hostAddress, - if (addr.hostName == addr.hostAddress) { - addr.canonicalHostName - } else { - addr.hostName - } + }.filter { + it is InetAddress + }.doOnNext { addr -> + addr as InetAddress + callback.invoke( + ComputerParcelable( + addr.hostAddress, + if (addr.hostName == addr.hostAddress) { + addr.canonicalHostName + } else { + addr.hostName + }, + ), ) - ) - }.sequential().subscribe() + }.sequential().subscribe() } private fun getNeighbourhoodHosts(): List { diff --git a/app/src/main/java/com/amaze/filemanager/utils/smb/SmbDeviceScannerObservable.kt b/app/src/main/java/com/amaze/filemanager/utils/smb/SmbDeviceScannerObservable.kt index 0d4afd52c4..b4c8d8c619 100644 --- a/app/src/main/java/com/amaze/filemanager/utils/smb/SmbDeviceScannerObservable.kt +++ b/app/src/main/java/com/amaze/filemanager/utils/smb/SmbDeviceScannerObservable.kt @@ -35,7 +35,6 @@ import java.net.InetAddress * Uses a series of [DiscoverDeviceStrategy] instances to discover nodes. */ class SmbDeviceScannerObservable : Observable() { - /** * Device discovery strategy interface. */ @@ -54,7 +53,7 @@ class SmbDeviceScannerObservable : Observable() { var discoverDeviceStrategies: Array = arrayOf( WsddDiscoverDeviceStrategy(), - SameSubnetDiscoverDeviceStrategy() + SameSubnetDiscoverDeviceStrategy(), ) @VisibleForTesting set @@ -83,18 +82,19 @@ class SmbDeviceScannerObservable : Observable() { */ override fun subscribeActual(observer: Observer) { this.observer = observer - this.disposable = merge( - discoverDeviceStrategies.map { strategy -> - fromCallable { - strategy.discoverDevices { addr -> - observer.onNext(ComputerParcelable(addr.addr, addr.name)) - } - }.subscribeOn(Schedulers.io()) - } - ).observeOn(Schedulers.computation()).doOnComplete { - discoverDeviceStrategies.forEach { strategy -> - strategy.onCancel() - } - }.subscribe() + this.disposable = + merge( + discoverDeviceStrategies.map { strategy -> + fromCallable { + strategy.discoverDevices { addr -> + observer.onNext(ComputerParcelable(addr.addr, addr.name)) + } + }.subscribeOn(Schedulers.io()) + }, + ).observeOn(Schedulers.computation()).doOnComplete { + discoverDeviceStrategies.forEach { strategy -> + strategy.onCancel() + } + }.subscribe() } } diff --git a/app/src/main/java/com/amaze/filemanager/utils/smb/SmbUtil.kt b/app/src/main/java/com/amaze/filemanager/utils/smb/SmbUtil.kt index eca1603f92..b56872cf84 100644 --- a/app/src/main/java/com/amaze/filemanager/utils/smb/SmbUtil.kt +++ b/app/src/main/java/com/amaze/filemanager/utils/smb/SmbUtil.kt @@ -47,7 +47,6 @@ import java.net.MalformedURLException * Class provides various utility methods for SMB client */ object SmbUtil { - @JvmStatic private val LOG = LoggerFactory.getLogger(SmbUtil::class.java) @@ -55,7 +54,10 @@ object SmbUtil { /** Parse path to decrypt smb password */ @JvmStatic - fun getSmbDecryptedPath(context: Context, path: String): String { + fun getSmbDecryptedPath( + context: Context, + path: String, + ): String { return buildPath(path, withPassword = { PasswordUtil.decryptPassword(context, it.urlDecoded()) }) @@ -63,7 +65,10 @@ object SmbUtil { /** Parse path to encrypt smb password */ @JvmStatic - fun getSmbEncryptedPath(context: Context, path: String): String { + fun getSmbEncryptedPath( + context: Context, + path: String, + ): String { return buildPath(path, withPassword = { PasswordUtil.encryptPassword(context, it) }) @@ -71,7 +76,10 @@ object SmbUtil { // At this point, credential is URL encoded to be safe from special chars. // No need to call URLEncoder.encode() again - private fun buildPath(path: String, withPassword: (String) -> String?): String { + private fun buildPath( + path: String, + withPassword: (String) -> String?, + ): String { if (!(path.contains(COLON) && path.contains(AT))) { // smb path doesn't have any credentials return path @@ -79,7 +87,7 @@ object SmbUtil { val buffer = StringBuilder() NetCopyConnectionInfo(path).let { connectionInfo -> buffer.append(connectionInfo.prefix).append( - connectionInfo.username.ifEmpty { "" } + connectionInfo.username.ifEmpty { "" }, ) if (false == connectionInfo.password?.isEmpty()) { val password = withPassword.invoke(connectionInfo.password) @@ -103,15 +111,16 @@ object SmbUtil { @Throws(MalformedURLException::class) fun create(path: String): SmbFile { val uri = Uri.parse(getSmbDecryptedPath(AppConfig.getInstance(), path)) - val disableIpcSigningCheck = uri.getQueryParameter( - PARAM_DISABLE_IPC_SIGNING_CHECK - ).toBoolean() + val disableIpcSigningCheck = + uri.getQueryParameter( + PARAM_DISABLE_IPC_SIGNING_CHECK, + ).toBoolean() val userInfo = uri.userInfo return SmbFile( if (path.indexOf('?') < 0) path else path.substring(0, path.indexOf('?')), createWithDisableIpcSigningCheck(path, disableIpcSigningCheck) - .withCredentials(createFrom(userInfo)) + .withCredentials(createFrom(userInfo)), ) } diff --git a/app/src/main/java/com/amaze/filemanager/utils/smb/WsddDiscoverDeviceStrategy.kt b/app/src/main/java/com/amaze/filemanager/utils/smb/WsddDiscoverDeviceStrategy.kt index db5a1ab86f..be788cf22c 100644 --- a/app/src/main/java/com/amaze/filemanager/utils/smb/WsddDiscoverDeviceStrategy.kt +++ b/app/src/main/java/com/amaze/filemanager/utils/smb/WsddDiscoverDeviceStrategy.kt @@ -66,20 +66,22 @@ import java.util.* * @author TranceLove */ class WsddDiscoverDeviceStrategy : SmbDeviceScannerObservable.DiscoverDeviceStrategy { + private val multicastRequestTemplate = + AppConfig.getInstance() + .resources.openRawResource(R.raw.wsdd_discovery) + .reader(Charsets.UTF_8).readText() - private val multicastRequestTemplate = AppConfig.getInstance() - .resources.openRawResource(R.raw.wsdd_discovery) - .reader(Charsets.UTF_8).readText() + private val wsdRequestTemplate = + AppConfig.getInstance() + .resources.openRawResource(R.raw.wsd_request) + .reader(Charsets.UTF_8).readText() - private val wsdRequestTemplate = AppConfig.getInstance() - .resources.openRawResource(R.raw.wsd_request) - .reader(Charsets.UTF_8).readText() - - private val wsdRequestHeaders = mutableMapOf( - Pair("Accept-Encoding", "Identity"), - Pair("Connection", "Close"), - Pair("User-Agent", "wsd") - ) + private val wsdRequestHeaders = + mutableMapOf( + Pair("Accept-Encoding", "Identity"), + Pair("Connection", "Close"), + Pair("User-Agent", "wsd"), + ) var multicastSocketFactory: () -> MulticastSocket = DEFAULT_MULTICAST_SOCKET_FACTORY @VisibleForTesting @@ -115,16 +117,18 @@ class WsddDiscoverDeviceStrategy : SmbDeviceScannerObservable.DiscoverDeviceStra // Specification said UUIDv5 which is device dependent. But random-based UUID should // also work here val tempDeviceUuid = UUID.randomUUID() - val request = multicastRequestTemplate - .replace("##MY_UUID##", tempDeviceUuid.toString()) - .toByteArray(Charsets.UTF_8) + val request = + multicastRequestTemplate + .replace("##MY_UUID##", tempDeviceUuid.toString()) + .toByteArray(Charsets.UTF_8) - val requestPacket = DatagramPacket( - request, - request.size, - multicastAddressV4, - UDP_PORT - ) + val requestPacket = + DatagramPacket( + request, + request.size, + multicastAddressV4, + UDP_PORT, + ) socket.send(requestPacket) runCatching { @@ -138,7 +142,7 @@ class WsddDiscoverDeviceStrategy : SmbDeviceScannerObservable.DiscoverDeviceStra sentFromAddress, tempDeviceUuid.toString(), replyPacket.data, - callback + callback, ) } } @@ -154,7 +158,7 @@ class WsddDiscoverDeviceStrategy : SmbDeviceScannerObservable.DiscoverDeviceStra sourceAddress: InetAddress, tempDeviceId: String, response: ByteArray, - callback: (ComputerParcelable) -> Unit + callback: (ComputerParcelable) -> Unit, ) { val values = parseXmlForResponse(response, arrayOf(WSD_TYPES, WSA_ADDRESS)) val type = values[WSD_TYPES] @@ -170,7 +174,7 @@ class WsddDiscoverDeviceStrategy : SmbDeviceScannerObservable.DiscoverDeviceStra sourceAddress: InetAddress, urn: String, tempDeviceId: String, - callback: (ComputerParcelable) -> Unit + callback: (ComputerParcelable) -> Unit, ) { if (type.endsWith(PUB_COMPUTER)) { val messageId = UUID.randomUUID().toString() @@ -178,36 +182,39 @@ class WsddDiscoverDeviceStrategy : SmbDeviceScannerObservable.DiscoverDeviceStra val endpoint = urn.substringAfter(URN_UUID) val dest = "http://${sourceAddress.hostAddress}:$TCP_PORT/$endpoint" - val requestBody = wsdRequestTemplate - .replace("##MESSAGE_ID##", "$URN_UUID$messageId") - .replace("##DEST_UUID##", urn) - .replace("##MY_UUID##", "$URN_UUID$tempDeviceId") - .toRequestBody("application/soap+xml".toMediaType()) + val requestBody = + wsdRequestTemplate + .replace("##MESSAGE_ID##", "$URN_UUID$messageId") + .replace("##DEST_UUID##", urn) + .replace("##MY_UUID##", "$URN_UUID$tempDeviceId") + .toRequestBody("application/soap+xml".toMediaType()) queue.newCall( Request.Builder() .url(dest) .post(requestBody) .headers(wsdRequestHeaders.toHeaders()) - .build() + .build(), ).execute().use { resp -> if (resp.isSuccessful && resp.body != null) { resp.body?.run { if (log.isTraceEnabled) log.trace("Response: $resp") - val values = parseXmlForResponse( - this.string(), - arrayOf(WSDP_TYPES, WSA_ADDRESS, PUB_COMPUTER) - ) + val values = + parseXmlForResponse( + this.string(), + arrayOf(WSDP_TYPES, WSA_ADDRESS, PUB_COMPUTER), + ) if (PUB_COMPUTER == values[WSDP_TYPES] && urn == values[WSA_ADDRESS]) { if (true == values[PUB_COMPUTER]?.isNotEmpty()) { - val computerName: String = values[PUB_COMPUTER].let { - if (it!!.contains(SLASH)) { - it.substringBefore(SLASH) - } else { - it + val computerName: String = + values[PUB_COMPUTER].let { + if (it!!.contains(SLASH)) { + it.substringBefore(SLASH) + } else { + it + } } - } callback( - ComputerParcelable(sourceAddress.hostAddress, computerName) + ComputerParcelable(sourceAddress.hostAddress, computerName), ) } } @@ -223,19 +230,25 @@ class WsddDiscoverDeviceStrategy : SmbDeviceScannerObservable.DiscoverDeviceStra cancelled = true } - private fun parseXmlForResponse(xml: ByteArray, tags: Array) = - parseXmlForResponse(xml.toString(Charsets.UTF_8), tags) + private fun parseXmlForResponse( + xml: ByteArray, + tags: Array, + ) = parseXmlForResponse(xml.toString(Charsets.UTF_8), tags) - private fun parseXmlForResponse(xml: String, tags: Array): Map { + private fun parseXmlForResponse( + xml: String, + tags: Array, + ): Map { if (xml.isEmpty()) { return emptyMap() } else { - val xmlParser = XmlPullParserFactory.newInstance().also { - it.isNamespaceAware = false - it.isValidating = false - }.newPullParser().also { - it.setInput(StringReader(xml)) - } + val xmlParser = + XmlPullParserFactory.newInstance().also { + it.isNamespaceAware = false + it.isValidating = false + }.newPullParser().also { + it.setInput(StringReader(xml)) + } val retval = WeakHashMap() var currentTag: String = "" var currentValue: String = "" diff --git a/app/src/main/res/xml/locales_config.xml b/app/src/main/res/xml/locales_config.xml index 27d85f4119..de0aa09fb3 100644 --- a/app/src/main/res/xml/locales_config.xml +++ b/app/src/main/res/xml/locales_config.xml @@ -49,10 +49,8 @@ - - diff --git a/app/src/play/java/com/amaze/filemanager/asynchronous/asynctasks/CloudLoaderAsyncTask.java b/app/src/play/java/com/amaze/filemanager/asynchronous/asynctasks/CloudLoaderAsyncTask.java index b80e207d48..83adc97e31 100644 --- a/app/src/play/java/com/amaze/filemanager/asynchronous/asynctasks/CloudLoaderAsyncTask.java +++ b/app/src/play/java/com/amaze/filemanager/asynchronous/asynctasks/CloudLoaderAsyncTask.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2022 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/play/java/com/amaze/filemanager/asynchronous/asynctasks/compress/RarHelperCallable.kt b/app/src/play/java/com/amaze/filemanager/asynchronous/asynctasks/compress/RarHelperCallable.kt index ea34c9378e..979bff7c7c 100644 --- a/app/src/play/java/com/amaze/filemanager/asynchronous/asynctasks/compress/RarHelperCallable.kt +++ b/app/src/play/java/com/amaze/filemanager/asynchronous/asynctasks/compress/RarHelperCallable.kt @@ -41,18 +41,18 @@ import java.util.* class RarHelperCallable( private val fileLocation: String, private val relativeDirectory: String, - goBack: Boolean + goBack: Boolean, ) : CompressedHelperCallable(goBack) { - @Throws(ArchiveException::class) override fun addElements(elements: ArrayList) { try { val rarFile = Archive(File(fileLocation)) - val relativeDirDiffSeparator = relativeDirectory.replace( - CompressedHelper.SEPARATOR, - "\\" - ) + val relativeDirDiffSeparator = + relativeDirectory.replace( + CompressedHelper.SEPARATOR, + "\\", + ) for (rarArchive in rarFile.fileHeaders) { val name = rarArchive.fileName if (!CompressedHelper.isEntryPathValid(name)) { @@ -61,20 +61,20 @@ class RarHelperCallable( val isInBaseDir = ( (relativeDirDiffSeparator == null || relativeDirDiffSeparator == "") && !name.contains("\\") - ) + ) val isInRelativeDir = ( relativeDirDiffSeparator != null && name.contains("\\") && name.substring(0, name.lastIndexOf("\\")) == relativeDirDiffSeparator - ) + ) if (isInBaseDir || isInRelativeDir) { elements.add( CompressedObjectParcelable( convertName(rarArchive), rarArchive.mTime.time, rarArchive.fullUnpackSize, - rarArchive.isDirectory - ) + rarArchive.isDirectory, + ), ) } } diff --git a/app/src/play/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/RarExtractor.kt b/app/src/play/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/RarExtractor.kt index f87b70f4a9..672298019f 100644 --- a/app/src/play/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/RarExtractor.kt +++ b/app/src/play/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/RarExtractor.kt @@ -50,41 +50,41 @@ class RarExtractor( filePath: String, outputPath: String, listener: OnUpdate, - updatePosition: UpdatePosition + updatePosition: UpdatePosition, ) : Extractor(context, filePath, outputPath, listener, updatePosition) { - private val isRobolectricTest = Build.HARDWARE == "robolectric" @Throws(IOException::class) override fun extractWithFilter(filter: Filter) { try { var totalBytes: Long = 0 - val rarFile = runCatching { - ArchivePasswordCache.getInstance()[filePath]?.let { - Archive(File(filePath), it).also { archive -> - archive.password = it - } - } ?: Archive(File(filePath)) - }.onFailure { - when { - // Hack. CorruptHeaderException will throw if archive is really corrupt or - // password-protected RAR with wrong password, hence have to distinguish two - // situations - ( - !ArchivePasswordCache.getInstance().containsKey(filePath) && - CorruptHeaderException::class.java.isAssignableFrom(it::class.java) + val rarFile = + runCatching { + ArchivePasswordCache.getInstance()[filePath]?.let { + Archive(File(filePath), it).also { archive -> + archive.password = it + } + } ?: Archive(File(filePath)) + }.onFailure { + when { + // Hack. CorruptHeaderException will throw if archive is really corrupt or + // password-protected RAR with wrong password, hence have to distinguish two + // situations + ( + !ArchivePasswordCache.getInstance().containsKey(filePath) && + CorruptHeaderException::class.java.isAssignableFrom(it::class.java) ) or - MainHeaderNullException::class.java.isAssignableFrom(it::class.java) -> { - throw BadArchiveNotice(it) - } - UnsupportedRarV5Exception::class.java.isAssignableFrom(it::class.java) -> { - throw it - } - else -> { - throw PasswordRequiredException(filePath) + MainHeaderNullException::class.java.isAssignableFrom(it::class.java) -> { + throw BadArchiveNotice(it) + } + UnsupportedRarV5Exception::class.java.isAssignableFrom(it::class.java) -> { + throw it + } + else -> { + throw PasswordRequiredException(filePath) + } } - } - }.getOrNull()!! + }.getOrNull()!! if (rarFile.isPasswordProtectedCompat() || rarFile.isEncrypted) { if (ArchivePasswordCache.getInstance().containsKey(filePath)) { @@ -134,14 +134,15 @@ class RarExtractor( context: Context, rarFile: Archive, entry: FileHeader, - outputDir: String + outputDir: String, ) { var _entry = entry val entrySpawnsVolumes = entry.isSplitAfter - val name = fixEntryName(entry.fileName).replace( - "\\\\".toRegex(), - CompressedHelper.SEPARATOR - ) + val name = + fixEntryName(entry.fileName).replace( + "\\\\".toRegex(), + CompressedHelper.SEPARATOR, + ) val outputFile = File(outputDir, name) if (!outputFile.canonicalPath.startsWith(outputDir) && (isRobolectricTest && !outputFile.canonicalPath.startsWith("/private$outputDir")) @@ -160,12 +161,13 @@ class RarExtractor( /* junrar doesn't throw exceptions if wrong archive password is supplied, until extracted file CRC is compared against the one stored in archive. So we can only rely on verifying CRC during extracting - */ + */ val inputStream = BufferedInputStream(rarFile.getInputStream(entry)) - val outputStream = CheckedOutputStream( - BufferedOutputStream(FileUtil.getOutputStream(outputFile, context)), - CRC32() - ) + val outputStream = + CheckedOutputStream( + BufferedOutputStream(FileUtil.getOutputStream(outputFile, context)), + CRC32(), + ) try { var len: Int val buf = ByteArray(GenericCopyUtil.DEFAULT_BUFFER_SIZE) @@ -173,7 +175,9 @@ class RarExtractor( if (!listener.isCancelled) { outputStream.write(buf, 0, len) ServiceWatcherUtil.position += len.toLong() - } else break + } else { + break + } } /* In multi-volume archives, FileHeader may have changed as the other parts of the archive is processed. Need to lookup the FileHeader in the volume the archive @@ -202,12 +206,15 @@ class RarExtractor( } } - private fun tryExtractSmallestFileInArchive(context: Context, archive: Archive): String { + private fun tryExtractSmallestFileInArchive( + context: Context, + archive: Archive, + ): String { archive.fileHeaders ?: throw IOException(CorruptHeaderException()) with( archive.fileHeaders.filter { !it.isDirectory - } + }, ) { if (isEmpty()) { throw IOException(CorruptHeaderException()) @@ -216,13 +223,15 @@ class RarExtractor( .minByOrNull { it.value }!!.run { - val header = archive.fileHeaders.find { - it.fileName.equals(this.key) - }!! - val filename = fixEntryName(header.fileName).replace( - "\\\\".toRegex(), - CompressedHelper.SEPARATOR - ) + val header = + archive.fileHeaders.find { + it.fileName.equals(this.key) + }!! + val filename = + fixEntryName(header.fileName).replace( + "\\\\".toRegex(), + CompressedHelper.SEPARATOR, + ) extractEntry(context, archive, header, context.externalCacheDir!!.absolutePath) return "${context.externalCacheDir!!.absolutePath}/$filename" } diff --git a/app/src/play/java/com/amaze/filemanager/filesystem/compressed/showcontents/helpers/RarDecompressor.kt b/app/src/play/java/com/amaze/filemanager/filesystem/compressed/showcontents/helpers/RarDecompressor.kt index 7c0e5abc14..7975985797 100644 --- a/app/src/play/java/com/amaze/filemanager/filesystem/compressed/showcontents/helpers/RarDecompressor.kt +++ b/app/src/play/java/com/amaze/filemanager/filesystem/compressed/showcontents/helpers/RarDecompressor.kt @@ -29,9 +29,8 @@ import com.github.junrar.rarfile.FileHeader class RarDecompressor(context: Context) : Decompressor(context) { override fun changePath( path: String, - addGoBackItem: Boolean - ) = - RarHelperCallable(filePath, path, addGoBackItem) + addGoBackItem: Boolean, + ) = RarHelperCallable(filePath, path, addGoBackItem) override fun realRelativeDirectory(dir: String): String { var dir = dir @@ -42,7 +41,6 @@ class RarDecompressor(context: Context) : Decompressor(context) { } companion object { - /** * Helper method to convert RAR [FileHeader] entries containing backslashes back to slashes. * diff --git a/app/src/play/java/com/amaze/filemanager/utils/Billing.kt b/app/src/play/java/com/amaze/filemanager/utils/Billing.kt index 5c73a158c0..93dc787279 100644 --- a/app/src/play/java/com/amaze/filemanager/utils/Billing.kt +++ b/app/src/play/java/com/amaze/filemanager/utils/Billing.kt @@ -49,7 +49,6 @@ import java.util.concurrent.Callable class Billing(private val activity: BasicActivity) : RecyclerView.Adapter(), PurchasesUpdatedListener { - private val LOG = LoggerFactory.getLogger(Billing::class.java) // List of predefined IAP products SKU. @@ -66,7 +65,10 @@ class Billing(private val activity: BasicActivity) : private lateinit var donationDialog: MaterialDialog - override fun onPurchasesUpdated(response: BillingResult, purchases: List?) { + override fun onPurchasesUpdated( + response: BillingResult, + purchases: List?, + ) { if (response.responseCode == BillingClient.BillingResponseCode.OK && purchases != null) { for (purchase in purchases) { val listener = ConsumeResponseListener { _: BillingResult, _: String -> } @@ -84,28 +86,28 @@ class Billing(private val activity: BasicActivity) : /** Start a purchase flow */ private fun initiatePurchaseFlow() { - val purchaseFlowRequest = Runnable { - val params = QueryProductDetailsParams.newBuilder().setProductList(productList) + val purchaseFlowRequest = + Runnable { + val params = QueryProductDetailsParams.newBuilder().setProductList(productList) - billingClient.queryProductDetailsAsync( - params.build() - ) { responseCode: BillingResult, queryResult: List -> - if (queryResult.isNotEmpty()) { - // Successfully fetched product details - productDetails = queryResult - popProductsList(responseCode, queryResult) - } else { - AppConfig.toast(activity, R.string.error_fetching_google_play_product_list) - if (BuildConfig.DEBUG) { - /* ktlint-disable max-line-length */ - LOG.warn( - "Error fetching product list - looks like you are running a DEBUG build." - ) - /* ktlint-enable max-line-length */ + billingClient.queryProductDetailsAsync( + params.build(), + ) { responseCode: BillingResult, queryResult: List -> + if (queryResult.isNotEmpty()) { + // Successfully fetched product details + productDetails = queryResult + popProductsList(responseCode, queryResult) + } else { + AppConfig.toast(activity, R.string.error_fetching_google_play_product_list) + @Suppress("ktlint:standard:max-line-length") + if (BuildConfig.DEBUG) { + LOG.warn( + "Error fetching product list - looks like you are running a DEBUG build.", + ) + } } } } - } executeServiceRequest(purchaseFlowRequest) } @@ -123,7 +125,7 @@ class Billing(private val activity: BasicActivity) : */ private fun popProductsList( response: BillingResult, - productDetailsQueryResult: List + productDetailsQueryResult: List, ) { if (response.responseCode == BillingClient.BillingResponseCode.OK && productDetailsQueryResult.isNotEmpty() @@ -132,29 +134,37 @@ class Billing(private val activity: BasicActivity) : } } - override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { - val rootView: View = AdapterDonationBinding.inflate( - LayoutInflater.from( - activity - ), - parent, - false - ).root + override fun onCreateViewHolder( + parent: ViewGroup, + viewType: Int, + ): RecyclerView.ViewHolder { + val rootView: View = + AdapterDonationBinding.inflate( + LayoutInflater.from( + activity, + ), + parent, + false, + ).root return DonationViewHolder(rootView) } - override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { + override fun onBindViewHolder( + holder: RecyclerView.ViewHolder, + position: Int, + ) { if (holder is DonationViewHolder && productDetails.isNotEmpty()) { val titleRaw: String = productDetails[position].title - holder.TITLE.text = titleRaw.subSequence( - 0, - titleRaw.lastIndexOf("(") - ) + holder.TITLE.text = + titleRaw.subSequence( + 0, + titleRaw.lastIndexOf("("), + ) holder.SUMMARY.text = productDetails[position].description holder.PRICE.text = productDetails[position].oneTimePurchaseOfferDetails?.formattedPrice holder.ROOT_VIEW.setOnClickListener { purchaseProduct.purchaseItem( - productDetails[position] + productDetails[position], ) } } @@ -164,34 +174,37 @@ class Billing(private val activity: BasicActivity) : private interface PurchaseProduct { fun purchaseItem(productDetails: ProductDetails) + fun purchaseCancel() } - private val purchaseProduct: PurchaseProduct = object : PurchaseProduct { - override fun purchaseItem(productDetailsArg: ProductDetails) { - val billingFlowParams: BillingFlowParams = - BillingFlowParams.newBuilder().setProductDetailsParamsList( - listOf( - BillingFlowParams.ProductDetailsParams.newBuilder() - .setProductDetails(productDetailsArg) - .build() - ) - ).build() - billingClient.launchBillingFlow(activity, billingFlowParams) - } + private val purchaseProduct: PurchaseProduct = + object : PurchaseProduct { + override fun purchaseItem(productDetailsArg: ProductDetails) { + val billingFlowParams: BillingFlowParams = + BillingFlowParams.newBuilder().setProductDetailsParamsList( + listOf( + BillingFlowParams.ProductDetailsParams.newBuilder() + .setProductDetails(productDetailsArg) + .build(), + ), + ).build() + billingClient.launchBillingFlow(activity, billingFlowParams) + } - override fun purchaseCancel() { - destroyBillingInstance() + override fun purchaseCancel() { + destroyBillingInstance() + } } - } init { - productList = listOf( - createProductWith("donations"), - createProductWith("donations_2"), - createProductWith("donations_3"), - createProductWith("donations_4") - ) + productList = + listOf( + createProductWith("donations"), + createProductWith("donations_2"), + createProductWith("donations_3"), + createProductWith("donations_4"), + ) billingClient = BillingClient.newBuilder(activity).setListener(this).enablePendingPurchases().build() initiatePurchaseFlow() @@ -231,7 +244,7 @@ class Billing(private val activity: BasicActivity) : override fun onBillingServiceDisconnected() { isServiceConnected = false } - } + }, ) } @@ -246,11 +259,11 @@ class Billing(private val activity: BasicActivity) : private fun showPaymentsDialog(context: BasicActivity) { /* - * As of Billing library 4.0, all callbacks are running on background thread. - * Need to use AppConfig.runInApplicationThread() for UI interactions - * - * - */ + * As of Billing library 4.0, all callbacks are running on background thread. + * Need to use AppConfig.runInApplicationThread() for UI interactions + * + * + */ AppConfig.getInstance() .runInApplicationThread( Callable { @@ -261,7 +274,7 @@ class Billing(private val activity: BasicActivity) : builder.cancelListener { purchaseProduct.purchaseCancel() } donationDialog = builder.show() null - } + }, ) } } diff --git a/app/src/play/java/com/amaze/filemanager/utils/PackageInstallValidation.kt b/app/src/play/java/com/amaze/filemanager/utils/PackageInstallValidation.kt index 3118f3956e..fcc5a2a4f4 100644 --- a/app/src/play/java/com/amaze/filemanager/utils/PackageInstallValidation.kt +++ b/app/src/play/java/com/amaze/filemanager/utils/PackageInstallValidation.kt @@ -31,7 +31,6 @@ import java.io.File * */ object PackageInstallValidation { - /** * Perform validation by getting [PackageInfo] of file at specified path, then see if it's us. * If yes, throw [PackageCannotBeInstalledException] and [FileUtils.installApk] should exit @@ -44,14 +43,14 @@ object PackageInstallValidation { val packageInfo: PackageInfo? = packageManager.getPackageArchiveInfo( f.absolutePath, - PackageManager.GET_ACTIVITIES + PackageManager.GET_ACTIVITIES, ) if (packageInfo == null) { throw IllegalStateException("Cannot get package info") } else { if (packageInfo.packageName == this.packageName) { throw PackageCannotBeInstalledException( - "Cannot update myself per Google Play policy" + "Cannot update myself per Google Play policy", ) } } diff --git a/app/src/test/java/com/amaze/filemanager/application/AppConfigTest.java b/app/src/test/java/com/amaze/filemanager/application/AppConfigTest.java index 84ea2611b4..c700e29975 100644 --- a/app/src/test/java/com/amaze/filemanager/application/AppConfigTest.java +++ b/app/src/test/java/com/amaze/filemanager/application/AppConfigTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/AbstractDeleteTaskTestBase.kt b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/AbstractDeleteTaskTestBase.kt index db67b7037b..c3e796df52 100644 --- a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/AbstractDeleteTaskTestBase.kt +++ b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/AbstractDeleteTaskTestBase.kt @@ -62,19 +62,19 @@ import org.robolectric.shadows.ShadowToast ShadowMultiDex::class, ShadowSmbUtil::class, ShadowTabHandler::class, - ShadowPasswordUtil::class + ShadowPasswordUtil::class, ], - sdk = [KITKAT, P, Build.VERSION_CODES.R] + sdk = [KITKAT, P, Build.VERSION_CODES.R], ) abstract class AbstractDeleteTaskTestBase { - private var ctx: Context? = null @Rule @JvmField @RequiresApi(Build.VERSION_CODES.R) - val allFilesPermissionRule = GrantPermissionRule - .grant(Manifest.permission.MANAGE_EXTERNAL_STORAGE) + val allFilesPermissionRule = + GrantPermissionRule + .grant(Manifest.permission.MANAGE_EXTERNAL_STORAGE) /** * Test case setup. @@ -134,7 +134,7 @@ abstract class AbstractDeleteTaskTestBase { }!!.apply { assertEquals(MainActivity.TAG_INTENT_FILTER_GENERAL, action) getParcelableArrayListExtra( - MainActivity.TAG_INTENT_FILTER_FAILED_OPS + MainActivity.TAG_INTENT_FILTER_FAILED_OPS, ) .run { assertTrue(size > 0) diff --git a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/DbViewerTaskTest.java b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/DbViewerTaskTest.java index b7de685a4c..5546f904b0 100644 --- a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/DbViewerTaskTest.java +++ b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/DbViewerTaskTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/SmbDeleteTaskTest.kt b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/SmbDeleteTaskTest.kt index 123a6c65f4..6af12add5d 100644 --- a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/SmbDeleteTaskTest.kt +++ b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/SmbDeleteTaskTest.kt @@ -26,7 +26,6 @@ import com.amaze.filemanager.utils.smb.SmbUtil import org.junit.Test class SmbDeleteTaskTest : AbstractDeleteTaskTestBase() { - /** * Test case to verify delete SMB file success scenario. * @@ -35,7 +34,7 @@ class SmbDeleteTaskTest : AbstractDeleteTaskTestBase() { @Test fun testDeleteSmbFileOk() { doTestDeleteFileOk( - HybridFileParcelable(SmbUtil.create("smb://user:password@1.2.3.4/just/a/file.txt")) + HybridFileParcelable(SmbUtil.create("smb://user:password@1.2.3.4/just/a/file.txt")), ) } diff --git a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/SshDeleteTaskTest.kt b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/SshDeleteTaskTest.kt index 4a95cf5b09..2ad715bd35 100644 --- a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/SshDeleteTaskTest.kt +++ b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/SshDeleteTaskTest.kt @@ -30,7 +30,6 @@ import org.mockito.Mockito.mock import org.mockito.Mockito.`when` class SshDeleteTaskTest : AbstractDeleteTaskTestBase() { - /** * Test case to verify delete SSH file success scenario. * @@ -54,26 +53,28 @@ class SshDeleteTaskTest : AbstractDeleteTaskTestBase() { } private fun createSshHybridFileParcelable(): HybridFileParcelable { - val ri = mock(RemoteResourceInfo::class.java).apply { - val fa = mock(FileAttributes::class.java).apply { - `when`(mtime).thenReturn(System.currentTimeMillis() / 1000) - `when`(size).thenReturn(16384) - `when`(permissions).thenReturn( - setOf( - FilePermission.USR_RWX, - FilePermission.GRP_RWX, - FilePermission.OTH_RWX - ) - ) + val ri = + mock(RemoteResourceInfo::class.java).apply { + val fa = + mock(FileAttributes::class.java).apply { + `when`(mtime).thenReturn(System.currentTimeMillis() / 1000) + `when`(size).thenReturn(16384) + `when`(permissions).thenReturn( + setOf( + FilePermission.USR_RWX, + FilePermission.GRP_RWX, + FilePermission.OTH_RWX, + ), + ) + } + `when`(name).thenReturn("test.file") + `when`(attributes).thenReturn(fa) } - `when`(name).thenReturn("test.file") - `when`(attributes).thenReturn(fa) - } return HybridFileParcelable( "ssh://user:password@127.0.0.1:22222", false, - ri + ri, ) } } diff --git a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/AbstractCompressedHelperCallableArchiveTest.kt b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/AbstractCompressedHelperCallableArchiveTest.kt index 13e5952269..70d34325ec 100644 --- a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/AbstractCompressedHelperCallableArchiveTest.kt +++ b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/AbstractCompressedHelperCallableArchiveTest.kt @@ -31,19 +31,19 @@ import java.time.ZonedDateTime @Suppress("TooManyFunctions", "StringLiteralDuplication") abstract class AbstractCompressedHelperCallableArchiveTest : AbstractCompressedHelperCallableTest() { - companion object { @JvmStatic - private val EXPECTED_TIMESTAMP = ZonedDateTime.of( - 2018, - 5, - 29, - 10, - 38, - 0, - 0, - ZoneId.of("UTC") - ).toInstant().toEpochMilli() + private val EXPECTED_TIMESTAMP = + ZonedDateTime.of( + 2018, + 5, + 29, + 10, + 38, + 0, + 0, + ZoneId.of("UTC"), + ).toInstant().toEpochMilli() } protected abstract val archiveFileName: String @@ -51,8 +51,7 @@ abstract class AbstractCompressedHelperCallableArchiveTest : /** * Assert archive entry timestamp is correct. */ - protected open fun assertEntryTimestampCorrect(entry: CompressedObjectParcelable) = - assertEquals(EXPECTED_TIMESTAMP, entry.date) + protected open fun assertEntryTimestampCorrect(entry: CompressedObjectParcelable) = assertEquals(EXPECTED_TIMESTAMP, entry.date) /** * Test browse archive top level. @@ -130,11 +129,11 @@ abstract class AbstractCompressedHelperCallableArchiveTest : protected fun createCallable(relativePath: String): CompressedHelperCallable = doCreateCallable( File(Environment.getExternalStorageDirectory(), archiveFileName), - relativePath + relativePath, ) protected abstract fun doCreateCallable( archive: File, - relativePath: String + relativePath: String, ): CompressedHelperCallable } diff --git a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/AbstractCompressedHelperCallableTest.kt b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/AbstractCompressedHelperCallableTest.kt index a9d4b780c2..91b74ae0bb 100644 --- a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/AbstractCompressedHelperCallableTest.kt +++ b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/AbstractCompressedHelperCallableTest.kt @@ -39,7 +39,6 @@ import java.util.* @RunWith(AndroidJUnit4::class) @Config(shadows = [ShadowMultiDex::class], sdk = [KITKAT, P, Build.VERSION_CODES.R]) abstract class AbstractCompressedHelperCallableTest { - private lateinit var systemTz: TimeZone /** @@ -67,8 +66,8 @@ abstract class AbstractCompressedHelperCallableTest { }?.forEach { FileInputStream(it).copyTo( FileOutputStream( - File(Environment.getExternalStorageDirectory(), it.name) - ) + File(Environment.getExternalStorageDirectory(), it.name), + ), ) } } diff --git a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/CompressedHelperForBadArchiveTest.kt b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/CompressedHelperForBadArchiveTest.kt index 908f1cc79f..6b7c2cf2a4 100644 --- a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/CompressedHelperForBadArchiveTest.kt +++ b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/CompressedHelperForBadArchiveTest.kt @@ -43,7 +43,6 @@ import java.io.FileOutputStream @RunWith(AndroidJUnit4::class) @Config(shadows = [ShadowMultiDex::class], sdk = [KITKAT, P]) class CompressedHelperForBadArchiveTest { - /** * Test handling of corrupt archive with random junk. */ @@ -62,17 +61,19 @@ class CompressedHelperForBadArchiveTest { private fun doTestBadArchive(data: ByteArray) { for ( - archiveType in supportedArchiveExtensions().subtract(excludedArchiveTypes) + archiveType in supportedArchiveExtensions().subtract(excludedArchiveTypes) ) { - val badArchive = File( - Environment.getExternalStorageDirectory(), - "bad-archive.$archiveType" - ) + val badArchive = + File( + Environment.getExternalStorageDirectory(), + "bad-archive.$archiveType", + ) ByteArrayInputStream(data).copyTo(FileOutputStream(badArchive)) - val task = CompressedHelper.getCompressorInstance( - ApplicationProvider.getApplicationContext(), - badArchive - ) + val task = + CompressedHelper.getCompressorInstance( + ApplicationProvider.getApplicationContext(), + badArchive, + ) Assert.assertNotNull(task) task!! try { @@ -82,14 +83,13 @@ class CompressedHelperForBadArchiveTest { Assert.assertNotNull(exception) Assert.assertTrue( "Thrown from ${task.javaClass}: ${exception.javaClass} was thrown", - ArchiveException::class.java.isAssignableFrom(exception.javaClass) + ArchiveException::class.java.isAssignableFrom(exception.javaClass), ) } } } companion object { - /* * tar and rar currently will produce empty list. * bz2, lzma, gz, xz by default must have one entry diff --git a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/EncryptedSevenZipHelperCallableTest.kt b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/EncryptedSevenZipHelperCallableTest.kt index 2e9c64debb..2538212502 100644 --- a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/EncryptedSevenZipHelperCallableTest.kt +++ b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/EncryptedSevenZipHelperCallableTest.kt @@ -23,14 +23,16 @@ package com.amaze.filemanager.asynchronous.asynctasks.compress import java.io.File class EncryptedSevenZipHelperCallableTest : AbstractCompressedHelperCallableArchiveTest() { - override val archiveFileName: String get() = "test-archive-encrypted.7z" - override fun doCreateCallable(archive: File, relativePath: String): CompressedHelperCallable = + override fun doCreateCallable( + archive: File, + relativePath: String, + ): CompressedHelperCallable = SevenZipHelperCallable( archive.absolutePath, relativePath, - false + false, ) } diff --git a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/EncryptedZipHelperCallableTest.kt b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/EncryptedZipHelperCallableTest.kt index 89f2341095..41a80b63b7 100644 --- a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/EncryptedZipHelperCallableTest.kt +++ b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/EncryptedZipHelperCallableTest.kt @@ -24,15 +24,17 @@ import androidx.test.core.app.ApplicationProvider import java.io.File class EncryptedZipHelperCallableTest : AbstractCompressedHelperCallableArchiveTest() { - override val archiveFileName: String get() = "test-archive-encrypted.zip" - override fun doCreateCallable(archive: File, relativePath: String): CompressedHelperCallable = + override fun doCreateCallable( + archive: File, + relativePath: String, + ): CompressedHelperCallable = ZipHelperCallable( ApplicationProvider.getApplicationContext(), archive.absolutePath, relativePath, - false + false, ) } diff --git a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/ListEncryptedSevenZipHelperCallableTest.kt b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/ListEncryptedSevenZipHelperCallableTest.kt index ee9ca6d61d..affdc8c0d8 100644 --- a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/ListEncryptedSevenZipHelperCallableTest.kt +++ b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/ListEncryptedSevenZipHelperCallableTest.kt @@ -24,11 +24,13 @@ import com.amaze.filemanager.fileoperations.filesystem.compressed.ArchivePasswor import java.io.File class ListEncryptedSevenZipHelperCallableTest : AbstractCompressedHelperCallableArchiveTest() { - override val archiveFileName: String get() = "test-archive-encrypted-list.7z" - override fun doCreateCallable(archive: File, relativePath: String): CompressedHelperCallable { + override fun doCreateCallable( + archive: File, + relativePath: String, + ): CompressedHelperCallable { archive.absolutePath.let { ArchivePasswordCache.getInstance()[it] = "123456" return SevenZipHelperCallable(it, relativePath, false) diff --git a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/SevenZipHelperCallableFullPathArchiveTest.kt b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/SevenZipHelperCallableFullPathArchiveTest.kt index 1db6ad57ec..ae22e4d8ed 100644 --- a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/SevenZipHelperCallableFullPathArchiveTest.kt +++ b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/SevenZipHelperCallableFullPathArchiveTest.kt @@ -26,7 +26,6 @@ import org.junit.Assert.assertTrue import java.io.File class SevenZipHelperCallableFullPathArchiveTest : AbstractCompressedHelperCallableArchiveTest() { - override val archiveFileName: String get() = "test-direct-paths.7z" @@ -37,17 +36,17 @@ class SevenZipHelperCallableFullPathArchiveTest : AbstractCompressedHelperCallab assertNotNull( result.find { it.name == "1" && it.directory - } + }, ) assertNotNull( result.find { it.name == "testdir" && it.directory - } + }, ) assertNotNull( result.find { it.name == "test.jpg" && !it.directory - } + }, ) } @@ -58,17 +57,17 @@ class SevenZipHelperCallableFullPathArchiveTest : AbstractCompressedHelperCallab assertNotNull( result.find { it.name == "1" && it.directory - } + }, ) assertNotNull( result.find { it.name == "testdir" && it.directory - } + }, ) assertNotNull( result.find { it.name == "test.jpg" && !it.directory - } + }, ) task = createCallable("1") result = task.call() @@ -77,10 +76,13 @@ class SevenZipHelperCallableFullPathArchiveTest : AbstractCompressedHelperCallab assertTrue(result[0].directory) } - override fun doCreateCallable(archive: File, relativePath: String): CompressedHelperCallable = + override fun doCreateCallable( + archive: File, + relativePath: String, + ): CompressedHelperCallable = SevenZipHelperCallable( archive.absolutePath, relativePath, - false + false, ) } diff --git a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/SevenZipHelperCallableInternalTest.kt b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/SevenZipHelperCallableInternalTest.kt index 433ba49dd9..670d174309 100644 --- a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/SevenZipHelperCallableInternalTest.kt +++ b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/SevenZipHelperCallableInternalTest.kt @@ -28,7 +28,6 @@ import org.junit.Test * Test [SevenZipHelperCallable] internals */ class SevenZipHelperCallableInternalTest { - /** * Test simple scenario of consolidate() */ @@ -56,22 +55,23 @@ class SevenZipHelperCallableInternalTest { @Test fun testConsolidateClassic() { val callable = SevenZipHelperCallable("dummy", "", false) - val list = listOf( - "test-archive", - "test-archive/1", - "test-archive/2", - "test-archive/3", - "test-archive/4", - "test-archive/a", - "test-archive/a/b", - "test-archive/a/b/c", - "test-archive/a/b/c/d", - "test-archive/1/8", - "test-archive/2/7", - "test-archive/3/6", - "test-archive/4/5", - "test-archive/a/b/c/d/lipsum.bin" - ) + val list = + listOf( + "test-archive", + "test-archive/1", + "test-archive/2", + "test-archive/3", + "test-archive/4", + "test-archive/a", + "test-archive/a/b", + "test-archive/a/b/c", + "test-archive/a/b/c/d", + "test-archive/1/8", + "test-archive/2/7", + "test-archive/3/6", + "test-archive/4/5", + "test-archive/a/b/c/d/lipsum.bin", + ) var result = callable.consolidate(list) assertEquals(1, result.size) assertEquals("test-archive", result.first()) diff --git a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/SevenZipHelperCallableTest.kt b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/SevenZipHelperCallableTest.kt index 7d28dcd241..3aa08dd811 100644 --- a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/SevenZipHelperCallableTest.kt +++ b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/SevenZipHelperCallableTest.kt @@ -23,14 +23,16 @@ package com.amaze.filemanager.asynchronous.asynctasks.compress import java.io.File class SevenZipHelperCallableTest : AbstractCompressedHelperCallableArchiveTest() { - override val archiveFileName: String get() = "test-archive.7z" - override fun doCreateCallable(archive: File, relativePath: String): CompressedHelperCallable = + override fun doCreateCallable( + archive: File, + relativePath: String, + ): CompressedHelperCallable = SevenZipHelperCallable( archive.absolutePath, relativePath, - false + false, ) } diff --git a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/SevenZipHelperCallableTest2.kt b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/SevenZipHelperCallableTest2.kt index e3f0b5cd49..c1cdb29769 100644 --- a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/SevenZipHelperCallableTest2.kt +++ b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/SevenZipHelperCallableTest2.kt @@ -27,7 +27,6 @@ import java.io.File @Ignore("Test skipped due to problem at upstream library.") class SevenZipHelperCallableTest2 : AbstractCompressedHelperCallableArchiveTest() { - override val archiveFileName: String get() = "compress.7z" @@ -42,10 +41,13 @@ class SevenZipHelperCallableTest2 : AbstractCompressedHelperCallableArchiveTest( @Ignore("Not testing this one") override fun testSublevels() = Unit - override fun doCreateCallable(archive: File, relativePath: String): CompressedHelperCallable = + override fun doCreateCallable( + archive: File, + relativePath: String, + ): CompressedHelperCallable = SevenZipHelperCallable( archive.absolutePath, relativePath, - false + false, ) } diff --git a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/SevenZipHelperCallableTest3.kt b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/SevenZipHelperCallableTest3.kt index d124800947..254bacc543 100644 --- a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/SevenZipHelperCallableTest3.kt +++ b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/SevenZipHelperCallableTest3.kt @@ -28,7 +28,6 @@ import java.io.File * Test for viewing 7z archives without timestamps in entries. See #3035 */ class SevenZipHelperCallableTest3 : AbstractCompressedHelperCallableArchiveTest() { - override val archiveFileName: String get() = "test-archive-no-timestamp.7z" @@ -36,10 +35,13 @@ class SevenZipHelperCallableTest3 : AbstractCompressedHelperCallableArchiveTest( assertEquals(0, entry.date) } - override fun doCreateCallable(archive: File, relativePath: String): CompressedHelperCallable = + override fun doCreateCallable( + archive: File, + relativePath: String, + ): CompressedHelperCallable = SevenZipHelperCallable( archive.absolutePath, relativePath, - false + false, ) } diff --git a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarBzip2HelperCallableTest.kt b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarBzip2HelperCallableTest.kt index ab7ff22ca5..97f0c762c3 100644 --- a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarBzip2HelperCallableTest.kt +++ b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarBzip2HelperCallableTest.kt @@ -27,11 +27,14 @@ class TarBzip2HelperCallableTest : AbstractCompressedHelperCallableArchiveTest() override val archiveFileName: String get() = "test-archive.tar.bz2" - override fun doCreateCallable(archive: File, relativePath: String): CompressedHelperCallable = + override fun doCreateCallable( + archive: File, + relativePath: String, + ): CompressedHelperCallable = TarBzip2HelperCallable( ApplicationProvider.getApplicationContext(), archive.absolutePath, relativePath, - false + false, ) } diff --git a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarGzHelperCallableTest.kt b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarGzHelperCallableTest.kt index f267b9fafc..a31bb86147 100644 --- a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarGzHelperCallableTest.kt +++ b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarGzHelperCallableTest.kt @@ -24,15 +24,17 @@ import androidx.test.core.app.ApplicationProvider import java.io.File class TarGzHelperCallableTest : AbstractCompressedHelperCallableArchiveTest() { - override val archiveFileName: String get() = "test-archive.tar.gz" - override fun doCreateCallable(archive: File, relativePath: String): CompressedHelperCallable = + override fun doCreateCallable( + archive: File, + relativePath: String, + ): CompressedHelperCallable = TarGzHelperCallable( ApplicationProvider.getApplicationContext(), archive.absolutePath, relativePath, - false + false, ) } diff --git a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarHelperCallableTest.kt b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarHelperCallableTest.kt index a3d898515b..968fc85a84 100644 --- a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarHelperCallableTest.kt +++ b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarHelperCallableTest.kt @@ -24,15 +24,17 @@ import androidx.test.core.app.ApplicationProvider import java.io.File class TarHelperCallableTest : AbstractCompressedHelperCallableArchiveTest() { - override val archiveFileName: String get() = "test-archive.tar" - override fun doCreateCallable(archive: File, relativePath: String): CompressedHelperCallable = + override fun doCreateCallable( + archive: File, + relativePath: String, + ): CompressedHelperCallable = TarHelperCallable( ApplicationProvider.getApplicationContext(), archive.absolutePath, relativePath, - false + false, ) } diff --git a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarLzmaHelperCallableTest.kt b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarLzmaHelperCallableTest.kt index c04439363c..7246d8398e 100644 --- a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarLzmaHelperCallableTest.kt +++ b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarLzmaHelperCallableTest.kt @@ -24,15 +24,17 @@ import androidx.test.core.app.ApplicationProvider import java.io.File class TarLzmaHelperCallableTest : AbstractCompressedHelperCallableArchiveTest() { - override val archiveFileName: String get() = "test-archive.tar.lzma" - override fun doCreateCallable(archive: File, relativePath: String): CompressedHelperCallable = + override fun doCreateCallable( + archive: File, + relativePath: String, + ): CompressedHelperCallable = TarLzmaHelperCallable( ApplicationProvider.getApplicationContext(), archive.absolutePath, relativePath, - false + false, ) } diff --git a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarXzHelperCallableTest.kt b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarXzHelperCallableTest.kt index a8ff1f0060..16ffc09d27 100644 --- a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarXzHelperCallableTest.kt +++ b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarXzHelperCallableTest.kt @@ -24,15 +24,17 @@ import androidx.test.core.app.ApplicationProvider import java.io.File class TarXzHelperCallableTest : AbstractCompressedHelperCallableArchiveTest() { - override val archiveFileName: String get() = "test-archive.tar.xz" - override fun doCreateCallable(archive: File, relativePath: String): CompressedHelperCallable = + override fun doCreateCallable( + archive: File, + relativePath: String, + ): CompressedHelperCallable = TarXzHelperCallable( ApplicationProvider.getApplicationContext(), archive.absolutePath, relativePath, - false + false, ) } diff --git a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarXzHelperCallableTest2.kt b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarXzHelperCallableTest2.kt index 0d83faf563..3a2baf8a2b 100644 --- a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarXzHelperCallableTest2.kt +++ b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/TarXzHelperCallableTest2.kt @@ -56,11 +56,14 @@ class TarXzHelperCallableTest2 : AbstractCompressedHelperCallableArchiveTest() { assertEquals(6, result[0].size) } - override fun doCreateCallable(archive: File, relativePath: String): CompressedHelperCallable = + override fun doCreateCallable( + archive: File, + relativePath: String, + ): CompressedHelperCallable = TarXzHelperCallable( ApplicationProvider.getApplicationContext(), archive.absolutePath, relativePath, - false + false, ) } diff --git a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/UnknownCompressedHelperCallableTest.kt b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/UnknownCompressedHelperCallableTest.kt index 921c797aac..4ef3318a49 100644 --- a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/UnknownCompressedHelperCallableTest.kt +++ b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/UnknownCompressedHelperCallableTest.kt @@ -26,7 +26,6 @@ import org.junit.Test import java.io.File class UnknownCompressedHelperCallableTest : AbstractCompressedHelperCallableTest() { - /** * Test file decompression. */ @@ -37,10 +36,10 @@ class UnknownCompressedHelperCallableTest : AbstractCompressedHelperCallableTest UnknownCompressedFileHelperCallable( File( Environment.getExternalStorageDirectory(), - "test.txt.$ext" + "test.txt.$ext", ).absolutePath, - false - ) + false, + ), ) } } diff --git a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/ZipHelperCallableTest.kt b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/ZipHelperCallableTest.kt index a4abb8ad1a..012683ce68 100644 --- a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/ZipHelperCallableTest.kt +++ b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/compress/ZipHelperCallableTest.kt @@ -27,7 +27,6 @@ import org.junit.Test import java.io.File class ZipHelperCallableTest : AbstractCompressedHelperCallableArchiveTest() { - override val archiveFileName: String get() = "test-archive.zip" @@ -39,20 +38,22 @@ class ZipHelperCallableTest : AbstractCompressedHelperCallableArchiveTest() { @Test fun testVariableYAssignment() { var a = "aaz" - var y = a.apply { - if (startsWith("/")) { - substring(1, length) + var y = + a.apply { + if (startsWith("/")) { + substring(1, length) + } } - } assertEquals("aaz", y) a = "/abcdefg" - y = a.let { - if (it.startsWith("/")) { - it.substring(1, it.length) - } else { - it + y = + a.let { + if (it.startsWith("/")) { + it.substring(1, it.length) + } else { + it + } } - } assertEquals("abcdefg", y) } @@ -65,15 +66,18 @@ class ZipHelperCallableTest : AbstractCompressedHelperCallableArchiveTest() { ApplicationProvider.getApplicationContext(), "mailto:test@test.com", "", - false + false, ).addElements(ArrayList()) } - override fun doCreateCallable(archive: File, relativePath: String): CompressedHelperCallable = + override fun doCreateCallable( + archive: File, + relativePath: String, + ): CompressedHelperCallable = ZipHelperCallable( ApplicationProvider.getApplicationContext(), archive.absolutePath, relativePath, - false + false, ) } diff --git a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/BasicSearchTest.kt b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/BasicSearchTest.kt index 5a5702e3fa..e5d40ed16c 100644 --- a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/BasicSearchTest.kt +++ b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/BasicSearchTest.kt @@ -85,12 +85,13 @@ class BasicSearchTest { */ @Test fun testSimpleSearchMatch() { - val basicSearch = BasicSearch( - "ab", - filePath, - EnumSet.of(SearchParameter.SHOW_HIDDEN_FILES), - context - ) + val basicSearch = + BasicSearch( + "ab", + filePath, + EnumSet.of(SearchParameter.SHOW_HIDDEN_FILES), + context, + ) val expectedMatchRanges = listOf(0..1) @@ -111,18 +112,19 @@ class BasicSearchTest { */ @Test fun testSimpleSearchNotMatch() { - val basicSearch = BasicSearch( - "ba", - filePath, - EnumSet.of(SearchParameter.SHOW_HIDDEN_FILES), - context - ) + val basicSearch = + BasicSearch( + "ba", + filePath, + EnumSet.of(SearchParameter.SHOW_HIDDEN_FILES), + context, + ) basicSearch.foundFilesLiveData.observeForever { actualResults -> Assert.assertNotNull(actualResults) Assert.assertTrue( listNotEmptyError(actualResults.size), - actualResults.isEmpty() + actualResults.isEmpty(), ) } @@ -137,18 +139,19 @@ class BasicSearchTest { */ @Test fun testSearchWithPathMatchButNameNotMatch() { - val basicSearch = BasicSearch( - "test", - filePath, - EnumSet.of(SearchParameter.SHOW_HIDDEN_FILES), - context - ) + val basicSearch = + BasicSearch( + "test", + filePath, + EnumSet.of(SearchParameter.SHOW_HIDDEN_FILES), + context, + ) basicSearch.foundFilesLiveData.observeForever { actualResults -> Assert.assertNotNull(actualResults) Assert.assertTrue( listNotEmptyError(actualResults.size), - actualResults.isEmpty() + actualResults.isEmpty(), ) } @@ -163,18 +166,19 @@ class BasicSearchTest { */ @Test fun testMatchHiddenFile() { - val basicSearch = BasicSearch( - "ab", - filePath, - EnumSet.noneOf(SearchParameter::class.java), - context - ) + val basicSearch = + BasicSearch( + "ab", + filePath, + EnumSet.noneOf(SearchParameter::class.java), + context, + ) basicSearch.foundFilesLiveData.observeForever { actualResults -> Assert.assertNotNull(actualResults) Assert.assertTrue( listNotEmptyError(actualResults.size), - actualResults.isEmpty() + actualResults.isEmpty(), ) } @@ -183,6 +187,5 @@ class BasicSearchTest { } } - private fun listNotEmptyError(size: Int) = - "List was not empty as expected but had $size elements" + private fun listNotEmptyError(size: Int) = "List was not empty as expected but had $size elements" } diff --git a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/DeepSearchTest.kt b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/DeepSearchTest.kt index cf26588e63..59c1992173 100644 --- a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/DeepSearchTest.kt +++ b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/DeepSearchTest.kt @@ -86,13 +86,14 @@ class DeepSearchTest { */ @Test fun testSimpleSearchMatch() { - val deepSearch = DeepSearch( - "ab", - filePath, - EnumSet.of(SearchParameter.SHOW_HIDDEN_FILES), - context, - OpenMode.FILE - ) + val deepSearch = + DeepSearch( + "ab", + filePath, + EnumSet.of(SearchParameter.SHOW_HIDDEN_FILES), + context, + OpenMode.FILE, + ) val expectedMatchRanges = listOf(0..1) @@ -113,19 +114,20 @@ class DeepSearchTest { */ @Test fun testSimpleSearchNotMatch() { - val deepSearch = DeepSearch( - "ba", - filePath, - EnumSet.of(SearchParameter.SHOW_HIDDEN_FILES), - context, - OpenMode.FILE - ) + val deepSearch = + DeepSearch( + "ba", + filePath, + EnumSet.of(SearchParameter.SHOW_HIDDEN_FILES), + context, + OpenMode.FILE, + ) deepSearch.foundFilesLiveData.observeForever { actualResults -> Assert.assertNotNull(actualResults) Assert.assertTrue( listNotEmptyError(actualResults.size), - actualResults.isEmpty() + actualResults.isEmpty(), ) } @@ -140,19 +142,20 @@ class DeepSearchTest { */ @Test fun testSearchWithPathMatchButNameNotMatch() { - val deepSearch = DeepSearch( - "test", - filePath, - EnumSet.of(SearchParameter.SHOW_HIDDEN_FILES), - context, - OpenMode.FILE - ) + val deepSearch = + DeepSearch( + "test", + filePath, + EnumSet.of(SearchParameter.SHOW_HIDDEN_FILES), + context, + OpenMode.FILE, + ) deepSearch.foundFilesLiveData.observeForever { actualResults -> Assert.assertNotNull(actualResults) Assert.assertTrue( listNotEmptyError(actualResults.size), - actualResults.isEmpty() + actualResults.isEmpty(), ) } @@ -167,19 +170,20 @@ class DeepSearchTest { */ @Test fun testMatchHiddenFile() { - val basicSearch = DeepSearch( - "ab", - filePath, - EnumSet.noneOf(SearchParameter::class.java), - context, - OpenMode.FILE - ) + val basicSearch = + DeepSearch( + "ab", + filePath, + EnumSet.noneOf(SearchParameter::class.java), + context, + OpenMode.FILE, + ) basicSearch.foundFilesLiveData.observeForever { actualResults -> Assert.assertNotNull(actualResults) Assert.assertTrue( listNotEmptyError(actualResults.size), - actualResults.isEmpty() + actualResults.isEmpty(), ) } @@ -188,6 +192,5 @@ class DeepSearchTest { } } - private fun listNotEmptyError(size: Int) = - "List was not empty as expected but had $size elements" + private fun listNotEmptyError(size: Int) = "List was not empty as expected but had $size elements" } diff --git a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/FileSearchTest.kt b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/FileSearchTest.kt index 57a8f61556..40e0cff922 100644 --- a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/FileSearchTest.kt +++ b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/FileSearchTest.kt @@ -29,31 +29,30 @@ class FileSearchTest { private fun getFileSearchMatch( query: String, path: String, - searchParameters: SearchParameters - ): FileSearch = object : FileSearch(query, path, searchParameters) { - override suspend fun search( - filter: SearchFilter - ) { - val matchRange = filter.searchFilter(path) - Assert.assertNotNull("Expected $path to match filter", matchRange) - Assert.assertTrue("Start of match range is negative", matchRange!!.first >= 0) - Assert.assertTrue( - "End of match range is larger than length of $path", - matchRange.last < path.length - ) - val expectedRange = 5..9 - Assert.assertEquals( - "Range was not as expected $expectedRange but $matchRange", - expectedRange, - matchRange - ) + searchParameters: SearchParameters, + ): FileSearch = + object : FileSearch(query, path, searchParameters) { + override suspend fun search(filter: SearchFilter) { + val matchRange = filter.searchFilter(path) + Assert.assertNotNull("Expected $path to match filter", matchRange) + Assert.assertTrue("Start of match range is negative", matchRange!!.first >= 0) + Assert.assertTrue( + "End of match range is larger than length of $path", + matchRange.last < path.length, + ) + val expectedRange = 5..9 + Assert.assertEquals( + "Range was not as expected $expectedRange but $matchRange", + expectedRange, + matchRange, + ) + } } - } private fun getFileSearchNotMatch( query: String, path: String, - searchParameters: SearchParameters + searchParameters: SearchParameters, ): FileSearch = object : FileSearch(query, path, searchParameters) { override suspend fun search(filter: SearchFilter) { @@ -65,121 +64,129 @@ class FileSearchTest { private fun getFileSearchRegexMatches( query: String, path: String, - searchParameters: SearchParameters - ): FileSearch = object : FileSearch(query, path, searchParameters) { - override suspend fun search( - filter: SearchFilter - ) { - val matchRange = filter.searchFilter(path) - Assert.assertNotNull("Expected $path to match filter", matchRange) - Assert.assertTrue("Start of match range is negative", matchRange!!.first >= 0) - Assert.assertTrue( - "End of match range is larger than length of $path", - matchRange.last < path.length - ) - val expectedRange = path.indices - Assert.assertEquals( - "Range was not as expected $expectedRange but $matchRange", - expectedRange, - matchRange - ) + searchParameters: SearchParameters, + ): FileSearch = + object : FileSearch(query, path, searchParameters) { + override suspend fun search(filter: SearchFilter) { + val matchRange = filter.searchFilter(path) + Assert.assertNotNull("Expected $path to match filter", matchRange) + Assert.assertTrue("Start of match range is negative", matchRange!!.first >= 0) + Assert.assertTrue( + "End of match range is larger than length of $path", + matchRange.last < path.length, + ) + val expectedRange = path.indices + Assert.assertEquals( + "Range was not as expected $expectedRange but $matchRange", + expectedRange, + matchRange, + ) + } } - } /** Test the simple filter with a path that matches the query */ @Test - fun simpleFilterMatchTest() = runTest { - getFileSearchMatch( - "abcde", - "01234ABcDe012", - EnumSet.noneOf(SearchParameter::class.java) - ).search() - } + fun simpleFilterMatchTest() = + runTest { + getFileSearchMatch( + "abcde", + "01234ABcDe012", + EnumSet.noneOf(SearchParameter::class.java), + ).search() + } /** Test the simple filter with a path that does not match the query */ @Test - fun simpleFilterNotMatchTest() = runTest { - // There is no "e" - getFileSearchNotMatch( - "abcde", - "01234abcd9012", - EnumSet.noneOf(SearchParameter::class.java) - ).search() - } + fun simpleFilterNotMatchTest() = + runTest { + // There is no "e" + getFileSearchNotMatch( + "abcde", + "01234abcd9012", + EnumSet.noneOf(SearchParameter::class.java), + ).search() + } /** Test the regex filter with a path that matches the query. The query contains `*`. */ @Test - fun regexFilterStarMatchTest() = runTest { - getFileSearchMatch( - "a*e", - "01234ABcDe012", - SearchParameters.of(SearchParameter.REGEX) - ).search() - } + fun regexFilterStarMatchTest() = + runTest { + getFileSearchMatch( + "a*e", + "01234ABcDe012", + SearchParameters.of(SearchParameter.REGEX), + ).search() + } /** Test the regex filter with a path that does not match the query. The query contains `*`. */ @Test - fun regexFilterStarNotMatchTest() = runTest { - // There is no "e" - getFileSearchNotMatch( - "a*e", - "01234aBcD9012", - SearchParameters.of(SearchParameter.REGEX) - ).search() - } + fun regexFilterStarNotMatchTest() = + runTest { + // There is no "e" + getFileSearchNotMatch( + "a*e", + "01234aBcD9012", + SearchParameters.of(SearchParameter.REGEX), + ).search() + } /** Test the regex filter with a path that matches the query. The query contains `?`. */ @Test - fun regexFilterQuestionMarkMatchTest() = runTest { - getFileSearchMatch( - "a???e", - "01234ABcDe0123", - SearchParameters.of(SearchParameter.REGEX) - ).search() - } + fun regexFilterQuestionMarkMatchTest() = + runTest { + getFileSearchMatch( + "a???e", + "01234ABcDe0123", + SearchParameters.of(SearchParameter.REGEX), + ).search() + } /** Test the regex filter with a path that does not match the query. The query contains `?`. */ @Test - fun regexFilterQuestionMarkNotMatchTest() = runTest { - // There is one character missing between "a" and "e" - getFileSearchNotMatch( - "a???e", - "01234ABce9012", - SearchParameters.of(SearchParameter.REGEX) - ).search() - } + fun regexFilterQuestionMarkNotMatchTest() = + runTest { + // There is one character missing between "a" and "e" + getFileSearchNotMatch( + "a???e", + "01234ABce9012", + SearchParameters.of(SearchParameter.REGEX), + ).search() + } /** * Test the regex filter with a path that does not match the query * because `-` is not recognized by `?` or `*`. */ @Test - fun regexFilterNotMatchNonWordCharacterTest() = runTest { - getFileSearchNotMatch( - "a?c*e", - "0A-corn search", - SearchParameters.of(SearchParameter.REGEX) - ).search() - } + fun regexFilterNotMatchNonWordCharacterTest() = + runTest { + getFileSearchNotMatch( + "a?c*e", + "0A-corn search", + SearchParameters.of(SearchParameter.REGEX), + ).search() + } /** Test the regex match filter with a path that completely matches the query */ @Test - fun regexMatchFilterMatchTest() = runTest { - getFileSearchRegexMatches( - "a*e", - "A1234ABcDe0123e", - SearchParameter.REGEX + SearchParameter.REGEX_MATCHES - ).search() - } + fun regexMatchFilterMatchTest() = + runTest { + getFileSearchRegexMatches( + "a*e", + "A1234ABcDe0123e", + SearchParameter.REGEX + SearchParameter.REGEX_MATCHES, + ).search() + } /** Test the regex match filter with a path that does not completely match the query */ @Test - fun regexMatchFilterNotMatchTest() = runTest { - // Pattern does not match whole name - getFileSearchNotMatch( - "a*e", - "01234ABcDe0123", - SearchParameter.REGEX + SearchParameter.REGEX_MATCHES - ).search() - } + fun regexMatchFilterNotMatchTest() = + runTest { + // Pattern does not match whole name + getFileSearchNotMatch( + "a*e", + "01234ABcDe0123", + SearchParameter.REGEX + SearchParameter.REGEX_MATCHES, + ).search() + } } diff --git a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/IndexedSearchTest.kt b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/IndexedSearchTest.kt index 6f78265f4c..e0d318108b 100644 --- a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/IndexedSearchTest.kt +++ b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/IndexedSearchTest.kt @@ -82,12 +82,13 @@ class IndexedSearchTest { val expectedPaths = listOf(filePath) val expectedRanges = listOf(0..1) - val indexedSearch = IndexedSearch( - "ab", - "/", - EnumSet.noneOf(SearchParameter::class.java), - mockCursor - ) + val indexedSearch = + IndexedSearch( + "ab", + "/", + EnumSet.noneOf(SearchParameter::class.java), + mockCursor, + ) indexedSearch.foundFilesLiveData.observeForever { actualResults -> Assert.assertNotNull(actualResults) Assert.assertEquals(expectedNames, actualResults!!.map { (file, _) -> file.name }) @@ -105,17 +106,18 @@ class IndexedSearchTest { */ @Test fun testSimpleSearchNotMatch() { - val indexedSearch = IndexedSearch( - "ba", - "/", - EnumSet.noneOf(SearchParameter::class.java), - mockCursor - ) + val indexedSearch = + IndexedSearch( + "ba", + "/", + EnumSet.noneOf(SearchParameter::class.java), + mockCursor, + ) indexedSearch.foundFilesLiveData.observeForever { actualResults -> Assert.assertNotNull(actualResults) Assert.assertTrue( listNotEmptyError(actualResults.size), - actualResults.isEmpty() + actualResults.isEmpty(), ) } runTest { @@ -129,17 +131,18 @@ class IndexedSearchTest { */ @Test fun testSearchWithPathMatchButNameNotMatch() { - val indexedSearch = IndexedSearch( - "te", - "/", - EnumSet.noneOf(SearchParameter::class.java), - mockCursor - ) + val indexedSearch = + IndexedSearch( + "te", + "/", + EnumSet.noneOf(SearchParameter::class.java), + mockCursor, + ) indexedSearch.foundFilesLiveData.observeForever { actualResults -> Assert.assertNotNull(actualResults) Assert.assertTrue( listNotEmptyError(actualResults.size), - actualResults.isEmpty() + actualResults.isEmpty(), ) } runTest { @@ -147,6 +150,5 @@ class IndexedSearchTest { } } - private fun listNotEmptyError(size: Int) = - "List was not empty as expected but had $size elements" + private fun listNotEmptyError(size: Int) = "List was not empty as expected but had $size elements" } diff --git a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/SearchParameterTest.kt b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/SearchParameterTest.kt index 4ae5630359..c9ed3863cb 100644 --- a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/SearchParameterTest.kt +++ b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/SearchParameterTest.kt @@ -25,7 +25,6 @@ import org.junit.Test import java.util.EnumSet class SearchParameterTest { - /** Tests [SearchParameter.and] */ @Test fun testAnd() { diff --git a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/SearchParametersTest.kt b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/SearchParametersTest.kt index 006669d43b..713eb48412 100644 --- a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/SearchParametersTest.kt +++ b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/SearchParametersTest.kt @@ -25,7 +25,6 @@ import org.junit.Test import java.util.EnumSet class SearchParametersTest { - /** Tests [SearchParameters.and] */ @Test fun testAnd() { @@ -69,34 +68,38 @@ class SearchParametersTest { /** Tests [searchParametersFromBoolean] with three flags turned on */ @Test fun testSearchParametersFromBooleanWithThree() { - val expected = EnumSet.of( - SearchParameter.ROOT, - SearchParameter.REGEX, - SearchParameter.REGEX_MATCHES - ) - val actual = searchParametersFromBoolean( - isRoot = true, - isRegexEnabled = true, - isRegexMatchesEnabled = true - ) + val expected = + EnumSet.of( + SearchParameter.ROOT, + SearchParameter.REGEX, + SearchParameter.REGEX_MATCHES, + ) + val actual = + searchParametersFromBoolean( + isRoot = true, + isRegexEnabled = true, + isRegexMatchesEnabled = true, + ) Assert.assertEquals(expected, actual) } /** Tests [searchParametersFromBoolean] with four flags turned on */ @Test fun testSearchParametersFromBooleanWithFour() { - val expected = EnumSet.of( - SearchParameter.ROOT, - SearchParameter.REGEX, - SearchParameter.REGEX_MATCHES, - SearchParameter.SHOW_HIDDEN_FILES - ) - val actual = searchParametersFromBoolean( - isRoot = true, - isRegexEnabled = true, - isRegexMatchesEnabled = true, - showHiddenFiles = true - ) + val expected = + EnumSet.of( + SearchParameter.ROOT, + SearchParameter.REGEX, + SearchParameter.REGEX_MATCHES, + SearchParameter.SHOW_HIDDEN_FILES, + ) + val actual = + searchParametersFromBoolean( + isRoot = true, + isRegexEnabled = true, + isRegexMatchesEnabled = true, + showHiddenFiles = true, + ) Assert.assertEquals(expected, actual) } } diff --git a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/SearchResultListSorterTest.kt b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/SearchResultListSorterTest.kt index 3ca332cd6f..9b630d2465 100644 --- a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/SearchResultListSorterTest.kt +++ b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/SearchResultListSorterTest.kt @@ -41,17 +41,22 @@ import java.util.regex.Pattern @RunWith(AndroidJUnit4::class) @Config( shadows = [ShadowMultiDex::class], - sdk = [Build.VERSION_CODES.KITKAT, Build.VERSION_CODES.P, Build.VERSION_CODES.R] + sdk = [Build.VERSION_CODES.KITKAT, Build.VERSION_CODES.P, Build.VERSION_CODES.R], ) @Suppress("StringLiteralDuplication", "ComplexMethod", "LongMethod", "LargeClass") class SearchResultListSorterTest { - - private fun getSimpleMatchRange(searchTerm: String, fileName: String): MatchRange { + private fun getSimpleMatchRange( + searchTerm: String, + fileName: String, + ): MatchRange { val startIndex = fileName.lowercase().indexOf(searchTerm.lowercase()) return startIndex..(startIndex + searchTerm.length) } - private fun getPatternMatchRange(pattern: Pattern, fileName: String): MatchRange { + private fun getPatternMatchRange( + pattern: Pattern, + fileName: String, + ): MatchRange { val matcher = pattern.matcher(fileName) matcher.find() return matcher.start()..matcher.end() @@ -73,48 +78,51 @@ class SearchResultListSorterTest { val title2 = "ABCDE.txt" val matchRange2 = getSimpleMatchRange(searchTerm, title2) - val searchResultListSorter = SearchResultListSorter( - DirSortBy.NONE_ON_TOP, - SortType(SortBy.RELEVANCE, SortOrder.ASC), - searchTerm - ) + val searchResultListSorter = + SearchResultListSorter( + DirSortBy.NONE_ON_TOP, + SortType(SortBy.RELEVANCE, SortOrder.ASC), + searchTerm, + ) - val file1 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - title1, - "C:\\AmazeFileManager\\abc", - "user", - "symlink", - "100", - 123L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ).generateBaseFile() + val file1 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + title1, + "C:\\AmazeFileManager\\abc", + "user", + "symlink", + "100", + 123L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ).generateBaseFile() - val file2 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "ABCDE.txt", - "C:\\AmazeFileManager\\ABCDE", - "user", - "symlink", - "101", - 124L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ).generateBaseFile() + val file2 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "ABCDE.txt", + "C:\\AmazeFileManager\\ABCDE", + "user", + "symlink", + "101", + 124L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ).generateBaseFile() Assert.assertEquals( -1, searchResultListSorter.compare( SearchResult(file1, matchRange1), - SearchResult(file2, matchRange2) - ).toLong() + SearchResult(file2, matchRange2), + ).toLong(), ) } @@ -133,45 +141,48 @@ class SearchResultListSorterTest { val matchRange1 = getSimpleMatchRange(searchTerm, title1) val title2 = "ABC.txt" val matchRange2 = getSimpleMatchRange(searchTerm, title2) - val searchResultListSorter = SearchResultListSorter( - DirSortBy.NONE_ON_TOP, - SortType(SortBy.RELEVANCE, SortOrder.ASC), - searchTerm - ) - val file1 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - title1, - "C:\\AmazeFileManager\\abcdefg", - "user", - "symlink", - "100", - 123L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ).generateBaseFile() - val file2 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - title2, - "C:\\AmazeFileManager\\ABC", - "user", - "symlink", - "101", - 124L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ).generateBaseFile() + val searchResultListSorter = + SearchResultListSorter( + DirSortBy.NONE_ON_TOP, + SortType(SortBy.RELEVANCE, SortOrder.ASC), + searchTerm, + ) + val file1 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + title1, + "C:\\AmazeFileManager\\abcdefg", + "user", + "symlink", + "100", + 123L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ).generateBaseFile() + val file2 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + title2, + "C:\\AmazeFileManager\\ABC", + "user", + "symlink", + "101", + 124L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ).generateBaseFile() Assert.assertEquals( 1, searchResultListSorter.compare( SearchResult(file1, matchRange1), - SearchResult(file2, matchRange2) - ).toLong() + SearchResult(file2, matchRange2), + ).toLong(), ) } @@ -192,45 +203,48 @@ class SearchResultListSorterTest { val title2 = "XYZ_ABC" val matchRange2 = getSimpleMatchRange(searchTerm, title2) - val searchResultListSorter = SearchResultListSorter( - DirSortBy.NONE_ON_TOP, - SortType(SortBy.RELEVANCE, SortOrder.ASC), - searchTerm - ) - val file1 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - title1, - "C:\\AmazeFileManager\\abc", - "user", - "symlink", - "100", - 123L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ).generateBaseFile() - val file2 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - title2, - "C:\\AmazeFileManager\\XYZ_ABC", - "user", - "symlink", - "101", - 124L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ).generateBaseFile() + val searchResultListSorter = + SearchResultListSorter( + DirSortBy.NONE_ON_TOP, + SortType(SortBy.RELEVANCE, SortOrder.ASC), + searchTerm, + ) + val file1 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + title1, + "C:\\AmazeFileManager\\abc", + "user", + "symlink", + "100", + 123L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ).generateBaseFile() + val file2 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + title2, + "C:\\AmazeFileManager\\XYZ_ABC", + "user", + "symlink", + "101", + 124L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ).generateBaseFile() Assert.assertEquals( -1, searchResultListSorter.compare( SearchResult(file1, matchRange1), - SearchResult(file2, matchRange2) - ).toLong() + SearchResult(file2, matchRange2), + ).toLong(), ) } @@ -251,45 +265,48 @@ class SearchResultListSorterTest { val title2 = "ABC.txt" val matchRange2 = getSimpleMatchRange(searchTerm, title2) - val searchResultListSorter = SearchResultListSorter( - DirSortBy.NONE_ON_TOP, - SortType(SortBy.RELEVANCE, SortOrder.ASC), - searchTerm - ) - val file1 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - title1, - "C:\\AmazeFileManager\\txt-abc", - "user", - "symlink", - "100", - 123L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ).generateBaseFile() - val file2 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - title2, - "C:\\AmazeFileManager\\ABC", - "user", - "symlink", - "101", - 124L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ).generateBaseFile() + val searchResultListSorter = + SearchResultListSorter( + DirSortBy.NONE_ON_TOP, + SortType(SortBy.RELEVANCE, SortOrder.ASC), + searchTerm, + ) + val file1 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + title1, + "C:\\AmazeFileManager\\txt-abc", + "user", + "symlink", + "100", + 123L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ).generateBaseFile() + val file2 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + title2, + "C:\\AmazeFileManager\\ABC", + "user", + "symlink", + "101", + 124L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ).generateBaseFile() Assert.assertEquals( 1, searchResultListSorter.compare( SearchResult(file1, matchRange1), - SearchResult(file2, matchRange2) - ).toLong() + SearchResult(file2, matchRange2), + ).toLong(), ) } @@ -312,45 +329,48 @@ class SearchResultListSorterTest { val title2 = "ABCD-FG.txt" val matchRange2 = getSimpleMatchRange(searchTerm, title2) - val searchResultListSorter = SearchResultListSorter( - DirSortBy.NONE_ON_TOP, - SortType(SortBy.RELEVANCE, SortOrder.ASC), - searchTerm - ) - val file1 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - title1, - "C:\\AmazeFileManager\\abc-efg", - "user", - "symlink", - "100", - 123L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ).generateBaseFile() - val file2 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - title2, - "C:\\AmazeFileManager\\ABCD-FG", - "user", - "symlink", - "101", - 124L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ).generateBaseFile() + val searchResultListSorter = + SearchResultListSorter( + DirSortBy.NONE_ON_TOP, + SortType(SortBy.RELEVANCE, SortOrder.ASC), + searchTerm, + ) + val file1 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + title1, + "C:\\AmazeFileManager\\abc-efg", + "user", + "symlink", + "100", + 123L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ).generateBaseFile() + val file2 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + title2, + "C:\\AmazeFileManager\\ABCD-FG", + "user", + "symlink", + "101", + 124L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ).generateBaseFile() Assert.assertEquals( -1, searchResultListSorter.compare( SearchResult(file1, matchRange1), - SearchResult(file2, matchRange2) - ).toLong() + SearchResult(file2, matchRange2), + ).toLong(), ) } @@ -372,45 +392,48 @@ class SearchResultListSorterTest { val matchRange1 = getSimpleMatchRange(searchTerm, title1) val title2 = "ABC_EFG" val matchRange2 = getSimpleMatchRange(searchTerm, title2) - val searchResultListSorter = SearchResultListSorter( - DirSortBy.NONE_ON_TOP, - SortType(SortBy.RELEVANCE, SortOrder.ASC), - searchTerm - ) - val file1 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - title1, - "C:\\AmazeFileManager\\abcdefg", - "user", - "symlink", - "100", - 123L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ).generateBaseFile() - val file2 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - title2, - "C:\\AmazeFileManager\\ABC_EFG", - "user", - "symlink", - "101", - 124L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ).generateBaseFile() + val searchResultListSorter = + SearchResultListSorter( + DirSortBy.NONE_ON_TOP, + SortType(SortBy.RELEVANCE, SortOrder.ASC), + searchTerm, + ) + val file1 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + title1, + "C:\\AmazeFileManager\\abcdefg", + "user", + "symlink", + "100", + 123L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ).generateBaseFile() + val file2 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + title2, + "C:\\AmazeFileManager\\ABC_EFG", + "user", + "symlink", + "101", + 124L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ).generateBaseFile() Assert.assertEquals( 1, searchResultListSorter.compare( SearchResult(file1, matchRange1), - SearchResult(file2, matchRange2) - ).toLong() + SearchResult(file2, matchRange2), + ).toLong(), ) } @@ -433,45 +456,48 @@ class SearchResultListSorterTest { val title2 = "ABC EFG" val matchRange2 = getSimpleMatchRange(searchTerm, title2) - val searchResultListSorter = SearchResultListSorter( - DirSortBy.NONE_ON_TOP, - SortType(SortBy.RELEVANCE, SortOrder.ASC), - "abc" - ) - val file1 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - title1, - "C:\\AmazeFileManager\\abcdefg", - "user", - "symlink", - "100", - 123L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ).generateBaseFile() - val file2 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - title2, - "C:\\AmazeFileManager\\ABC EFG", - "user", - "symlink", - "101", - 124L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ).generateBaseFile() + val searchResultListSorter = + SearchResultListSorter( + DirSortBy.NONE_ON_TOP, + SortType(SortBy.RELEVANCE, SortOrder.ASC), + "abc", + ) + val file1 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + title1, + "C:\\AmazeFileManager\\abcdefg", + "user", + "symlink", + "100", + 123L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ).generateBaseFile() + val file2 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + title2, + "C:\\AmazeFileManager\\ABC EFG", + "user", + "symlink", + "101", + 124L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ).generateBaseFile() Assert.assertEquals( 1, searchResultListSorter.compare( SearchResult(file1, matchRange1), - SearchResult(file2, matchRange2) - ).toLong() + SearchResult(file2, matchRange2), + ).toLong(), ) } @@ -494,45 +520,48 @@ class SearchResultListSorterTest { val title2 = "ABC.EFG" val matchRange2 = getSimpleMatchRange(searchTerm, title2) - val searchResultListSorter = SearchResultListSorter( - DirSortBy.NONE_ON_TOP, - SortType(SortBy.RELEVANCE, SortOrder.ASC), - searchTerm - ) - val file1 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - title1, - "C:\\AmazeFileManager\\abcdefg", - "user", - "symlink", - "100", - 123L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ).generateBaseFile() - val file2 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - title2, - "C:\\AmazeFileManager\\ABC.EFG", - "user", - "symlink", - "101", - 124L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ).generateBaseFile() + val searchResultListSorter = + SearchResultListSorter( + DirSortBy.NONE_ON_TOP, + SortType(SortBy.RELEVANCE, SortOrder.ASC), + searchTerm, + ) + val file1 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + title1, + "C:\\AmazeFileManager\\abcdefg", + "user", + "symlink", + "100", + 123L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ).generateBaseFile() + val file2 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + title2, + "C:\\AmazeFileManager\\ABC.EFG", + "user", + "symlink", + "101", + 124L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ).generateBaseFile() Assert.assertEquals( 1, searchResultListSorter.compare( SearchResult(file1, matchRange1), - SearchResult(file2, matchRange2) - ).toLong() + SearchResult(file2, matchRange2), + ).toLong(), ) } @@ -555,46 +584,49 @@ class SearchResultListSorterTest { val title2 = "ABC_EFG" val matchRange2 = getSimpleMatchRange(searchTerm, title2) - val searchResultListSorter = SearchResultListSorter( - DirSortBy.NONE_ON_TOP, - SortType(SortBy.RELEVANCE, SortOrder.ASC), - searchTerm - ) + val searchResultListSorter = + SearchResultListSorter( + DirSortBy.NONE_ON_TOP, + SortType(SortBy.RELEVANCE, SortOrder.ASC), + searchTerm, + ) val currentTime = Date().time - val file1 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - title1, - "C:\\AmazeFileManager\\abc.efg", - "user", - "symlink", - "100", - 123L, - true, - (currentTime - TimeUnit.MINUTES.toMillis(5)).toString(), - false, - false, - OpenMode.UNKNOWN - ).generateBaseFile() - val file2 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - title2, - "C:\\AmazeFileManager\\ABC_EFG", - "user", - "symlink", - "101", - 124L, - true, - (currentTime - TimeUnit.MINUTES.toMillis(10)).toString(), - false, - false, - OpenMode.UNKNOWN - ).generateBaseFile() + val file1 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + title1, + "C:\\AmazeFileManager\\abc.efg", + "user", + "symlink", + "100", + 123L, + true, + (currentTime - TimeUnit.MINUTES.toMillis(5)).toString(), + false, + false, + OpenMode.UNKNOWN, + ).generateBaseFile() + val file2 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + title2, + "C:\\AmazeFileManager\\ABC_EFG", + "user", + "symlink", + "101", + 124L, + true, + (currentTime - TimeUnit.MINUTES.toMillis(10)).toString(), + false, + false, + OpenMode.UNKNOWN, + ).generateBaseFile() Assert.assertEquals( -1, searchResultListSorter.compare( SearchResult(file1, matchRange1), - SearchResult(file2, matchRange2) - ).toLong() + SearchResult(file2, matchRange2), + ).toLong(), ) } @@ -617,46 +649,49 @@ class SearchResultListSorterTest { val title2 = "ABC_EFG" val matchRange2 = getSimpleMatchRange(searchTerm, title2) - val searchResultListSorter = SearchResultListSorter( - DirSortBy.NONE_ON_TOP, - SortType(SortBy.RELEVANCE, SortOrder.ASC), - searchTerm - ) + val searchResultListSorter = + SearchResultListSorter( + DirSortBy.NONE_ON_TOP, + SortType(SortBy.RELEVANCE, SortOrder.ASC), + searchTerm, + ) val currentTime = Date().time - val file1 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - title1, - "C:\\AmazeFileManager\\abc.efg", - "user", - "symlink", - "100", - 123L, - true, - (currentTime - TimeUnit.MINUTES.toMillis(10)).toString(), - false, - false, - OpenMode.UNKNOWN - ).generateBaseFile() - val file2 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - title2, - "C:\\AmazeFileManager\\ABC_EFG", - "user", - "symlink", - "101", - 124L, - true, - (currentTime - TimeUnit.MINUTES.toMillis(5)).toString(), - false, - false, - OpenMode.UNKNOWN - ).generateBaseFile() + val file1 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + title1, + "C:\\AmazeFileManager\\abc.efg", + "user", + "symlink", + "100", + 123L, + true, + (currentTime - TimeUnit.MINUTES.toMillis(10)).toString(), + false, + false, + OpenMode.UNKNOWN, + ).generateBaseFile() + val file2 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + title2, + "C:\\AmazeFileManager\\ABC_EFG", + "user", + "symlink", + "101", + 124L, + true, + (currentTime - TimeUnit.MINUTES.toMillis(5)).toString(), + false, + false, + OpenMode.UNKNOWN, + ).generateBaseFile() Assert.assertEquals( 1, searchResultListSorter.compare( SearchResult(file1, matchRange1), - SearchResult(file2, matchRange2) - ).toLong() + SearchResult(file2, matchRange2), + ).toLong(), ) } @@ -679,45 +714,48 @@ class SearchResultListSorterTest { val title2 = "ABC_EFG" val matchRange2 = getSimpleMatchRange(searchTerm, title2) - val searchResultListSorter = SearchResultListSorter( - DirSortBy.NONE_ON_TOP, - SortType(SortBy.RELEVANCE, SortOrder.ASC), - searchTerm - ) - val file1 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - title1, - "C:\\AmazeFileManager\\abc.efg", - "user", - "symlink", - "100", - 123L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ).generateBaseFile() - val file2 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - title2, - "C:\\AmazeFileManager\\ABC_EFG", - "user", - "symlink", - "101", - 124L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ).generateBaseFile() + val searchResultListSorter = + SearchResultListSorter( + DirSortBy.NONE_ON_TOP, + SortType(SortBy.RELEVANCE, SortOrder.ASC), + searchTerm, + ) + val file1 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + title1, + "C:\\AmazeFileManager\\abc.efg", + "user", + "symlink", + "100", + 123L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ).generateBaseFile() + val file2 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + title2, + "C:\\AmazeFileManager\\ABC_EFG", + "user", + "symlink", + "101", + 124L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ).generateBaseFile() Assert.assertEquals( 0, searchResultListSorter.compare( SearchResult(file1, matchRange1), - SearchResult(file2, matchRange2) - ).toLong() + SearchResult(file2, matchRange2), + ).toLong(), ) } @@ -740,55 +778,58 @@ class SearchResultListSorterTest { val title2 = "EFGABC" val matchRange2 = getSimpleMatchRange(searchTerm, title2) - val searchResultListSorter = SearchResultListSorter( - DirSortBy.NONE_ON_TOP, - SortType(SortBy.RELEVANCE, SortOrder.ASC), - "abc" - ) + val searchResultListSorter = + SearchResultListSorter( + DirSortBy.NONE_ON_TOP, + SortType(SortBy.RELEVANCE, SortOrder.ASC), + "abc", + ) val currentTime = Date().time // matches 3/10 // starts with search term // contains search as whole word // modification time is less recent - val file1 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - title1, - "C:\\AmazeFileManager\\abc.efghij", - "user", - "symlink", - "100", - 123L, - true, - (currentTime - TimeUnit.MINUTES.toMillis(10)).toString(), - false, - false, - OpenMode.UNKNOWN - ).generateBaseFile() + val file1 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + title1, + "C:\\AmazeFileManager\\abc.efghij", + "user", + "symlink", + "100", + 123L, + true, + (currentTime - TimeUnit.MINUTES.toMillis(10)).toString(), + false, + false, + OpenMode.UNKNOWN, + ).generateBaseFile() // matches 3/6 // doesn't start with search term // doesn't contain as whole word // modification time is more recent - val file2 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - title2, - "C:\\AmazeFileManager\\EFGABC", - "user", - "symlink", - "101", - 124L, - true, - (currentTime - TimeUnit.MINUTES.toMillis(5)).toString(), - false, - false, - OpenMode.UNKNOWN - ).generateBaseFile() + val file2 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + title2, + "C:\\AmazeFileManager\\EFGABC", + "user", + "symlink", + "101", + 124L, + true, + (currentTime - TimeUnit.MINUTES.toMillis(5)).toString(), + false, + false, + OpenMode.UNKNOWN, + ).generateBaseFile() Assert.assertEquals( -1, searchResultListSorter.compare( SearchResult(file1, matchRange1), - SearchResult(file2, matchRange2) - ).toLong() + SearchResult(file2, matchRange2), + ).toLong(), ) } } diff --git a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/ssh/PemToKeyPairObservableEd25519Test.kt b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/ssh/PemToKeyPairObservableEd25519Test.kt index 748e4e3732..845ae38282 100644 --- a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/ssh/PemToKeyPairObservableEd25519Test.kt +++ b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/ssh/PemToKeyPairObservableEd25519Test.kt @@ -44,10 +44,9 @@ import org.robolectric.annotation.Config @RunWith(AndroidJUnit4::class) @Config( shadows = [ShadowMultiDex::class, ShadowTabHandler::class], - sdk = [KITKAT, P, VERSION_CODES.R] + sdk = [KITKAT, P, VERSION_CODES.R], ) class PemToKeyPairObservableEd25519Test { - companion object { // public key for authorized_keys: ssh-ed25519 // AAAAC3NzaC1lZDI1NTE5AAAAIGxJHFewxU9tJn9hUq9e2C/+ELFw83NpmJ5NLFOzU7O3 test-openssh-key @@ -59,7 +58,7 @@ class PemToKeyPairObservableEd25519Test { "AAAECjSjwwMXPzbZWq/EBoA4HA9Lr7B1/Tw78K+k1zqAJwA2xJHFewxU9tJn9hUq9e2C/+\n" + "ELFw83NpmJ5NLFOzU7O3AAAADmFpcndhdmVAaHN2MDEwAQIDBAUGBw==\n" + "-----END OPENSSH PRIVATE KEY-----" - ) + ) // Passphrase = 12345678 // public key for authorized_keys: ssh-ed25519 @@ -73,7 +72,7 @@ class PemToKeyPairObservableEd25519Test { "wrHcd/Z92eQ0E7NV6b6LnghGYlyCjpSBW+mxa0AAYPD21c95d/HvJF6zxQl/IKCCLdOrr/\n" + "ilMCSIGQEdg71hA3MMZsRbUvazsnZTZXD9PLI=\n" + "-----END OPENSSH PRIVATE KEY-----" - ) + ) } /** @@ -107,15 +106,16 @@ class PemToKeyPairObservableEd25519Test { val task = PemToKeyPairObservable(encryptedOpenSshKey) val field = PemToKeyPairObservable::class.java.getDeclaredField("passwordFinder") field.isAccessible = true - field[task] = object : PasswordFinder { - override fun reqPassword(resource: Resource<*>?): CharArray { - return "12345678".toCharArray() - } + field[task] = + object : PasswordFinder { + override fun reqPassword(resource: Resource<*>?): CharArray { + return "12345678".toCharArray() + } - override fun shouldRetry(resource: Resource<*>?): Boolean { - return false + override fun shouldRetry(resource: Resource<*>?): Boolean { + return false + } } - } val result = Observable.create(task).subscribeOn(Schedulers.single()).blockingFirst() Assert.assertNotNull(result) Assert.assertNotNull(result.public) diff --git a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/ssh/PemToKeyPairObservableRsaTest.kt b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/ssh/PemToKeyPairObservableRsaTest.kt index dac149d755..84a21ab6b4 100644 --- a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/ssh/PemToKeyPairObservableRsaTest.kt +++ b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/ssh/PemToKeyPairObservableRsaTest.kt @@ -64,10 +64,9 @@ import java.util.concurrent.TimeUnit @RunWith(AndroidJUnit4::class) @Config( shadows = [ShadowMultiDex::class, ShadowTabHandler::class], - sdk = [KITKAT, P, VERSION_CODES.R] + sdk = [KITKAT, P, VERSION_CODES.R], ) class PemToKeyPairObservableRsaTest { - companion object { private const val unencryptedPuttyKey = ( "PuTTY-User-Key-File-2: ssh-rsa\n" + @@ -96,7 +95,7 @@ class PemToKeyPairObservableRsaTest { "THdPSgA2f6EmqCOPR1VAA4jdQkK8VkN3/O3zWFdfRGqN5Kka7a7cmcyd93sq3LIU\n" + "EYe4EYW7BQwe1W5ZCO+lRzjquGAB5rMhdAnzYfvkPc7sfJ8=\n" + "Private-MAC: 2cd5ec740c5dd854e8a6bea3773f98697670bdc6" - ) + ) // Passphrase = test private const val encryptedPuttyKey = ( @@ -126,7 +125,7 @@ class PemToKeyPairObservableRsaTest { "Gs4agAG3InJnMiuIOzaNOIFLGM9STtYNyvG411rj6tR4EEQ6cJCxIlVe5a1mEt7M\n" + "GVfbB5wUvow0o0a56OBmFMZOCxV2Vpxu6PuGTD8QQ0O0YzNDWFk3Fj2RRnnLCBLF\n" + "Private-MAC: f742e2954fbb0c98984db0d9855a0f15507ecc0a" - ) + ) } private lateinit var scenario: ActivityScenario @@ -173,10 +172,12 @@ class PemToKeyPairObservableRsaTest { val task = PemToKeyPairObservable(encryptedPuttyKey) val field = PemToKeyPairObservable::class.java.getDeclaredField("passwordFinder") field.isAccessible = true - field[task] = object : PasswordFinder { - override fun reqPassword(resource: Resource<*>): CharArray = "test".toCharArray() - override fun shouldRetry(resource: Resource<*>): Boolean = false - } + field[task] = + object : PasswordFinder { + override fun reqPassword(resource: Resource<*>): CharArray = "test".toCharArray() + + override fun shouldRetry(resource: Resource<*>): Boolean = false + } val result = Observable.create(task).subscribeOn(Schedulers.single()).blockingFirst() assertNotNull(result) assertNotNull(result?.public) @@ -194,10 +195,12 @@ class PemToKeyPairObservableRsaTest { val field = PemToKeyPairObservable::class.java.getDeclaredField("passwordFinder") var result: KeyPair? = null field.isAccessible = true - field[task] = object : PasswordFinder { - override fun reqPassword(resource: Resource<*>): CharArray = "foobar".toCharArray() - override fun shouldRetry(resource: Resource<*>): Boolean = false - } + field[task] = + object : PasswordFinder { + override fun reqPassword(resource: Resource<*>): CharArray = "foobar".toCharArray() + + override fun shouldRetry(resource: Resource<*>): Boolean = false + } Observable.create(task).subscribeOn(Schedulers.io()) .retryWhen { exceptions -> exceptions.flatMap { exception -> @@ -228,7 +231,7 @@ class PemToKeyPairObservableRsaTest { (ShadowDialog.getLatestDialog() as MaterialDialog).let { dialog -> assertEquals( AppConfig.getInstance().resources.getText(R.string.ssh_key_prompt_passphrase), - dialog.titleView.text + dialog.titleView.text, ) dialog.customView?.run { lap++ @@ -273,7 +276,7 @@ class PemToKeyPairObservableRsaTest { (ShadowDialog.getLatestDialog() as MaterialDialog).let { dialog -> assertEquals( AppConfig.getInstance().resources.getText(R.string.ssh_key_prompt_passphrase), - dialog.titleView.text + dialog.titleView.text, ) dialog.getActionButton(DialogAction.NEGATIVE).performClick() } @@ -284,10 +287,10 @@ class PemToKeyPairObservableRsaTest { AppConfig.getInstance().resources.getString( R.string.ssh_pem_key_parse_error, AppConfig.getInstance().resources.getString( - R.string.ssh_key_no_decoder_decrypt - ) + R.string.ssh_key_no_decoder_decrypt, + ), ), - ShadowToast.getTextOfLatestToast() + ShadowToast.getTextOfLatestToast(), ) } } diff --git a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/ssh/SshAuthenticationTaskTest.kt b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/ssh/SshAuthenticationTaskTest.kt index 5f7f0cfc8e..eb2b972aa8 100644 --- a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/ssh/SshAuthenticationTaskTest.kt +++ b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/ssh/SshAuthenticationTaskTest.kt @@ -66,11 +66,10 @@ import java.util.concurrent.CountDownLatch @RunWith(AndroidJUnit4::class) @Config( shadows = [ShadowMultiDex::class, ShadowPasswordUtil::class], - sdk = [KITKAT, P, Build.VERSION_CODES.R] + sdk = [KITKAT, P, Build.VERSION_CODES.R], ) @Suppress("StringLiteralDuplication") class SshAuthenticationTaskTest { - /** * Test setup */ @@ -87,22 +86,24 @@ class SshAuthenticationTaskTest { */ @Test fun testAuthenticationUsernamePasswordSuccess() { - val sshClient = mock(SSHClient::class.java).apply { - doNothing().`when`(this).addHostKeyVerifier(anyString()) - doNothing().`when`(this).connect(anyString(), anyInt()) - doNothing().`when`(this).authPassword(anyString(), anyString()) - doNothing().`when`(this).disconnect() - `when`(isConnected).thenReturn(true) - `when`(isAuthenticated).thenReturn(true) - } + val sshClient = + mock(SSHClient::class.java).apply { + doNothing().`when`(this).addHostKeyVerifier(anyString()) + doNothing().`when`(this).connect(anyString(), anyInt()) + doNothing().`when`(this).authPassword(anyString(), anyString()) + doNothing().`when`(this).disconnect() + `when`(isConnected).thenReturn(true) + `when`(isAuthenticated).thenReturn(true) + } prepareSshConnectionPool(sshClient) - val task = SshAuthenticationTask( - hostKey = "", - hostname = "127.0.0.1", - port = 22222, - username = "user", - password = PasswordUtil.encryptPassword(AppConfig.getInstance(), "password") - ) + val task = + SshAuthenticationTask( + hostKey = "", + hostname = "127.0.0.1", + port = 22222, + username = "user", + password = PasswordUtil.encryptPassword(AppConfig.getInstance(), "password"), + ) val latch = CountDownLatch(1) var e: Throwable? = null var result: SSHClient? = null @@ -130,23 +131,25 @@ class SshAuthenticationTaskTest { */ @Test fun testAuthenticationUsernamePasswordFail() { - val sshClient = mock(SSHClient::class.java).apply { - doNothing().`when`(this).addHostKeyVerifier(anyString()) - doNothing().`when`(this).connect(anyString(), anyInt()) - doThrow(UserAuthException(DisconnectReason.NO_MORE_AUTH_METHODS_AVAILABLE)) - .`when`(this).authPassword(anyString(), anyString()) - doNothing().`when`(this).disconnect() - `when`(isConnected).thenReturn(true) - `when`(isAuthenticated).thenReturn(true) - } + val sshClient = + mock(SSHClient::class.java).apply { + doNothing().`when`(this).addHostKeyVerifier(anyString()) + doNothing().`when`(this).connect(anyString(), anyInt()) + doThrow(UserAuthException(DisconnectReason.NO_MORE_AUTH_METHODS_AVAILABLE)) + .`when`(this).authPassword(anyString(), anyString()) + doNothing().`when`(this).disconnect() + `when`(isConnected).thenReturn(true) + `when`(isAuthenticated).thenReturn(true) + } prepareSshConnectionPool(sshClient) - val task = SshAuthenticationTask( - hostKey = "", - hostname = "127.0.0.1", - port = 22222, - username = "user", - password = "password" - ) + val task = + SshAuthenticationTask( + hostKey = "", + hostname = "127.0.0.1", + port = 22222, + username = "user", + password = "password", + ) val latch = CountDownLatch(1) var e: Throwable? = null var result: SSHClient? = null @@ -170,7 +173,7 @@ class SshAuthenticationTaskTest { ApplicationProvider .getApplicationContext() .getString(R.string.ssh_authentication_failure_password), - ShadowToast.getTextOfLatestToast() + ShadowToast.getTextOfLatestToast(), ) } @@ -180,22 +183,24 @@ class SshAuthenticationTaskTest { @Test fun testAuthenticationKeyPairSuccess() { val keyProvider = TestKeyProvider() - val sshClient = mock(SSHClient::class.java).apply { - doNothing().`when`(this).addHostKeyVerifier(anyString()) - doNothing().`when`(this).connect(anyString(), anyInt()) - doNothing().`when`(this).authPublickey(anyString(), eq(keyProvider)) - doNothing().`when`(this).disconnect() - `when`(isConnected).thenReturn(true) - `when`(isAuthenticated).thenReturn(true) - } + val sshClient = + mock(SSHClient::class.java).apply { + doNothing().`when`(this).addHostKeyVerifier(anyString()) + doNothing().`when`(this).connect(anyString(), anyInt()) + doNothing().`when`(this).authPublickey(anyString(), eq(keyProvider)) + doNothing().`when`(this).disconnect() + `when`(isConnected).thenReturn(true) + `when`(isAuthenticated).thenReturn(true) + } prepareSshConnectionPool(sshClient) - val task = SshAuthenticationTask( - hostKey = "", - hostname = "127.0.0.1", - port = 22222, - username = "user", - privateKey = keyProvider.keyPair - ) + val task = + SshAuthenticationTask( + hostKey = "", + hostname = "127.0.0.1", + port = 22222, + username = "user", + privateKey = keyProvider.keyPair, + ) val latch = CountDownLatch(1) var e: Throwable? = null var result: SSHClient? = null @@ -223,24 +228,26 @@ class SshAuthenticationTaskTest { @Test fun testAuthenticationKeyPairFail() { val keyProvider = TestKeyProvider() - val sshClient = mock(SSHClient::class.java).apply { - doNothing().`when`(this).addHostKeyVerifier(anyString()) - doNothing().`when`(this).connect(anyString(), anyInt()) - doThrow( - UserAuthException(DisconnectReason.KEY_EXCHANGE_FAILED) - ).`when`(this).authPublickey(anyString(), any()) - doNothing().`when`(this).disconnect() - `when`(isConnected).thenReturn(true) - `when`(isAuthenticated).thenReturn(true) - } + val sshClient = + mock(SSHClient::class.java).apply { + doNothing().`when`(this).addHostKeyVerifier(anyString()) + doNothing().`when`(this).connect(anyString(), anyInt()) + doThrow( + UserAuthException(DisconnectReason.KEY_EXCHANGE_FAILED), + ).`when`(this).authPublickey(anyString(), any()) + doNothing().`when`(this).disconnect() + `when`(isConnected).thenReturn(true) + `when`(isAuthenticated).thenReturn(true) + } prepareSshConnectionPool(sshClient) - val task = SshAuthenticationTask( - hostKey = "", - hostname = "127.0.0.1", - port = 22222, - username = "user", - privateKey = keyProvider.keyPair - ) + val task = + SshAuthenticationTask( + hostKey = "", + hostname = "127.0.0.1", + port = 22222, + username = "user", + privateKey = keyProvider.keyPair, + ) val latch = CountDownLatch(1) var e: Throwable? = null var result: SSHClient? = null @@ -264,7 +271,7 @@ class SshAuthenticationTaskTest { ApplicationProvider .getApplicationContext() .getString(R.string.ssh_authentication_failure_key), - ShadowToast.getTextOfLatestToast() + ShadowToast.getTextOfLatestToast(), ) } @@ -273,24 +280,26 @@ class SshAuthenticationTaskTest { */ @Test fun testConnectionTimeout() { - val sshClient = mock(SSHClient::class.java).apply { - doNothing().`when`(this).addHostKeyVerifier(anyString()) - doThrow( - SocketException("Connection timeout") - ).`when`(this).connect(anyString(), anyInt()) - doNothing().`when`(this).authPassword(anyString(), anyString()) - doNothing().`when`(this).disconnect() - `when`(isConnected).thenReturn(true) - `when`(isAuthenticated).thenReturn(true) - } + val sshClient = + mock(SSHClient::class.java).apply { + doNothing().`when`(this).addHostKeyVerifier(anyString()) + doThrow( + SocketException("Connection timeout"), + ).`when`(this).connect(anyString(), anyInt()) + doNothing().`when`(this).authPassword(anyString(), anyString()) + doNothing().`when`(this).disconnect() + `when`(isConnected).thenReturn(true) + `when`(isAuthenticated).thenReturn(true) + } prepareSshConnectionPool(sshClient) - val task = SshAuthenticationTask( - hostKey = "", - hostname = "127.0.0.1", - port = 22222, - username = "user", - password = PasswordUtil.encryptPassword(AppConfig.getInstance(), "password") - ) + val task = + SshAuthenticationTask( + hostKey = "", + hostname = "127.0.0.1", + port = 22222, + username = "user", + password = PasswordUtil.encryptPassword(AppConfig.getInstance(), "password"), + ) val latch = CountDownLatch(1) var e: Throwable? = null var result: SSHClient? = null @@ -316,9 +325,9 @@ class SshAuthenticationTaskTest { R.string.ssh_connect_failed, "127.0.0.1", 22222, - "Connection timeout" + "Connection timeout", ), - ShadowToast.getTextOfLatestToast() + ShadowToast.getTextOfLatestToast(), ) } @@ -333,14 +342,15 @@ class SshAuthenticationTaskTest { this.set( NetCopyClientConnectionPool, mutableMapOf( - Pair("ssh://user:password@127.0.0.1:22222", sshClient) - ) + Pair("ssh://user:password@127.0.0.1:22222", sshClient), + ), ) } - NetCopyClientConnectionPool.sshClientFactory = object : - NetCopyClientConnectionPool.SSHClientFactory { - override fun create(config: net.schmizz.sshj.Config): SSHClient = sshClient - } + NetCopyClientConnectionPool.sshClientFactory = + object : + NetCopyClientConnectionPool.SSHClientFactory { + override fun create(config: net.schmizz.sshj.Config): SSHClient = sshClient + } } } diff --git a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/texteditor/read/ReadTextFileCallableTest.kt b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/texteditor/read/ReadTextFileCallableTest.kt index b4805a0ce4..ba2f6e8aa5 100644 --- a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/texteditor/read/ReadTextFileCallableTest.kt +++ b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/texteditor/read/ReadTextFileCallableTest.kt @@ -46,10 +46,9 @@ import kotlin.random.Random @RunWith(AndroidJUnit4::class) @Config( shadows = [ShadowMultiDex::class], - sdk = [KITKAT, P, Build.VERSION_CODES.R] + sdk = [KITKAT, P, Build.VERSION_CODES.R], ) class ReadTextFileCallableTest { - /** * Test read an empty file with [ReadTextFileCallable] */ @@ -57,7 +56,7 @@ class ReadTextFileCallableTest { @Throws( ShellNotRunningException::class, IOException::class, - StreamNotFoundException::class + StreamNotFoundException::class, ) fun testReadEmptyFile() { val uri = generatePath() @@ -65,16 +64,17 @@ class ReadTextFileCallableTest { val cr = ctx.contentResolver val input = ByteArrayInputStream("".toByteArray()) Shadows.shadowOf(cr).registerInputStream(uri, input) - val task = ReadTextFileCallable( - cr, - EditableFileAbstraction(ctx, uri), - null, - false - ) + val task = + ReadTextFileCallable( + cr, + EditableFileAbstraction(ctx, uri), + null, + false, + ) val result = task.call() Assert.assertEquals( result, - ReturnedValueOnReadFile("", null, false) + ReturnedValueOnReadFile("", null, false), ) } @@ -85,7 +85,7 @@ class ReadTextFileCallableTest { @Throws( ShellNotRunningException::class, IOException::class, - StreamNotFoundException::class + StreamNotFoundException::class, ) fun testReadNormalFile() { val random = Random(123) @@ -98,16 +98,17 @@ class ReadTextFileCallableTest { val cr = ctx.contentResolver val input = ByteArrayInputStream(fileContents.toByteArray()) Shadows.shadowOf(cr).registerInputStream(uri, input) - val task = ReadTextFileCallable( - cr, - EditableFileAbstraction(ctx, uri), - null, - false - ) + val task = + ReadTextFileCallable( + cr, + EditableFileAbstraction(ctx, uri), + null, + false, + ) val result = task.call() Assert.assertEquals( result, - ReturnedValueOnReadFile(fileContents, null, false) + ReturnedValueOnReadFile(fileContents, null, false), ) } @@ -118,7 +119,7 @@ class ReadTextFileCallableTest { @Throws( ShellNotRunningException::class, IOException::class, - StreamNotFoundException::class + StreamNotFoundException::class, ) fun testReadBigFile() { val random = Random(123) @@ -131,16 +132,17 @@ class ReadTextFileCallableTest { val cr = ctx.contentResolver val input = ByteArrayInputStream(fileContents.toByteArray()) Shadows.shadowOf(cr).registerInputStream(uri, input) - val task = ReadTextFileCallable( - cr, - EditableFileAbstraction(ctx, uri), - null, - false - ) + val task = + ReadTextFileCallable( + cr, + EditableFileAbstraction(ctx, uri), + null, + false, + ) val result = task.call() Assert.assertEquals( result, - ReturnedValueOnReadFile(fileContents.substring(0, MAX_FILE_SIZE_CHARS), null, true) + ReturnedValueOnReadFile(fileContents.substring(0, MAX_FILE_SIZE_CHARS), null, true), ) } diff --git a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/texteditor/write/WriteTextFileCallableTest.java b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/texteditor/write/WriteTextFileCallableTest.java index ca7e6d6b6d..75fc954662 100644 --- a/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/texteditor/write/WriteTextFileCallableTest.java +++ b/app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/texteditor/write/WriteTextFileCallableTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/test/java/com/amaze/filemanager/asynchronous/services/DecryptServiceTest.kt b/app/src/test/java/com/amaze/filemanager/asynchronous/services/DecryptServiceTest.kt index 3d3bff1c76..d4cfdc8c2b 100644 --- a/app/src/test/java/com/amaze/filemanager/asynchronous/services/DecryptServiceTest.kt +++ b/app/src/test/java/com/amaze/filemanager/asynchronous/services/DecryptServiceTest.kt @@ -67,7 +67,6 @@ import kotlin.random.Random @Config(shadows = [ShadowMultiDex::class], sdk = [KITKAT, P, Build.VERSION_CODES.R]) @Suppress("StringLiteralDuplication") class DecryptServiceTest { - private lateinit var source: ByteArray private lateinit var service: DecryptService private lateinit var notificationManager: ShadowNotificationManager @@ -79,10 +78,11 @@ class DecryptServiceTest { fun setUp() { source = Random(System.currentTimeMillis()).nextBytes(73) service = Robolectric.setupService(DecryptService::class.java) - notificationManager = shadowOf( - ApplicationProvider.getApplicationContext() - .getSystemService(NOTIFICATION_SERVICE) as NotificationManager - ) + notificationManager = + shadowOf( + ApplicationProvider.getApplicationContext() + .getSystemService(NOTIFICATION_SERVICE) as NotificationManager, + ) initMockSecretKeygen() } @@ -111,12 +111,13 @@ class DecryptServiceTest { ArrayList(), "test.bin${CryptUtil.CRYPT_EXTENSION}", false, - null - ) - val targetFile = File( - Environment.getExternalStorageDirectory(), - "test.bin${CryptUtil.CRYPT_EXTENSION}" + null, ) + val targetFile = + File( + Environment.getExternalStorageDirectory(), + "test.bin${CryptUtil.CRYPT_EXTENSION}", + ) assertTrue(targetFile.exists()) sourceFile.delete() @@ -126,7 +127,7 @@ class DecryptServiceTest { TAG_SOURCE, HybridFileParcelable(targetFile.absolutePath).also { it.setSize(targetFile.length()) - } + }, ) putExtra(TAG_DECRYPT_PATH, Environment.getExternalStorageDirectory().absolutePath) assertEquals(START_NOT_STICKY, service.onStartCommand(this, 0, 0)) @@ -165,15 +166,16 @@ class DecryptServiceTest { @Test fun testAescryptWorkflow() { if (SDK_INT >= M) { - val sourceFile = File( - Environment.getExternalStorageDirectory(), - "test.bin${CryptUtil.AESCRYPT_EXTENSION}" - ) + val sourceFile = + File( + Environment.getExternalStorageDirectory(), + "test.bin${CryptUtil.AESCRYPT_EXTENSION}", + ) val targetFile = File(Environment.getExternalStorageDirectory(), "test.bin") AESCrypt("passW0rD").encrypt( `in` = ByteArrayInputStream(source), out = FileOutputStream(sourceFile), - progressHandler = ProgressHandler() + progressHandler = ProgressHandler(), ) await().atMost(10, TimeUnit.SECONDS).until { sourceFile.length() > source.size @@ -184,7 +186,7 @@ class DecryptServiceTest { TAG_SOURCE, HybridFileParcelable(sourceFile.absolutePath).also { it.setSize(sourceFile.length()) - } + }, ) putExtra(TAG_DECRYPT_PATH, Environment.getExternalStorageDirectory().absolutePath) putExtra(TAG_PASSWORD, "passW0rD") diff --git a/app/src/test/java/com/amaze/filemanager/asynchronous/services/EncryptServiceTest.kt b/app/src/test/java/com/amaze/filemanager/asynchronous/services/EncryptServiceTest.kt index bbf62280f7..2bac482d89 100644 --- a/app/src/test/java/com/amaze/filemanager/asynchronous/services/EncryptServiceTest.kt +++ b/app/src/test/java/com/amaze/filemanager/asynchronous/services/EncryptServiceTest.kt @@ -70,7 +70,6 @@ import kotlin.random.Random @RunWith(AndroidJUnit4::class) @Config(shadows = [ShadowMultiDex::class], sdk = [KITKAT, P, Build.VERSION_CODES.R]) class EncryptServiceTest { - private lateinit var service: EncryptService private lateinit var notificationManager: ShadowNotificationManager private lateinit var source: ByteArray @@ -84,10 +83,11 @@ class EncryptServiceTest { @Before fun setUp() { service = Robolectric.setupService(EncryptService::class.java) - notificationManager = shadowOf( - ApplicationProvider.getApplicationContext() - .getSystemService(NOTIFICATION_SERVICE) as NotificationManager - ) + notificationManager = + shadowOf( + ApplicationProvider.getApplicationContext() + .getSystemService(NOTIFICATION_SERVICE) as NotificationManager, + ) source = Random(System.currentTimeMillis()).nextBytes(73) sourceFile = File(Environment.getExternalStorageDirectory(), "test.bin") ByteArrayInputStream(source).copyTo(FileOutputStream(sourceFile)) @@ -141,7 +141,7 @@ class EncryptServiceTest { Environment.getExternalStorageDirectory().absolutePath, ProgressHandler(), ArrayList(), - null + null, ) val verifyFile = File(Environment.getExternalStorageDirectory(), "test.bin") await().atMost(10, TimeUnit.SECONDS).until { @@ -181,9 +181,9 @@ class EncryptServiceTest { source.contentEquals( File( Environment.getExternalStorageDirectory(), - targetFilename - ).readBytes() - ) + targetFilename, + ).readBytes(), + ), ) val verify = ByteArrayOutputStream() AESCrypt("passW0rD").decrypt(targetFile.length(), FileInputStream(targetFile), verify) diff --git a/app/src/test/java/com/amaze/filemanager/asynchronous/services/ExtractServiceTest.kt b/app/src/test/java/com/amaze/filemanager/asynchronous/services/ExtractServiceTest.kt index 8765894503..fe071ccc28 100644 --- a/app/src/test/java/com/amaze/filemanager/asynchronous/services/ExtractServiceTest.kt +++ b/app/src/test/java/com/amaze/filemanager/asynchronous/services/ExtractServiceTest.kt @@ -75,7 +75,6 @@ import java.util.concurrent.TimeUnit @LooperMode(LooperMode.Mode.PAUSED) @Suppress("TooManyFunctions", "StringLiteralDuplication") class ExtractServiceTest { - private val zipfile1: File private val zipfile2: File private val zipfile3: File @@ -101,8 +100,9 @@ class ExtractServiceTest { @Rule @JvmField @RequiresApi(VERSION_CODES.R) - val allFilesPermissionRule = GrantPermissionRule - .grant(Manifest.permission.MANAGE_EXTERNAL_STORAGE) + val allFilesPermissionRule = + GrantPermissionRule + .grant(Manifest.permission.MANAGE_EXTERNAL_STORAGE) init { Environment.getExternalStorageDirectory().run { @@ -217,7 +217,7 @@ class ExtractServiceTest { assertEquals( ApplicationProvider.getApplicationContext() .getString(R.string.multiple_invalid_archive_entries), - ShadowToast.getTextOfLatestToast() + ShadowToast.getTextOfLatestToast(), ) } @@ -232,7 +232,7 @@ class ExtractServiceTest { assertEquals( ApplicationProvider.getApplicationContext() .getString(R.string.multiple_invalid_archive_entries), - ShadowToast.getTextOfLatestToast() + ShadowToast.getTextOfLatestToast(), ) } @@ -437,10 +437,11 @@ class ExtractServiceTest { private fun doTestBadArchive(data: ByteArray) { for (archiveType in supportedArchiveExtensions()) { - val badArchive = File( - Environment.getExternalStorageDirectory(), - "bad-archive.$archiveType" - ) + val badArchive = + File( + Environment.getExternalStorageDirectory(), + "bad-archive.$archiveType", + ) ByteArrayInputStream(data).copyTo(FileOutputStream(badArchive)) performTest(badArchive) ShadowLooper.idleMainLooper() @@ -468,7 +469,7 @@ class ExtractServiceTest { .putExtra( ExtractService.KEY_PATH_EXTRACT, File(Environment.getExternalStorageDirectory(), "test-archive") - .absolutePath + .absolutePath, ) service.onStartCommand(intent, 0, 0) } diff --git a/app/src/test/java/com/amaze/filemanager/asynchronous/services/FtpServiceAndroidFileSystemIntegrationTest.kt b/app/src/test/java/com/amaze/filemanager/asynchronous/services/FtpServiceAndroidFileSystemIntegrationTest.kt index 1b728a2ff8..4c212a026e 100644 --- a/app/src/test/java/com/amaze/filemanager/asynchronous/services/FtpServiceAndroidFileSystemIntegrationTest.kt +++ b/app/src/test/java/com/amaze/filemanager/asynchronous/services/FtpServiceAndroidFileSystemIntegrationTest.kt @@ -66,7 +66,6 @@ import kotlin.random.Random @LooperMode(LooperMode.Mode.PAUSED) @Suppress("StringLiteralDuplication") class FtpServiceAndroidFileSystemIntegrationTest { - private val FTP_PORT = 62222 private var server: FtpServer? = null @@ -76,21 +75,21 @@ class FtpServiceAndroidFileSystemIntegrationTest { private var ftpClient: FTPClient? = null companion object { - - val directories = arrayOf( - Environment.DIRECTORY_MUSIC, - Environment.DIRECTORY_PODCASTS, - Environment.DIRECTORY_RINGTONES, - Environment.DIRECTORY_ALARMS, - Environment.DIRECTORY_NOTIFICATIONS, - Environment.DIRECTORY_PICTURES, - Environment.DIRECTORY_MOVIES, - Environment.DIRECTORY_DOWNLOADS, - Environment.DIRECTORY_DCIM, - Environment.DIRECTORY_DOCUMENTS, - "1/2/3/4/5/6/7", - "lost+found" - ) + val directories = + arrayOf( + Environment.DIRECTORY_MUSIC, + Environment.DIRECTORY_PODCASTS, + Environment.DIRECTORY_RINGTONES, + Environment.DIRECTORY_ALARMS, + Environment.DIRECTORY_NOTIFICATIONS, + Environment.DIRECTORY_PICTURES, + Environment.DIRECTORY_MOVIES, + Environment.DIRECTORY_DOWNLOADS, + Environment.DIRECTORY_DCIM, + Environment.DIRECTORY_DOCUMENTS, + "1/2/3/4/5/6/7", + "lost+found", + ) } /** @@ -109,7 +108,7 @@ class FtpServiceAndroidFileSystemIntegrationTest { .run { edit().putString( FtpService.KEY_PREFERENCE_PATH, - Environment.getExternalStorageDirectory().absolutePath + Environment.getExternalStorageDirectory().absolutePath, ) .apply() } @@ -129,62 +128,67 @@ class FtpServiceAndroidFileSystemIntegrationTest { connectionConfig = connectionConfigFactory.createConnectionConfig() userManager.save(user) - fileSystem = AndroidFileSystemFactory( - ApplicationProvider.getApplicationContext() - ) + fileSystem = + AndroidFileSystemFactory( + ApplicationProvider.getApplicationContext(), + ) addListener( "default", ListenerFactory().also { it.port = FTP_PORT - }.createListener() + }.createListener(), ) - server = createServer().apply { - start() - } + server = + createServer().apply { + start() + } } - ftpClient = FTPClient().also { - it.connect("127.0.0.1", FTP_PORT) - it.login("anonymous", "no@e.mail") - it.enterLocalPassiveMode() - } + ftpClient = + FTPClient().also { + it.connect("127.0.0.1", FTP_PORT) + it.login("anonymous", "no@e.mail") + it.enterLocalPassiveMode() + } } private fun setupNetwork() { - val cm = shadowOf( - ApplicationProvider.getApplicationContext() - .getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager - ) - val wifiManager = shadowOf( - ApplicationProvider.getApplicationContext() - .getSystemService(Context.WIFI_SERVICE) as WifiManager - ) + val cm = + shadowOf( + ApplicationProvider.getApplicationContext() + .getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager, + ) + val wifiManager = + shadowOf( + ApplicationProvider.getApplicationContext() + .getSystemService(Context.WIFI_SERVICE) as WifiManager, + ) cm.setActiveNetworkInfo( ShadowNetworkInfo.newInstance( NetworkInfo.DetailedState.CONNECTED, ConnectivityManager.TYPE_WIFI, -1, true, - NetworkInfo.State.CONNECTED - ) + NetworkInfo.State.CONNECTED, + ), ) ReflectionHelpers.callInstanceMethod( wifiManager, "setWifiEnabled", - ReflectionHelpers.ClassParameter.from(Boolean::class.java, true) + ReflectionHelpers.ClassParameter.from(Boolean::class.java, true), ) ReflectionHelpers.callInstanceMethod( wifiManager, - "getConnectionInfo" + "getConnectionInfo", ).run { ReflectionHelpers.callInstanceMethod( this, "setInetAddress", ReflectionHelpers.ClassParameter.from( InetAddress::class.java, - InetAddress.getLoopbackAddress() - ) + InetAddress.getLoopbackAddress(), + ), ) } } @@ -247,8 +251,8 @@ class FtpServiceAndroidFileSystemIntegrationTest { assertFalse( retrieveFile( "/barrier/nonexist.file.jpg", - FileOutputStream(File.createTempFile("notused", "output")) - ) + FileOutputStream(File.createTempFile("notused", "output")), + ), ) assertTrue(changeWorkingDirectory("/")) retrieveFileStream("test.bin").let { diff --git a/app/src/test/java/com/amaze/filemanager/asynchronous/services/FtpServiceSupportedCiphersTest.kt b/app/src/test/java/com/amaze/filemanager/asynchronous/services/FtpServiceSupportedCiphersTest.kt index 8b6bbc41ac..9ee4a56c3c 100644 --- a/app/src/test/java/com/amaze/filemanager/asynchronous/services/FtpServiceSupportedCiphersTest.kt +++ b/app/src/test/java/com/amaze/filemanager/asynchronous/services/FtpServiceSupportedCiphersTest.kt @@ -38,7 +38,6 @@ import org.robolectric.annotation.Config @RunWith(AndroidJUnit4::class) @Config(shadows = [ShadowMultiDex::class]) class FtpServiceSupportedCiphersTest { - /** * Check for enabled ciphers, to ensure no unsupported ciphers on the list. * diff --git a/app/src/test/java/com/amaze/filemanager/asynchronous/services/ZipServiceTest.kt b/app/src/test/java/com/amaze/filemanager/asynchronous/services/ZipServiceTest.kt index d77db736ca..a4bfd04153 100644 --- a/app/src/test/java/com/amaze/filemanager/asynchronous/services/ZipServiceTest.kt +++ b/app/src/test/java/com/amaze/filemanager/asynchronous/services/ZipServiceTest.kt @@ -59,27 +59,27 @@ import kotlin.random.Random @LooperMode(LooperMode.Mode.PAUSED) @Config(shadows = [ShadowMultiDex::class], sdk = [KITKAT, P, Build.VERSION_CODES.R]) class ZipServiceTest { - val dt = DateTimeFormatter.ofPattern("yyyyMMddkkmm") - val dates = listOf( - parse("201906121300", dt).atZone(of("Antarctica/South_Pole")), - parse("201906152100", dt).atZone(of("Asia/Taipei")), - parse("201906161530", dt).atZone(of("Australia/Adelaide")), - parse("201907020000", dt).atZone(of("Pacific/Norfolk")), - parse("201907211330", dt).atZone(of("Europe/Dublin")), - parse("201908180929", dt).atZone(of("Europe/Warsaw")), - parse("201908230700", dt).atZone(of("America/Indianapolis")), - parse("201908312330", dt).atZone(of("Asia/Tokyo")), - parse("201909191315", dt).atZone(of("Asia/Ho_Chi_Minh")), - parse("201910010700", dt).atZone(of("America/Havana")), - parse("201911080109", dt).atZone(of("Europe/Oslo")), - parse("201911111030", dt).atZone(of("Australia/North")), - parse("201911120300", dt).atZone(of("Asia/Gaza")), - parse("201911170400", dt).atZone(of("Europe/Kiev")), - parse("201912312300", dt).atZone(of("America/Ojinaga")), - parse("202006301900", dt).atZone(of("Africa/Nairobi")), - parse("202008230830", dt).atZone(of("Pacific/Guam")) - ) + val dates = + listOf( + parse("201906121300", dt).atZone(of("Antarctica/South_Pole")), + parse("201906152100", dt).atZone(of("Asia/Taipei")), + parse("201906161530", dt).atZone(of("Australia/Adelaide")), + parse("201907020000", dt).atZone(of("Pacific/Norfolk")), + parse("201907211330", dt).atZone(of("Europe/Dublin")), + parse("201908180929", dt).atZone(of("Europe/Warsaw")), + parse("201908230700", dt).atZone(of("America/Indianapolis")), + parse("201908312330", dt).atZone(of("Asia/Tokyo")), + parse("201909191315", dt).atZone(of("Asia/Ho_Chi_Minh")), + parse("201910010700", dt).atZone(of("America/Havana")), + parse("201911080109", dt).atZone(of("Europe/Oslo")), + parse("201911111030", dt).atZone(of("Australia/North")), + parse("201911120300", dt).atZone(of("Asia/Gaza")), + parse("201911170400", dt).atZone(of("Europe/Kiev")), + parse("201912312300", dt).atZone(of("America/Ojinaga")), + parse("202006301900", dt).atZone(of("Africa/Nairobi")), + parse("202008230830", dt).atZone(of("Pacific/Guam")), + ) var context: Context? = null @@ -99,13 +99,14 @@ class ZipServiceTest { val zipPath = File(context!!.getExternalFilesDir(null), "files.zip") val files = generateSomeRandomFiles() - val intent = Intent() - .setClass(context!!, ZipService::class.java) - .putParcelableArrayListExtra( - KEY_COMPRESS_FILES, - ArrayList(listOf(HybridFileParcelable(files[0].absolutePath))) - ) - .putExtra(KEY_COMPRESS_PATH, zipPath.absolutePath) + val intent = + Intent() + .setClass(context!!, ZipService::class.java) + .putParcelableArrayListExtra( + KEY_COMPRESS_FILES, + ArrayList(listOf(HybridFileParcelable(files[0].absolutePath))), + ) + .putExtra(KEY_COMPRESS_PATH, zipPath.absolutePath) Robolectric.buildService(ZipService::class.java, intent).bind().startCommand(0, 0) @@ -127,7 +128,7 @@ class ZipServiceTest { "${Date(this[idx].lastModified())} " + "vs ${Date(entry.lastModifiedTimeEpoch)}", this[idx].lastModified(), - entry.lastModifiedTimeEpoch + entry.lastModifiedTimeEpoch, ) } } @@ -150,10 +151,22 @@ class ZipServiceTest { } } } - File(root1, "a").apply { mkdirs(); files.add(this); } - File(root1, "a/b").apply { mkdirs(); files.add(this); } - File(root1, "a/b/c").apply { mkdirs(); files.add(this); } - File(root1, "a/b/c/d").apply { mkdirs(); files.add(this); } + File(root1, "a").apply { + mkdirs() + files.add(this) + } + File(root1, "a/b").apply { + mkdirs() + files.add(this) + } + File(root1, "a/b/c").apply { + mkdirs() + files.add(this) + } + File(root1, "a/b/c/d").apply { + mkdirs() + files.add(this) + } val root2 = File(root1, "a/b/c/d") for (x in 1..4) { @@ -168,12 +181,12 @@ class ZipServiceTest { run { Files.getFileAttributeView( Paths.get(files[index].absolutePath), - BasicFileAttributeView::class.java + BasicFileAttributeView::class.java, ) .setTimes( FileTime.from(zonedDateTime.toInstant()), FileTime.from(zonedDateTime.toInstant()), - null + null, ) } } diff --git a/app/src/test/java/com/amaze/filemanager/database/ExplorerDatabaseMigrationTest.kt b/app/src/test/java/com/amaze/filemanager/database/ExplorerDatabaseMigrationTest.kt index 37932fd892..f14726982f 100644 --- a/app/src/test/java/com/amaze/filemanager/database/ExplorerDatabaseMigrationTest.kt +++ b/app/src/test/java/com/amaze/filemanager/database/ExplorerDatabaseMigrationTest.kt @@ -44,18 +44,18 @@ import java.io.IOException @RunWith(AndroidJUnit4::class) @Config( shadows = [ShadowMultiDex::class, ShadowPasswordUtil::class], - sdk = [KITKAT, P, Build.VERSION_CODES.R] + sdk = [KITKAT, P, Build.VERSION_CODES.R], ) @Suppress("StringLiteralDuplication", "ComplexMethod", "LongMethod") class ExplorerDatabaseMigrationTest { - @Rule @JvmField - val helper = MigrationTestHelper( - InstrumentationRegistry.getInstrumentation(), - ExplorerDatabase::class.java.canonicalName, - FrameworkSQLiteOpenHelperFactory() - ) + val helper = + MigrationTestHelper( + InstrumentationRegistry.getInstrumentation(), + ExplorerDatabase::class.java.canonicalName, + FrameworkSQLiteOpenHelperFactory(), + ) /** * Sanity check for all migrations. @@ -65,24 +65,25 @@ class ExplorerDatabaseMigrationTest { fun migrateAll() { val db = helper.createDatabase(TEST_DB, 1) db.close() - val explorerDatabase = Room.databaseBuilder( - InstrumentationRegistry.getInstrumentation().targetContext, - ExplorerDatabase::class.java, - TEST_DB - ) - .addMigrations( - ExplorerDatabase.MIGRATION_1_2, - ExplorerDatabase.MIGRATION_2_3, - ExplorerDatabase.MIGRATION_3_4, - ExplorerDatabase.MIGRATION_4_5, - ExplorerDatabase.MIGRATION_5_6, - ExplorerDatabase.MIGRATION_6_7, - ExplorerDatabase.MIGRATION_7_8, - ExplorerDatabase.MIGRATION_8_9, - ExplorerDatabase.MIGRATION_9_10, - ExplorerDatabase.MIGRATION_10_11 + val explorerDatabase = + Room.databaseBuilder( + InstrumentationRegistry.getInstrumentation().targetContext, + ExplorerDatabase::class.java, + TEST_DB, ) - .build() + .addMigrations( + ExplorerDatabase.MIGRATION_1_2, + ExplorerDatabase.MIGRATION_2_3, + ExplorerDatabase.MIGRATION_3_4, + ExplorerDatabase.MIGRATION_4_5, + ExplorerDatabase.MIGRATION_5_6, + ExplorerDatabase.MIGRATION_6_7, + ExplorerDatabase.MIGRATION_7_8, + ExplorerDatabase.MIGRATION_8_9, + ExplorerDatabase.MIGRATION_9_10, + ExplorerDatabase.MIGRATION_10_11, + ) + .build() explorerDatabase.openHelper.writableDatabase explorerDatabase.close() } @@ -95,20 +96,21 @@ class ExplorerDatabaseMigrationTest { fun migrateFromV5() { val db = helper.createDatabase(TEST_DB, 5) db.close() - val explorerDatabase = Room.databaseBuilder( - InstrumentationRegistry.getInstrumentation().targetContext, - ExplorerDatabase::class.java, - TEST_DB - ) - .addMigrations( - ExplorerDatabase.MIGRATION_5_6, - ExplorerDatabase.MIGRATION_6_7, - ExplorerDatabase.MIGRATION_7_8, - ExplorerDatabase.MIGRATION_8_9, - ExplorerDatabase.MIGRATION_9_10, - ExplorerDatabase.MIGRATION_10_11 + val explorerDatabase = + Room.databaseBuilder( + InstrumentationRegistry.getInstrumentation().targetContext, + ExplorerDatabase::class.java, + TEST_DB, ) - .build() + .addMigrations( + ExplorerDatabase.MIGRATION_5_6, + ExplorerDatabase.MIGRATION_6_7, + ExplorerDatabase.MIGRATION_7_8, + ExplorerDatabase.MIGRATION_8_9, + ExplorerDatabase.MIGRATION_9_10, + ExplorerDatabase.MIGRATION_10_11, + ) + .build() explorerDatabase.openHelper.writableDatabase explorerDatabase.close() } @@ -121,19 +123,20 @@ class ExplorerDatabaseMigrationTest { fun migrateFromV6() { val db = helper.createDatabase(TEST_DB, 6) db.close() - val explorerDatabase = Room.databaseBuilder( - InstrumentationRegistry.getInstrumentation().targetContext, - ExplorerDatabase::class.java, - TEST_DB - ) - .addMigrations( - ExplorerDatabase.MIGRATION_6_7, - ExplorerDatabase.MIGRATION_7_8, - ExplorerDatabase.MIGRATION_8_9, - ExplorerDatabase.MIGRATION_9_10, - ExplorerDatabase.MIGRATION_10_11 + val explorerDatabase = + Room.databaseBuilder( + InstrumentationRegistry.getInstrumentation().targetContext, + ExplorerDatabase::class.java, + TEST_DB, ) - .build() + .addMigrations( + ExplorerDatabase.MIGRATION_6_7, + ExplorerDatabase.MIGRATION_7_8, + ExplorerDatabase.MIGRATION_8_9, + ExplorerDatabase.MIGRATION_9_10, + ExplorerDatabase.MIGRATION_10_11, + ) + .build() explorerDatabase.openHelper.writableDatabase explorerDatabase.close() } @@ -156,7 +159,7 @@ class ExplorerDatabaseMigrationTest { ExplorerDatabase.COLUMN_CLOUD_PERSIST + ") VALUES (1," + (OpenMode.GDRIVE.ordinal - 1) + - ",'abcd')" + ",'abcd')", ) db.execSQL( "INSERT INTO " + @@ -169,7 +172,7 @@ class ExplorerDatabaseMigrationTest { ExplorerDatabase.COLUMN_CLOUD_PERSIST + ") VALUES (2," + (OpenMode.DROPBOX.ordinal - 1) + - ",'efgh')" + ",'efgh')", ) db.execSQL( "INSERT INTO " + @@ -182,7 +185,7 @@ class ExplorerDatabaseMigrationTest { ExplorerDatabase.COLUMN_CLOUD_PERSIST + ") VALUES (3," + (OpenMode.BOX.ordinal - 1) + - ",'ijkl')" + ",'ijkl')", ) db.execSQL( "INSERT INTO " + @@ -195,48 +198,53 @@ class ExplorerDatabaseMigrationTest { ExplorerDatabase.COLUMN_CLOUD_PERSIST + ") VALUES (4," + (OpenMode.ONEDRIVE.ordinal - 1) + - ",'mnop')" + ",'mnop')", ) db.close() - val explorerDatabase = Room.databaseBuilder( - InstrumentationRegistry.getInstrumentation().targetContext, - ExplorerDatabase::class.java, - TEST_DB - ) - .addMigrations( - ExplorerDatabase.MIGRATION_7_8, - ExplorerDatabase.MIGRATION_8_9, - ExplorerDatabase.MIGRATION_9_10, - ExplorerDatabase.MIGRATION_10_11 - ).allowMainThreadQueries() - .build() + val explorerDatabase = + Room.databaseBuilder( + InstrumentationRegistry.getInstrumentation().targetContext, + ExplorerDatabase::class.java, + TEST_DB, + ) + .addMigrations( + ExplorerDatabase.MIGRATION_7_8, + ExplorerDatabase.MIGRATION_8_9, + ExplorerDatabase.MIGRATION_9_10, + ExplorerDatabase.MIGRATION_10_11, + ).allowMainThreadQueries() + .build() explorerDatabase.openHelper.writableDatabase - var verify = explorerDatabase - .cloudEntryDao() - .findByServiceType(OpenMode.GDRIVE.ordinal) - .subscribeOn(Schedulers.trampoline()) - .blockingGet() + var verify = + explorerDatabase + .cloudEntryDao() + .findByServiceType(OpenMode.GDRIVE.ordinal) + .subscribeOn(Schedulers.trampoline()) + .blockingGet() Assert.assertEquals(1, verify.id.toLong()) Assert.assertEquals("abcd", verify.persistData.toString()) - verify = explorerDatabase - .cloudEntryDao() - .findByServiceType(OpenMode.BOX.ordinal) - .subscribeOn(Schedulers.trampoline()) - .blockingGet() + verify = + explorerDatabase + .cloudEntryDao() + .findByServiceType(OpenMode.BOX.ordinal) + .subscribeOn(Schedulers.trampoline()) + .blockingGet() Assert.assertEquals(3, verify.id.toLong()) Assert.assertEquals("ijkl", verify.persistData.toString()) - verify = explorerDatabase - .cloudEntryDao() - .findByServiceType(OpenMode.DROPBOX.ordinal) - .subscribeOn(Schedulers.trampoline()) - .blockingGet() + verify = + explorerDatabase + .cloudEntryDao() + .findByServiceType(OpenMode.DROPBOX.ordinal) + .subscribeOn(Schedulers.trampoline()) + .blockingGet() Assert.assertEquals(2, verify.id.toLong()) Assert.assertEquals("efgh", verify.persistData.toString()) - verify = explorerDatabase - .cloudEntryDao() - .findByServiceType(OpenMode.ONEDRIVE.ordinal) - .subscribeOn(Schedulers.trampoline()) - .blockingGet() + verify = + explorerDatabase + .cloudEntryDao() + .findByServiceType(OpenMode.ONEDRIVE.ordinal) + .subscribeOn(Schedulers.trampoline()) + .blockingGet() Assert.assertEquals(4, verify.id.toLong()) Assert.assertEquals("mnop", verify.persistData.toString()) explorerDatabase.close() @@ -260,7 +268,7 @@ class ExplorerDatabaseMigrationTest { ExplorerDatabase.COLUMN_CLOUD_PERSIST + ") VALUES (1," + (OpenMode.GDRIVE.ordinal) + - ",'abcd')" + ",'abcd')", ) db.execSQL( "INSERT INTO " + @@ -273,7 +281,7 @@ class ExplorerDatabaseMigrationTest { ExplorerDatabase.COLUMN_CLOUD_PERSIST + ") VALUES (2," + (OpenMode.DROPBOX.ordinal) + - ",'efgh')" + ",'efgh')", ) db.execSQL( "INSERT INTO " + @@ -286,7 +294,7 @@ class ExplorerDatabaseMigrationTest { ExplorerDatabase.COLUMN_CLOUD_PERSIST + ") VALUES (3," + (OpenMode.BOX.ordinal) + - ",'ijkl')" + ",'ijkl')", ) db.execSQL( "INSERT INTO " + @@ -299,48 +307,53 @@ class ExplorerDatabaseMigrationTest { ExplorerDatabase.COLUMN_CLOUD_PERSIST + ") VALUES (4," + (OpenMode.ONEDRIVE.ordinal) + - ",'mnop')" + ",'mnop')", ) db.close() - val explorerDatabase = Room.databaseBuilder( - InstrumentationRegistry.getInstrumentation().targetContext, - ExplorerDatabase::class.java, - TEST_DB - ) - .addMigrations( - ExplorerDatabase.MIGRATION_8_9, - ExplorerDatabase.MIGRATION_9_10, - ExplorerDatabase.MIGRATION_10_11 + val explorerDatabase = + Room.databaseBuilder( + InstrumentationRegistry.getInstrumentation().targetContext, + ExplorerDatabase::class.java, + TEST_DB, ) - .allowMainThreadQueries() - .build() + .addMigrations( + ExplorerDatabase.MIGRATION_8_9, + ExplorerDatabase.MIGRATION_9_10, + ExplorerDatabase.MIGRATION_10_11, + ) + .allowMainThreadQueries() + .build() explorerDatabase.openHelper.writableDatabase - var verify = explorerDatabase - .cloudEntryDao() - .findByServiceType(OpenMode.GDRIVE.ordinal) - .subscribeOn(Schedulers.trampoline()) - .blockingGet() + var verify = + explorerDatabase + .cloudEntryDao() + .findByServiceType(OpenMode.GDRIVE.ordinal) + .subscribeOn(Schedulers.trampoline()) + .blockingGet() Assert.assertEquals(1, verify.id.toLong()) Assert.assertEquals("abcd", verify.persistData.toString()) - verify = explorerDatabase - .cloudEntryDao() - .findByServiceType(OpenMode.BOX.ordinal) - .subscribeOn(Schedulers.trampoline()) - .blockingGet() + verify = + explorerDatabase + .cloudEntryDao() + .findByServiceType(OpenMode.BOX.ordinal) + .subscribeOn(Schedulers.trampoline()) + .blockingGet() Assert.assertEquals(3, verify.id.toLong()) Assert.assertEquals("ijkl", verify.persistData.toString()) - verify = explorerDatabase - .cloudEntryDao() - .findByServiceType(OpenMode.DROPBOX.ordinal) - .subscribeOn(Schedulers.trampoline()) - .blockingGet() + verify = + explorerDatabase + .cloudEntryDao() + .findByServiceType(OpenMode.DROPBOX.ordinal) + .subscribeOn(Schedulers.trampoline()) + .blockingGet() Assert.assertEquals(2, verify.id.toLong()) Assert.assertEquals("efgh", verify.persistData.toString()) - verify = explorerDatabase - .cloudEntryDao() - .findByServiceType(OpenMode.ONEDRIVE.ordinal) - .subscribeOn(Schedulers.trampoline()) - .blockingGet() + verify = + explorerDatabase + .cloudEntryDao() + .findByServiceType(OpenMode.ONEDRIVE.ordinal) + .subscribeOn(Schedulers.trampoline()) + .blockingGet() Assert.assertEquals(4, verify.id.toLong()) Assert.assertEquals("mnop", verify.persistData.toString()) explorerDatabase.close() diff --git a/app/src/test/java/com/amaze/filemanager/database/MigrationTestHelper.java b/app/src/test/java/com/amaze/filemanager/database/MigrationTestHelper.java index e5094cfa30..b5b7829de7 100644 --- a/app/src/test/java/com/amaze/filemanager/database/MigrationTestHelper.java +++ b/app/src/test/java/com/amaze/filemanager/database/MigrationTestHelper.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2021 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/test/java/com/amaze/filemanager/database/UtilitiesDatabaseMigrationTest.kt b/app/src/test/java/com/amaze/filemanager/database/UtilitiesDatabaseMigrationTest.kt index e790bfca0f..d8dce58635 100644 --- a/app/src/test/java/com/amaze/filemanager/database/UtilitiesDatabaseMigrationTest.kt +++ b/app/src/test/java/com/amaze/filemanager/database/UtilitiesDatabaseMigrationTest.kt @@ -52,21 +52,21 @@ import org.robolectric.annotation.Config @RunWith(AndroidJUnit4::class) @Config( shadows = [ShadowMultiDex::class, ShadowPasswordUtil::class], - sdk = [KITKAT, P, Build.VERSION_CODES.R] + sdk = [KITKAT, P, Build.VERSION_CODES.R], ) class UtilitiesDatabaseMigrationTest { - companion object { private const val TEST_DB = "utilities-test" } @Rule @JvmField - val helper = MigrationTestHelper( - InstrumentationRegistry.getInstrumentation(), - UtilitiesDatabase::class.java.canonicalName, - FrameworkSQLiteOpenHelperFactory() - ) + val helper = + MigrationTestHelper( + InstrumentationRegistry.getInstrumentation(), + UtilitiesDatabase::class.java.canonicalName, + FrameworkSQLiteOpenHelperFactory(), + ) /** * Sanity check for all migrations. @@ -76,20 +76,21 @@ class UtilitiesDatabaseMigrationTest { val db = helper.createDatabase(TEST_DB, 1) db.close() - val utilitiesDatabase = Room.databaseBuilder( - InstrumentationRegistry.getInstrumentation().targetContext, - UtilitiesDatabase::class.java, - TEST_DB - ) - .allowMainThreadQueries() - .addMigrations( - UtilitiesDatabase.MIGRATION_1_2, - UtilitiesDatabase.MIGRATION_2_3, - UtilitiesDatabase.MIGRATION_3_4, - UtilitiesDatabase.MIGRATION_4_5, - UtilitiesDatabase.MIGRATION_5_6 + val utilitiesDatabase = + Room.databaseBuilder( + InstrumentationRegistry.getInstrumentation().targetContext, + UtilitiesDatabase::class.java, + TEST_DB, ) - .build() + .allowMainThreadQueries() + .addMigrations( + UtilitiesDatabase.MIGRATION_1_2, + UtilitiesDatabase.MIGRATION_2_3, + UtilitiesDatabase.MIGRATION_3_4, + UtilitiesDatabase.MIGRATION_4_5, + UtilitiesDatabase.MIGRATION_5_6, + ) + .build() utilitiesDatabase.openHelper.writableDatabase utilitiesDatabase.close() } @@ -102,44 +103,47 @@ class UtilitiesDatabaseMigrationTest { fun testMigrationFrom5To6() { val db: SupportSQLiteDatabase = helper.createDatabase(TEST_DB, 5) - val password1 = PasswordUtil.encryptPassword( - InstrumentationRegistry.getInstrumentation().targetContext, - "passw0rd", - Base64.DEFAULT - ) - val password2 = PasswordUtil.encryptPassword( - InstrumentationRegistry.getInstrumentation().targetContext, - "\\password/%&*()", - Base64.DEFAULT - ) + val password1 = + PasswordUtil.encryptPassword( + InstrumentationRegistry.getInstrumentation().targetContext, + "passw0rd", + Base64.DEFAULT, + ) + val password2 = + PasswordUtil.encryptPassword( + InstrumentationRegistry.getInstrumentation().targetContext, + "\\password/%&*()", + Base64.DEFAULT, + ) db.execSQL( "INSERT INTO $TABLE_SMB ($COLUMN_NAME, $COLUMN_PATH) " + - "VALUES ('test', 'smb://user:$password1@127.0.0.1/user')" + "VALUES ('test', 'smb://user:$password1@127.0.0.1/user')", ) db.execSQL( "INSERT INTO $TABLE_SMB ($COLUMN_NAME, $COLUMN_PATH) " + - "VALUES ('test anonymous', 'smb://127.0.0.1/Public')" + "VALUES ('test anonymous', 'smb://127.0.0.1/Public')", ) db.execSQL( "INSERT INTO $TABLE_SFTP ($COLUMN_NAME, $COLUMN_PATH, $COLUMN_HOST_PUBKEY) " + - "VALUES ('test password', 'ssh://user:$password2@10.0.0.1', '12345678')" + "VALUES ('test password', 'ssh://user:$password2@10.0.0.1', '12345678')", ) db.execSQL( "INSERT INTO $TABLE_SFTP ($COLUMN_NAME, $COLUMN_PATH, $COLUMN_HOST_PUBKEY, " + "$COLUMN_PRIVATE_KEY_NAME, $COLUMN_PRIVATE_KEY) " + "VALUES ('test no password', 'ssh://user@10.0.0.2', '1234'," + - " 'test private key', 'abcd')" + " 'test private key', 'abcd')", ) db.close() - val utilitiesDatabase = Room.databaseBuilder( - InstrumentationRegistry.getInstrumentation().targetContext, - UtilitiesDatabase::class.java, - TEST_DB - ) - .addMigrations(UtilitiesDatabase.MIGRATION_5_6) - .allowMainThreadQueries() - .build() + val utilitiesDatabase = + Room.databaseBuilder( + InstrumentationRegistry.getInstrumentation().targetContext, + UtilitiesDatabase::class.java, + TEST_DB, + ) + .addMigrations(UtilitiesDatabase.MIGRATION_5_6) + .allowMainThreadQueries() + .build() utilitiesDatabase.openHelper.writableDatabase val smbEntries = utilitiesDatabase.smbEntryDao().list().blockingGet() smbEntries.find { it.name == "test" }?.run { @@ -147,8 +151,8 @@ class UtilitiesDatabaseMigrationTest { "smb://user:passw0rd@127.0.0.1/user", SmbUtil.getSmbDecryptedPath( InstrumentationRegistry.getInstrumentation().targetContext, - this.path - ) + this.path, + ), ) } // smbEntries.find { it.name == "test anonymous" }?.run { diff --git a/app/src/test/java/com/amaze/filemanager/database/UtilsHandlerTest.kt b/app/src/test/java/com/amaze/filemanager/database/UtilsHandlerTest.kt index 842c7506f8..b3569d9177 100644 --- a/app/src/test/java/com/amaze/filemanager/database/UtilsHandlerTest.kt +++ b/app/src/test/java/com/amaze/filemanager/database/UtilsHandlerTest.kt @@ -53,10 +53,9 @@ import java.io.File @RunWith(AndroidJUnit4::class) @Config( shadows = [ShadowMultiDex::class, ShadowPasswordUtil::class], - sdk = [KITKAT, P, Build.VERSION_CODES.R] + sdk = [KITKAT, P, Build.VERSION_CODES.R], ) class UtilsHandlerTest { - companion object { /** * Enforce use of in-mem database during test. @@ -91,14 +90,15 @@ class UtilsHandlerTest { @Test fun testSimpleSaveSmb() { val path = "smb://user:password@127.0.0.1/user" - val o = OperationData( - UtilsHandler.Operation.SMB, - "SMB Connection 1", - SmbUtil.getSmbEncryptedPath( - AppConfig.getInstance(), - path + val o = + OperationData( + UtilsHandler.Operation.SMB, + "SMB Connection 1", + SmbUtil.getSmbEncryptedPath( + AppConfig.getInstance(), + path, + ), ) - ) AppConfig.getInstance().run { utilsHandler.run { saveToDatabase(o) @@ -107,9 +107,9 @@ class UtilsHandlerTest { assertEquals( SmbUtil.getSmbEncryptedPath( AppConfig.getInstance(), - path + path, ), - verify[0][1] + verify[0][1], ) } utilitiesDatabase.run { @@ -126,14 +126,15 @@ class UtilsHandlerTest { @Test fun testRepeatedSaveSmb() { val path = "smb://user:password@127.0.0.1/user" - val o = OperationData( - UtilsHandler.Operation.SMB, - "SMB Connection 1", - SmbUtil.getSmbEncryptedPath( - AppConfig.getInstance(), - path + val o = + OperationData( + UtilsHandler.Operation.SMB, + "SMB Connection 1", + SmbUtil.getSmbEncryptedPath( + AppConfig.getInstance(), + path, + ), ) - ) AppConfig.getInstance().run { utilsHandler.run { saveToDatabase(o) @@ -181,25 +182,26 @@ class UtilsHandlerTest { fun testSaveCommonBookmarks() { AppConfig.getInstance().utilsHandler.run { addCommonBookmarks() - val verify = bookmarksList.map { - Pair(it[0], it[1]) - } + val verify = + bookmarksList.map { + Pair(it[0], it[1]) + } for ( - d in arrayOf( - DIRECTORY_DOWNLOADS, - DIRECTORY_DCIM, - DIRECTORY_MUSIC, - DIRECTORY_MOVIES, - DIRECTORY_PICTURES - ) + d in arrayOf( + DIRECTORY_DOWNLOADS, + DIRECTORY_DCIM, + DIRECTORY_MUSIC, + DIRECTORY_MOVIES, + DIRECTORY_PICTURES, + ) ) { assertTrue( verify.contains( Pair( d, - File(Environment.getExternalStorageDirectory(), d).absolutePath - ) - ) + File(Environment.getExternalStorageDirectory(), d).absolutePath, + ), + ), ) } } @@ -210,14 +212,15 @@ class UtilsHandlerTest { */ @Test fun testRepeatedSaveSshWithPassword() { - val o = OperationData( - UtilsHandler.Operation.SFTP, - "ssh://root:toor@127.0.0.1/root/.ssh", - "SSH connection 1", - "ab:cd:ef:gh", - null, - null - ) + val o = + OperationData( + UtilsHandler.Operation.SFTP, + "ssh://root:toor@127.0.0.1/root/.ssh", + "SSH connection 1", + "ab:cd:ef:gh", + null, + null, + ) AppConfig.getInstance().run { utilsHandler.run { saveToDatabase(o) @@ -247,14 +250,15 @@ class UtilsHandlerTest { */ @Test fun testRepeatedSaveSshWithKeyAuth() { - val o = OperationData( - UtilsHandler.Operation.SFTP, - "ssh://root@127.0.0.1/root/.ssh", - "SSH connection 1", - "ab:cd:ef:gh", - "Test SSH key", - "abcdefghijkl" - ) + val o = + OperationData( + UtilsHandler.Operation.SFTP, + "ssh://root@127.0.0.1/root/.ssh", + "SSH connection 1", + "ab:cd:ef:gh", + "Test SSH key", + "abcdefghijkl", + ) AppConfig.getInstance().run { utilsHandler.run { saveToDatabase(o) diff --git a/app/src/test/java/com/amaze/filemanager/database/models/utilities/GridTest.kt b/app/src/test/java/com/amaze/filemanager/database/models/utilities/GridTest.kt index 46b8596ed6..28539c6f1c 100644 --- a/app/src/test/java/com/amaze/filemanager/database/models/utilities/GridTest.kt +++ b/app/src/test/java/com/amaze/filemanager/database/models/utilities/GridTest.kt @@ -29,7 +29,6 @@ import org.junit.Test */ @Suppress("StringLiteralDuplication") class GridTest { - /** * Test [Grid.equals] for equality. */ diff --git a/app/src/test/java/com/amaze/filemanager/database/models/utilities/ListTest.kt b/app/src/test/java/com/amaze/filemanager/database/models/utilities/ListTest.kt index 3bd24e1b16..8b778e62bf 100644 --- a/app/src/test/java/com/amaze/filemanager/database/models/utilities/ListTest.kt +++ b/app/src/test/java/com/amaze/filemanager/database/models/utilities/ListTest.kt @@ -29,7 +29,6 @@ import org.junit.Test */ @Suppress("StringLiteralDuplication") class ListTest { - /** * Test [List.equals] for equality. */ diff --git a/app/src/test/java/com/amaze/filemanager/database/models/utilities/SftpEntryTest.kt b/app/src/test/java/com/amaze/filemanager/database/models/utilities/SftpEntryTest.kt index bba5965b12..ee5a1f49d9 100644 --- a/app/src/test/java/com/amaze/filemanager/database/models/utilities/SftpEntryTest.kt +++ b/app/src/test/java/com/amaze/filemanager/database/models/utilities/SftpEntryTest.kt @@ -28,60 +28,65 @@ import org.junit.Test */ @Suppress("StringLiteralDuplication") class SftpEntryTest { - /** * Equality test. equals() check for name, path, host SSH key and private key combinations. */ @Test fun testEquals() { - val a = SftpEntry( - "ssh://root@127.0.0.1:22222", - "SSH connection 1", - "ab:cd:ef:gh:ij:kl:00", - "SSH key", - "abcdefghijkl" - ) - val b = SftpEntry( - "ssh://root@127.0.0.1:22222", - "SSH connection 1", - "ab:cd:ef:gh:ij:kl:00", - "SSH key", - "abcdefghijkl" - ) + val a = + SftpEntry( + "ssh://root@127.0.0.1:22222", + "SSH connection 1", + "ab:cd:ef:gh:ij:kl:00", + "SSH key", + "abcdefghijkl", + ) + val b = + SftpEntry( + "ssh://root@127.0.0.1:22222", + "SSH connection 1", + "ab:cd:ef:gh:ij:kl:00", + "SSH key", + "abcdefghijkl", + ) assertEquals(a, b) assertEquals(a.hashCode(), b.hashCode()) - val c = SftpEntry( - "ssh://root@127.0.0.1:22222", - "SSH connection 1", - "ab:cd:ef:gh:ij:kl:00", - "SSH key", - "abcdefghijkl" - ) - val d = SftpEntry( - "ssh://root@127.0.0.1:22222", - "SSH connection 1", - "ab:cd:ef:gh:ij:kl:00", - "SSH test auth key", - "abcdefghijkl" - ) + val c = + SftpEntry( + "ssh://root@127.0.0.1:22222", + "SSH connection 1", + "ab:cd:ef:gh:ij:kl:00", + "SSH key", + "abcdefghijkl", + ) + val d = + SftpEntry( + "ssh://root@127.0.0.1:22222", + "SSH connection 1", + "ab:cd:ef:gh:ij:kl:00", + "SSH test auth key", + "abcdefghijkl", + ) assertEquals(c, d) assertEquals(c.hashCode(), d.hashCode()) - val e = SftpEntry( - "ssh://root:toor@127.0.0.1:22222", - "SSH connection 1", - "ab:cd:ef:gh:ij:kl:00", - null, - null - ) - val f = SftpEntry( - "ssh://root:toor@127.0.0.1:22222", - "SSH connection 1", - "ab:cd:ef:gh:ij:kl:00", - null, - null - ) + val e = + SftpEntry( + "ssh://root:toor@127.0.0.1:22222", + "SSH connection 1", + "ab:cd:ef:gh:ij:kl:00", + null, + null, + ) + val f = + SftpEntry( + "ssh://root:toor@127.0.0.1:22222", + "SSH connection 1", + "ab:cd:ef:gh:ij:kl:00", + null, + null, + ) assertEquals(e, f) assertEquals(e.hashCode(), f.hashCode()) } diff --git a/app/src/test/java/com/amaze/filemanager/database/models/utilities/SmbEntryTest.kt b/app/src/test/java/com/amaze/filemanager/database/models/utilities/SmbEntryTest.kt index 7c6a244158..d8e089ec16 100644 --- a/app/src/test/java/com/amaze/filemanager/database/models/utilities/SmbEntryTest.kt +++ b/app/src/test/java/com/amaze/filemanager/database/models/utilities/SmbEntryTest.kt @@ -29,7 +29,6 @@ import org.junit.Test */ @Suppress("StringLiteralDuplication") class SmbEntryTest { - /** * Test [SmbEntry.equals] for equality. */ diff --git a/app/src/test/java/com/amaze/filemanager/database/typeconverters/EncryptedStringTypeConverterTest.kt b/app/src/test/java/com/amaze/filemanager/database/typeconverters/EncryptedStringTypeConverterTest.kt index 50019217b0..ac93635ea2 100644 --- a/app/src/test/java/com/amaze/filemanager/database/typeconverters/EncryptedStringTypeConverterTest.kt +++ b/app/src/test/java/com/amaze/filemanager/database/typeconverters/EncryptedStringTypeConverterTest.kt @@ -38,10 +38,9 @@ import org.robolectric.annotation.Config @RunWith(AndroidJUnit4::class) @Config( shadows = [ShadowMultiDex::class, ShadowPasswordUtil::class], - sdk = [KITKAT, P, Build.VERSION_CODES.R] + sdk = [KITKAT, P, Build.VERSION_CODES.R], ) class EncryptedStringTypeConverterTest { - /** * Test encrypt and decrypt capability. */ diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/AbstractFilenameHelperIncrementNameTests.kt b/app/src/test/java/com/amaze/filemanager/filesystem/AbstractFilenameHelperIncrementNameTests.kt index 1b199e3cff..26dfb75e16 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/AbstractFilenameHelperIncrementNameTests.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/AbstractFilenameHelperIncrementNameTests.kt @@ -42,47 +42,47 @@ import org.robolectric.annotation.Config @RunWith(AndroidJUnit4::class) @Config( shadows = [ShadowMultiDex::class], - sdk = [KITKAT, P, Build.VERSION_CODES.R] + sdk = [KITKAT, P, Build.VERSION_CODES.R], ) @Suppress("StringLiteralDuplication") abstract class AbstractFilenameHelperIncrementNameTests { - protected abstract val formatFlag: FilenameFormatFlag protected lateinit var file: HybridFile - private val existingFiles = arrayOf( - "/test/afile", - "/test/abc (2) - Copy - Copy.txt", - "/test/abc (2) - Copy.txt", - "/test/abc.txt", - "/test/bar.txt", - "/test/foo (2).txt", - "/test/foo 2 2.txt", - "/test/foo 2.txt", - "/test/foo 22.txt", - "/test/foo 3 copy.txt", - "/test/foo copy 2.txt", - "/test/foo copy 3.txt", - "/test/foo copy 4.txt", - "/test/foo copy 5.txt", - "/test/foo copy 6.txt", - "/test/foo copy.txt", - "/test/foo.txt", - "/test/one (copy).txt", - "/test/one.txt", - "/test/qux (2).txt", - "/test/qux 2.txt", - "/test/qux.txt", - "/test/sub/foo.txt", - "/test/sub/bar.txt", - "/test/sub/nested/bar.txt", - "/test/sub/nested/foo.txt", - "/test/sub/nested/foo copy.txt", - "/test/sub/nested/qux.txt", - "/test/sub/nested/qux 2.txt", - "/test/sub/nested/qux (2).txt" - ) + private val existingFiles = + arrayOf( + "/test/afile", + "/test/abc (2) - Copy - Copy.txt", + "/test/abc (2) - Copy.txt", + "/test/abc.txt", + "/test/bar.txt", + "/test/foo (2).txt", + "/test/foo 2 2.txt", + "/test/foo 2.txt", + "/test/foo 22.txt", + "/test/foo 3 copy.txt", + "/test/foo copy 2.txt", + "/test/foo copy 3.txt", + "/test/foo copy 4.txt", + "/test/foo copy 5.txt", + "/test/foo copy 6.txt", + "/test/foo copy.txt", + "/test/foo.txt", + "/test/one (copy).txt", + "/test/one.txt", + "/test/qux (2).txt", + "/test/qux 2.txt", + "/test/qux.txt", + "/test/sub/foo.txt", + "/test/sub/bar.txt", + "/test/sub/nested/bar.txt", + "/test/sub/nested/foo.txt", + "/test/sub/nested/foo copy.txt", + "/test/sub/nested/qux.txt", + "/test/sub/nested/qux 2.txt", + "/test/sub/nested/qux (2).txt", + ) /** * Sanity check. @@ -126,7 +126,7 @@ abstract class AbstractFilenameHelperIncrementNameTests { pairs: Array>, strip: Boolean = false, removeRawNumbers: Boolean = false, - start: Int = 1 + start: Int = 1, ) { for (pair in pairs) performTest(pair, strip, removeRawNumbers, start) } @@ -135,7 +135,7 @@ abstract class AbstractFilenameHelperIncrementNameTests { pair: Pair, strip: Boolean = false, removeRawNumbers: Boolean = false, - start: Int = 1 + start: Int = 1, ) { Mockito.mockConstruction(HybridFile::class.java) { file, context -> file.mode = context.arguments()[0] as OpenMode diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/AbstractOperationsTestBase.kt b/app/src/test/java/com/amaze/filemanager/filesystem/AbstractOperationsTestBase.kt index ff553eaec1..d910ae3917 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/AbstractOperationsTestBase.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/AbstractOperationsTestBase.kt @@ -62,27 +62,38 @@ import org.robolectric.shadows.ShadowSQLiteConnection ShadowSmbUtil::class, ShadowMultiDex::class, ShadowTabHandler::class, - ShadowPasswordUtil::class + ShadowPasswordUtil::class, ], - sdk = [KITKAT, P, Build.VERSION_CODES.R] + sdk = [KITKAT, P, Build.VERSION_CODES.R], ) abstract class AbstractOperationsTestBase { - private var ctx: Context? = null - private val blankCallback = object : Operations.ErrorCallBack { - override fun exists(file: HybridFile?) = Unit - override fun launchSAF(file: HybridFile?) = Unit - override fun launchSAF(file: HybridFile?, file1: HybridFile?) = Unit - override fun done(hFile: HybridFile?, b: Boolean) = Unit - override fun invalidName(file: HybridFile?) = Unit - } + private val blankCallback = + object : Operations.ErrorCallBack { + override fun exists(file: HybridFile?) = Unit + + override fun launchSAF(file: HybridFile?) = Unit + + override fun launchSAF( + file: HybridFile?, + file1: HybridFile?, + ) = Unit + + override fun done( + hFile: HybridFile?, + b: Boolean, + ) = Unit + + override fun invalidName(file: HybridFile?) = Unit + } @Rule @JvmField @RequiresApi(Build.VERSION_CODES.R) - val allFilesPermissionRule = GrantPermissionRule - .grant(Manifest.permission.MANAGE_EXTERNAL_STORAGE) + val allFilesPermissionRule = + GrantPermissionRule + .grant(Manifest.permission.MANAGE_EXTERNAL_STORAGE) /** * Test case setup. @@ -110,7 +121,7 @@ abstract class AbstractOperationsTestBase { protected fun testRenameFileAccessDenied( fileMode: OpenMode, oldFilePath: String, - newFilePath: String + newFilePath: String, ) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) TestUtils.initializeInternalStorage() @@ -130,7 +141,7 @@ abstract class AbstractOperationsTestBase { assertEquals(MainActivity.TAG_INTENT_FILTER_GENERAL, this.action) this .getParcelableArrayListExtra( - MainActivity.TAG_INTENT_FILTER_FAILED_OPS + MainActivity.TAG_INTENT_FILTER_FAILED_OPS, ) .run { assertNotNull(this) diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/EditableFileAbstractionTest.java b/app/src/test/java/com/amaze/filemanager/filesystem/EditableFileAbstractionTest.java index eac28874d3..a7de457697 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/EditableFileAbstractionTest.java +++ b/app/src/test/java/com/amaze/filemanager/filesystem/EditableFileAbstractionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/FilenameHelperDarwinIncrementNameTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/FilenameHelperDarwinIncrementNameTest.kt index 534820812a..bb7a1a4f23 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/FilenameHelperDarwinIncrementNameTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/FilenameHelperDarwinIncrementNameTest.kt @@ -29,7 +29,6 @@ import org.junit.Test */ @Suppress("StringLiteralDuplication") class FilenameHelperDarwinIncrementNameTest : AbstractFilenameHelperIncrementNameTests() { - override val formatFlag: FilenameFormatFlag get() = FilenameFormatFlag.DARWIN @@ -38,12 +37,13 @@ class FilenameHelperDarwinIncrementNameTest : AbstractFilenameHelperIncrementNam */ @Test fun testDarwinIncrementSimple() { - val pairs = arrayOf( - Pair("/test/file.txt", "/test/file copy.txt"), - Pair("/test/sub/foo.txt", "/test/sub/foo copy.txt"), - Pair("/test/sub/nested/foo.txt", "/test/sub/nested/foo copy 2.txt"), - Pair("/test/afile", "/test/afile copy") - ) + val pairs = + arrayOf( + Pair("/test/file.txt", "/test/file copy.txt"), + Pair("/test/sub/foo.txt", "/test/sub/foo copy.txt"), + Pair("/test/sub/nested/foo.txt", "/test/sub/nested/foo copy 2.txt"), + Pair("/test/afile", "/test/afile copy"), + ) performTest(pairs, true) } @@ -53,16 +53,17 @@ class FilenameHelperDarwinIncrementNameTest : AbstractFilenameHelperIncrementNam */ @Test fun testDarwinIncrementStripExistingRawNumbersBeforeIncrement() { - val pairs = arrayOf( - Pair("/test/foo.txt", "/test/foo copy 7.txt"), - Pair("/test/foo 2.txt", "/test/foo copy 7.txt"), - Pair("/test/foo copy.txt", "/test/foo copy 7.txt"), - Pair("/test/qux 2.txt", "/test/qux copy.txt"), - Pair("/test/abc (2) - Copy.txt", "/test/abc copy.txt"), - Pair("/test/abc (2) - Copy Copy.txt", "/test/abc copy.txt"), - Pair("/test/sub/nested/foo copy.txt", "/test/sub/nested/foo copy 2.txt"), - Pair("/test/sub/nested/foo copy 3.txt", "/test/sub/nested/foo copy 2.txt") - ) + val pairs = + arrayOf( + Pair("/test/foo.txt", "/test/foo copy 7.txt"), + Pair("/test/foo 2.txt", "/test/foo copy 7.txt"), + Pair("/test/foo copy.txt", "/test/foo copy 7.txt"), + Pair("/test/qux 2.txt", "/test/qux copy.txt"), + Pair("/test/abc (2) - Copy.txt", "/test/abc copy.txt"), + Pair("/test/abc (2) - Copy Copy.txt", "/test/abc copy.txt"), + Pair("/test/sub/nested/foo copy.txt", "/test/sub/nested/foo copy 2.txt"), + Pair("/test/sub/nested/foo copy 3.txt", "/test/sub/nested/foo copy 2.txt"), + ) performTest(pairs, strip = true, removeRawNumbers = true) } @@ -72,16 +73,17 @@ class FilenameHelperDarwinIncrementNameTest : AbstractFilenameHelperIncrementNam */ @Test fun testDarwinIncrementStripExistingNumbersBeforeIncrement() { - val pairs = arrayOf( - Pair("/test/file.txt", "/test/file copy.txt"), - Pair("/test/foo 2.txt", "/test/foo 2 copy.txt"), - Pair("/test/foo copy.txt", "/test/foo copy 7.txt"), - Pair("/test/qux 2.txt", "/test/qux 2 copy.txt"), - Pair("/test/abc (2) - Copy.txt", "/test/abc copy.txt"), - Pair("/test/abc (2) - Copy Copy.txt", "/test/abc copy.txt"), - Pair("/test/sub/nested/foo copy.txt", "/test/sub/nested/foo copy 2.txt"), - Pair("/test/sub/nested/foo copy 3.txt", "/test/sub/nested/foo copy 2.txt") - ) + val pairs = + arrayOf( + Pair("/test/file.txt", "/test/file copy.txt"), + Pair("/test/foo 2.txt", "/test/foo 2 copy.txt"), + Pair("/test/foo copy.txt", "/test/foo copy 7.txt"), + Pair("/test/qux 2.txt", "/test/qux 2 copy.txt"), + Pair("/test/abc (2) - Copy.txt", "/test/abc copy.txt"), + Pair("/test/abc (2) - Copy Copy.txt", "/test/abc copy.txt"), + Pair("/test/sub/nested/foo copy.txt", "/test/sub/nested/foo copy 2.txt"), + Pair("/test/sub/nested/foo copy 3.txt", "/test/sub/nested/foo copy 2.txt"), + ) performTest(pairs, strip = true, removeRawNumbers = false) } @@ -91,22 +93,23 @@ class FilenameHelperDarwinIncrementNameTest : AbstractFilenameHelperIncrementNam */ @Test fun testDarwinIncrementStartWithSpecifiedNumber() { - val pairs = arrayOf( - Pair("/test/foo copy 7.txt", 1), - Pair("/test/foo copy 7.txt", 2), - Pair("/test/foo copy 7.txt", 3), - Pair("/test/foo copy 7.txt", 4), - Pair("/test/foo copy 7.txt", 5), - Pair("/test/foo copy 7.txt", 6), - Pair("/test/foo copy 7.txt", 7), - Pair("/test/foo copy 8.txt", 8), - Pair("/test/foo copy 101.txt", 101) - ) + val pairs = + arrayOf( + Pair("/test/foo copy 7.txt", 1), + Pair("/test/foo copy 7.txt", 2), + Pair("/test/foo copy 7.txt", 3), + Pair("/test/foo copy 7.txt", 4), + Pair("/test/foo copy 7.txt", 5), + Pair("/test/foo copy 7.txt", 6), + Pair("/test/foo copy 7.txt", 7), + Pair("/test/foo copy 8.txt", 8), + Pair("/test/foo copy 101.txt", 101), + ) for (pair in pairs) { performTest( Pair("/test/foo.txt", pair.first), true, - start = pair.second + start = pair.second, ) } } @@ -117,11 +120,12 @@ class FilenameHelperDarwinIncrementNameTest : AbstractFilenameHelperIncrementNam */ @Test fun testDarwinIncrementStripOff() { - val pairs = arrayOf( - Pair("/test/foo.txt", "/test/foo copy 7.txt"), - Pair("/test/foo 2.txt", "/test/foo 2 copy.txt"), - Pair("/test/foo copy.txt", "/test/foo copy copy.txt") - ) + val pairs = + arrayOf( + Pair("/test/foo.txt", "/test/foo copy 7.txt"), + Pair("/test/foo 2.txt", "/test/foo 2 copy.txt"), + Pair("/test/foo copy.txt", "/test/foo copy copy.txt"), + ) performTest(pairs, false) } } diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/FilenameHelperLinuxIncrementNameTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/FilenameHelperLinuxIncrementNameTest.kt index dcd5f98f89..794229dbc3 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/FilenameHelperLinuxIncrementNameTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/FilenameHelperLinuxIncrementNameTest.kt @@ -29,7 +29,6 @@ import org.junit.Test */ @Suppress("StringLiteralDuplication") class FilenameHelperLinuxIncrementNameTest : AbstractFilenameHelperIncrementNameTests() { - override val formatFlag: FilenameFormatFlag get() = FilenameFormatFlag.LINUX @@ -38,12 +37,13 @@ class FilenameHelperLinuxIncrementNameTest : AbstractFilenameHelperIncrementName */ @Test fun testLinuxIncrementSimple() { - val pairs = arrayOf( - Pair("/test/file.txt", "/test/file (copy).txt"), - Pair("sub/foo.txt", "sub/foo (copy).txt"), - Pair("sub/nested/foo.txt", "sub/nested/foo (copy).txt"), - Pair("/test/afile", "/test/afile (copy)") - ) + val pairs = + arrayOf( + Pair("/test/file.txt", "/test/file (copy).txt"), + Pair("sub/foo.txt", "sub/foo (copy).txt"), + Pair("sub/nested/foo.txt", "sub/nested/foo (copy).txt"), + Pair("/test/afile", "/test/afile (copy)"), + ) performTest(pairs, true) } @@ -53,17 +53,18 @@ class FilenameHelperLinuxIncrementNameTest : AbstractFilenameHelperIncrementName */ @Test fun testLinuxIncrementStripExistingNumbersBeforeIncrement() { - val pairs = arrayOf( - Pair("/test/file.txt", "/test/file (copy).txt"), - Pair("/test/file 2.txt", "/test/file (copy).txt"), - Pair("/test/foo copy.txt", "/test/foo (copy).txt"), - Pair("/test/one (copy).txt", "/test/one (another copy).txt"), - Pair("/test/qux 2.txt", "/test/qux (copy).txt"), - Pair("/test/abc (2) - Copy.txt", "/test/abc (copy).txt"), - Pair("/test/abc (2) - Copy Copy.txt", "/test/abc (copy).txt"), - Pair("/test/sub/nested/foo copy.txt", "/test/sub/nested/foo (copy).txt"), - Pair("/test/sub/nested/foo copy 2.txt", "/test/sub/nested/foo (copy).txt") - ) + val pairs = + arrayOf( + Pair("/test/file.txt", "/test/file (copy).txt"), + Pair("/test/file 2.txt", "/test/file (copy).txt"), + Pair("/test/foo copy.txt", "/test/foo (copy).txt"), + Pair("/test/one (copy).txt", "/test/one (another copy).txt"), + Pair("/test/qux 2.txt", "/test/qux (copy).txt"), + Pair("/test/abc (2) - Copy.txt", "/test/abc (copy).txt"), + Pair("/test/abc (2) - Copy Copy.txt", "/test/abc (copy).txt"), + Pair("/test/sub/nested/foo copy.txt", "/test/sub/nested/foo (copy).txt"), + Pair("/test/sub/nested/foo copy 2.txt", "/test/sub/nested/foo (copy).txt"), + ) performTest(pairs, strip = true, removeRawNumbers = true) } @@ -73,17 +74,18 @@ class FilenameHelperLinuxIncrementNameTest : AbstractFilenameHelperIncrementName */ @Test fun testLinuxIncrementNotStripExistingNumbersBeforeIncrement() { - val pairs = arrayOf( - Pair("/test/file.txt", "/test/file (copy).txt"), - Pair("/test/file 2.txt", "/test/file 2 (copy).txt"), - Pair("/test/foo copy.txt", "/test/foo (copy).txt"), - Pair("/test/one (copy).txt", "/test/one (another copy).txt"), - Pair("/test/qux 2.txt", "/test/qux 2 (copy).txt"), - Pair("/test/abc (2) - Copy.txt", "/test/abc (copy).txt"), - Pair("/test/abc (2) - Copy Copy.txt", "/test/abc (copy).txt"), - Pair("/test/sub/nested/foo copy.txt", "/test/sub/nested/foo (copy).txt"), - Pair("/test/sub/nested/foo copy 2.txt", "/test/sub/nested/foo (copy).txt") - ) + val pairs = + arrayOf( + Pair("/test/file.txt", "/test/file (copy).txt"), + Pair("/test/file 2.txt", "/test/file 2 (copy).txt"), + Pair("/test/foo copy.txt", "/test/foo (copy).txt"), + Pair("/test/one (copy).txt", "/test/one (another copy).txt"), + Pair("/test/qux 2.txt", "/test/qux 2 (copy).txt"), + Pair("/test/abc (2) - Copy.txt", "/test/abc (copy).txt"), + Pair("/test/abc (2) - Copy Copy.txt", "/test/abc (copy).txt"), + Pair("/test/sub/nested/foo copy.txt", "/test/sub/nested/foo (copy).txt"), + Pair("/test/sub/nested/foo copy 2.txt", "/test/sub/nested/foo (copy).txt"), + ) performTest(pairs, strip = true, removeRawNumbers = false) } @@ -95,33 +97,34 @@ class FilenameHelperLinuxIncrementNameTest : AbstractFilenameHelperIncrementName fun testLinuxIncrementWithSpecifiedNumbers() { performTest( Pair("/test/file.txt", "/test/file (copy).txt"), - start = 0 - ) - val pairs = arrayOf( - Pair(3, "3rd"), - Pair(4, "4th"), - Pair(5, "5th"), - Pair(6, "6th"), - Pair(7, "7th"), - Pair(8, "8th"), - Pair(9, "9th"), - Pair(10, "10th"), - Pair(11, "11th"), - Pair(12, "12th"), - Pair(13, "13th"), - Pair(14, "14th"), - Pair(112, "112th"), - Pair(1112, "1112th"), - Pair(22, "22nd"), - Pair(122, "122nd"), - Pair(1122, "1122nd"), - Pair(102, "102nd"), - Pair(103, "103rd") + start = 0, ) + val pairs = + arrayOf( + Pair(3, "3rd"), + Pair(4, "4th"), + Pair(5, "5th"), + Pair(6, "6th"), + Pair(7, "7th"), + Pair(8, "8th"), + Pair(9, "9th"), + Pair(10, "10th"), + Pair(11, "11th"), + Pair(12, "12th"), + Pair(13, "13th"), + Pair(14, "14th"), + Pair(112, "112th"), + Pair(1112, "1112th"), + Pair(22, "22nd"), + Pair(122, "122nd"), + Pair(1122, "1122nd"), + Pair(102, "102nd"), + Pair(103, "103rd"), + ) for (pair in pairs) { performTest( Pair("/test/file.txt", "/test/file (${pair.second} copy).txt"), - start = pair.first + start = pair.first, ) } } @@ -132,11 +135,12 @@ class FilenameHelperLinuxIncrementNameTest : AbstractFilenameHelperIncrementName */ @Test fun testLinuxIncrementStripOff() { - val pairs = arrayOf( - Pair("/test/file.txt", "/test/file (copy).txt"), - Pair("/test/foo 2.txt", "/test/foo 2 (copy).txt"), - Pair("/test/foo copy.txt", "/test/foo copy (copy).txt") - ) + val pairs = + arrayOf( + Pair("/test/file.txt", "/test/file (copy).txt"), + Pair("/test/foo 2.txt", "/test/foo 2 (copy).txt"), + Pair("/test/foo copy.txt", "/test/foo copy (copy).txt"), + ) performTest(pairs, false) } } diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/FilenameHelperTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/FilenameHelperTest.kt index 921eee9653..3329c0fe98 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/FilenameHelperTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/FilenameHelperTest.kt @@ -27,7 +27,6 @@ import org.junit.Test @Suppress("StringLiteralDuplication") class FilenameHelperTest { - /** * [FilenameHelper.strip] should remove linux-style increments from a filename. */ diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/FilenameHelperWindowsIncrementNameTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/FilenameHelperWindowsIncrementNameTest.kt index acb824380a..2f98c49c1a 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/FilenameHelperWindowsIncrementNameTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/FilenameHelperWindowsIncrementNameTest.kt @@ -29,7 +29,6 @@ import org.junit.Test */ @Suppress("StringLiteralDuplication") class FilenameHelperWindowsIncrementNameTest : AbstractFilenameHelperIncrementNameTests() { - override val formatFlag: FilenameFormatFlag get() = FilenameFormatFlag.WINDOWS @@ -38,12 +37,13 @@ class FilenameHelperWindowsIncrementNameTest : AbstractFilenameHelperIncrementNa */ @Test fun testWindowsIncrementSimple() { - val pairs = arrayOf( - Pair("/test/file.txt", "/test/file (1).txt"), - Pair("sub/foo.txt", "sub/foo (1).txt"), - Pair("sub/nested/foo.txt", "sub/nested/foo (1).txt"), - Pair("/test/afile", "/test/afile (1)") - ) + val pairs = + arrayOf( + Pair("/test/file.txt", "/test/file (1).txt"), + Pair("sub/foo.txt", "sub/foo (1).txt"), + Pair("sub/nested/foo.txt", "sub/nested/foo (1).txt"), + Pair("/test/afile", "/test/afile (1)"), + ) performTest(pairs, true) } @@ -53,16 +53,17 @@ class FilenameHelperWindowsIncrementNameTest : AbstractFilenameHelperIncrementNa */ @Test fun testWindowsStripRawNumbersAndIncrementsBeforeUpdatingIncrement() { - val pairs = arrayOf( - Pair("/test/foo.txt", "/test/foo (1).txt"), - Pair("/test/foo 2.txt", "/test/foo (1).txt"), - Pair("/test/foo copy.txt", "/test/foo (1).txt"), - Pair("/test/qux 2.txt", "/test/qux (1).txt"), - Pair("/test/abc (2) - Copy.txt", "/test/abc (1).txt"), - Pair("/test/abc (2) - Copy Copy.txt", "/test/abc (1).txt"), - Pair("/test/sub/nested/foo copy.txt", "/test/sub/nested/foo (1).txt"), - Pair("/test/sub/nested/foo copy 2.txt", "/test/sub/nested/foo (1).txt") - ) + val pairs = + arrayOf( + Pair("/test/foo.txt", "/test/foo (1).txt"), + Pair("/test/foo 2.txt", "/test/foo (1).txt"), + Pair("/test/foo copy.txt", "/test/foo (1).txt"), + Pair("/test/qux 2.txt", "/test/qux (1).txt"), + Pair("/test/abc (2) - Copy.txt", "/test/abc (1).txt"), + Pair("/test/abc (2) - Copy Copy.txt", "/test/abc (1).txt"), + Pair("/test/sub/nested/foo copy.txt", "/test/sub/nested/foo (1).txt"), + Pair("/test/sub/nested/foo copy 2.txt", "/test/sub/nested/foo (1).txt"), + ) performTest(pairs, strip = true, removeRawNumbers = true) } @@ -72,16 +73,17 @@ class FilenameHelperWindowsIncrementNameTest : AbstractFilenameHelperIncrementNa */ @Test fun testWindowsStripBeforeUpdatingIncrement() { - val pairs = arrayOf( - Pair("/test/foo.txt", "/test/foo (1).txt"), - Pair("/test/foo 2.txt", "/test/foo 2 (1).txt"), - Pair("/test/foo copy.txt", "/test/foo (1).txt"), - Pair("/test/qux 2.txt", "/test/qux 2 (1).txt"), - Pair("/test/abc (2) - Copy.txt", "/test/abc (1).txt"), - Pair("/test/abc (2) - Copy Copy.txt", "/test/abc (1).txt"), - Pair("/test/sub/nested/foo copy.txt", "/test/sub/nested/foo (1).txt"), - Pair("/test/sub/nested/foo copy 2.txt", "/test/sub/nested/foo (1).txt") - ) + val pairs = + arrayOf( + Pair("/test/foo.txt", "/test/foo (1).txt"), + Pair("/test/foo 2.txt", "/test/foo 2 (1).txt"), + Pair("/test/foo copy.txt", "/test/foo (1).txt"), + Pair("/test/qux 2.txt", "/test/qux 2 (1).txt"), + Pair("/test/abc (2) - Copy.txt", "/test/abc (1).txt"), + Pair("/test/abc (2) - Copy Copy.txt", "/test/abc (1).txt"), + Pair("/test/sub/nested/foo copy.txt", "/test/sub/nested/foo (1).txt"), + Pair("/test/sub/nested/foo copy 2.txt", "/test/sub/nested/foo (1).txt"), + ) performTest(pairs, strip = true, removeRawNumbers = false) } @@ -91,22 +93,23 @@ class FilenameHelperWindowsIncrementNameTest : AbstractFilenameHelperIncrementNa */ @Test fun testWindowsIncrementStartWithSpecifiedNumber() { - val pairs = arrayOf( - Pair("/test/foo (1).txt", 1), - Pair("/test/foo (3).txt", 2), - Pair("/test/foo (3).txt", 3), - Pair("/test/foo (4).txt", 4), - Pair("/test/foo (5).txt", 5), - Pair("/test/foo (6).txt", 6), - Pair("/test/foo (7).txt", 7), - Pair("/test/foo (101).txt", 101), - Pair("/test/foo (102).txt", 102) - ) + val pairs = + arrayOf( + Pair("/test/foo (1).txt", 1), + Pair("/test/foo (3).txt", 2), + Pair("/test/foo (3).txt", 3), + Pair("/test/foo (4).txt", 4), + Pair("/test/foo (5).txt", 5), + Pair("/test/foo (6).txt", 6), + Pair("/test/foo (7).txt", 7), + Pair("/test/foo (101).txt", 101), + Pair("/test/foo (102).txt", 102), + ) for (pair in pairs) { performTest( Pair("/test/foo.txt", pair.first), true, - start = pair.second + start = pair.second, ) } } @@ -117,11 +120,12 @@ class FilenameHelperWindowsIncrementNameTest : AbstractFilenameHelperIncrementNa */ @Test fun testWindowsIncrementStripOff() { - val pairs = arrayOf( - Pair("/test/foo.txt", "/test/foo (1).txt"), - Pair("/test/foo 2.txt", "/test/foo 2 (1).txt"), - Pair("/test/foo copy.txt", "/test/foo copy (1).txt") - ) + val pairs = + arrayOf( + Pair("/test/foo.txt", "/test/foo (1).txt"), + Pair("/test/foo 2.txt", "/test/foo 2 (1).txt"), + Pair("/test/foo copy.txt", "/test/foo copy (1).txt"), + ) performTest(pairs, false) } } diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/HybridFileTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/HybridFileTest.kt index eba4d8dbde..2c29b3fb08 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/HybridFileTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/HybridFileTest.kt @@ -18,6 +18,8 @@ * along with this program. If not, see . */ +@file:Suppress("ktlint:standard:max-line-length") + package com.amaze.filemanager.filesystem import android.os.Build @@ -37,12 +39,10 @@ import java.io.File import java.net.URLDecoder import kotlin.random.Random -/* ktlint-disable max-line-length */ @RunWith(AndroidJUnit4::class) @Config(shadows = [ShadowMultiDex::class], sdk = [KITKAT, P, Build.VERSION_CODES.R]) @Suppress("StringLiteralDuplication") class HybridFileTest { - /** * Test [HybridFile.getParent] */ @@ -70,7 +70,7 @@ class HybridFileTest { val file = HybridFile(OpenMode.SFTP, "ssh://user@127.0.0.1/home/user/next/project/") assertEquals( "ssh://user@127.0.0.1/home/user/next/", - file.getParent(ApplicationProvider.getApplicationContext()) + file.getParent(ApplicationProvider.getApplicationContext()), ) } @@ -82,7 +82,7 @@ class HybridFileTest { val file = HybridFile(OpenMode.SFTP, "ssh://user@127.0.0.1/home/user/next/project") assertEquals( "ssh://user@127.0.0.1/home/user/next/", - file.getParent(ApplicationProvider.getApplicationContext()) + file.getParent(ApplicationProvider.getApplicationContext()), ) } @@ -91,21 +91,23 @@ class HybridFileTest { */ @Test fun testDocumentFileAndroidDataGetParent1() { - var file = HybridFile( - OpenMode.DOCUMENT_FILE, - "content://com.android.externalstorage.documents/tree/primary:Android/data/com.amaze.filemanager.debug/cache" - ) + var file = + HybridFile( + OpenMode.DOCUMENT_FILE, + "content://com.android.externalstorage.documents/tree/primary:Android/data/com.amaze.filemanager.debug/cache", + ) assertEquals( "content://com.android.externalstorage.documents/tree/primary:Android/data/com.amaze.filemanager.debug/", - file.getParent(AppConfig.getInstance()) - ) - file = HybridFile( - OpenMode.DOCUMENT_FILE, - file.getParent(AppConfig.getInstance()) + file.getParent(AppConfig.getInstance()), ) + file = + HybridFile( + OpenMode.DOCUMENT_FILE, + file.getParent(AppConfig.getInstance()), + ) assertEquals( File(Environment.getExternalStorageDirectory(), "Android/data").absolutePath, - file.getParent(AppConfig.getInstance()) + file.getParent(AppConfig.getInstance()), ) } @@ -114,29 +116,32 @@ class HybridFileTest { */ @Test fun testDocumentFileAndroidDataGetParent2() { - var file = HybridFile( - OpenMode.DOCUMENT_FILE, - "content://com.android.externalstorage.documents/tree/primary:Android/data/com.amaze.filemanager.debug/files/external" - ) + var file = + HybridFile( + OpenMode.DOCUMENT_FILE, + "content://com.android.externalstorage.documents/tree/primary:Android/data/com.amaze.filemanager.debug/files/external", + ) assertEquals( "content://com.android.externalstorage.documents/tree/primary:Android/data/com.amaze.filemanager.debug/files/", - file.getParent(AppConfig.getInstance()) - ) - file = HybridFile( - OpenMode.DOCUMENT_FILE, - file.getParent(AppConfig.getInstance()) + file.getParent(AppConfig.getInstance()), ) + file = + HybridFile( + OpenMode.DOCUMENT_FILE, + file.getParent(AppConfig.getInstance()), + ) assertEquals( "content://com.android.externalstorage.documents/tree/primary:Android/data/com.amaze.filemanager.debug/", - file.getParent(AppConfig.getInstance()) - ) - file = HybridFile( - OpenMode.DOCUMENT_FILE, - file.getParent(AppConfig.getInstance()) + file.getParent(AppConfig.getInstance()), ) + file = + HybridFile( + OpenMode.DOCUMENT_FILE, + file.getParent(AppConfig.getInstance()), + ) assertEquals( File(Environment.getExternalStorageDirectory(), "Android/data").absolutePath, - file.getParent(AppConfig.getInstance()) + file.getParent(AppConfig.getInstance()), ) } @@ -145,21 +150,23 @@ class HybridFileTest { */ @Test fun testDocumentFileAndroidObbGetParent3() { - var file = HybridFile( - OpenMode.DOCUMENT_FILE, - "content://com.android.externalstorage.documents/tree/primary:Android/obb/com.amaze.filemanager.debug/cache" - ) + var file = + HybridFile( + OpenMode.DOCUMENT_FILE, + "content://com.android.externalstorage.documents/tree/primary:Android/obb/com.amaze.filemanager.debug/cache", + ) assertEquals( "content://com.android.externalstorage.documents/tree/primary:Android/obb/com.amaze.filemanager.debug/", - file.getParent(AppConfig.getInstance()) - ) - file = HybridFile( - OpenMode.DOCUMENT_FILE, - file.getParent(AppConfig.getInstance()) + file.getParent(AppConfig.getInstance()), ) + file = + HybridFile( + OpenMode.DOCUMENT_FILE, + file.getParent(AppConfig.getInstance()), + ) assertEquals( File(Environment.getExternalStorageDirectory(), "Android/obb").absolutePath, - file.getParent(AppConfig.getInstance()) + file.getParent(AppConfig.getInstance()), ) } @@ -168,29 +175,32 @@ class HybridFileTest { */ @Test fun testDocumentFileAndroidObbGetParent2() { - var file = HybridFile( - OpenMode.DOCUMENT_FILE, - "content://com.android.externalstorage.documents/tree/primary:Android/obb/com.amaze.filemanager.debug/files/external" - ) + var file = + HybridFile( + OpenMode.DOCUMENT_FILE, + "content://com.android.externalstorage.documents/tree/primary:Android/obb/com.amaze.filemanager.debug/files/external", + ) assertEquals( "content://com.android.externalstorage.documents/tree/primary:Android/obb/com.amaze.filemanager.debug/files/", - file.getParent(AppConfig.getInstance()) - ) - file = HybridFile( - OpenMode.DOCUMENT_FILE, - file.getParent(AppConfig.getInstance()) + file.getParent(AppConfig.getInstance()), ) + file = + HybridFile( + OpenMode.DOCUMENT_FILE, + file.getParent(AppConfig.getInstance()), + ) assertEquals( "content://com.android.externalstorage.documents/tree/primary:Android/obb/com.amaze.filemanager.debug/", - file.getParent(AppConfig.getInstance()) - ) - file = HybridFile( - OpenMode.DOCUMENT_FILE, - file.getParent(AppConfig.getInstance()) + file.getParent(AppConfig.getInstance()), ) + file = + HybridFile( + OpenMode.DOCUMENT_FILE, + file.getParent(AppConfig.getInstance()), + ) assertEquals( File(Environment.getExternalStorageDirectory(), "Android/obb").absolutePath, - file.getParent(AppConfig.getInstance()) + file.getParent(AppConfig.getInstance()), ) } @@ -200,17 +210,17 @@ class HybridFileTest { @Test fun testGetName() { for ( - name: String in arrayOf( - "newfolder", - "new folder 2", - "new%20folder%203", - "あいうえお" - ) + name: String in arrayOf( + "newfolder", + "new folder 2", + "new%20folder%203", + "あいうえお", + ) ) { val file = HybridFile(OpenMode.FTP, "ftp://user:password@127.0.0.1/$name") assertEquals( URLDecoder.decode(name, Charsets.UTF_8.name()), - file.getName(AppConfig.getInstance()) + file.getName(AppConfig.getInstance()), ) } } @@ -220,10 +230,11 @@ class HybridFileTest { */ @Test fun testGetName2() { - val file = HybridFile( - OpenMode.FTP, - "ftp://user:password@127.0.0.1:22222/multiple/levels/down the pipe" - ) + val file = + HybridFile( + OpenMode.FTP, + "ftp://user:password@127.0.0.1:22222/multiple/levels/down the pipe", + ) assertEquals("down the pipe", file.getName(AppConfig.getInstance())) } @@ -236,37 +247,36 @@ class HybridFileTest { "ftp://user:password@127.0.0.1:22222/multiple/levels/down/the/pipe", HybridFile( OpenMode.FTP, - "ftp://user:password@127.0.0.1:22222//multiple///levels////down////the/pipe" - ).path + "ftp://user:password@127.0.0.1:22222//multiple///levels////down////the/pipe", + ).path, ) assertEquals( "ssh://user@127.0.0.1/multiple/levels/down/the/pipe", HybridFile( OpenMode.SFTP, - "ssh://user@127.0.0.1//multiple///levels////down////the/pipe" - ).path + "ssh://user@127.0.0.1//multiple///levels////down////the/pipe", + ).path, ) assertEquals( "ssh://user@127.0.0.1/multiple/levels/down/the/pipe", HybridFile( OpenMode.SFTP, - "ssh://user@127.0.0.1/multiple/levels/down/the/pipe" - ).path + "ssh://user@127.0.0.1/multiple/levels/down/the/pipe", + ).path, ) assertEquals( "smb://127.0.0.1/legacy?disableIpcSigningCheck=true", HybridFile( OpenMode.SMB, - "smb://127.0.0.1/legacy?disableIpcSigningCheck=true" - ).path + "smb://127.0.0.1/legacy?disableIpcSigningCheck=true", + ).path, ) assertEquals( "smb://127.0.0.1/legacy/again/try/duplicate/folder?disableIpcSigningCheck=true", HybridFile( OpenMode.SMB, - "smb://127.0.0.1/legacy//again/try/duplicate/////folder?disableIpcSigningCheck=true" - ).path + "smb://127.0.0.1/legacy//again/try/duplicate/////folder?disableIpcSigningCheck=true", + ).path, ) } } -/* ktlint-enable max-line-length */ diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/OperationsTest.java b/app/src/test/java/com/amaze/filemanager/filesystem/OperationsTest.java index a5ddee4c1a..c0868b7061 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/OperationsTest.java +++ b/app/src/test/java/com/amaze/filemanager/filesystem/OperationsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/RandomPathGenerator.kt b/app/src/test/java/com/amaze/filemanager/filesystem/RandomPathGenerator.kt index ab48a8fb79..cf9f5c5f76 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/RandomPathGenerator.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/RandomPathGenerator.kt @@ -33,7 +33,10 @@ object RandomPathGenerator { /** * Generates a valid random path */ - fun generateRandomPath(random: Random, length: Int): String { + fun generateRandomPath( + random: Random, + length: Int, + ): String { assert(length > 0) val slashesInPath = random.nextInt(length / 4) @@ -44,14 +47,19 @@ object RandomPathGenerator { /** * Generates a valid random path, with a specific amount of directories */ - fun generateRandomPath(random: Random, length: Int, slashesInPath: Int): String { + fun generateRandomPath( + random: Random, + length: Int, + slashesInPath: Int, + ): String { assert(length > slashesInPath * 2) val namesInPath = slashesInPath + 1 - val filenameLengths = List(namesInPath) { - (length - slashesInPath) / namesInPath - } + val filenameLengths = + List(namesInPath) { + (length - slashesInPath) / namesInPath + } val pathBuilder = mutableListOf() @@ -83,14 +91,18 @@ object RandomPathGenerator { return path } - private fun generateRandomFilename(random: Random, length: Int): String { + private fun generateRandomFilename( + random: Random, + length: Int, + ): String { assert(length > 0) var name = "" while (reservedFileNames.contains(name)) { - name = List(length) { generateRandomCharacter(random) } - .joinToString("") + name = + List(length) { generateRandomCharacter(random) } + .joinToString("") } return name diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/RootHelperTest.java b/app/src/test/java/com/amaze/filemanager/filesystem/RootHelperTest.java index 3e01e85d4a..a5ca73548f 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/RootHelperTest.java +++ b/app/src/test/java/com/amaze/filemanager/filesystem/RootHelperTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/SmbOperationsTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/SmbOperationsTest.kt index b13515bedd..fe599ab397 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/SmbOperationsTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/SmbOperationsTest.kt @@ -25,7 +25,6 @@ import com.amaze.filemanager.shadows.ShadowSmbUtil.Companion.PATH_CANNOT_RENAME_ import org.junit.Test class SmbOperationsTest : AbstractOperationsTestBase() { - /** * Test case to verify rename SMB file failure scenario. * @@ -36,7 +35,7 @@ class SmbOperationsTest : AbstractOperationsTestBase() { super.testRenameFileAccessDenied( OpenMode.SMB, PATH_CANNOT_RENAME_OLDFILE, - "smb://user:password@1.2.3.4/cannot/rename.file.new" + "smb://user:password@1.2.3.4/cannot/rename.file.new", ) } } diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/SshOperationsTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/SshOperationsTest.kt index 2124892ecb..615bf542bb 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/SshOperationsTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/SshOperationsTest.kt @@ -25,7 +25,6 @@ import com.amaze.filemanager.filesystem.ssh.test.MockSshConnectionPools import org.junit.Test class SshOperationsTest : AbstractOperationsTestBase() { - /** * Test case to verify rename SSH file failure scenario. * @@ -37,7 +36,7 @@ class SshOperationsTest : AbstractOperationsTestBase() { super.testRenameFileAccessDenied( OpenMode.SFTP, "ssh://user:password@127.0.0.1:22222/tmp/old.file", - "ssh://user:password@127.0.0.1:22222/tmp/new.file" + "ssh://user:password@127.0.0.1:22222/tmp/new.file", ) } } diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/cloud/CloudUtilTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/cloud/CloudUtilTest.kt index 1550a799c3..7e5c4c6293 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/cloud/CloudUtilTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/cloud/CloudUtilTest.kt @@ -39,13 +39,14 @@ class CloudUtilTest { } val generatePathForMode = { mode: OpenMode, path: String -> - val prefix = when (mode) { - DROPBOX -> CloudHandler.CLOUD_PREFIX_DROPBOX - BOX -> CloudHandler.CLOUD_PREFIX_BOX - GDRIVE -> CloudHandler.CLOUD_PREFIX_GOOGLE_DRIVE - ONEDRIVE -> CloudHandler.CLOUD_PREFIX_ONE_DRIVE - else -> null - } + val prefix = + when (mode) { + DROPBOX -> CloudHandler.CLOUD_PREFIX_DROPBOX + BOX -> CloudHandler.CLOUD_PREFIX_BOX + GDRIVE -> CloudHandler.CLOUD_PREFIX_GOOGLE_DRIVE + ONEDRIVE -> CloudHandler.CLOUD_PREFIX_ONE_DRIVE + else -> null + } requireNotNull(prefix) prefix + RandomPathGenerator.separator + path } diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/B0rkenZipTest.java b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/B0rkenZipTest.java index 99bb6b9944..ee5e9c6b05 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/B0rkenZipTest.java +++ b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/B0rkenZipTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/CompressedHelperTest.java b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/CompressedHelperTest.java index 85b15ab939..e011837730 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/CompressedHelperTest.java +++ b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/CompressedHelperTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/TestArchives.java b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/TestArchives.java index d15fa2b309..fe2a925fed 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/TestArchives.java +++ b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/TestArchives.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/AbstractArchiveExtractorTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/AbstractArchiveExtractorTest.kt index c43a886873..453424ef9a 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/AbstractArchiveExtractorTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/AbstractArchiveExtractorTest.kt @@ -37,26 +37,25 @@ import java.time.ZonedDateTime import java.util.concurrent.CountDownLatch abstract class AbstractArchiveExtractorTest : AbstractExtractorTest() { - companion object { @JvmStatic - private val EXPECTED_TIMESTAMP = ZonedDateTime.of( - 2018, - 5, - 29, - 10, - 38, - 0, - 0, - ZoneId.of("UTC") - ).toInstant().toEpochMilli() + private val EXPECTED_TIMESTAMP = + ZonedDateTime.of( + 2018, + 5, + 29, + 10, + 38, + 0, + 0, + ZoneId.of("UTC"), + ).toInstant().toEpochMilli() } /** * run assertion on file timestamp correctness. */ - protected open fun assertFileTimestampCorrect(file: File) = - assertEquals(EXPECTED_TIMESTAMP, file.lastModified()) + protected open fun assertFileTimestampCorrect(file: File) = assertEquals(EXPECTED_TIMESTAMP, file.lastModified()) /** * Test extractor ability to correct problematic archive entries for security @@ -64,26 +63,33 @@ abstract class AbstractArchiveExtractorTest : AbstractExtractorTest() { @Test @Suppress("StringLiteralDuplication") fun testFixEntryName() { - val extractor = extractorClass() - .getConstructor( - Context::class.java, - String::class.java, - String::class.java, - Extractor.OnUpdate::class.java, - UpdatePosition::class.java - ) - .newInstance( - ApplicationProvider.getApplicationContext(), - archiveFile.absolutePath, - Environment.getExternalStorageDirectory().absolutePath, - object : Extractor.OnUpdate { - override fun onStart(totalBytes: Long, firstEntryName: String) = Unit - override fun onUpdate(entryPath: String) = Unit - override fun isCancelled(): Boolean = false - override fun onFinish() = Unit - }, - ServiceWatcherUtil.UPDATE_POSITION - ) + val extractor = + extractorClass() + .getConstructor( + Context::class.java, + String::class.java, + String::class.java, + Extractor.OnUpdate::class.java, + UpdatePosition::class.java, + ) + .newInstance( + ApplicationProvider.getApplicationContext(), + archiveFile.absolutePath, + Environment.getExternalStorageDirectory().absolutePath, + object : Extractor.OnUpdate { + override fun onStart( + totalBytes: Long, + firstEntryName: String, + ) = Unit + + override fun onUpdate(entryPath: String) = Unit + + override fun isCancelled(): Boolean = false + + override fun onFinish() = Unit + }, + ServiceWatcherUtil.UPDATE_POSITION, + ) assertEquals("test.txt", extractor.fixEntryName("test.txt")) assertEquals("test.txt", extractor.fixEntryName("/test.txt")) assertEquals("test.txt", extractor.fixEntryName("/////////test.txt")) @@ -105,34 +111,41 @@ abstract class AbstractArchiveExtractorTest : AbstractExtractorTest() { @Throws(Exception::class) override fun doTestExtractFiles() { val latch = CountDownLatch(1) - val extractor = extractorClass() - .getConstructor( - Context::class.java, - String::class.java, - String::class.java, - Extractor.OnUpdate::class.java, - UpdatePosition::class.java - ) - .newInstance( - ApplicationProvider.getApplicationContext(), - archiveFile.absolutePath, - Environment.getExternalStorageDirectory().absolutePath, - object : Extractor.OnUpdate { - override fun onStart(totalBytes: Long, firstEntryName: String) = Unit - override fun onUpdate(entryPath: String) = Unit - override fun isCancelled(): Boolean = false - override fun onFinish() { - latch.countDown() - try { - verifyExtractedArchiveContents() - } catch (e: IOException) { - e.printStackTrace() - fail("Error verifying extracted archive contents") + val extractor = + extractorClass() + .getConstructor( + Context::class.java, + String::class.java, + String::class.java, + Extractor.OnUpdate::class.java, + UpdatePosition::class.java, + ) + .newInstance( + ApplicationProvider.getApplicationContext(), + archiveFile.absolutePath, + Environment.getExternalStorageDirectory().absolutePath, + object : Extractor.OnUpdate { + override fun onStart( + totalBytes: Long, + firstEntryName: String, + ) = Unit + + override fun onUpdate(entryPath: String) = Unit + + override fun isCancelled(): Boolean = false + + override fun onFinish() { + latch.countDown() + try { + verifyExtractedArchiveContents() + } catch (e: IOException) { + e.printStackTrace() + fail("Error verifying extracted archive contents") + } } - } - }, - ServiceWatcherUtil.UPDATE_POSITION - ) + }, + ServiceWatcherUtil.UPDATE_POSITION, + ) extractor.extractEverything() latch.await() } diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/AbstractCompressedFileExtractorTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/AbstractCompressedFileExtractorTest.kt index 077c1050d0..5e9b7f2c43 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/AbstractCompressedFileExtractorTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/AbstractCompressedFileExtractorTest.kt @@ -31,32 +31,38 @@ import java.io.File import java.util.concurrent.CountDownLatch abstract class AbstractCompressedFileExtractorTest : AbstractExtractorTest() { - @Throws(Exception::class) override fun doTestExtractFiles() { val latch = CountDownLatch(1) - val extractor = extractorClass() - .getConstructor( - Context::class.java, - String::class.java, - String::class.java, - Extractor.OnUpdate::class.java, - UpdatePosition::class.java - ) - .newInstance( - ApplicationProvider.getApplicationContext(), - archiveFile.absolutePath, - Environment.getExternalStorageDirectory().absolutePath, - object : Extractor.OnUpdate { - override fun onStart(totalBytes: Long, firstEntryName: String) = Unit - override fun onUpdate(entryPath: String) = Unit - override fun isCancelled(): Boolean = false - override fun onFinish() { - latch.countDown() - } - }, - ServiceWatcherUtil.UPDATE_POSITION - ) + val extractor = + extractorClass() + .getConstructor( + Context::class.java, + String::class.java, + String::class.java, + Extractor.OnUpdate::class.java, + UpdatePosition::class.java, + ) + .newInstance( + ApplicationProvider.getApplicationContext(), + archiveFile.absolutePath, + Environment.getExternalStorageDirectory().absolutePath, + object : Extractor.OnUpdate { + override fun onStart( + totalBytes: Long, + firstEntryName: String, + ) = Unit + + override fun onUpdate(entryPath: String) = Unit + + override fun isCancelled(): Boolean = false + + override fun onFinish() { + latch.countDown() + } + }, + ServiceWatcherUtil.UPDATE_POSITION, + ) extractor.extractEverything() latch.await() verifyExtractedArchiveContents() diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/AbstractExtractorPasswordProtectedArchivesTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/AbstractExtractorPasswordProtectedArchivesTest.kt index a5d8a654c7..d8f98e9761 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/AbstractExtractorPasswordProtectedArchivesTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/AbstractExtractorPasswordProtectedArchivesTest.kt @@ -28,7 +28,6 @@ import java.io.File import java.io.IOException abstract class AbstractExtractorPasswordProtectedArchivesTest : AbstractArchiveExtractorTest() { - /** * Test extract files without password. */ @@ -92,10 +91,11 @@ abstract class AbstractExtractorPasswordProtectedArchivesTest : AbstractArchiveE } override val archiveFile: File - get() = File( - Environment.getExternalStorageDirectory(), - "test-archive-encrypted.$archiveType" - ) + get() = + File( + Environment.getExternalStorageDirectory(), + "test-archive-encrypted.$archiveType", + ) protected abstract fun expectedRootExceptionClass(): Array> @@ -108,7 +108,9 @@ abstract class AbstractExtractorPasswordProtectedArchivesTest : AbstractArchiveE } else { c.isAssignableFrom(e.javaClass) } - ) return + ) { + return + } } Assert.fail("Exception verification failed.") throw e diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/AbstractExtractorTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/AbstractExtractorTest.kt index dbc2444af7..1d4a7612ef 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/AbstractExtractorTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/AbstractExtractorTest.kt @@ -47,8 +47,8 @@ import java.util.* @RunWith(AndroidJUnit4::class) @Config(shadows = [ShadowMultiDex::class], sdk = [KITKAT, P, Build.VERSION_CODES.R]) abstract class AbstractExtractorTest { - protected abstract fun extractorClass(): Class + protected abstract val archiveType: String private lateinit var systemTz: TimeZone @@ -95,26 +95,33 @@ abstract class AbstractExtractorTest { @Test open fun testExtractBadArchive() { val badArchive = File(Environment.getExternalStorageDirectory(), "bad-archive.$archiveType") - val extractor = extractorClass() - .getConstructor( - Context::class.java, - String::class.java, - String::class.java, - Extractor.OnUpdate::class.java, - UpdatePosition::class.java - ) - .newInstance( - ApplicationProvider.getApplicationContext(), - badArchive.absolutePath, - Environment.getExternalStorageDirectory().absolutePath, - object : Extractor.OnUpdate { - override fun onStart(totalBytes: Long, firstEntryName: String) = Unit - override fun onUpdate(entryPath: String) = Unit - override fun isCancelled(): Boolean = false - override fun onFinish() = Unit - }, - ServiceWatcherUtil.UPDATE_POSITION - ) + val extractor = + extractorClass() + .getConstructor( + Context::class.java, + String::class.java, + String::class.java, + Extractor.OnUpdate::class.java, + UpdatePosition::class.java, + ) + .newInstance( + ApplicationProvider.getApplicationContext(), + badArchive.absolutePath, + Environment.getExternalStorageDirectory().absolutePath, + object : Extractor.OnUpdate { + override fun onStart( + totalBytes: Long, + firstEntryName: String, + ) = Unit + + override fun onUpdate(entryPath: String) = Unit + + override fun isCancelled(): Boolean = false + + override fun onFinish() = Unit + }, + ServiceWatcherUtil.UPDATE_POSITION, + ) try { extractor.extractEverything() fail("BadArchiveNotice was not thrown") @@ -130,13 +137,13 @@ abstract class AbstractExtractorTest { }?.forEach { FileInputStream(it).copyTo( FileOutputStream( - File(Environment.getExternalStorageDirectory(), it.name) - ) + File(Environment.getExternalStorageDirectory(), it.name), + ), ) ByteArrayInputStream(randomBytes()).copyTo( FileOutputStream( - File(Environment.getExternalStorageDirectory(), "bad-archive.$archiveType") - ) + File(Environment.getExternalStorageDirectory(), "bad-archive.$archiveType"), + ), ) } } diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/Bzip2ExtractorTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/Bzip2ExtractorTest.kt index 0f0e86e2f9..88f6756881 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/Bzip2ExtractorTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/Bzip2ExtractorTest.kt @@ -23,7 +23,6 @@ package com.amaze.filemanager.filesystem.compressed.extractcontents import com.amaze.filemanager.filesystem.compressed.extractcontents.helpers.Bzip2Extractor class Bzip2ExtractorTest : AbstractCompressedFileExtractorTest() { - override fun extractorClass(): Class = Bzip2Extractor::class.java override val archiveType: String = "bz2" diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/GzipExtractorTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/GzipExtractorTest.kt index c6688dd343..933218c135 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/GzipExtractorTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/GzipExtractorTest.kt @@ -23,7 +23,6 @@ package com.amaze.filemanager.filesystem.compressed.extractcontents import com.amaze.filemanager.filesystem.compressed.extractcontents.helpers.GzipExtractor class GzipExtractorTest : AbstractCompressedFileExtractorTest() { - override fun extractorClass(): Class = GzipExtractor::class.java override val archiveType: String = "gz" diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/ListPasswordProtected7ZipTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/ListPasswordProtected7ZipTest.kt index 3b987f9380..87c8917415 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/ListPasswordProtected7ZipTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/ListPasswordProtected7ZipTest.kt @@ -24,9 +24,9 @@ import android.os.Environment import java.io.File class ListPasswordProtected7ZipTest : PasswordProtected7ZipTest() { - - override val archiveFile: File = File( - Environment.getExternalStorageDirectory(), - "test-archive-encrypted-list.$archiveType" - ) + override val archiveFile: File = + File( + Environment.getExternalStorageDirectory(), + "test-archive-encrypted-list.$archiveType", + ) } diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/LzmaExtractorTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/LzmaExtractorTest.kt index 257aacac56..9ceea6283a 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/LzmaExtractorTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/LzmaExtractorTest.kt @@ -23,7 +23,6 @@ package com.amaze.filemanager.filesystem.compressed.extractcontents import com.amaze.filemanager.filesystem.compressed.extractcontents.helpers.LzmaExtractor class LzmaExtractorTest : AbstractCompressedFileExtractorTest() { - override fun extractorClass(): Class = LzmaExtractor::class.java override val archiveType: String = "lzma" diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/PasswordProtected7ZipTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/PasswordProtected7ZipTest.kt index 587c77dcaf..4c8efafc9c 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/PasswordProtected7ZipTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/PasswordProtected7ZipTest.kt @@ -25,7 +25,6 @@ import org.apache.commons.compress.PasswordRequiredException import org.tukaani.xz.CorruptedInputException open class PasswordProtected7ZipTest : AbstractExtractorPasswordProtectedArchivesTest() { - override fun extractorClass(): Class = SevenZipExtractor::class.java override fun expectedRootExceptionClass(): Array> = diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/PasswordProtectedZipTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/PasswordProtectedZipTest.kt index 29329d6e8f..1a3acf8045 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/PasswordProtectedZipTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/PasswordProtectedZipTest.kt @@ -24,12 +24,12 @@ import com.amaze.filemanager.filesystem.compressed.extractcontents.helpers.ZipEx import org.apache.commons.compress.PasswordRequiredException class PasswordProtectedZipTest : AbstractExtractorPasswordProtectedArchivesTest() { - override fun extractorClass(): Class = ZipExtractor::class.java - override fun expectedRootExceptionClass(): Array> = arrayOf( - PasswordRequiredException::class.java - ) + override fun expectedRootExceptionClass(): Array> = + arrayOf( + PasswordRequiredException::class.java, + ) override val archiveType: String = "zip" } diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/SevenZipExtractorTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/SevenZipExtractorTest.kt index 58e7a9a536..d730b39644 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/SevenZipExtractorTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/SevenZipExtractorTest.kt @@ -23,7 +23,6 @@ package com.amaze.filemanager.filesystem.compressed.extractcontents import com.amaze.filemanager.filesystem.compressed.extractcontents.helpers.SevenZipExtractor open class SevenZipExtractorTest : AbstractArchiveExtractorTest() { - override val archiveType: String = "7z" override fun extractorClass(): Class = SevenZipExtractor::class.java diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/SevenZipWithoutTimestampTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/SevenZipWithoutTimestampTest.kt index 1261fe45b7..72b1efaaaf 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/SevenZipWithoutTimestampTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/SevenZipWithoutTimestampTest.kt @@ -28,12 +28,12 @@ import java.io.File * Test for extracting 7z archives without timestamps in entries. See #3035 */ class SevenZipWithoutTimestampTest : SevenZipExtractorTest() { - override val archiveFile: File - get() = File( - Environment.getExternalStorageDirectory(), - "test-archive-no-timestamp.$archiveType" - ) + get() = + File( + Environment.getExternalStorageDirectory(), + "test-archive-no-timestamp.$archiveType", + ) /** * As timestamp is only the time we extract the file, we just check it's created recently. diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/TarBzip2ExtractorTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/TarBzip2ExtractorTest.kt index cff04f12ca..53761d1387 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/TarBzip2ExtractorTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/TarBzip2ExtractorTest.kt @@ -23,7 +23,6 @@ package com.amaze.filemanager.filesystem.compressed.extractcontents import com.amaze.filemanager.filesystem.compressed.extractcontents.helpers.TarBzip2Extractor open class TarBzip2ExtractorTest : AbstractArchiveExtractorTest() { - override val archiveType: String = "tar.bz2" override fun extractorClass(): Class = TarBzip2Extractor::class.java diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/TarBzip2ExtractorTest2.kt b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/TarBzip2ExtractorTest2.kt index c8545fd50e..ae8ada8978 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/TarBzip2ExtractorTest2.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/TarBzip2ExtractorTest2.kt @@ -21,6 +21,5 @@ package com.amaze.filemanager.filesystem.compressed.extractcontents class TarBzip2ExtractorTest2 : TarBzip2ExtractorTest() { - override val archiveType: String = "tbz" } diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/TarExtractorTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/TarExtractorTest.kt index 958aca73c3..2fe7e3f066 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/TarExtractorTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/TarExtractorTest.kt @@ -25,7 +25,6 @@ import org.junit.Ignore import org.junit.Test class TarExtractorTest : AbstractArchiveExtractorTest() { - override val archiveType: String = "tar" override fun extractorClass(): Class = TarExtractor::class.java diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/TarGzExtractorTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/TarGzExtractorTest.kt index 6789bcb563..0f537554b4 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/TarGzExtractorTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/TarGzExtractorTest.kt @@ -23,7 +23,6 @@ package com.amaze.filemanager.filesystem.compressed.extractcontents import com.amaze.filemanager.filesystem.compressed.extractcontents.helpers.TarGzExtractor open class TarGzExtractorTest : AbstractArchiveExtractorTest() { - override val archiveType: String = "tar.gz" override fun extractorClass(): Class = TarGzExtractor::class.java diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/TarLzmaExtractorTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/TarLzmaExtractorTest.kt index 60285cc34b..e4d0707408 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/TarLzmaExtractorTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/TarLzmaExtractorTest.kt @@ -23,7 +23,6 @@ package com.amaze.filemanager.filesystem.compressed.extractcontents import com.amaze.filemanager.filesystem.compressed.extractcontents.helpers.TarLzmaExtractor class TarLzmaExtractorTest : AbstractArchiveExtractorTest() { - override val archiveType: String = "tar.lzma" override fun extractorClass(): Class = TarLzmaExtractor::class.java diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/TarXzExtractorTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/TarXzExtractorTest.kt index 40f37afa70..6125b05b7f 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/TarXzExtractorTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/TarXzExtractorTest.kt @@ -23,7 +23,6 @@ package com.amaze.filemanager.filesystem.compressed.extractcontents import com.amaze.filemanager.filesystem.compressed.extractcontents.helpers.TarXzExtractor class TarXzExtractorTest : AbstractArchiveExtractorTest() { - override val archiveType: String = "tar.xz" override fun extractorClass(): Class = TarXzExtractor::class.java diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/TgzExtractorTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/TgzExtractorTest.kt index 6835e38725..72267c773d 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/TgzExtractorTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/TgzExtractorTest.kt @@ -21,6 +21,5 @@ package com.amaze.filemanager.filesystem.compressed.extractcontents class TgzExtractorTest : TarGzExtractorTest() { - override val archiveType: String = "tgz" } diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/XzExtractorTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/XzExtractorTest.kt index 63a9f1db36..85060b0b60 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/XzExtractorTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/XzExtractorTest.kt @@ -23,7 +23,6 @@ package com.amaze.filemanager.filesystem.compressed.extractcontents import com.amaze.filemanager.filesystem.compressed.extractcontents.helpers.XzExtractor class XzExtractorTest : AbstractCompressedFileExtractorTest() { - override fun extractorClass(): Class = XzExtractor::class.java override val archiveType: String = "xz" diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/ZipExtractorTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/ZipExtractorTest.kt index 98414c268d..418868998e 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/ZipExtractorTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/ZipExtractorTest.kt @@ -23,7 +23,6 @@ package com.amaze.filemanager.filesystem.compressed.extractcontents import com.amaze.filemanager.filesystem.compressed.extractcontents.helpers.ZipExtractor class ZipExtractorTest : AbstractArchiveExtractorTest() { - override val archiveType: String = "zip" override fun extractorClass(): Class = ZipExtractor::class.java diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/files/FileListSorterTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/files/FileListSorterTest.kt index 5a4f657bd9..cf77873108 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/files/FileListSorterTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/files/FileListSorterTest.kt @@ -43,7 +43,7 @@ import org.robolectric.annotation.Config @RunWith(AndroidJUnit4::class) @Config( shadows = [ShadowMultiDex::class], - sdk = [Build.VERSION_CODES.KITKAT, Build.VERSION_CODES.P, Build.VERSION_CODES.R] + sdk = [Build.VERSION_CODES.KITKAT, Build.VERSION_CODES.P, Build.VERSION_CODES.R], ) @Suppress("StringLiteralDuplication", "ComplexMethod", "LongMethod", "LargeClass") class FileListSorterTest { @@ -57,38 +57,41 @@ class FileListSorterTest { */ @Test fun testDir0File1DirAndFile2NoDir() { - val fileListSorter = FileListSorter( - DirSortBy.DIR_ON_TOP, - SortType(SortBy.NAME, SortOrder.ASC) - ) - val file1 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "abc1", - "C:\\AmazeFileManager\\abc1", - "user", - "symlink", - "100", - 123L, - true, - "1234", - true, - false, - OpenMode.UNKNOWN - ) - val file2 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "abc2.txt", - "C:\\AmazeFileManager\\abc2", - "user", - "symlink", - "101", - 124L, - true, - "1235", - false, - false, - OpenMode.UNKNOWN - ) + val fileListSorter = + FileListSorter( + DirSortBy.DIR_ON_TOP, + SortType(SortBy.NAME, SortOrder.ASC), + ) + val file1 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "abc1", + "C:\\AmazeFileManager\\abc1", + "user", + "symlink", + "100", + 123L, + true, + "1234", + true, + false, + OpenMode.UNKNOWN, + ) + val file2 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "abc2.txt", + "C:\\AmazeFileManager\\abc2", + "user", + "symlink", + "101", + 124L, + true, + "1235", + false, + false, + OpenMode.UNKNOWN, + ) Assert.assertEquals(fileListSorter.compare(file1, file2).toLong(), -1) } @@ -96,7 +99,8 @@ class FileListSorterTest { public LayoutElementParcelable(String title, String path, String permissions, String symlink, String size, long longSize, boolean header, String date, boolean isDirectory, boolean useThumbs, OpenMode openMode) - */ + */ + /** * Purpose: when dirsOnTop is [DirSortBy.DIR_ON_TOP], if file1 is not directory && file2 is directory, result is 1 * @@ -107,38 +111,41 @@ class FileListSorterTest { */ @Test fun testDir0File1NoDirAndFile2Dir() { - val fileListSorter = FileListSorter( - DirSortBy.DIR_ON_TOP, - SortType(SortBy.NAME, SortOrder.ASC) - ) - val file1 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "abc1.txt", - "C:\\AmazeFileManager\\abc1", - "user", - "symlink", - "100", - 123L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ) - val file2 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "abc2", - "C:\\AmazeFileManager\\abc2", - "user", - "symlink", - "101", - 124L, - true, - "1235", - true, - false, - OpenMode.UNKNOWN - ) + val fileListSorter = + FileListSorter( + DirSortBy.DIR_ON_TOP, + SortType(SortBy.NAME, SortOrder.ASC), + ) + val file1 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "abc1.txt", + "C:\\AmazeFileManager\\abc1", + "user", + "symlink", + "100", + 123L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ) + val file2 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "abc2", + "C:\\AmazeFileManager\\abc2", + "user", + "symlink", + "101", + 124L, + true, + "1235", + true, + false, + OpenMode.UNKNOWN, + ) Assert.assertEquals(fileListSorter.compare(file1, file2).toLong(), 1) } @@ -152,38 +159,41 @@ class FileListSorterTest { */ @Test fun testDir1File1DirAndFile2NoDir() { - val fileListSorter = FileListSorter( - DirSortBy.FILE_ON_TOP, - SortType(SortBy.NAME, SortOrder.ASC) - ) - val file1 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "abc1", - "C:\\AmazeFileManager\\abc1", - "user", - "symlink", - "100", - 123L, - true, - "1234", - true, - false, - OpenMode.UNKNOWN - ) - val file2 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "abc2.txt", - "C:\\AmazeFileManager\\abc2", - "user", - "symlink", - "101", - 124L, - true, - "1235", - false, - false, - OpenMode.UNKNOWN - ) + val fileListSorter = + FileListSorter( + DirSortBy.FILE_ON_TOP, + SortType(SortBy.NAME, SortOrder.ASC), + ) + val file1 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "abc1", + "C:\\AmazeFileManager\\abc1", + "user", + "symlink", + "100", + 123L, + true, + "1234", + true, + false, + OpenMode.UNKNOWN, + ) + val file2 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "abc2.txt", + "C:\\AmazeFileManager\\abc2", + "user", + "symlink", + "101", + 124L, + true, + "1235", + false, + false, + OpenMode.UNKNOWN, + ) Assert.assertEquals(fileListSorter.compare(file1, file2).toLong(), 1) } @@ -197,42 +207,46 @@ class FileListSorterTest { */ @Test fun testDir1File1NoDirAndFile2Dir() { - val fileListSorter = FileListSorter( - DirSortBy.FILE_ON_TOP, - SortType(SortBy.NAME, SortOrder.ASC) - ) - val file1 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "abc1.txt", - "C:\\AmazeFileManager\\abc1", - "user", - "symlink", - "100", - 123L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ) - val file2 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "abc2", - "C:\\AmazeFileManager\\abc2", - "user", - "symlink", - "101", - 124L, - true, - "1235", - true, - false, - OpenMode.UNKNOWN - ) + val fileListSorter = + FileListSorter( + DirSortBy.FILE_ON_TOP, + SortType(SortBy.NAME, SortOrder.ASC), + ) + val file1 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "abc1.txt", + "C:\\AmazeFileManager\\abc1", + "user", + "symlink", + "100", + 123L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ) + val file2 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "abc2", + "C:\\AmazeFileManager\\abc2", + "user", + "symlink", + "101", + 124L, + true, + "1235", + true, + false, + OpenMode.UNKNOWN, + ) Assert.assertEquals(fileListSorter.compare(file1, file2).toLong(), -1) } // From here, use dir is not DIR_ON_TOP or FILE_ON_TOP. -> Select dir is NONE_ON_TOP + /** * Purpose: when sort is [SortBy.NAME], if file1 title's length bigger than file2 title's length, result is * positive @@ -244,38 +258,41 @@ class FileListSorterTest { */ @Test fun testSort0File1TitleBigger() { - val fileListSorter = FileListSorter( - DirSortBy.NONE_ON_TOP, - SortType(SortBy.NAME, SortOrder.ASC) - ) - val file1 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "abc1.txt", - "C:\\AmazeFileManager\\abc1", - "user", - "symlink", - "100", - 123L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ) - val file2 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "abc.txt", - "C:\\AmazeFileManager\\abc", - "user", - "symlink", - "101", - 124L, - true, - "1235", - false, - false, - OpenMode.UNKNOWN - ) + val fileListSorter = + FileListSorter( + DirSortBy.NONE_ON_TOP, + SortType(SortBy.NAME, SortOrder.ASC), + ) + val file1 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "abc1.txt", + "C:\\AmazeFileManager\\abc1", + "user", + "symlink", + "100", + 123L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ) + val file2 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "abc.txt", + "C:\\AmazeFileManager\\abc", + "user", + "symlink", + "101", + 124L, + true, + "1235", + false, + false, + OpenMode.UNKNOWN, + ) Assert.assertThat(fileListSorter.compare(file1, file2), Matchers.greaterThan(0)) } @@ -290,38 +307,41 @@ class FileListSorterTest { */ @Test fun testSort0File2TitleBigger() { - val fileListSorter = FileListSorter( - DirSortBy.NONE_ON_TOP, - SortType(SortBy.NAME, SortOrder.ASC) - ) - val file1 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "abc.txt", - "C:\\AmazeFileManager\\abc", - "user", - "symlink", - "100", - 123L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ) - val file2 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "abc2.txt", - "C:\\AmazeFileManager\\abc2", - "user", - "symlink", - "101", - 124L, - true, - "1235", - false, - false, - OpenMode.UNKNOWN - ) + val fileListSorter = + FileListSorter( + DirSortBy.NONE_ON_TOP, + SortType(SortBy.NAME, SortOrder.ASC), + ) + val file1 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "abc.txt", + "C:\\AmazeFileManager\\abc", + "user", + "symlink", + "100", + 123L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ) + val file2 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "abc2.txt", + "C:\\AmazeFileManager\\abc2", + "user", + "symlink", + "101", + 124L, + true, + "1235", + false, + false, + OpenMode.UNKNOWN, + ) Assert.assertThat(fileListSorter.compare(file1, file2), Matchers.lessThan(0)) } @@ -336,38 +356,41 @@ class FileListSorterTest { */ @Test fun testSort0TitleSame() { - val fileListSorter = FileListSorter( - DirSortBy.NONE_ON_TOP, - SortType(SortBy.NAME, SortOrder.ASC) - ) - val file1 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "abc.txt", - "C:\\AmazeFileManager\\abc", - "user", - "symlink", - "100", - 123L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ) - val file2 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "ABC.txt", - "C:\\AmazeFileManager\\ABC", - "user", - "symlink", - "101", - 124L, - true, - "1235", - false, - false, - OpenMode.UNKNOWN - ) + val fileListSorter = + FileListSorter( + DirSortBy.NONE_ON_TOP, + SortType(SortBy.NAME, SortOrder.ASC), + ) + val file1 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "abc.txt", + "C:\\AmazeFileManager\\abc", + "user", + "symlink", + "100", + 123L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ) + val file2 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "ABC.txt", + "C:\\AmazeFileManager\\ABC", + "user", + "symlink", + "101", + 124L, + true, + "1235", + false, + false, + OpenMode.UNKNOWN, + ) Assert.assertEquals(fileListSorter.compare(file1, file2).toLong(), 0) } @@ -381,38 +404,41 @@ class FileListSorterTest { */ @Test fun testSort1File1DateLatest() { - val fileListSorter = FileListSorter( - DirSortBy.NONE_ON_TOP, - SortType(SortBy.LAST_MODIFIED, SortOrder.ASC) - ) - val file1 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "abc.txt", - "C:\\AmazeFileManager\\abc", - "user", - "symlink", - "100", - 123L, - true, - "1235", - false, - false, - OpenMode.UNKNOWN - ) - val file2 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "abc2.txt", - "C:\\AmazeFileManager\\abc2", - "user", - "symlink", - "101", - 124L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ) + val fileListSorter = + FileListSorter( + DirSortBy.NONE_ON_TOP, + SortType(SortBy.LAST_MODIFIED, SortOrder.ASC), + ) + val file1 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "abc.txt", + "C:\\AmazeFileManager\\abc", + "user", + "symlink", + "100", + 123L, + true, + "1235", + false, + false, + OpenMode.UNKNOWN, + ) + val file2 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "abc2.txt", + "C:\\AmazeFileManager\\abc2", + "user", + "symlink", + "101", + 124L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ) Assert.assertThat(fileListSorter.compare(file1, file2), Matchers.greaterThan(0)) } @@ -426,38 +452,41 @@ class FileListSorterTest { */ @Test fun testSort1File2DateLatest() { - val fileListSorter = FileListSorter( - DirSortBy.NONE_ON_TOP, - SortType(SortBy.LAST_MODIFIED, SortOrder.ASC) - ) - val file1 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "abc.txt", - "C:\\AmazeFileManager\\abc", - "user", - "symlink", - "100", - 123L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ) - val file2 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "abc2.txt", - "C:\\AmazeFileManager\\abc2", - "user", - "symlink", - "101", - 124L, - true, - "1235", - false, - false, - OpenMode.UNKNOWN - ) + val fileListSorter = + FileListSorter( + DirSortBy.NONE_ON_TOP, + SortType(SortBy.LAST_MODIFIED, SortOrder.ASC), + ) + val file1 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "abc.txt", + "C:\\AmazeFileManager\\abc", + "user", + "symlink", + "100", + 123L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ) + val file2 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "abc2.txt", + "C:\\AmazeFileManager\\abc2", + "user", + "symlink", + "101", + 124L, + true, + "1235", + false, + false, + OpenMode.UNKNOWN, + ) Assert.assertThat(fileListSorter.compare(file1, file2), Matchers.lessThan(0)) } @@ -471,38 +500,41 @@ class FileListSorterTest { */ @Test fun testSort1FileDateSame() { - val fileListSorter = FileListSorter( - DirSortBy.NONE_ON_TOP, - SortType(SortBy.LAST_MODIFIED, SortOrder.ASC) - ) - val file1 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "abc.txt", - "C:\\AmazeFileManager\\abc", - "user", - "symlink", - "100", - 123L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ) - val file2 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "abc2.txt", - "C:\\AmazeFileManager\\abc2", - "user", - "symlink", - "101", - 124L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ) + val fileListSorter = + FileListSorter( + DirSortBy.NONE_ON_TOP, + SortType(SortBy.LAST_MODIFIED, SortOrder.ASC), + ) + val file1 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "abc.txt", + "C:\\AmazeFileManager\\abc", + "user", + "symlink", + "100", + 123L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ) + val file2 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "abc2.txt", + "C:\\AmazeFileManager\\abc2", + "user", + "symlink", + "101", + 124L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ) Assert.assertEquals(fileListSorter.compare(file1, file2).toLong(), 0) } @@ -517,38 +549,41 @@ class FileListSorterTest { */ @Test fun testSort2NoDirAndFile1SizeBigger() { - val fileListSorter = FileListSorter( - DirSortBy.NONE_ON_TOP, - SortType(SortBy.SIZE, SortOrder.ASC) - ) - val file1 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "abc.txt", - "C:\\AmazeFileManager\\abc", - "user", - "symlink", - "101", - 124L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ) - val file2 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "abc2.txt", - "C:\\AmazeFileManager\\abc2", - "user", - "symlink", - "100", - 123L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ) + val fileListSorter = + FileListSorter( + DirSortBy.NONE_ON_TOP, + SortType(SortBy.SIZE, SortOrder.ASC), + ) + val file1 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "abc.txt", + "C:\\AmazeFileManager\\abc", + "user", + "symlink", + "101", + 124L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ) + val file2 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "abc2.txt", + "C:\\AmazeFileManager\\abc2", + "user", + "symlink", + "100", + 123L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ) Assert.assertThat(fileListSorter.compare(file1, file2), Matchers.greaterThan(0)) } @@ -563,38 +598,41 @@ class FileListSorterTest { */ @Test fun testSort2NoDirAndFile2SizeBigger() { - val fileListSorter = FileListSorter( - DirSortBy.NONE_ON_TOP, - SortType(SortBy.SIZE, SortOrder.ASC) - ) - val file1 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "abc.txt", - "C:\\AmazeFileManager\\abc", - "user", - "symlink", - "100", - 123L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ) - val file2 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "abc2.txt", - "C:\\AmazeFileManager\\abc2", - "user", - "symlink", - "101", - 124L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ) + val fileListSorter = + FileListSorter( + DirSortBy.NONE_ON_TOP, + SortType(SortBy.SIZE, SortOrder.ASC), + ) + val file1 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "abc.txt", + "C:\\AmazeFileManager\\abc", + "user", + "symlink", + "100", + 123L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ) + val file2 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "abc2.txt", + "C:\\AmazeFileManager\\abc2", + "user", + "symlink", + "101", + 124L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ) Assert.assertThat(fileListSorter.compare(file1, file2), Matchers.lessThan(0)) } @@ -609,38 +647,41 @@ class FileListSorterTest { */ @Test fun testSort2NoDirAndFileSizeSame() { - val fileListSorter = FileListSorter( - DirSortBy.NONE_ON_TOP, - SortType(SortBy.SIZE, SortOrder.ASC) - ) - val file1 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "abc.txt", - "C:\\AmazeFileManager\\abc", - "user", - "symlink", - "100", - 123L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ) - val file2 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "abc2.txt", - "C:\\AmazeFileManager\\abc2", - "user", - "symlink", - "100", - 123L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ) + val fileListSorter = + FileListSorter( + DirSortBy.NONE_ON_TOP, + SortType(SortBy.SIZE, SortOrder.ASC), + ) + val file1 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "abc.txt", + "C:\\AmazeFileManager\\abc", + "user", + "symlink", + "100", + 123L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ) + val file2 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "abc2.txt", + "C:\\AmazeFileManager\\abc2", + "user", + "symlink", + "100", + 123L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ) Assert.assertEquals(fileListSorter.compare(file1, file2).toLong(), 0) } @@ -655,38 +696,41 @@ class FileListSorterTest { */ @Test fun testSort2File1DirAndFile1TitleBigger() { - val fileListSorter = FileListSorter( - DirSortBy.NONE_ON_TOP, - SortType(SortBy.SIZE, SortOrder.ASC) - ) - val file1 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "abc1", - "C:\\AmazeFileManager\\abc1", - "user", - "symlink", - "101", - 124L, - true, - "1234", - true, - false, - OpenMode.UNKNOWN - ) - val file2 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "abc.txt", - "C:\\AmazeFileManager\\abc", - "user", - "symlink", - "100", - 123L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ) + val fileListSorter = + FileListSorter( + DirSortBy.NONE_ON_TOP, + SortType(SortBy.SIZE, SortOrder.ASC), + ) + val file1 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "abc1", + "C:\\AmazeFileManager\\abc1", + "user", + "symlink", + "101", + 124L, + true, + "1234", + true, + false, + OpenMode.UNKNOWN, + ) + val file2 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "abc.txt", + "C:\\AmazeFileManager\\abc", + "user", + "symlink", + "100", + 123L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ) Assert.assertThat(fileListSorter.compare(file1, file2), Matchers.greaterThan(0)) } @@ -701,38 +745,41 @@ class FileListSorterTest { */ @Test fun testSort2File1DirAndFile2TitleBigger() { - val fileListSorter = FileListSorter( - DirSortBy.NONE_ON_TOP, - SortType(SortBy.SIZE, SortOrder.ASC) - ) - val file1 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "abc", - "C:\\AmazeFileManager\\abc", - "user", - "symlink", - "100", - 123L, - true, - "1234", - true, - false, - OpenMode.UNKNOWN - ) - val file2 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "abc2.txt", - "C:\\AmazeFileManager\\abc2", - "user", - "symlink", - "101", - 124L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ) + val fileListSorter = + FileListSorter( + DirSortBy.NONE_ON_TOP, + SortType(SortBy.SIZE, SortOrder.ASC), + ) + val file1 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "abc", + "C:\\AmazeFileManager\\abc", + "user", + "symlink", + "100", + 123L, + true, + "1234", + true, + false, + OpenMode.UNKNOWN, + ) + val file2 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "abc2.txt", + "C:\\AmazeFileManager\\abc2", + "user", + "symlink", + "101", + 124L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ) Assert.assertThat(fileListSorter.compare(file1, file2), Matchers.lessThan(0)) } @@ -747,38 +794,41 @@ class FileListSorterTest { */ @Test fun testSort2File2DirAndFile1TitleBigger() { - val fileListSorter = FileListSorter( - DirSortBy.NONE_ON_TOP, - SortType(SortBy.SIZE, SortOrder.ASC) - ) - val file1 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "abc1.txt", - "C:\\AmazeFileManager\\abc1", - "user", - "symlink", - "101", - 124L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ) - val file2 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "abc", - "C:\\AmazeFileManager\\abc", - "user", - "symlink", - "100", - 123L, - true, - "1234", - true, - false, - OpenMode.UNKNOWN - ) + val fileListSorter = + FileListSorter( + DirSortBy.NONE_ON_TOP, + SortType(SortBy.SIZE, SortOrder.ASC), + ) + val file1 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "abc1.txt", + "C:\\AmazeFileManager\\abc1", + "user", + "symlink", + "101", + 124L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ) + val file2 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "abc", + "C:\\AmazeFileManager\\abc", + "user", + "symlink", + "100", + 123L, + true, + "1234", + true, + false, + OpenMode.UNKNOWN, + ) Assert.assertThat(fileListSorter.compare(file1, file2), Matchers.greaterThan(0)) } @@ -793,38 +843,41 @@ class FileListSorterTest { */ @Test fun testSort2File2DirAndFile2TitleBigger() { - val fileListSorter = FileListSorter( - DirSortBy.NONE_ON_TOP, - SortType(SortBy.SIZE, SortOrder.ASC) - ) - val file1 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "abc.txt", - "C:\\AmazeFileManager\\abc", - "user", - "symlink", - "100", - 123L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ) - val file2 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "abc2", - "C:\\AmazeFileManager\\abc2", - "user", - "symlink", - "101", - 124L, - true, - "1234", - true, - false, - OpenMode.UNKNOWN - ) + val fileListSorter = + FileListSorter( + DirSortBy.NONE_ON_TOP, + SortType(SortBy.SIZE, SortOrder.ASC), + ) + val file1 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "abc.txt", + "C:\\AmazeFileManager\\abc", + "user", + "symlink", + "100", + 123L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ) + val file2 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "abc2", + "C:\\AmazeFileManager\\abc2", + "user", + "symlink", + "101", + 124L, + true, + "1234", + true, + false, + OpenMode.UNKNOWN, + ) Assert.assertThat(fileListSorter.compare(file1, file2), Matchers.lessThan(0)) } @@ -839,38 +892,41 @@ class FileListSorterTest { */ @Test fun testSort2File2DirAndFileTitleSame() { - val fileListSorter = FileListSorter( - DirSortBy.NONE_ON_TOP, - SortType(SortBy.SIZE, SortOrder.ASC) - ) - val file1 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "abc", - "C:\\AmazeFileManager\\abc", - "user", - "symlink", - "100", - 123L, - true, - "1234", - true, - false, - OpenMode.UNKNOWN - ) - val file2 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "abc", - "C:\\AmazeFileManager\\abc", - "user", - "symlink", - "101", - 124L, - true, - "1234", - true, - false, - OpenMode.UNKNOWN - ) + val fileListSorter = + FileListSorter( + DirSortBy.NONE_ON_TOP, + SortType(SortBy.SIZE, SortOrder.ASC), + ) + val file1 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "abc", + "C:\\AmazeFileManager\\abc", + "user", + "symlink", + "100", + 123L, + true, + "1234", + true, + false, + OpenMode.UNKNOWN, + ) + val file2 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "abc", + "C:\\AmazeFileManager\\abc", + "user", + "symlink", + "101", + 124L, + true, + "1234", + true, + false, + OpenMode.UNKNOWN, + ) Assert.assertEquals(fileListSorter.compare(file1, file2).toLong(), 0) } @@ -885,38 +941,41 @@ class FileListSorterTest { */ @Test fun testSort3FileExtensionSameAndFile1TitleBigger() { - val fileListSorter = FileListSorter( - DirSortBy.NONE_ON_TOP, - SortType(SortBy.TYPE, SortOrder.ASC) - ) - val file1 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "abc1.txt", - "C:\\AmazeFileManager\\abc1", - "user", - "symlink", - "100", - 123L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ) - val file2 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "abc.txt", - "C:\\AmazeFileManager\\abc", - "user", - "symlink", - "101", - 124L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ) + val fileListSorter = + FileListSorter( + DirSortBy.NONE_ON_TOP, + SortType(SortBy.TYPE, SortOrder.ASC), + ) + val file1 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "abc1.txt", + "C:\\AmazeFileManager\\abc1", + "user", + "symlink", + "100", + 123L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ) + val file2 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "abc.txt", + "C:\\AmazeFileManager\\abc", + "user", + "symlink", + "101", + 124L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ) Assert.assertThat(fileListSorter.compare(file1, file2), Matchers.greaterThan(0)) } @@ -931,38 +990,41 @@ class FileListSorterTest { */ @Test fun testSort3FileExtensionSameAndFile2TitleBigger() { - val fileListSorter = FileListSorter( - DirSortBy.NONE_ON_TOP, - SortType(SortBy.TYPE, SortOrder.ASC) - ) - val file1 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "abc.txt", - "C:\\AmazeFileManager\\abc", - "user", - "symlink", - "100", - 123L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ) - val file2 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "abc2.txt", - "C:\\AmazeFileManager\\abc2", - "user", - "symlink", - "101", - 124L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ) + val fileListSorter = + FileListSorter( + DirSortBy.NONE_ON_TOP, + SortType(SortBy.TYPE, SortOrder.ASC), + ) + val file1 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "abc.txt", + "C:\\AmazeFileManager\\abc", + "user", + "symlink", + "100", + 123L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ) + val file2 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "abc2.txt", + "C:\\AmazeFileManager\\abc2", + "user", + "symlink", + "101", + 124L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ) Assert.assertThat(fileListSorter.compare(file1, file2), Matchers.lessThan(0)) } @@ -977,38 +1039,41 @@ class FileListSorterTest { */ @Test fun testSort3FileExtensionSameAndFileTitleSame() { - val fileListSorter = FileListSorter( - DirSortBy.NONE_ON_TOP, - SortType(SortBy.TYPE, SortOrder.ASC) - ) - val file1 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "abc.txt", - "C:\\AmazeFileManager\\abc", - "user", - "symlink", - "100", - 123L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ) - val file2 = LayoutElementParcelable( - ApplicationProvider.getApplicationContext(), - "ABC.txt", - "C:\\AmazeFileManager\\ABC", - "user", - "symlink", - "101", - 124L, - true, - "1234", - false, - false, - OpenMode.UNKNOWN - ) + val fileListSorter = + FileListSorter( + DirSortBy.NONE_ON_TOP, + SortType(SortBy.TYPE, SortOrder.ASC), + ) + val file1 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "abc.txt", + "C:\\AmazeFileManager\\abc", + "user", + "symlink", + "100", + 123L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ) + val file2 = + LayoutElementParcelable( + ApplicationProvider.getApplicationContext(), + "ABC.txt", + "C:\\AmazeFileManager\\ABC", + "user", + "symlink", + "101", + 124L, + true, + "1234", + false, + false, + OpenMode.UNKNOWN, + ) Assert.assertEquals(fileListSorter.compare(file1, file2).toLong(), 0) } } diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/files/FileUtilsTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/files/FileUtilsTest.kt index 7b8af9aafd..0133d70cba 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/files/FileUtilsTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/files/FileUtilsTest.kt @@ -41,7 +41,6 @@ import java.util.* @Config(sdk = [KITKAT, P, Build.VERSION_CODES.R]) @Suppress("TooManyFunctions", "StringLiteralDuplication") class FileUtilsTest { - /** * Test FileUtils.getPathsInPath() for directory * @@ -58,9 +57,9 @@ class FileUtilsTest { "/etc/default", "/etc/default/grub", "/etc/default/grub/2", - "/etc/default/grub/2/conf.d" + "/etc/default/grub/2/conf.d", ), - this + this, ) } } @@ -82,9 +81,9 @@ class FileUtilsTest { "/var/log/nginx", "/var/log/nginx/access", "/var/log/nginx/access/2021-01-01", - "/var/log/nginx/access/2021-01-01/error.log" + "/var/log/nginx/access/2021-01-01/error.log", ), - this + this, ) } } @@ -106,9 +105,9 @@ class FileUtilsTest { "/system/lib/modules", "/system/lib/modules/drivers", "/system/lib/modules/drivers/net", - "/system/lib/modules/drivers/net/broadcom" + "/system/lib/modules/drivers/net/broadcom", ), - this + this, ) } } @@ -130,9 +129,9 @@ class FileUtilsTest { "/some/nasty/path", "/some/nasty/path/with", "/some/nasty/path/with/space", - "/some/nasty/path/with/space/prefixed" + "/some/nasty/path/with/space/prefixed", ), - this + this, ) } } @@ -155,9 +154,9 @@ class FileUtilsTest { "/some/nasty/path/with", "/some/nasty/path/with/space ", "/some/nasty/path/with/space / in", - "/some/nasty/path/with/space / in/between" + "/some/nasty/path/with/space / in/between", ), - this + this, ) } } @@ -180,9 +179,9 @@ class FileUtilsTest { "/some/nasty/path/without", "/some/nasty/path/without/slash ", "/some/nasty/path/without/slash /as", - "/some/nasty/path/without/slash /as/ prefix" + "/some/nasty/path/without/slash /as/ prefix", ), - this + this, ) } } @@ -202,9 +201,9 @@ class FileUtilsTest { "smb://1.2.3.4/some", "smb://1.2.3.4/some/folder", "smb://1.2.3.4/some/folder/on", - "smb://1.2.3.4/some/folder/on/smb" + "smb://1.2.3.4/some/folder/on/smb", ), - this + this, ) } } @@ -224,9 +223,9 @@ class FileUtilsTest { "smb://user@1.2.3.4/some", "smb://user@1.2.3.4/some/folder", "smb://user@1.2.3.4/some/folder/on", - "smb://user@1.2.3.4/some/folder/on/smb" + "smb://user@1.2.3.4/some/folder/on/smb", ), - this + this, ) } } @@ -246,9 +245,9 @@ class FileUtilsTest { "smb://user:password@1.2.3.4/some", "smb://user:password@1.2.3.4/some/folder", "smb://user:password@1.2.3.4/some/folder/on", - "smb://user:password@1.2.3.4/some/folder/on/smb" + "smb://user:password@1.2.3.4/some/folder/on/smb", ), - this + this, ) } } @@ -268,9 +267,9 @@ class FileUtilsTest { "smb://user;workgroup:password@1.2.3.4/some", "smb://user;workgroup:password@1.2.3.4/some/folder", "smb://user;workgroup:password@1.2.3.4/some/folder/on", - "smb://user;workgroup:password@1.2.3.4/some/folder/on/smb" + "smb://user;workgroup:password@1.2.3.4/some/folder/on/smb", ), - this + this, ) } } @@ -291,9 +290,9 @@ class FileUtilsTest { arrayOf( "smb://user;workgroup:password@1.2.3.4", "smb://user;workgroup:password@1.2.3.4/user", - "smb://user;workgroup:password@1.2.3.4/user/My Documents" + "smb://user;workgroup:password@1.2.3.4/user/My Documents", ), - this + this, ) } } @@ -313,9 +312,9 @@ class FileUtilsTest { "ftp://user:password@1.2.3.4:3721/some", "ftp://user:password@1.2.3.4:3721/some/folder", "ftp://user:password@1.2.3.4:3721/some/folder/on", - "ftp://user:password@1.2.3.4:3721/some/folder/on/ftp" + "ftp://user:password@1.2.3.4:3721/some/folder/on/ftp", ), - this + this, ) } } @@ -339,9 +338,9 @@ class FileUtilsTest { "ftp://user:password@1.2.3.4:3721/あ/い", "ftp://user:password@1.2.3.4:3721/あ/い/う", "ftp://user:password@1.2.3.4:3721/あ/い/う/え", - "ftp://user:password@1.2.3.4:3721/あ/い/う/え/お" + "ftp://user:password@1.2.3.4:3721/あ/い/う/え/お", ), - this + this, ) } } @@ -389,18 +388,19 @@ class FileUtilsTest { /** * Test [FileUtils.parseName] */ + @Suppress("ktlint:standard:max-line-length") @Test fun testParseStringForHybridFileParcelable() { - /* ktlint-disable max-line-length */ // ls - val lsLines = arrayOf( - "-rwxr-x--- 1 root shell 29431 2009-01-01 08:00 init.rc", - "lrw-r--r-- 1 root root 15 2009-01-01 08:00 product -> /system/product", - "drwxr-xr-x 17 root root 4096 1970-05-19 08:40 system", - "-r--r--r-- 1 root root 10 1970-01-13 07:32 cpu_variant:arm", - "lrwxrwxrwx 1 root root 0 2022-10-05 15:39 ac -> ../../devices/platform/GFSH0001:00/power_supply/ac", - "lrwxrwxrwx 1 root root 0 2022-10-05 00:16 usb -> ../../devices/platform/soc/c440000.qcom,spmi/spmi-0/spmi0-02/c440000.qcom,spmi:qcom,pm8150b@2:qcom,qpnp-smb5/power_supply/usb" - ) + val lsLines = + arrayOf( + "-rwxr-x--- 1 root shell 29431 2009-01-01 08:00 init.rc", + "lrw-r--r-- 1 root root 15 2009-01-01 08:00 product -> /system/product", + "drwxr-xr-x 17 root root 4096 1970-05-19 08:40 system", + "-r--r--r-- 1 root root 10 1970-01-13 07:32 cpu_variant:arm", + "lrwxrwxrwx 1 root root 0 2022-10-05 15:39 ac -> ../../devices/platform/GFSH0001:00/power_supply/ac", + "lrwxrwxrwx 1 root root 0 2022-10-05 00:16 usb -> ../../devices/platform/soc/c440000.qcom,spmi/spmi-0/spmi0-02/c440000.qcom,spmi:qcom,pm8150b@2:qcom,qpnp-smb5/power_supply/usb", + ) // stat with old toybox or busybox // val a1 = "-rwxr-x--- 1 shell root 512 2009-01-01 08:00:00.000000000 `init.rc'" @@ -408,15 +408,15 @@ class FileUtilsTest { // val c1 = "drwxr-xr-x 17 root root 512 1970-05-19 08:40:27.269999949 `system'" // stat with new toybox - val statLines = arrayOf( - "-rwxr-x--- 1 shell root 512 1230796800 `init.rc'", - "lrw-r--r-- 1 root root 512 1230796800 `product' -> `/system/product'", - "drwxr-xr-x 17 root root 512 11922027 `system'", - "-r--r--r-- 1 root root 512 1035141 `cpu_variant:arm'", - "lrwxrwxrwx 1 root root 512 1664955558 /sys/class/power_supply/ac -> '../../devices/platform/GFSH0001:00/power_supply/ac'", - "lrwxrwxrwx 1 root root 512 1664956626 /sys/class/power_supply/usb -> '../../devices/platform/soc/c440000.qcom,spmi/spmi-0/spmi0-02/c440000.qcom,spmi:qcom,pm8150b@2:qcom,qpnp-smb5/power_supply/usb'" - ) - /* ktlint-enable max-line-length */ + val statLines = + arrayOf( + "-rwxr-x--- 1 shell root 512 1230796800 `init.rc'", + "lrw-r--r-- 1 root root 512 1230796800 `product' -> `/system/product'", + "drwxr-xr-x 17 root root 512 11922027 `system'", + "-r--r--r-- 1 root root 512 1035141 `cpu_variant:arm'", + "lrwxrwxrwx 1 root root 512 1664955558 /sys/class/power_supply/ac -> '../../devices/platform/GFSH0001:00/power_supply/ac'", + "lrwxrwxrwx 1 root root 512 1664956626 /sys/class/power_supply/usb -> '../../devices/platform/soc/c440000.qcom,spmi/spmi-0/spmi0-02/c440000.qcom,spmi:qcom,pm8150b@2:qcom,qpnp-smb5/power_supply/usb'", + ) val systemTz = TimeZone.getDefault() TimeZone.setDefault(TimeZone.getTimeZone("UTC")) @@ -427,12 +427,12 @@ class FileUtilsTest { assertEquals( "Parse error at index $index.\n lsLines=[$s]\n statLines=[${statLines[index]}]\n", result1.name, - result2.name + result2.name, ) assertEquals( "Parse error at index $index.\n lsLines=[$s]\n statLines=[${statLines[index]}]\n", result1.path, - result2.path + result2.path, ) } diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/files/GenericCopyUtilTest.java b/app/src/test/java/com/amaze/filemanager/filesystem/files/GenericCopyUtilTest.java index 76bcc296dc..89d19d94d4 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/files/GenericCopyUtilTest.java +++ b/app/src/test/java/com/amaze/filemanager/filesystem/files/GenericCopyUtilTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/files/sort/DirSortByTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/files/sort/DirSortByTest.kt index a4635fcc45..188618514d 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/files/sort/DirSortByTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/files/sort/DirSortByTest.kt @@ -32,7 +32,7 @@ import kotlin.random.Random @RunWith(AndroidJUnit4::class) @Config( shadows = [ShadowMultiDex::class], - sdk = [Build.VERSION_CODES.KITKAT, Build.VERSION_CODES.P, Build.VERSION_CODES.R] + sdk = [Build.VERSION_CODES.KITKAT, Build.VERSION_CODES.P, Build.VERSION_CODES.R], ) class DirSortByTest { /** Tests if [DirSortBy.getDirSortBy] returns the correct [DirSortBy] corresponding to the given index */ @@ -41,24 +41,24 @@ class DirSortByTest { Assert.assertEquals( "DirSortBy.getDirSortBy(0) did not return DIR_ON_TOP", DirSortBy.DIR_ON_TOP, - DirSortBy.getDirSortBy(0) + DirSortBy.getDirSortBy(0), ) Assert.assertEquals( "DirSortBy.getDirSortBy(1) did not return FILE_ON_TOP", DirSortBy.FILE_ON_TOP, - DirSortBy.getDirSortBy(1) + DirSortBy.getDirSortBy(1), ) Assert.assertEquals( "DirSortBy.getDirSortBy(2) did not return NONE_ON_TOP", DirSortBy.NONE_ON_TOP, - DirSortBy.getDirSortBy(2) + DirSortBy.getDirSortBy(2), ) // could be any int except 0 to 2 val randomIndex = Random.nextInt(3, Int.MAX_VALUE) Assert.assertEquals( "DirSortBy.getDirSortBy($randomIndex) did not return NONE_ON_TOP", DirSortBy.NONE_ON_TOP, - DirSortBy.getDirSortBy(randomIndex) + DirSortBy.getDirSortBy(randomIndex), ) } } diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/files/sort/SortByTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/files/sort/SortByTest.kt index c928b33587..673dfe2d39 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/files/sort/SortByTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/files/sort/SortByTest.kt @@ -32,44 +32,43 @@ import kotlin.random.Random @RunWith(AndroidJUnit4::class) @Config( shadows = [ShadowMultiDex::class], - sdk = [Build.VERSION_CODES.KITKAT, Build.VERSION_CODES.P, Build.VERSION_CODES.R] + sdk = [Build.VERSION_CODES.KITKAT, Build.VERSION_CODES.P, Build.VERSION_CODES.R], ) class SortByTest { - /** Tests if [SortBy.getSortBy] returns the correct [SortBy] corresponding to the given index */ @Test fun getSortByTest() { Assert.assertEquals( "SortBy.getSortBy(0) did not return NAME", SortBy.NAME, - SortBy.getSortBy(0) + SortBy.getSortBy(0), ) Assert.assertEquals( "SortBy.getSortBy(1) did not return LAST_MODIFIED", SortBy.LAST_MODIFIED, - SortBy.getSortBy(1) + SortBy.getSortBy(1), ) Assert.assertEquals( "SortBy.getSortBy(2) did not return SIZE", SortBy.SIZE, - SortBy.getSortBy(2) + SortBy.getSortBy(2), ) Assert.assertEquals( "SortBy.getSortBy(3) did not return TYPE", SortBy.TYPE, - SortBy.getSortBy(3) + SortBy.getSortBy(3), ) Assert.assertEquals( "SortBy.getSortBy(4) did not return RELEVANCE", SortBy.RELEVANCE, - SortBy.getSortBy(4) + SortBy.getSortBy(4), ) // could be any int except 0 to 4 val randomIndex = Random.nextInt(5, Int.MAX_VALUE) Assert.assertEquals( "SortBy.getDirectorySortBy($randomIndex) did not return NAME", SortBy.NAME, - SortBy.getDirectorySortBy(randomIndex) + SortBy.getDirectorySortBy(randomIndex), ) } @@ -79,29 +78,29 @@ class SortByTest { Assert.assertEquals( "SortBy.getDirectorySortBy(0) did not return NAME", SortBy.NAME, - SortBy.getDirectorySortBy(0) + SortBy.getDirectorySortBy(0), ) Assert.assertEquals( "SortBy.getDirectorySortBy(1) did not return LAST_MODIFIED", SortBy.LAST_MODIFIED, - SortBy.getDirectorySortBy(1) + SortBy.getDirectorySortBy(1), ) Assert.assertEquals( "SortBy.getDirectorySortBy(2) did not return SIZE", SortBy.SIZE, - SortBy.getDirectorySortBy(2) + SortBy.getDirectorySortBy(2), ) Assert.assertEquals( "SortBy.getDirectorySortBy(3) did not return TYPE", SortBy.TYPE, - SortBy.getDirectorySortBy(3) + SortBy.getDirectorySortBy(3), ) // could be any int except 0 to 3 val randomIndex = Random.nextInt(4, Int.MAX_VALUE) Assert.assertEquals( "SortBy.getDirectorySortBy($randomIndex) did not return NAME", SortBy.NAME, - SortBy.getDirectorySortBy(randomIndex) + SortBy.getDirectorySortBy(randomIndex), ) } } diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/files/sort/SortTypeTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/files/sort/SortTypeTest.kt index a01db7aeb6..204dab7dd5 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/files/sort/SortTypeTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/files/sort/SortTypeTest.kt @@ -31,62 +31,61 @@ import org.robolectric.annotation.Config @RunWith(AndroidJUnit4::class) @Config( shadows = [ShadowMultiDex::class], - sdk = [Build.VERSION_CODES.KITKAT, Build.VERSION_CODES.P, Build.VERSION_CODES.R] + sdk = [Build.VERSION_CODES.KITKAT, Build.VERSION_CODES.P, Build.VERSION_CODES.R], ) class SortTypeTest { - /** Tests if the Int returned from [SortType.toDirectorySortInt] is as expected */ @Test fun toDirectorySortIntTest() { Assert.assertEquals( "SortType with SortBy.NAME and SortOrder.ASC was not 0", 0, - SortType(SortBy.NAME, SortOrder.ASC).toDirectorySortInt() + SortType(SortBy.NAME, SortOrder.ASC).toDirectorySortInt(), ) Assert.assertEquals( "SortType with SortBy.LAST_MODIFIED and SortOrder.ASC was not 1", 1, - SortType(SortBy.LAST_MODIFIED, SortOrder.ASC).toDirectorySortInt() + SortType(SortBy.LAST_MODIFIED, SortOrder.ASC).toDirectorySortInt(), ) Assert.assertEquals( "SortType with SortBy.SIZE and SortOrder.ASC was not 2", 2, - SortType(SortBy.SIZE, SortOrder.ASC).toDirectorySortInt() + SortType(SortBy.SIZE, SortOrder.ASC).toDirectorySortInt(), ) Assert.assertEquals( "SortType with SortBy.TYPE and SortOrder.ASC was not 3", 3, - SortType(SortBy.TYPE, SortOrder.ASC).toDirectorySortInt() + SortType(SortBy.TYPE, SortOrder.ASC).toDirectorySortInt(), ) Assert.assertEquals( "SortType with SortBy.NAME and SortOrder.DESC was not 4", 4, - SortType(SortBy.NAME, SortOrder.DESC).toDirectorySortInt() + SortType(SortBy.NAME, SortOrder.DESC).toDirectorySortInt(), ) Assert.assertEquals( "SortType with SortBy.LAST_MODIFIED and SortOrder.DESC was not 5", 5, - SortType(SortBy.LAST_MODIFIED, SortOrder.DESC).toDirectorySortInt() + SortType(SortBy.LAST_MODIFIED, SortOrder.DESC).toDirectorySortInt(), ) Assert.assertEquals( "SortType with SortBy.SIZE and SortOrder.DESC was not 6", 6, - SortType(SortBy.SIZE, SortOrder.DESC).toDirectorySortInt() + SortType(SortBy.SIZE, SortOrder.DESC).toDirectorySortInt(), ) Assert.assertEquals( "SortType with SortBy.TYPE and SortOrder.DESC was not 7", 7, - SortType(SortBy.TYPE, SortOrder.DESC).toDirectorySortInt() + SortType(SortBy.TYPE, SortOrder.DESC).toDirectorySortInt(), ) Assert.assertEquals( "SortType with SortBy.RELEVANCE and SortOrder.ASC was not 0", 0, - SortType(SortBy.RELEVANCE, SortOrder.ASC).toDirectorySortInt() + SortType(SortBy.RELEVANCE, SortOrder.ASC).toDirectorySortInt(), ) Assert.assertEquals( "SortType with SortBy.RELEVANCE and SortOrder.DESC was not 4", 4, - SortType(SortBy.RELEVANCE, SortOrder.DESC).toDirectorySortInt() + SortType(SortBy.RELEVANCE, SortOrder.DESC).toDirectorySortInt(), ) } @@ -96,42 +95,42 @@ class SortTypeTest { Assert.assertEquals( "0 was not translated to SortType with SortBy.NAME and SortOrder.ASC", SortType(SortBy.NAME, SortOrder.ASC), - SortType.getDirectorySortType(0) + SortType.getDirectorySortType(0), ) Assert.assertEquals( "1 was not translated to SortType with SortBy.LAST_MODIFIED and SortOrder.ASC", SortType(SortBy.LAST_MODIFIED, SortOrder.ASC), - SortType.getDirectorySortType(1) + SortType.getDirectorySortType(1), ) Assert.assertEquals( "2 was not translated to SortType with SortBy.SIZE and SortOrder.ASC", SortType(SortBy.SIZE, SortOrder.ASC), - SortType.getDirectorySortType(2) + SortType.getDirectorySortType(2), ) Assert.assertEquals( "3 was not translated to SortType with SortBy.TYPE and SortOrder.ASC", SortType(SortBy.TYPE, SortOrder.ASC), - SortType.getDirectorySortType(3) + SortType.getDirectorySortType(3), ) Assert.assertEquals( "4 was not translated to SortType with SortBy.NAME and SortOrder.DESC", SortType(SortBy.NAME, SortOrder.DESC), - SortType.getDirectorySortType(4) + SortType.getDirectorySortType(4), ) Assert.assertEquals( "5 was not translated to SortType with SortBy.LAST_MODIFIED and SortOrder.DESC", SortType(SortBy.LAST_MODIFIED, SortOrder.DESC), - SortType.getDirectorySortType(5) + SortType.getDirectorySortType(5), ) Assert.assertEquals( "6 was not translated to SortType with SortBy.SIZE and SortOrder.DESC", SortType(SortBy.SIZE, SortOrder.DESC), - SortType.getDirectorySortType(6) + SortType.getDirectorySortType(6), ) Assert.assertEquals( "7 was not translated to SortType with SortBy.TYPE and SortOrder.DESC", SortType(SortBy.TYPE, SortOrder.DESC), - SortType.getDirectorySortType(7) + SortType.getDirectorySortType(7), ) } } diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/ftp/FtpHybridFileAnonymousLoginTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/ftp/FtpHybridFileAnonymousLoginTest.kt index fbb1de7394..f773ad61eb 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/ftp/FtpHybridFileAnonymousLoginTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/ftp/FtpHybridFileAnonymousLoginTest.kt @@ -33,43 +33,43 @@ import org.junit.Ignore */ @Ignore class FtpHybridFileAnonymousLoginTest : FtpHybridFileTest() { - override val ftpPort: Int get() = PORT override val ftpUrl: String - get() = NetCopyClientUtils.encryptFtpPathAsNecessary( - "${ftpPrefix}127.0.0.1:$ftpPort" - ) + get() = + NetCopyClientUtils.encryptFtpPathAsNecessary( + "${ftpPrefix}127.0.0.1:$ftpPort", + ) override fun saveConnectionSettings() { TestUtils.saveFtpConnectionSettings("", "") } companion object { - private const val PORT = 2223 /** * Extracted [FtpServerFactory] with anonymous login support into separate factory method. */ @JvmStatic - fun createAnonymousFtpServerFactory(): FtpServerFactory = FtpServerFactory().also { - val connectionConfigFactory = ConnectionConfigFactory() - connectionConfigFactory.isAnonymousLoginEnabled = true - val user = BaseUser() - user.name = FTPClientImpl.ANONYMOUS - user.homeDirectory = Environment.getExternalStorageDirectory().absolutePath - user.authorities = listOf(WritePermission()) - it.userManager.save(user) - it.connectionConfig = connectionConfigFactory.createConnectionConfig() - } + fun createAnonymousFtpServerFactory(): FtpServerFactory = + FtpServerFactory().also { + val connectionConfigFactory = ConnectionConfigFactory() + connectionConfigFactory.isAnonymousLoginEnabled = true + val user = BaseUser() + user.name = FTPClientImpl.ANONYMOUS + user.homeDirectory = Environment.getExternalStorageDirectory().absolutePath + user.authorities = listOf(WritePermission()) + it.userManager.save(user) + it.connectionConfig = connectionConfigFactory.createConnectionConfig() + } } override fun createFtpServerFactory(): FtpServerFactory { return createAnonymousFtpServerFactory().also { it.addListener( "default", - createDefaultFtpServerListener() + createDefaultFtpServerListener(), ) } } diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/ftp/FtpHybridFileTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/ftp/FtpHybridFileTest.kt index 76e1770dce..5b38f6efc3 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/ftp/FtpHybridFileTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/ftp/FtpHybridFileTest.kt @@ -61,12 +61,11 @@ import java.util.concurrent.TimeUnit @RunWith(AndroidJUnit4::class) @Config( sdk = [P], - shadows = [ShadowPasswordUtil::class, ShadowMultiDex::class] + shadows = [ShadowPasswordUtil::class, ShadowMultiDex::class], ) @Suppress("StringLiteralDuplication") @Ignore open class FtpHybridFileTest { - protected lateinit var tmpFile: File protected lateinit var hybridFile: HybridFile protected lateinit var ftpServer: FtpServer @@ -81,9 +80,10 @@ open class FtpHybridFileTest { protected open val ftpPort: Int get() = PORT protected open val ftpUrl: String - get() = NetCopyClientUtils.encryptFtpPathAsNecessary( - "${ftpPrefix}$USERNAME:$PASSWORD@127.0.0.1:$ftpPort" - ) + get() = + NetCopyClientUtils.encryptFtpPathAsNecessary( + "${ftpPrefix}$USERNAME:$PASSWORD@127.0.0.1:$ftpPort", + ) companion object { const val USERNAME = "ftpuser" @@ -133,7 +133,7 @@ open class FtpHybridFileTest { "\n" + " Was trying $ftpUrl, FTP server is running at " + getLoopbackAddress().hostAddress + - " and port $ftpPort" + " and port $ftpPort", ) } @@ -273,13 +273,13 @@ open class FtpHybridFileTest { @FlakyTest() fun testMkdir() { for ( - dir: String in arrayOf( + dir: String in arrayOf( // "newfolder", // "new folder 2", - "new%20folder%203", - "あいうえお", - "multiple/levels/down the pipe" - ) + "new%20folder%203", + "あいうえお", + "multiple/levels/down the pipe", + ) ) { val newFile = HybridFile(OpenMode.FTP, "$ftpUrl/$dir") val latch = CountDownLatch(1) @@ -289,12 +289,15 @@ open class FtpHybridFileTest { AppConfig.getInstance(), false, object : OperationsTest.AbstractErrorCallback() { - override fun done(file: HybridFile?, b: Boolean) { + override fun done( + file: HybridFile?, + b: Boolean, + ) { assertTrue(true == file?.exists()) assertEquals(newFile.path, file?.path) latch.countDown() } - } + }, ) latch.await() } @@ -302,8 +305,7 @@ open class FtpHybridFileTest { protected open fun beforeCreateFtpServer() = Unit - protected open fun saveConnectionSettings() = - TestUtils.saveFtpConnectionSettings(USERNAME, PASSWORD) + protected open fun saveConnectionSettings() = TestUtils.saveFtpConnectionSettings(USERNAME, PASSWORD) protected open fun createConnection(): NetCopyClient? { return NetCopyClientConnectionPool.getConnection(ftpUrl) @@ -321,7 +323,7 @@ open class FtpHybridFileTest { it.connectionConfig = connectionConfigFactory.createConnectionConfig() it.addListener( "default", - createDefaultFtpServerListener() + createDefaultFtpServerListener(), ) } } diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/ftp/FtpsHybridFileAnonymousLoginTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/ftp/FtpsHybridFileAnonymousLoginTest.kt index 9585a500ad..af80d05a0c 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/ftp/FtpsHybridFileAnonymousLoginTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/ftp/FtpsHybridFileAnonymousLoginTest.kt @@ -29,26 +29,25 @@ import org.junit.Ignore */ @Ignore class FtpsHybridFileAnonymousLoginTest : FtpsHybridFileTest() { - override val ftpPort: Int get() = PORT override val ftpUrl: String - get() = NetCopyClientUtils.encryptFtpPathAsNecessary( - "${ftpPrefix}127.0.0.1:$ftpPort" - ) + get() = + NetCopyClientUtils.encryptFtpPathAsNecessary( + "${ftpPrefix}127.0.0.1:$ftpPort", + ) companion object { private const val PORT = 2224 } - override fun saveConnectionSettings() = - TestUtils.saveFtpConnectionSettings("", "", certInfo, PORT) + override fun saveConnectionSettings() = TestUtils.saveFtpConnectionSettings("", "", certInfo, PORT) override fun createFtpServerFactory(): FtpServerFactory = FtpHybridFileAnonymousLoginTest.createAnonymousFtpServerFactory().also { it.addListener( "default", - createDefaultFtpServerListener() + createDefaultFtpServerListener(), ) } } diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/ftp/FtpsHybridFileTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/ftp/FtpsHybridFileTest.kt index 0cda1778a3..a67f46b6b1 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/ftp/FtpsHybridFileTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/ftp/FtpsHybridFileTest.kt @@ -39,7 +39,6 @@ import javax.security.cert.X509Certificate @Ignore open class FtpsHybridFileTest : FtpHybridFileTest() { - private lateinit var keyStore: KeyStore private lateinit var keyStorePassword: CharArray protected lateinit var certInfo: JSONObject @@ -58,35 +57,38 @@ open class FtpsHybridFileTest : FtpHybridFileTest() { keyStorePassword = BuildConfig.FTP_SERVER_KEYSTORE_PASSWORD.toCharArray() keyStore.load( AppConfig.getInstance().resources.openRawResource(R.raw.key), - keyStorePassword + keyStorePassword, ) - certInfo = JSONObject( - X509CertificateUtil.parse( - X509Certificate.getInstance(keyStore.getCertificate("ftpserver").encoded) + certInfo = + JSONObject( + X509CertificateUtil.parse( + X509Certificate.getInstance(keyStore.getCertificate("ftpserver").encoded), + ), ) - ) super.setUp() } - override fun saveConnectionSettings() = - TestUtils.saveFtpConnectionSettings(USERNAME, PASSWORD, certInfo, PORT) + override fun saveConnectionSettings() = TestUtils.saveFtpConnectionSettings(USERNAME, PASSWORD, certInfo, PORT) override fun createDefaultFtpServerListener(): Listener { - val keyManagerFactory = KeyManagerFactory - .getInstance(KeyManagerFactory.getDefaultAlgorithm()) + val keyManagerFactory = + KeyManagerFactory + .getInstance(KeyManagerFactory.getDefaultAlgorithm()) keyManagerFactory.init(keyStore, keyStorePassword) - val trustManagerFactory = TrustManagerFactory - .getInstance(TrustManagerFactory.getDefaultAlgorithm()) + val trustManagerFactory = + TrustManagerFactory + .getInstance(TrustManagerFactory.getDefaultAlgorithm()) trustManagerFactory.init(keyStore) return ListenerFactory().apply { - sslConfiguration = DefaultSslConfiguration( - keyManagerFactory, - trustManagerFactory, - ClientAuth.WANT, - "TLSv1.2", - null, - "ftpserver" - ) + sslConfiguration = + DefaultSslConfiguration( + keyManagerFactory, + trustManagerFactory, + ClientAuth.WANT, + "TLSv1.2", + null, + "ftpserver", + ) isImplicitSsl = true port = ftpPort }.createListener() diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/ftp/NetCopyClientConnectionPoolFtpTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/ftp/NetCopyClientConnectionPoolFtpTest.kt index 3ba38ab049..356c6f2154 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/ftp/NetCopyClientConnectionPoolFtpTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/ftp/NetCopyClientConnectionPoolFtpTest.kt @@ -64,10 +64,9 @@ import kotlin.text.Charsets.UTF_8 @RunWith(AndroidJUnit4::class) @Config( shadows = [ShadowMultiDex::class, ShadowPasswordUtil::class], - sdk = [KITKAT, P, Build.VERSION_CODES.R] + sdk = [KITKAT, P, Build.VERSION_CODES.R], ) class NetCopyClientConnectionPoolFtpTest { - /** * Post test cleanup. */ @@ -89,11 +88,12 @@ class NetCopyClientConnectionPoolFtpTest { host = HOST, port = PORT, username = "testuser", - password = PasswordUtil.encryptPassword( - AppConfig.getInstance(), - "testpassword" - ) - ) + password = + PasswordUtil.encryptPassword( + AppConfig.getInstance(), + "testpassword", + ), + ), ) assertNull( getConnection( @@ -101,11 +101,12 @@ class NetCopyClientConnectionPoolFtpTest { host = HOST, port = PORT, username = "invaliduser", - password = PasswordUtil.encryptPassword( - AppConfig.getInstance(), - "invalidpassword" - ) - ) + password = + PasswordUtil.encryptPassword( + AppConfig.getInstance(), + "invalidpassword", + ), + ), ) verify(mock, times(2)).connect(HOST, PORT) verify(mock).login("testuser", "testpassword") @@ -203,24 +204,28 @@ class NetCopyClientConnectionPoolFtpTest { doRunTest(validUsername, validPassword) } - private fun doRunTest(validUsername: String, validPassword: String) { + private fun doRunTest( + validUsername: String, + validPassword: String, + ) { val encodedUsername = encode(validUsername, UTF_8.name()) val encodedPassword = encode(validPassword, UTF_8.name()) - val encryptedPassword = PasswordUtil.encryptPassword( - AppConfig.getInstance(), - encodedPassword - )?.replace("\n", "") + val encryptedPassword = + PasswordUtil.encryptPassword( + AppConfig.getInstance(), + encodedPassword, + )?.replace("\n", "") val mock = createFTPClient(validUsername, validPassword) TestUtils.saveFtpConnectionSettings(validUsername, validPassword) assertNotNull( getConnection( - "ftp://$encodedUsername:$encryptedPassword@127.0.0.1:22222" - ) + "ftp://$encodedUsername:$encryptedPassword@127.0.0.1:22222", + ), ) assertNull( getConnection( - "ftp://$encodedInvalidUsername:$encodedInvalidPassword@127.0.0.1:22222" - ) + "ftp://$encodedInvalidUsername:$encodedInvalidPassword@127.0.0.1:22222", + ), ) verify(mock, atLeastOnce()).connectTimeout = NetCopyClientConnectionPool.CONNECT_TIMEOUT verify(mock, atLeastOnce()).connect(HOST, PORT) @@ -228,7 +233,10 @@ class NetCopyClientConnectionPoolFtpTest { verify(mock, atMostOnce()).login(invalidUsername, invalidPassword) } - private fun createFTPClient(validUsername: String, validPassword: String): FTPClient { + private fun createFTPClient( + validUsername: String, + validPassword: String, + ): FTPClient { val mock = Mockito.mock(FTPClient::class.java) doNothing().`when`(mock).connect(HOST, PORT) doNothing().`when`(mock).disconnect() @@ -237,9 +245,9 @@ class NetCopyClientConnectionPoolFtpTest { mock.login( not(eq(validUsername)), not( - eq(validPassword) - ) - ) + eq(validPassword), + ), + ), ).thenReturn(false) // reset(mock); NetCopyClientConnectionPool.ftpClientFactory = @@ -250,7 +258,6 @@ class NetCopyClientConnectionPoolFtpTest { } companion object { - const val HOST = "127.0.0.1" const val PORT = 22222 private const val invalidUsername = "invaliduser" diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/ftp/NetCopyClientUtilTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/ftp/NetCopyClientUtilTest.kt index 07feec3382..f4033b4bc8 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/ftp/NetCopyClientUtilTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/ftp/NetCopyClientUtilTest.kt @@ -25,7 +25,6 @@ import org.junit.Test @Suppress("StringLiteralDuplication") class NetCopyClientUtilTest { - /** * Test [NetCopyClientUtils.deriveUriFrom]. */ @@ -39,8 +38,8 @@ class NetCopyClientUtilTest { password = "password", hostname = "127.0.0.1", port = 22222, - defaultPath = null - ) + defaultPath = null, + ), ) assertEquals( "ssh://user@127.0.0.1:22222/", @@ -50,8 +49,8 @@ class NetCopyClientUtilTest { password = null, hostname = "127.0.0.1", port = 22222, - defaultPath = null - ) + defaultPath = null, + ), ) } @@ -63,34 +62,34 @@ class NetCopyClientUtilTest { assertEquals( "/home/user/foo/bar", NetCopyClientUtils.extractRemotePathFrom( - "ssh://user:password@127.0.0.1:22/home/user/foo/bar" - ) + "ssh://user:password@127.0.0.1:22/home/user/foo/bar", + ), ) assertEquals( "/", - NetCopyClientUtils.extractRemotePathFrom("ssh://user:password@127.0.0.1:22/") + NetCopyClientUtils.extractRemotePathFrom("ssh://user:password@127.0.0.1:22/"), ) assertEquals( "/", - NetCopyClientUtils.extractRemotePathFrom("ssh://user:password@127.0.0.1:22") + NetCopyClientUtils.extractRemotePathFrom("ssh://user:password@127.0.0.1:22"), ) assertEquals( "/", - NetCopyClientUtils.extractRemotePathFrom("ssh://root:a8/875dbc-==@127.0.0.1:9899") + NetCopyClientUtils.extractRemotePathFrom("ssh://root:a8/875dbc-==@127.0.0.1:9899"), ) assertEquals( "/root/.config", NetCopyClientUtils.extractRemotePathFrom( - "ssh://root:YTgvODc1ZGJjLT09@127.0.0.1:9899/root/.config" - ) + "ssh://root:YTgvODc1ZGJjLT09@127.0.0.1:9899/root/.config", + ), ) assertEquals( "/Incoming/shared", - NetCopyClientUtils.extractRemotePathFrom("ftp://127.0.0.1:2211/Incoming/shared") + NetCopyClientUtils.extractRemotePathFrom("ftp://127.0.0.1:2211/Incoming/shared"), ) assertEquals( "/pub/notice.txt", - NetCopyClientUtils.extractRemotePathFrom("ftp://127.0.0.1:2211/pub/notice.txt") + NetCopyClientUtils.extractRemotePathFrom("ftp://127.0.0.1:2211/pub/notice.txt"), ) } @@ -101,45 +100,45 @@ class NetCopyClientUtilTest { fun testExtractBaseUriFromUri() { assertEquals( "ssh://root@127.0.0.1", - NetCopyClientUtils.extractBaseUriFrom("ssh://root@127.0.0.1") + NetCopyClientUtils.extractBaseUriFrom("ssh://root@127.0.0.1"), ) assertEquals( "ssh://root@127.0.0.1:2233", - NetCopyClientUtils.extractBaseUriFrom("ssh://root@127.0.0.1:2233") + NetCopyClientUtils.extractBaseUriFrom("ssh://root@127.0.0.1:2233"), ) assertEquals( "ssh://root@127.0.0.1", - NetCopyClientUtils.extractBaseUriFrom("ssh://root@127.0.0.1/root/.config") + NetCopyClientUtils.extractBaseUriFrom("ssh://root@127.0.0.1/root/.config"), ) assertEquals( "ssh://root:password@127.0.0.1", - NetCopyClientUtils.extractBaseUriFrom("ssh://root:password@127.0.0.1") + NetCopyClientUtils.extractBaseUriFrom("ssh://root:password@127.0.0.1"), ) assertEquals( "ssh://root:password@127.0.0.1:3456", - NetCopyClientUtils.extractBaseUriFrom("ssh://root:password@127.0.0.1:3456/root/.config") + NetCopyClientUtils.extractBaseUriFrom("ssh://root:password@127.0.0.1:3456/root/.config"), ) assertEquals( "ssh://root:a8/875dbc-==@127.0.0.1:9899", - NetCopyClientUtils.extractBaseUriFrom("ssh://root:a8/875dbc-==@127.0.0.1:9899") + NetCopyClientUtils.extractBaseUriFrom("ssh://root:a8/875dbc-==@127.0.0.1:9899"), ) assertEquals( "ssh://root:a8/875dbc-==@127.0.0.1:9899", NetCopyClientUtils.extractBaseUriFrom( - "ssh://root:a8/875dbc-==@127.0.0.1:9899/root/.config" - ) + "ssh://root:a8/875dbc-==@127.0.0.1:9899/root/.config", + ), ) assertEquals( "ftp://127.0.0.1:2211", - NetCopyClientUtils.extractBaseUriFrom("ftp://127.0.0.1:2211") + NetCopyClientUtils.extractBaseUriFrom("ftp://127.0.0.1:2211"), ) assertEquals( "ftp://127.0.0.1:2211", - NetCopyClientUtils.extractBaseUriFrom("ftp://127.0.0.1:2211/Incoming/shared") + NetCopyClientUtils.extractBaseUriFrom("ftp://127.0.0.1:2211/Incoming/shared"), ) assertEquals( "ftp://127.0.0.1:2211", - NetCopyClientUtils.extractBaseUriFrom("ftp://127.0.0.1:2211/pub/notice.txt") + NetCopyClientUtils.extractBaseUriFrom("ftp://127.0.0.1:2211/pub/notice.txt"), ) } } diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/ftp/NetCopyConnectionInfoTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/ftp/NetCopyConnectionInfoTest.kt index 279b660215..0b291a43b4 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/ftp/NetCopyConnectionInfoTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/ftp/NetCopyConnectionInfoTest.kt @@ -18,6 +18,8 @@ * along with this program. If not, see . */ +@file:Suppress("ktlint:standard:max-line-length") + package com.amaze.filemanager.filesystem.ftp import androidx.test.ext.junit.runners.AndroidJUnit4 @@ -31,14 +33,12 @@ import org.robolectric.annotation.Config import java.net.URLDecoder.decode import java.net.URLEncoder.encode -/* ktlint-disable max-line-length */ @RunWith(AndroidJUnit4::class) @Config( - shadows = [ShadowPasswordUtil::class, ShadowMultiDex::class] + shadows = [ShadowPasswordUtil::class, ShadowMultiDex::class], ) @Suppress("StringLiteralDuplication") class NetCopyConnectionInfoTest { - /** * Test unsupported URL prefixes should throw IllegalArgumentException. */ @@ -71,7 +71,7 @@ class NetCopyConnectionInfoTest { @Test fun testSimple() { NetCopyConnectionInfo( - "ftp://testuser:testpassword@127.0.0.1:22222" + "ftp://testuser:testpassword@127.0.0.1:22222", ).run { assertEquals("ftp://", prefix) assertEquals("testuser", username) @@ -91,7 +91,7 @@ class NetCopyConnectionInfoTest { @Test fun testQueryString() { NetCopyConnectionInfo( - "ftps://testuser:testpassword@127.0.0.1:22222?tls=implicit&passive=false" + "ftps://testuser:testpassword@127.0.0.1:22222?tls=implicit&passive=false", ).run { assertEquals("ftps://", prefix) assertEquals("testuser", username) @@ -115,7 +115,7 @@ class NetCopyConnectionInfoTest { @Test fun testDefaultPath() { NetCopyConnectionInfo( - "ftps://testuser:testpassword@127.0.0.1:22222/srv/tomopet-service" + "ftps://testuser:testpassword@127.0.0.1:22222/srv/tomopet-service", ).run { assertEquals("ftps://", prefix) assertEquals("testuser", username) @@ -135,7 +135,7 @@ class NetCopyConnectionInfoTest { @Test fun testDefaultPathWithFilename() { NetCopyConnectionInfo( - "ftps://testuser:testpassword@127.0.0.1:22222/srv/tomopet-service/history.txt" + "ftps://testuser:testpassword@127.0.0.1:22222/srv/tomopet-service/history.txt", ).run { assertEquals("ftps://", prefix) assertEquals("testuser", username) @@ -155,7 +155,7 @@ class NetCopyConnectionInfoTest { @Test fun testDefaultPathWithQueryString() { NetCopyConnectionInfo( - "ftps://testuser:testpassword@127.0.0.1:22222/srv/tomopet-service?tls=explicit&passive=true" + "ftps://testuser:testpassword@127.0.0.1:22222/srv/tomopet-service?tls=explicit&passive=true", ).run { assertEquals("ftps://", prefix) assertEquals("testuser", username) @@ -179,7 +179,7 @@ class NetCopyConnectionInfoTest { @Test fun testDefaultPathURLEncoded() { NetCopyConnectionInfo( - "ftps://testuser:testpassword@127.0.0.1:22222/Users/TranceLove/My+Documents/%40TranceLove%231433%261434" + "ftps://testuser:testpassword@127.0.0.1:22222/Users/TranceLove/My+Documents/%40TranceLove%231433%261434", ).run { assertEquals("ftps://", prefix) assertEquals("testuser", username) @@ -189,7 +189,7 @@ class NetCopyConnectionInfoTest { assertEquals("/Users/TranceLove/My+Documents/%40TranceLove%231433%261434", defaultPath) assertEquals( "/Users/TranceLove/My Documents/@TranceLove#1433&1434", - defaultPath?.urlDecoded() + defaultPath?.urlDecoded(), ) assertEquals("%40TranceLove%231433%261434", lastPathSegment()) assertEquals("@TranceLove#1433&1434", lastPathSegment()?.urlDecoded()) @@ -204,7 +204,7 @@ class NetCopyConnectionInfoTest { @Test fun testDefaultPathWithFilenameURLEncoded() { NetCopyConnectionInfo( - "ftps://testuser:testpassword@127.0.0.1:22222/home/trancelove/My+Web+Sites/Test/Awesome-stars/%7BMaruell+Horbis%7D+Tris%2BSurplus+40%25+off+%40rugio.txt" + "ftps://testuser:testpassword@127.0.0.1:22222/home/trancelove/My+Web+Sites/Test/Awesome-stars/%7BMaruell+Horbis%7D+Tris%2BSurplus+40%25+off+%40rugio.txt", ).run { assertEquals("ftps://", prefix) assertEquals("testuser", username) @@ -214,15 +214,15 @@ class NetCopyConnectionInfoTest { assertEquals("/home/trancelove/My+Web+Sites/Test/Awesome-stars", defaultPath) assertEquals( "/home/trancelove/My Web Sites/Test/Awesome-stars", - defaultPath?.urlDecoded() + defaultPath?.urlDecoded(), ) assertEquals( "%7BMaruell+Horbis%7D+Tris%2BSurplus+40%25+off+%40rugio.txt", - lastPathSegment() + lastPathSegment(), ) assertEquals( "{Maruell Horbis} Tris+Surplus 40% off @rugio.txt", - lastPathSegment()?.urlDecoded() + lastPathSegment()?.urlDecoded(), ) assertNull(queryString) assertNull(arguments) @@ -235,7 +235,7 @@ class NetCopyConnectionInfoTest { @Test fun testDefaultPathWithQueryStringURLEncoded() { NetCopyConnectionInfo( - "ftps://testuser:testpassword@127.0.0.1:22222/home/trancelove/My+Web+Sites/Test/Awesome-stars/%7BMaruell+Horbis%7D+Tris%2BSurplus+40%25+off+%40rugio.txt?easter_egg=%7B%7D%28%29%26%5E%25*%3C%3E%21%40%23%24%25%3F%3A%22%3B%27" + "ftps://testuser:testpassword@127.0.0.1:22222/home/trancelove/My+Web+Sites/Test/Awesome-stars/%7BMaruell+Horbis%7D+Tris%2BSurplus+40%25+off+%40rugio.txt?easter_egg=%7B%7D%28%29%26%5E%25*%3C%3E%21%40%23%24%25%3F%3A%22%3B%27", ).run { assertEquals("ftps://", prefix) assertEquals("testuser", username) @@ -245,25 +245,25 @@ class NetCopyConnectionInfoTest { assertEquals("/home/trancelove/My+Web+Sites/Test/Awesome-stars", defaultPath) assertEquals( "/home/trancelove/My Web Sites/Test/Awesome-stars", - defaultPath?.urlDecoded() + defaultPath?.urlDecoded(), ) assertEquals( "%7BMaruell+Horbis%7D+Tris%2BSurplus+40%25+off+%40rugio.txt", - lastPathSegment() + lastPathSegment(), ) assertEquals( "{Maruell Horbis} Tris+Surplus 40% off @rugio.txt", - lastPathSegment()?.urlDecoded() + lastPathSegment()?.urlDecoded(), ) assertEquals( "easter_egg=%7B%7D%28%29%26%5E%25*%3C%3E%21%40%23%24%25%3F%3A%22%3B%27", - queryString + queryString, ) assertNotNull(arguments) arguments?.run { assertEquals( "%7B%7D%28%29%26%5E%25*%3C%3E%21%40%23%24%25%3F%3A%22%3B%27", - this["easter_egg"] + this["easter_egg"], ) assertEquals("{}()&^%*<>!@#\$%?:\";'", this["easter_egg"]?.urlDecoded()) } @@ -276,7 +276,7 @@ class NetCopyConnectionInfoTest { @Test fun testDifficultCredentials() { NetCopyConnectionInfo( - "ftp://testuser:${encode("testP@##word", Charsets.UTF_8.name())}@127.0.0.1:22222" + "ftp://testuser:${encode("testP@##word", Charsets.UTF_8.name())}@127.0.0.1:22222", ).run { assertEquals("ftp://", prefix) assertEquals("testuser", username) @@ -326,11 +326,10 @@ class NetCopyConnectionInfoTest { assertNotNull(this.lastPathSegment()) } NetCopyConnectionInfo( - "ftp://127.0.0.1////a/bunch///of///slash//folders////////////test.log" + "ftp://127.0.0.1////a/bunch///of///slash//folders////////////test.log", ).run { // assertEquals("ftp://127.0.0.1/a/bunch/of/slash/folders", this.toString()) assertEquals("test.log", this.lastPathSegment()) } } } -/* ktlint-disable max-line-length */ diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/ftpserver/commands/AVBLCommandTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/ftpserver/commands/AVBLCommandTest.kt index 752d31eba7..8b0e7fa9ac 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/ftpserver/commands/AVBLCommandTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/ftpserver/commands/AVBLCommandTest.kt @@ -47,9 +47,7 @@ import java.io.File * Unit test for [AVBL]. */ class AVBLCommandTest : AbstractFtpserverCommandTest() { - companion object { - private lateinit var fsFactory: FileSystemFactory private lateinit var fsView: NativeFileSystemView @@ -100,13 +98,13 @@ class AVBLCommandTest : AbstractFtpserverCommandTest() { executeRequest( "AVBL", listOf(WritePermission()), - mock(AndroidFileSystemFactory::class.java) + mock(AndroidFileSystemFactory::class.java), ) assertEquals(1, logger.messages.size) assertEquals(502, logger.messages[0].code) assertEquals( AppConfig.getInstance().getString(R.string.ftp_error_AVBL_notimplemented), - logger.messages[0].message + logger.messages[0].message, ) } @@ -153,7 +151,7 @@ class AVBLCommandTest : AbstractFtpserverCommandTest() { assertEquals(550, logger.messages[0].code) assertEquals( AppConfig.getInstance().getString(R.string.ftp_error_AVBL_missing), - logger.messages[0].message + logger.messages[0].message, ) } @@ -167,7 +165,7 @@ class AVBLCommandTest : AbstractFtpserverCommandTest() { assertEquals(550, logger.messages[0].code) assertEquals( AppConfig.getInstance().getString(R.string.ftp_error_AVBL_accessdenied), - logger.messages[0].message + logger.messages[0].message, ) } @@ -182,7 +180,7 @@ class AVBLCommandTest : AbstractFtpserverCommandTest() { assertEquals(550, logger.messages[0].code) assertEquals( AppConfig.getInstance().getString(R.string.ftp_error_AVBL_accessdenied), - logger.messages[0].message + logger.messages[0].message, ) } @@ -196,28 +194,29 @@ class AVBLCommandTest : AbstractFtpserverCommandTest() { assertEquals(550, logger.messages[0].code) assertEquals( AppConfig.getInstance().getString(R.string.ftp_error_AVBL_isafile), - logger.messages[0].message + logger.messages[0].message, ) } private fun executeRequest( commandLine: String, permissions: List, - fileSystemFactory: FileSystemFactory = fsFactory + fileSystemFactory: FileSystemFactory = fsFactory, ) { val context = mock(FtpServerContext::class.java) val ftpSession = FtpIoSession(session, context) - ftpSession.user = BaseUser().also { - it.homeDirectory = Environment.getExternalStorageDirectory().absolutePath - it.authorities = permissions - } + ftpSession.user = + BaseUser().also { + it.homeDirectory = Environment.getExternalStorageDirectory().absolutePath + it.authorities = permissions + } ftpSession.setLogin(fsView) `when`(context.fileSystemManager).thenReturn(fileSystemFactory) val command = AVBL() command.execute( session = ftpSession, context = context, - request = DefaultFtpRequest(commandLine) + request = DefaultFtpRequest(commandLine), ) } } diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/ftpserver/commands/AbstractFtpserverCommandTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/ftpserver/commands/AbstractFtpserverCommandTest.kt index 6a9bbde6e9..89d884bf66 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/ftpserver/commands/AbstractFtpserverCommandTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/ftpserver/commands/AbstractFtpserverCommandTest.kt @@ -38,10 +38,9 @@ import org.robolectric.annotation.Config @RunWith(AndroidJUnit4::class) @Config( shadows = [ShadowMultiDex::class], - sdk = [KITKAT, P, Build.VERSION_CODES.R] + sdk = [KITKAT, P, Build.VERSION_CODES.R], ) abstract class AbstractFtpserverCommandTest { - protected lateinit var logger: LogMessageFilter protected lateinit var session: IoSession diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/ftpserver/commands/FEATCommandTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/ftpserver/commands/FEATCommandTest.kt index 7b066fe70b..be466613d4 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/ftpserver/commands/FEATCommandTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/ftpserver/commands/FEATCommandTest.kt @@ -34,7 +34,6 @@ import org.mockito.Mockito * Unit test for [FEAT]. */ class FEATCommandTest : AbstractFtpserverCommandTest() { - /** * Test command output. Expect AVBL is among list of extensions implemented. */ @@ -46,13 +45,13 @@ class FEATCommandTest : AbstractFtpserverCommandTest() { command.execute( session = ftpSession, context = context, - request = DefaultFtpRequest("FEAT") + request = DefaultFtpRequest("FEAT"), ) assertEquals(1, logger.messages.size) assertEquals(211, logger.messages[0].code) assertEquals( AppConfig.getInstance().getString(R.string.ftp_command_FEAT), - logger.messages[0].message + logger.messages[0].message, ) assertTrue(logger.messages[0].message.contains("AVBL")) } diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/ftpserver/commands/LogMessageFilter.kt b/app/src/test/java/com/amaze/filemanager/filesystem/ftpserver/commands/LogMessageFilter.kt index 28a853a7d0..4f97e99047 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/ftpserver/commands/LogMessageFilter.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/ftpserver/commands/LogMessageFilter.kt @@ -35,7 +35,7 @@ class LogMessageFilter : IoFilterAdapter() { override fun messageSent( nextFilter: IoFilter.NextFilter, session: IoSession, - writeRequest: WriteRequest + writeRequest: WriteRequest, ) { writeRequest.message.run { messages.add(this as FtpReply) diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/ftpserver/commands/PWDCommandTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/ftpserver/commands/PWDCommandTest.kt index 0e6e78886c..61955ddb1a 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/ftpserver/commands/PWDCommandTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/ftpserver/commands/PWDCommandTest.kt @@ -42,7 +42,6 @@ import java.io.File */ @Suppress("StringLiteralDuplication") class PWDCommandTest : AbstractFtpserverCommandTest() { - private lateinit var fsView: NativeFileSystemView private lateinit var user: User @@ -50,7 +49,6 @@ class PWDCommandTest : AbstractFtpserverCommandTest() { private lateinit var ftpSession: FtpIoSession companion object { - // Nobody is interested in this, nor asking it any question. // Of course in reality FtpServerContext will never be static private lateinit var context: FtpServerContext @@ -75,10 +73,11 @@ class PWDCommandTest : AbstractFtpserverCommandTest() { override fun setUp() { super.setUp() File(Environment.getExternalStorageDirectory(), "Music").mkdirs() - user = BaseUser().also { - it.homeDirectory = Environment.getExternalStorageDirectory().absolutePath - it.authorities = listOf(WritePermission()) - } + user = + BaseUser().also { + it.homeDirectory = Environment.getExternalStorageDirectory().absolutePath + it.authorities = listOf(WritePermission()) + } fsView = NativeFileSystemView(user, false) ftpSession = FtpIoSession(session, context) @@ -139,7 +138,7 @@ class PWDCommandTest : AbstractFtpserverCommandTest() { command.execute( session = ftpSession, context = context, - request = DefaultFtpRequest("PWD") + request = DefaultFtpRequest("PWD"), ) } } diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/root/ListFilesCommandTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/root/ListFilesCommandTest.kt index 7f80ba0802..2df3522804 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/root/ListFilesCommandTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/root/ListFilesCommandTest.kt @@ -54,10 +54,9 @@ import java.io.InputStreamReader @RunWith(AndroidJUnit4::class) @Config( shadows = [ShadowMultiDex::class, ShadowNativeOperations::class], - sdk = [KITKAT, P, Build.VERSION_CODES.R] + sdk = [KITKAT, P, Build.VERSION_CODES.R], ) class ListFilesCommandTest { - private val sharedPreferences: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(ApplicationProvider.getApplicationContext()) private val statLines = @@ -85,7 +84,7 @@ class ListFilesCommandTest { anyBoolean(), anyBoolean(), argumentCaptor<(OpenMode) -> Unit>().capture(), - argumentCaptor<(HybridFileParcelable) -> Unit>().capture() + argumentCaptor<(HybridFileParcelable) -> Unit>().capture(), ) } answers { callOriginal() } every { @@ -94,7 +93,9 @@ class ListFilesCommandTest { every { ListFilesCommand.runShellCommand("pwd") }.answers { object : Shell.Result() { override fun getOut(): MutableList = listOf("/").toMutableList() + override fun getErr(): MutableList = emptyList().toMutableList() + override fun getCode(): Int = 0 } } @@ -124,7 +125,7 @@ class ListFilesCommandTest { root = true, showHidden = false, openModeCallback = {}, - onFileFoundCallback = { ++statCount } + onFileFoundCallback = { ++statCount }, ) assertEquals(statLines.size, statCount) statCount = 0 @@ -133,7 +134,7 @@ class ListFilesCommandTest { root = true, showHidden = false, openModeCallback = {}, - onFileFoundCallback = { ++statCount } + onFileFoundCallback = { ++statCount }, ) assertEquals(statRootLines.size, statCount) @@ -145,7 +146,7 @@ class ListFilesCommandTest { root = true, showHidden = false, openModeCallback = {}, - onFileFoundCallback = { ++lsCount } + onFileFoundCallback = { ++lsCount }, ) assertEquals(lsLines.size - 1, lsCount) lsCount = 0 @@ -154,7 +155,7 @@ class ListFilesCommandTest { root = true, showHidden = false, openModeCallback = {}, - onFileFoundCallback = { ++lsCount } + onFileFoundCallback = { ++lsCount }, ) assertEquals(lsRootLines.size - 1, lsCount) } diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/root/ListFilesCommandTest2.kt b/app/src/test/java/com/amaze/filemanager/filesystem/root/ListFilesCommandTest2.kt index 5aa9403f76..a7d32e2485 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/root/ListFilesCommandTest2.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/root/ListFilesCommandTest2.kt @@ -59,10 +59,9 @@ import java.io.InputStreamReader @RunWith(AndroidJUnit4::class) @Config( shadows = [ShadowMultiDex::class, ShadowNativeOperations::class], - sdk = [KITKAT, P, Build.VERSION_CODES.R] + sdk = [KITKAT, P, Build.VERSION_CODES.R], ) class ListFilesCommandTest2 { - val sharedPreferences: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(ApplicationProvider.getApplicationContext()) val lsLines = @@ -81,28 +80,30 @@ class ListFilesCommandTest2 { anyBoolean(), anyBoolean(), argumentCaptor<(OpenMode) -> Unit>().capture(), - argumentCaptor<(HybridFileParcelable) -> Unit>().capture() - ) + argumentCaptor<(HybridFileParcelable) -> Unit>().capture(), + ), ).thenCallRealMethod() `when`( mockCommand.executeRootCommand( anyString(), anyBoolean(), - anyBoolean() - ) + anyBoolean(), + ), ).thenCallRealMethod() `when`(mockCommand.runShellCommand("pwd")).thenReturn( object : Shell.Result() { override fun getOut(): MutableList = listOf("/").toMutableList() + override fun getErr(): MutableList = emptyList().toMutableList() + override fun getCode(): Int = 0 - } + }, ) `when`(mockCommand.runShellCommandToList("ls -l \"/bin\"")).thenReturn(lsLines) `when`( mockCommand.runShellCommandToList( - "stat -c '%A %h %G %U %B %Y %N' /bin/*" - ) + "stat -c '%A %h %G %U %B %Y %N' /bin/*", + ), ).thenThrow(ShellCommandInvalidException("Intentional exception")) TestUtils.replaceObjectInstance(ListFilesCommand.javaClass, mockCommand) } diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/smb/CifsContextsTest.java b/app/src/test/java/com/amaze/filemanager/filesystem/smb/CifsContextsTest.java index 8695fdf445..7c118cf953 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/smb/CifsContextsTest.java +++ b/app/src/test/java/com/amaze/filemanager/filesystem/smb/CifsContextsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/smb/SmbHybridFileTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/smb/SmbHybridFileTest.kt index 64e6376701..c67581ff68 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/smb/SmbHybridFileTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/smb/SmbHybridFileTest.kt @@ -45,11 +45,10 @@ import org.robolectric.shadows.ShadowSQLiteConnection @RunWith(AndroidJUnit4::class) @Config( shadows = [ShadowSmbUtil::class, ShadowMultiDex::class], - sdk = [KITKAT, P, Build.VERSION_CODES.R] + sdk = [KITKAT, P, Build.VERSION_CODES.R], ) @LooperMode(LooperMode.Mode.PAUSED) class SmbHybridFileTest { - private var ctx: Context? = null /** diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/ssh/AbstractSftpServerTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/ssh/AbstractSftpServerTest.kt index 7d5bb60441..a7cab8f40d 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/ssh/AbstractSftpServerTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/ssh/AbstractSftpServerTest.kt @@ -65,10 +65,9 @@ import kotlin.text.Charsets.UTF_8 @RunWith(AndroidJUnit4::class) @Config( shadows = [ShadowMultiDex::class, ShadowPasswordUtil::class], - sdk = [KITKAT, P, VERSION_CODES.R] + sdk = [KITKAT, P, VERSION_CODES.R], ) abstract class AbstractSftpServerTest { - protected var encryptedPassword: String? = PasswordUtil.encryptPassword(AppConfig.getInstance(), PASSWORD)?.replace("\n", "") protected var serverPort = 0 @@ -80,19 +79,20 @@ abstract class AbstractSftpServerTest { @Before @Throws(IOException::class) open fun setUp() { - serverPort = createSshServer( - VirtualFileSystemFactory( - Paths.get(Environment.getExternalStorageDirectory().absolutePath) - ), - 64000 - ) + serverPort = + createSshServer( + VirtualFileSystemFactory( + Paths.get(Environment.getExternalStorageDirectory().absolutePath), + ), + 64000, + ) prepareSshConnection() TestUtils.saveSshConnectionSettings( hostKeyPair = hostKeyProvider.keyPair, validUsername = encode(USERNAME, UTF_8.name()), validPassword = encryptedPassword, privateKey = null, - port = 64000 + port = 64000, ) } @@ -117,12 +117,15 @@ abstract class AbstractSftpServerTest { hostFingerprint, USERNAME, PasswordUtil.encryptPassword(AppConfig.getInstance(), PASSWORD)?.replace("\n", ""), - null + null, ) } @Throws(IOException::class) - protected fun createSshServer(fileSystemFactory: FileSystemFactory, startPort: Int): Int { + protected fun createSshServer( + fileSystemFactory: FileSystemFactory, + startPort: Int, + ): Int { server = SshServer.setUpDefaultServer() server.fileSystemFactory = fileSystemFactory server.publickeyAuthenticator = AcceptAllPublickeyAuthenticator.INSTANCE @@ -144,7 +147,6 @@ abstract class AbstractSftpServerTest { } companion object { - @JvmStatic protected val HOST = "127.0.0.1" diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/ssh/FilesOnSshdTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/ssh/FilesOnSshdTest.kt index 858618e436..076e7149ee 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/ssh/FilesOnSshdTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/ssh/FilesOnSshdTest.kt @@ -47,7 +47,6 @@ import java.util.concurrent.TimeUnit */ @Suppress("StringLiteralDuplication") class FilesOnSshdTest : AbstractSftpServerTest() { - /** * Test list directories normally */ @@ -76,10 +75,11 @@ class FilesOnSshdTest : AbstractSftpServerTest() { fun testListFilesWithSpecialChars() { createFilesAndDirectoriesWithSpecialChars() performVerify2() - val file = HybridFile( - OpenMode.SFTP, - "ssh://$USERNAME:$encryptedPassword@$HOST:$serverPort/sysroot%2Bv2/test%2Bfile.bin" - ) + val file = + HybridFile( + OpenMode.SFTP, + "ssh://$USERNAME:$encryptedPassword@$HOST:$serverPort/sysroot%2Bv2/test%2Bfile.bin", + ) val content = file.getInputStream(AppConfig.getInstance())?.readBytes() assertNotNull(content) assertTrue(true == content?.isNotEmpty()) @@ -94,7 +94,7 @@ class FilesOnSshdTest : AbstractSftpServerTest() { subdir.mkdir() Files.createSymbolicLink( Paths.get(File(root, s).absolutePath), - Paths.get(subdir.absolutePath) + Paths.get(subdir.absolutePath), ) } for (s in arrayOf("bin", "lib", "usr")) { @@ -117,10 +117,11 @@ class FilesOnSshdTest : AbstractSftpServerTest() { private fun performVerify(): Boolean { val result: MutableList = ArrayList() - val file = HybridFile( - OpenMode.SFTP, - "ssh://$USERNAME:$encryptedPassword@$HOST:$serverPort" - ) + val file = + HybridFile( + OpenMode.SFTP, + "ssh://$USERNAME:$encryptedPassword@$HOST:$serverPort", + ) file.forEachChildrenFile( ApplicationProvider.getApplicationContext(), false, @@ -129,22 +130,23 @@ class FilesOnSshdTest : AbstractSftpServerTest() { assertTrue("${fileFound.path} not seen as directory", fileFound.isDirectory) result.add(fileFound.name) } - } + }, ) await().until { result.size == 8 } assertThat>( result, - Matchers.hasItems("sysroot", "srv", "var", "tmp", "bin", "lib", "usr", "sysroot+v2") + Matchers.hasItems("sysroot", "srv", "var", "tmp", "bin", "lib", "usr", "sysroot+v2"), ) return true } private fun performVerify2(): Boolean { val result: MutableList = ArrayList() - var file = HybridFile( - OpenMode.SFTP, - "ssh://$USERNAME:$encryptedPassword@$HOST:$serverPort/sysroot%2Bv2" - ) + var file = + HybridFile( + OpenMode.SFTP, + "ssh://$USERNAME:$encryptedPassword@$HOST:$serverPort/sysroot%2Bv2", + ) file.forEachChildrenFile( ApplicationProvider.getApplicationContext(), false, @@ -152,18 +154,19 @@ class FilesOnSshdTest : AbstractSftpServerTest() { override fun onFileFound(fileFound: HybridFileParcelable) { result.add(fileFound.name) } - } + }, ) await().atMost(90, TimeUnit.SECONDS).until { result.size == 2 } assertThat>( result, - Matchers.hasItems("test+file.bin", "D:") + Matchers.hasItems("test+file.bin", "D:"), ) result.clear() - file = HybridFile( - OpenMode.SFTP, - "ssh://$USERNAME:$encryptedPassword@$HOST:$serverPort/sysroot%2Bv2/D:" - ) + file = + HybridFile( + OpenMode.SFTP, + "ssh://$USERNAME:$encryptedPassword@$HOST:$serverPort/sysroot%2Bv2/D:", + ) file.forEachChildrenFile( ApplicationProvider.getApplicationContext(), false, @@ -171,18 +174,19 @@ class FilesOnSshdTest : AbstractSftpServerTest() { override fun onFileFound(fileFound: HybridFileParcelable) { result.add(fileFound.name) } - } + }, ) await().until { result.size == 1 } assertThat>( result, - Matchers.hasItems("Users") + Matchers.hasItems("Users"), ) result.clear() - file = HybridFile( - OpenMode.SFTP, - "ssh://$USERNAME:$encryptedPassword@$HOST:$serverPort/sysroot%2Bv2/D%3A" - ) + file = + HybridFile( + OpenMode.SFTP, + "ssh://$USERNAME:$encryptedPassword@$HOST:$serverPort/sysroot%2Bv2/D%3A", + ) file.forEachChildrenFile( ApplicationProvider.getApplicationContext(), false, @@ -190,12 +194,12 @@ class FilesOnSshdTest : AbstractSftpServerTest() { override fun onFileFound(fileFound: HybridFileParcelable) { result.add(fileFound.name) } - } + }, ) await().until { result.size == 1 } assertThat>( result, - Matchers.hasItems("Users") + Matchers.hasItems("Users"), ) return true } @@ -215,17 +219,18 @@ class FilesOnSshdTest : AbstractSftpServerTest() { Files.createSymbolicLink( Paths.get( File(Environment.getExternalStorageDirectory(), "symlink$i.txt") - .absolutePath + .absolutePath, ), - Paths.get(f.absolutePath) + Paths.get(f.absolutePath), ) } val dirs: MutableList = ArrayList() val files: MutableList = ArrayList() - val file = HybridFile( - OpenMode.SFTP, - "ssh://$USERNAME:$encryptedPassword@$HOST:$serverPort" - ) + val file = + HybridFile( + OpenMode.SFTP, + "ssh://$USERNAME:$encryptedPassword@$HOST:$serverPort", + ) file.forEachChildrenFile( ApplicationProvider.getApplicationContext(), false, @@ -234,23 +239,23 @@ class FilesOnSshdTest : AbstractSftpServerTest() { if (!fileFound.name.endsWith(".txt")) { assertTrue( fileFound.path + " not seen as directory", - fileFound.isDirectory + fileFound.isDirectory, ) dirs.add(fileFound.name) } else { assertFalse( fileFound.path + " not seen as file", - fileFound.isDirectory + fileFound.isDirectory, ) files.add(fileFound.name) } } - } + }, ) await().until { dirs.size == 8 } assertThat>( dirs, - Matchers.hasItems("sysroot", "srv", "var", "tmp", "bin", "lib", "usr", "sysroot+v2") + Matchers.hasItems("sysroot", "srv", "var", "tmp", "bin", "lib", "usr", "sysroot+v2"), ) assertThat>( files, @@ -262,8 +267,8 @@ class FilesOnSshdTest : AbstractSftpServerTest() { "symlink1.txt", "symlink2.txt", "symlink3.txt", - "symlink4.txt" - ) + "symlink4.txt", + ), ) } @@ -277,9 +282,9 @@ class FilesOnSshdTest : AbstractSftpServerTest() { Files.createSymbolicLink( Paths.get( File(Environment.getExternalStorageDirectory(), "b0rken.symlink") - .absolutePath + .absolutePath, ), - Paths.get(File("/tmp/notfound.file").absolutePath) + Paths.get(File("/tmp/notfound.file").absolutePath), ) assertTrue(performVerify()) } @@ -298,10 +303,11 @@ class FilesOnSshdTest : AbstractSftpServerTest() { out.close() } val result: MutableList = ArrayList() - var file = HybridFile( - OpenMode.SFTP, - "ssh://$USERNAME:$encryptedPassword@$HOST:$serverPort/tmp" - ) + var file = + HybridFile( + OpenMode.SFTP, + "ssh://$USERNAME:$encryptedPassword@$HOST:$serverPort/tmp", + ) file.forEachChildrenFile( ApplicationProvider.getApplicationContext(), false, @@ -310,12 +316,12 @@ class FilesOnSshdTest : AbstractSftpServerTest() { assertFalse("${fileFound.path} not seen as directory", fileFound.isDirectory) result.add(fileFound.name) } - } + }, ) await().until { result.size == 4 } assertThat>( result, - Matchers.hasItems("1.txt", "2.txt", "3.txt", "4.txt") + Matchers.hasItems("1.txt", "2.txt", "3.txt", "4.txt"), ) val result2: MutableList = ArrayList() file = @@ -328,12 +334,12 @@ class FilesOnSshdTest : AbstractSftpServerTest() { assertTrue("${fileFound.path} not seen as directory", fileFound.isDirectory) result2.add(fileFound.name) } - } + }, ) await().until { result2.size == 8 } assertThat>( result2, - Matchers.hasItems("sysroot", "srv", "var", "tmp", "bin", "lib", "usr", "sysroot+v2") + Matchers.hasItems("sysroot", "srv", "var", "tmp", "bin", "lib", "usr", "sysroot+v2"), ) } } diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/ssh/NetCopyClientConnectionPoolSshTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/ssh/NetCopyClientConnectionPoolSshTest.kt index 7d8151c47e..b3d6e9d07b 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/ssh/NetCopyClientConnectionPoolSshTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/ssh/NetCopyClientConnectionPoolSshTest.kt @@ -75,10 +75,9 @@ import kotlin.text.Charsets.UTF_8 @RunWith(AndroidJUnit4::class) @Config( shadows = [ShadowMultiDex::class, ShadowPasswordUtil::class], - sdk = [KITKAT, P, Build.VERSION_CODES.R] + sdk = [KITKAT, P, Build.VERSION_CODES.R], ) class NetCopyClientConnectionPoolSshTest { - /** * Post test cleanup. */ @@ -104,10 +103,10 @@ class NetCopyClientConnectionPoolSshTest { "testuser", PasswordUtil.encryptPassword( AppConfig.getInstance(), - "testpassword" + "testpassword", ), - null - ) + null, + ), ) assertNull( getConnection( @@ -118,16 +117,16 @@ class NetCopyClientConnectionPoolSshTest { "invaliduser", PasswordUtil.encryptPassword( AppConfig.getInstance(), - "invalidpassword" + "invalidpassword", ), - null - ) + null, + ), ) verify(mock, times(2)) .addHostKeyVerifier( SecurityUtils.getFingerprint( - hostKeyPair.public - ) + hostKeyPair.public, + ), ) verify(mock, times(2)).connect(HOST, PORT) verify(mock).authPassword("testuser", "testpassword") @@ -149,8 +148,8 @@ class NetCopyClientConnectionPoolSshTest { SecurityUtils.getFingerprint(hostKeyPair.public), "testuser", null, - userKeyPair - ) + userKeyPair, + ), ) shutdown() assertNull( @@ -161,14 +160,14 @@ class NetCopyClientConnectionPoolSshTest { SecurityUtils.getFingerprint(hostKeyPair.public), "invaliduser", null, - userKeyPair - ) + userKeyPair, + ), ) verify(mock, times(2)) .addHostKeyVerifier( SecurityUtils.getFingerprint( - hostKeyPair.public - ) + hostKeyPair.public, + ), ) verify(mock, times(2)).connect(HOST, PORT) verify(mock).authPublickey("testuser", sshKeyProvider) @@ -314,20 +313,25 @@ class NetCopyClientConnectionPoolSshTest { doRunTest(validUsername, validPassword) } - private fun doRunTest(validUsername: String, validPassword: String, subPath: String? = null) { + private fun doRunTest( + validUsername: String, + validPassword: String, + subPath: String? = null, + ) { val encodedUsername = encode(validUsername, UTF_8.name()) val encodedPassword = encode(validPassword, UTF_8.name()) - val encryptedPassword = PasswordUtil.encryptPassword( - AppConfig.getInstance(), - encodedPassword - )?.replace("\n", "") + val encryptedPassword = + PasswordUtil.encryptPassword( + AppConfig.getInstance(), + encodedPassword, + )?.replace("\n", "") val mock = createSshServer(validUsername, validPassword) TestUtils.saveSshConnectionSettings( hostKeyPair, encodedUsername, encryptedPassword, null, - subPath + subPath, ) assertNotNull( getConnection( @@ -335,8 +339,8 @@ class NetCopyClientConnectionPoolSshTest { "ssh://$encodedUsername:$encryptedPassword@$HOST:$PORT" } else { "ssh://$encodedUsername:$encryptedPassword@$HOST:$PORT$subPath" - } - ) + }, + ), ) assertNull( getConnection( @@ -345,15 +349,15 @@ class NetCopyClientConnectionPoolSshTest { "ssh://$encodedInvalidUsername:$encodedInvalidPassword@$HOST:$PORT" } else { "ssh://$encodedInvalidUsername:$encodedInvalidPassword@$HOST:$PORT$subPath" - } - ) - ) + }, + ), + ), ) verify(mock, atLeastOnce()) .addHostKeyVerifier( SecurityUtils.getFingerprint( - hostKeyPair.public - ) + hostKeyPair.public, + ), ) verify(mock, atLeastOnce()).connectTimeout = NetCopyClientConnectionPool.CONNECT_TIMEOUT @@ -366,7 +370,7 @@ class NetCopyClientConnectionPoolSshTest { private fun doRunTest( validUsername: String, validPrivateKey: PrivateKey = userKeyPair.private, - subPath: String? = null + subPath: String? = null, ) { val encodedUsername = encode(validUsername, UTF_8.name()) val mock = createSshServer(validUsername, null) @@ -375,7 +379,7 @@ class NetCopyClientConnectionPoolSshTest { encodedUsername, null, validPrivateKey, - subPath + subPath, ) assertNotNull( getConnection( @@ -383,8 +387,8 @@ class NetCopyClientConnectionPoolSshTest { "ssh://$encodedUsername@$HOST:$PORT" } else { "ssh://$encodedUsername@$HOST:$PORT$subPath" - } - ) + }, + ), ) assertNull( getConnection( @@ -392,14 +396,14 @@ class NetCopyClientConnectionPoolSshTest { "ssh://$encodedInvalidUsername@$HOST:$PORT" } else { "ssh://$encodedInvalidUsername@$HOST:$PORT$subPath" - } - ) + }, + ), ) verify(mock, atLeastOnce()) .addHostKeyVerifier( SecurityUtils.getFingerprint( - hostKeyPair.public - ) + hostKeyPair.public, + ), ) verify(mock, atLeastOnce()).connectTimeout = NetCopyClientConnectionPool.CONNECT_TIMEOUT @@ -410,15 +414,18 @@ class NetCopyClientConnectionPoolSshTest { } @Throws(IOException::class) - private fun createSshServer(validUsername: String, validPassword: String?): SSHClient { + private fun createSshServer( + validUsername: String, + validPassword: String?, + ): SSHClient { val mock = Mockito.mock(SSHClient::class.java) doNothing().`when`(mock).connect(HOST, PORT) doNothing() .`when`(mock) .addHostKeyVerifier( SecurityUtils.getFingerprint( - hostKeyPair.public - ) + hostKeyPair.public, + ), ) doNothing().`when`(mock).disconnect() if (!Utils.isNullOrEmpty(validPassword)) { @@ -427,7 +434,7 @@ class NetCopyClientConnectionPoolSshTest { .`when`(mock) .authPassword( not(eq(validUsername)), - not(eq(validPassword)) + not(eq(validPassword)), ) } else { doNothing().`when`(mock).authPublickey(validUsername, sshKeyProvider) @@ -435,7 +442,7 @@ class NetCopyClientConnectionPoolSshTest { .`when`(mock) .authPublickey( not(eq(validUsername)), - eq(sshKeyProvider) + eq(sshKeyProvider), ) } `when`(mock.isConnected).thenReturn(true) @@ -450,7 +457,6 @@ class NetCopyClientConnectionPoolSshTest { } companion object { - const val HOST = "127.0.0.1" const val PORT = 22222 private const val invalidUsername = "invaliduser" @@ -470,22 +476,22 @@ class NetCopyClientConnectionPoolSshTest { fun bootstrap() { hostKeyPair = TestUtils.createKeyPair() userKeyPair = TestUtils.createKeyPair() - sshKeyProvider = object : KeyProvider { - - override fun getPrivate() = userKeyPair.private + sshKeyProvider = + object : KeyProvider { + override fun getPrivate() = userKeyPair.private - override fun getPublic() = userKeyPair.public + override fun getPublic() = userKeyPair.public - override fun getType() = KeyType.RSA + override fun getType() = KeyType.RSA - override fun equals(other: Any?): Boolean { - return if (other !is KeyProvider) { - false - } else { - other.private == private && other.public == public + override fun equals(other: Any?): Boolean { + return if (other !is KeyProvider) { + false + } else { + other.private == private && other.public == public + } } } - } RxJavaPlugins.reset() RxJavaPlugins.setIoSchedulerHandler { Schedulers.trampoline() diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/ssh/SshClientUtilsTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/ssh/SshClientUtilsTest.kt index 0954732853..3c18a2d865 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/ssh/SshClientUtilsTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/ssh/SshClientUtilsTest.kt @@ -39,7 +39,6 @@ import java.io.IOException * Unit tests for [SshClientUtils]. */ class SshClientUtilsTest { - companion object { private const val SYSROOT_ETC = "/sysroot/etc" } @@ -57,8 +56,8 @@ class SshClientUtilsTest { 22, null, "root", - "toor" - ) + "toor", + ), ) assertEquals( "ssh://root:toor@127.0.0.1:22", @@ -68,8 +67,8 @@ class SshClientUtilsTest { 22, "", "root", - "toor" - ) + "toor", + ), ) } @@ -135,7 +134,7 @@ class SshClientUtilsTest { assertThrows(IOException::class.java) { SshClientUtils.isDirectory( mockClient, - mock + mock, ) } } @@ -157,7 +156,7 @@ class SshClientUtilsTest { assertThrows(IOException::class.java) { SshClientUtils.isDirectory( mockClient, - mock + mock, ) } } diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/ssh/SshHybridFileTest.kt b/app/src/test/java/com/amaze/filemanager/filesystem/ssh/SshHybridFileTest.kt index 8b317fda6e..9957eae5dd 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/ssh/SshHybridFileTest.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/ssh/SshHybridFileTest.kt @@ -46,10 +46,9 @@ import org.robolectric.annotation.LooperMode @LooperMode(LooperMode.Mode.PAUSED) @Config( shadows = [ShadowMultiDex::class, ShadowPasswordUtil::class], - sdk = [KITKAT, P, Build.VERSION_CODES.R] + sdk = [KITKAT, P, Build.VERSION_CODES.R], ) class SshHybridFileTest { - private var ctx: Context? = null private val path: String = "ssh://user:password@127.0.0.1:22222/test.file" diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/ssh/test/BlockFileCreationFileSystemProvider.java b/app/src/test/java/com/amaze/filemanager/filesystem/ssh/test/BlockFileCreationFileSystemProvider.java index a88dcf9574..13a9bb1a13 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/ssh/test/BlockFileCreationFileSystemProvider.java +++ b/app/src/test/java/com/amaze/filemanager/filesystem/ssh/test/BlockFileCreationFileSystemProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/ssh/test/MockSshConnectionPools.kt b/app/src/test/java/com/amaze/filemanager/filesystem/ssh/test/MockSshConnectionPools.kt index cea22372a2..5861b5d595 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/ssh/test/MockSshConnectionPools.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/ssh/test/MockSshConnectionPools.kt @@ -37,7 +37,6 @@ import org.mockito.Mockito.mock import org.mockito.Mockito.`when` object MockSshConnectionPools { - private const val ACCESS_DENIED = "Access is denied." private val hostKeyPair = TestUtils.createKeyPair() @@ -59,39 +58,43 @@ object MockSshConnectionPools { "user", "password", userKeyPair.private, - null + null, ) - val fileAttributes = mock(FileAttributes::class.java).apply { - `when`(type).thenReturn(FileMode.Type.DIRECTORY) - } - val sftpClient = mock(SFTPClient::class.java).apply { - doThrow(SFTPException(ACCESS_DENIED)) - .`when`(this).rename("/tmp/old.file", "/tmp/new.file") - `when`(stat("/tmp/old.file")).thenReturn(fileAttributes) - `when`(stat("/tmp/new.file")).thenReturn(null) - val fa = mock(FileAttributes::class.java).apply { - `when`(type).thenReturn(FileMode.Type.REGULAR) + val fileAttributes = + mock(FileAttributes::class.java).apply { + `when`(type).thenReturn(FileMode.Type.DIRECTORY) } - `when`(stat("/test.file")).thenReturn(fa) + val sftpClient = + mock(SFTPClient::class.java).apply { + doThrow(SFTPException(ACCESS_DENIED)) + .`when`(this).rename("/tmp/old.file", "/tmp/new.file") + `when`(stat("/tmp/old.file")).thenReturn(fileAttributes) + `when`(stat("/tmp/new.file")).thenReturn(null) + val fa = + mock(FileAttributes::class.java).apply { + `when`(type).thenReturn(FileMode.Type.REGULAR) + } + `when`(stat("/test.file")).thenReturn(fa) - if (canDelete) { - doNothing().`when`(this).rm(anyString()) - doNothing().`when`(this).rmdir(anyString()) - } else { - `when`(rm(anyString())).thenThrow(SFTPException(ACCESS_DENIED)) - `when`(rmdir(anyString())).thenThrow(SFTPException(ACCESS_DENIED)) + if (canDelete) { + doNothing().`when`(this).rm(anyString()) + doNothing().`when`(this).rmdir(anyString()) + } else { + `when`(rm(anyString())).thenThrow(SFTPException(ACCESS_DENIED)) + `when`(rmdir(anyString())).thenThrow(SFTPException(ACCESS_DENIED)) + } + } + val sshClient = + mock(SSHClient::class.java).apply { + doNothing().`when`(this).addHostKeyVerifier(anyString()) + doNothing().`when`(this).connect(anyString(), anyInt()) + doNothing().`when`(this).authPassword(anyString(), anyString()) + doNothing().`when`(this).disconnect() + `when`(isConnected).thenReturn(true) + `when`(isAuthenticated).thenReturn(true) + `when`(newSFTPClient()).thenReturn(sftpClient) } - } - val sshClient = mock(SSHClient::class.java).apply { - doNothing().`when`(this).addHostKeyVerifier(anyString()) - doNothing().`when`(this).connect(anyString(), anyInt()) - doNothing().`when`(this).authPassword(anyString(), anyString()) - doNothing().`when`(this).disconnect() - `when`(isConnected).thenReturn(true) - `when`(isAuthenticated).thenReturn(true) - `when`(newSFTPClient()).thenReturn(sftpClient) - } /* * We don't need to go through authentication flow here, and in fact SshAuthenticationTask @@ -105,15 +108,16 @@ object MockSshConnectionPools { mutableMapOf( Pair>( "ssh://user:password@127.0.0.1:22222", - SSHClientImpl(sshClient) - ) - ) + SSHClientImpl(sshClient), + ), + ), ) } - NetCopyClientConnectionPool.sshClientFactory = object : - NetCopyClientConnectionPool.SSHClientFactory { - override fun create(config: Config): SSHClient = sshClient - } + NetCopyClientConnectionPool.sshClientFactory = + object : + NetCopyClientConnectionPool.SSHClientFactory { + override fun create(config: Config): SSHClient = sshClient + } } } diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/ssh/test/TestKeyProvider.java b/app/src/test/java/com/amaze/filemanager/filesystem/ssh/test/TestKeyProvider.java index c8f1bcee86..b76067d0fa 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/ssh/test/TestKeyProvider.java +++ b/app/src/test/java/com/amaze/filemanager/filesystem/ssh/test/TestKeyProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/ssh/test/TestUtils.kt b/app/src/test/java/com/amaze/filemanager/filesystem/ssh/test/TestUtils.kt index e816db9acc..35b1854a58 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/ssh/test/TestUtils.kt +++ b/app/src/test/java/com/amaze/filemanager/filesystem/ssh/test/TestUtils.kt @@ -44,7 +44,6 @@ import java.security.SecureRandom * Test support util methods. */ object TestUtils { - /** * Generate a [KeyPair] for testing. */ @@ -61,16 +60,17 @@ object TestUtils { validUsername: String, validPassword: String, certInfo: JSONObject? = null, - port: Int = NetCopyClientConnectionPoolFtpTest.PORT + port: Int = NetCopyClientConnectionPoolFtpTest.PORT, ) { val utilsHandler = AppConfig.getInstance().utilsHandler - val fullUri: StringBuilder = StringBuilder().append( - if (certInfo != null) { - FTPS_URI_PREFIX - } else { - FTP_URI_PREFIX - } - ) + val fullUri: StringBuilder = + StringBuilder().append( + if (certInfo != null) { + FTPS_URI_PREFIX + } else { + FTP_URI_PREFIX + }, + ) if (validUsername != "" && validPassword != "") { fullUri.append(validUsername) fullUri.append(':').append(validPassword).append("@") @@ -84,8 +84,8 @@ object TestUtils { "Test", certInfo?.toString(), null, - null - ) + null, + ), ) Shadows.shadowOf(Looper.getMainLooper()).idle() } @@ -99,7 +99,7 @@ object TestUtils { validPassword: String?, privateKey: PrivateKey?, subpath: String? = null, - port: Int = NetCopyClientConnectionPoolSshTest.PORT + port: Int = NetCopyClientConnectionPoolSshTest.PORT, ) { val utilsHandler = AppConfig.getInstance().utilsHandler var privateKeyContents: String? = null @@ -111,36 +111,41 @@ object TestUtils { jw.close() privateKeyContents = writer.toString() } - val fullUri: StringBuilder = StringBuilder() - .append(SSH_URI_PREFIX).append(validUsername) + val fullUri: StringBuilder = + StringBuilder() + .append(SSH_URI_PREFIX).append(validUsername) if (validPassword != null) fullUri.append(':').append(validPassword) fullUri.append( - "@${NetCopyClientConnectionPoolSshTest.HOST}:$port" + "@${NetCopyClientConnectionPoolSshTest.HOST}:$port", ) if (true == subpath?.isNotEmpty()) { fullUri.append(subpath) } - if (validPassword != null) utilsHandler.saveToDatabase( - OperationData( - UtilsHandler.Operation.SFTP, - fullUri.toString(), - "Test", - SecurityUtils.getFingerprint(hostKeyPair.public), - null, - null + if (validPassword != null) { + utilsHandler.saveToDatabase( + OperationData( + UtilsHandler.Operation.SFTP, + fullUri.toString(), + "Test", + SecurityUtils.getFingerprint(hostKeyPair.public), + null, + null, + ), ) - ) else utilsHandler.saveToDatabase( - OperationData( - UtilsHandler.Operation.SFTP, - encryptFtpPathAsNecessary(fullUri.toString()), - "Test", - SecurityUtils.getFingerprint(hostKeyPair.public), - "id_rsa", - privateKeyContents + } else { + utilsHandler.saveToDatabase( + OperationData( + UtilsHandler.Operation.SFTP, + encryptFtpPathAsNecessary(fullUri.toString()), + "Test", + SecurityUtils.getFingerprint(hostKeyPair.public), + "id_rsa", + privateKeyContents, + ), ) - ) + } Shadows.shadowOf(Looper.getMainLooper()).idle() } } diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/usb/ReflectionHelpers.java b/app/src/test/java/com/amaze/filemanager/filesystem/usb/ReflectionHelpers.java index faa833c091..49253194dc 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/usb/ReflectionHelpers.java +++ b/app/src/test/java/com/amaze/filemanager/filesystem/usb/ReflectionHelpers.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. @@ -79,8 +79,11 @@ static void addUsbOtgDevice(Activity activity) { @RequiresApi(Build.VERSION_CODES.LOLLIPOP) static void configureUsbDevice(UsbDevice device) - throws NoSuchMethodException, ClassNotFoundException, InvocationTargetException, - InstantiationException, IllegalAccessException { + throws NoSuchMethodException, + ClassNotFoundException, + InvocationTargetException, + InstantiationException, + IllegalAccessException { UsbConfiguration usbConfiguration = callUsbConfigurationConstructor(0, "", 0, 0); configureUsbConfiguration(usbConfiguration); @@ -91,8 +94,11 @@ static void configureUsbDevice(UsbDevice device) @RequiresApi(Build.VERSION_CODES.LOLLIPOP) static void configureUsbConfiguration(UsbConfiguration usbConfiguration) - throws NoSuchMethodException, ClassNotFoundException, InvocationTargetException, - InstantiationException, IllegalAccessException { + throws NoSuchMethodException, + ClassNotFoundException, + InvocationTargetException, + InstantiationException, + IllegalAccessException { UsbInterface usbInterface = callUsbInterfaceConstructor(01, 0, "", USB_CLASS_MASS_STORAGE, 0, 0); @@ -103,8 +109,11 @@ static void configureUsbConfiguration(UsbConfiguration usbConfiguration) @RequiresApi(Build.VERSION_CODES.KITKAT) static Parcelable[] configureUsbDevice() - throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, - InstantiationException, IllegalAccessException { + throws ClassNotFoundException, + NoSuchMethodException, + InvocationTargetException, + InstantiationException, + IllegalAccessException { UsbInterface usbInterface = (UsbInterface) callUsbInterfaceConstructor(01, USB_CLASS_MASS_STORAGE, 0, 0, null); @@ -123,8 +132,11 @@ static UsbDevice callUsbDeviceConstructor( @Nullable String productName, @NonNull String version, @Nullable String serialNumber) - throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, - InvocationTargetException, InstantiationException { + throws ClassNotFoundException, + NoSuchMethodException, + IllegalAccessException, + InvocationTargetException, + InstantiationException { Class clazz = (Class) Class.forName("android.hardware.usb.UsbDevice"); Constructor constructor = @@ -164,8 +176,11 @@ static UsbDevice callUsbDeviceConstructor( @Nullable String manufacturerName, @Nullable String productName, @Nullable String serialNumber) - throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, - InvocationTargetException, InstantiationException { + throws ClassNotFoundException, + NoSuchMethodException, + IllegalAccessException, + InvocationTargetException, + InstantiationException { Class clazz = (Class) Class.forName("android.hardware.usb.UsbDevice"); Constructor constructor = @@ -201,8 +216,11 @@ static UsbDevice callUsbDeviceConstructor( int subClass, int protocol, @NonNull Parcelable[] interfaces) - throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, - InvocationTargetException, InstantiationException { + throws ClassNotFoundException, + NoSuchMethodException, + IllegalAccessException, + InvocationTargetException, + InstantiationException { Class clazz = (Class) Class.forName("android.hardware.usb.UsbDevice"); Constructor constructor = @@ -222,8 +240,11 @@ static UsbDevice callUsbDeviceConstructor( @RequiresApi(Build.VERSION_CODES.LOLLIPOP) static UsbConfiguration callUsbConfigurationConstructor( int id, @Nullable String name, int attributes, int maxPower) - throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, - InvocationTargetException, InstantiationException { + throws ClassNotFoundException, + NoSuchMethodException, + IllegalAccessException, + InvocationTargetException, + InstantiationException { Class clazz = (Class) Class.forName("android.hardware.usb.UsbConfiguration"); @@ -236,8 +257,11 @@ static UsbConfiguration callUsbConfigurationConstructor( @RequiresApi(Build.VERSION_CODES.LOLLIPOP) static UsbInterface callUsbInterfaceConstructor( int id, int alternateSetting, @Nullable String name, int usbClass, int subClass, int protocol) - throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, - InvocationTargetException, InstantiationException { + throws ClassNotFoundException, + NoSuchMethodException, + IllegalAccessException, + InvocationTargetException, + InstantiationException { Class clazz = (Class) Class.forName("android.hardware.usb.UsbInterface"); @@ -250,8 +274,11 @@ static UsbInterface callUsbInterfaceConstructor( @RequiresApi(Build.VERSION_CODES.KITKAT) static UsbInterface callUsbInterfaceConstructor( int id, int usbClass, int subClass, int protocol, @Nullable Parcelable[] endpoints) - throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, - InvocationTargetException, InstantiationException { + throws ClassNotFoundException, + NoSuchMethodException, + IllegalAccessException, + InvocationTargetException, + InstantiationException { Class clazz = (Class) Class.forName("android.hardware.usb.UsbInterface"); diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/usb/SingletonUsbOtgTest.java b/app/src/test/java/com/amaze/filemanager/filesystem/usb/SingletonUsbOtgTest.java index 9094fb3028..038b31b035 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/usb/SingletonUsbOtgTest.java +++ b/app/src/test/java/com/amaze/filemanager/filesystem/usb/SingletonUsbOtgTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/test/java/com/amaze/filemanager/filesystem/usb/UsbOtgTest.java b/app/src/test/java/com/amaze/filemanager/filesystem/usb/UsbOtgTest.java index 3d2cd6d9c7..5039cc0ba8 100644 --- a/app/src/test/java/com/amaze/filemanager/filesystem/usb/UsbOtgTest.java +++ b/app/src/test/java/com/amaze/filemanager/filesystem/usb/UsbOtgTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/test/java/com/amaze/filemanager/ui/activities/AbstractMainActivityTestBase.kt b/app/src/test/java/com/amaze/filemanager/ui/activities/AbstractMainActivityTestBase.kt index aae1333837..bba0121b90 100644 --- a/app/src/test/java/com/amaze/filemanager/ui/activities/AbstractMainActivityTestBase.kt +++ b/app/src/test/java/com/amaze/filemanager/ui/activities/AbstractMainActivityTestBase.kt @@ -59,8 +59,8 @@ import org.robolectric.shadows.ShadowStorageManager ShadowMultiDex::class, ShadowStorageManager::class, ShadowPasswordUtil::class, - ShadowSmbFile::class - ] + ShadowSmbFile::class, + ], ) /* * Need to make LooperMode PAUSED and flush the main looper before activity can show up. @@ -69,7 +69,6 @@ import org.robolectric.shadows.ShadowStorageManager */ @LooperMode(LooperMode.Mode.PAUSED) abstract class AbstractMainActivityTestBase { - @Rule @NonNull @JvmField @@ -98,8 +97,8 @@ abstract class AbstractMainActivityTestBase { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Shadows.shadowOf( ApplicationProvider.getApplicationContext().getSystemService( - StorageManager::class.java - ) + StorageManager::class.java, + ), ).resetStorageVolumeList() } } diff --git a/app/src/test/java/com/amaze/filemanager/ui/activities/MainActivityTest.kt b/app/src/test/java/com/amaze/filemanager/ui/activities/MainActivityTest.kt index 79aeb00fa5..fb971d4caf 100644 --- a/app/src/test/java/com/amaze/filemanager/ui/activities/MainActivityTest.kt +++ b/app/src/test/java/com/amaze/filemanager/ui/activities/MainActivityTest.kt @@ -37,24 +37,25 @@ import java.util.concurrent.TimeUnit */ @Suppress("StringLiteralDuplication") class MainActivityTest : AbstractMainActivityTestBase() { - /** * Test update SMB connection should never throw [NullPointerException] i.e. the correct * connection is updated. */ @Test fun testUpdateSmbExceptionShouldNotThrowNPE() { - val scenario = ActivityScenario.launch( - MainActivity::class.java - ) + val scenario = + ActivityScenario.launch( + MainActivity::class.java, + ) ShadowLooper.idleMainLooper() scenario.moveToState(Lifecycle.State.STARTED) scenario.onActivity { activity: MainActivity -> val path = "smb://root:toor@192.168.1.1" - val encryptedPath = getSmbEncryptedPath( - ApplicationProvider.getApplicationContext(), - path - ) + val encryptedPath = + getSmbEncryptedPath( + ApplicationProvider.getApplicationContext(), + path, + ) val oldName = "SMB connection" val newName = "root@192.168.1.1" try { @@ -63,14 +64,14 @@ class MainActivityTest : AbstractMainActivityTestBase() { oldName, encryptedPath, null, - null + null, ) activity.addConnection( true, newName, encryptedPath, oldName, - encryptedPath + encryptedPath, ) ShadowLooper.idleMainLooper() await() @@ -84,7 +85,7 @@ class MainActivityTest : AbstractMainActivityTestBase() { .utilsHandler .smbList[0][0] == newName - ) + ) } val verify: List> = AppConfig.getInstance().utilsHandler.smbList assertEquals(1, verify.size.toLong()) diff --git a/app/src/test/java/com/amaze/filemanager/ui/activities/PermissionsActivityTest.kt b/app/src/test/java/com/amaze/filemanager/ui/activities/PermissionsActivityTest.kt index 69741eb77e..7fe654ea58 100644 --- a/app/src/test/java/com/amaze/filemanager/ui/activities/PermissionsActivityTest.kt +++ b/app/src/test/java/com/amaze/filemanager/ui/activities/PermissionsActivityTest.kt @@ -63,10 +63,9 @@ import org.robolectric.shadows.ShadowStorageManager @RunWith(AndroidJUnit4::class) @Config( sdk = [KITKAT, P, Build.VERSION_CODES.R], - shadows = [ShadowMultiDex::class, ShadowStorageManager::class] + shadows = [ShadowMultiDex::class, ShadowStorageManager::class], ) class PermissionsActivityTest { - private lateinit var scenario: ActivityScenario /** @@ -92,8 +91,8 @@ class PermissionsActivityTest { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Shadows.shadowOf( ApplicationProvider.getApplicationContext().getSystemService( - StorageManager::class.java - ) + StorageManager::class.java, + ), ).resetStorageVolumeList() } } @@ -111,13 +110,13 @@ class PermissionsActivityTest { val shadowApplication = shadowOf(RuntimeEnvironment.getApplication()) shadowOf( activity.getSystemService( - AppOpsManager::class.java - ) + AppOpsManager::class.java, + ), ).setMode( 92, activity.applicationInfo.uid, activity.packageName, - AppOpsManager.MODE_IGNORED + AppOpsManager.MODE_IGNORED, ) activity.requestAllFilesAccess { } assertNotNull(ShadowDialog.getLatestDialog()) @@ -126,18 +125,18 @@ class PermissionsActivityTest { (this as MaterialDialog).run { assertEquals( activity.getString(com.amaze.filemanager.R.string.grantper), - this.titleView.text + this.titleView.text, ) assertEquals( activity.getString( - com.amaze.filemanager.R.string.grant_all_files_permission + com.amaze.filemanager.R.string.grant_all_files_permission, ), - this.contentView?.text.toString() + this.contentView?.text.toString(), ) this.getActionButton(DialogAction.POSITIVE).run { assertEquals( activity.getString(com.amaze.filemanager.R.string.grant), - this.text + this.text, ) performClick() } @@ -145,7 +144,7 @@ class PermissionsActivityTest { assertNotNull(intent) assertEquals( Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION, - intent.action + intent.action, ) assertEquals(Uri.parse("package:${activity.packageName}"), intent.data) } diff --git a/app/src/test/java/com/amaze/filemanager/ui/activities/PreferencesActivityTestBase.kt b/app/src/test/java/com/amaze/filemanager/ui/activities/PreferencesActivityTestBase.kt index 53352a8bfc..0e2f5e227f 100644 --- a/app/src/test/java/com/amaze/filemanager/ui/activities/PreferencesActivityTestBase.kt +++ b/app/src/test/java/com/amaze/filemanager/ui/activities/PreferencesActivityTestBase.kt @@ -31,13 +31,10 @@ import org.robolectric.shadows.ShadowLooper * Base class for preference fragments, started from [PreferencesActivity]. */ abstract class PreferencesActivityTestBase : AbstractMainActivityTestBase() { - /** * Put in your test here. */ - protected open fun doTestPreferenceFragment( - test: (PreferencesActivity, PrefsFragment) -> Unit - ) { + protected open fun doTestPreferenceFragment(test: (PreferencesActivity, PrefsFragment) -> Unit) { val scenario = ActivityScenario.launch(PreferencesActivity::class.java) ShadowLooper.idleMainLooper() scenario.moveToState(Lifecycle.State.STARTED) @@ -46,7 +43,7 @@ abstract class PreferencesActivityTestBase : AbstractMainActivityTestBase() { assertTrue(activity.supportFragmentManager.fragments.first() is PrefsFragment) test.invoke( activity, - activity.supportFragmentManager.fragments.first() as PrefsFragment + activity.supportFragmentManager.fragments.first() as PrefsFragment, ) } } diff --git a/app/src/test/java/com/amaze/filemanager/ui/activities/TextEditorActivityTest.java b/app/src/test/java/com/amaze/filemanager/ui/activities/TextEditorActivityTest.java index 3209d48ad1..af5b150df3 100644 --- a/app/src/test/java/com/amaze/filemanager/ui/activities/TextEditorActivityTest.java +++ b/app/src/test/java/com/amaze/filemanager/ui/activities/TextEditorActivityTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/test/java/com/amaze/filemanager/ui/colors/ColorUtilsTest.java b/app/src/test/java/com/amaze/filemanager/ui/colors/ColorUtilsTest.java index 949a8d5f57..19c8d0e929 100644 --- a/app/src/test/java/com/amaze/filemanager/ui/colors/ColorUtilsTest.java +++ b/app/src/test/java/com/amaze/filemanager/ui/colors/ColorUtilsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/test/java/com/amaze/filemanager/ui/dialogs/AbstractEncryptDialogTests.kt b/app/src/test/java/com/amaze/filemanager/ui/dialogs/AbstractEncryptDialogTests.kt index ba3ac95807..5fd8606f4b 100644 --- a/app/src/test/java/com/amaze/filemanager/ui/dialogs/AbstractEncryptDialogTests.kt +++ b/app/src/test/java/com/amaze/filemanager/ui/dialogs/AbstractEncryptDialogTests.kt @@ -47,17 +47,17 @@ import org.robolectric.annotation.Config @RunWith(AndroidJUnit4::class) @Config( shadows = [ShadowMultiDex::class, ShadowTabHandler::class], - sdk = [KITKAT, P, Build.VERSION_CODES.R] + sdk = [KITKAT, P, Build.VERSION_CODES.R], ) abstract class AbstractEncryptDialogTests { - protected lateinit var scenario: ActivityScenario @Rule @JvmField @RequiresApi(Build.VERSION_CODES.R) - var allFilesPermissionRule = GrantPermissionRule - .grant(Manifest.permission.MANAGE_EXTERNAL_STORAGE) + var allFilesPermissionRule = + GrantPermissionRule + .grant(Manifest.permission.MANAGE_EXTERNAL_STORAGE) /** * MainActivity setup. diff --git a/app/src/test/java/com/amaze/filemanager/ui/dialogs/ColorPickerDialogTest.kt b/app/src/test/java/com/amaze/filemanager/ui/dialogs/ColorPickerDialogTest.kt index 9b408770ef..08f0cb2798 100644 --- a/app/src/test/java/com/amaze/filemanager/ui/dialogs/ColorPickerDialogTest.kt +++ b/app/src/test/java/com/amaze/filemanager/ui/dialogs/ColorPickerDialogTest.kt @@ -41,20 +41,20 @@ import org.robolectric.annotation.Config @RunWith(AndroidJUnit4::class) @Config( shadows = [ShadowMultiDex::class, ShadowTabHandler::class], - sdk = [KITKAT, P, VERSION_CODES.R] + sdk = [KITKAT, P, VERSION_CODES.R], ) class ColorPickerDialogTest { - /** * Tests [ColorPickerDialog.onCreateDialog] as sanity check. */ @Test fun testCreateDialog() { - val dialog = ColorPickerDialog.newInstance( - PreferencesConstants.PRESELECTED_CONFIGS, - ColorPreferenceHelper.randomize(AppConfig.getInstance()), - AppTheme.LIGHT - ) + val dialog = + ColorPickerDialog.newInstance( + PreferencesConstants.PRESELECTED_CONFIGS, + ColorPreferenceHelper.randomize(AppConfig.getInstance()), + AppTheme.LIGHT, + ) assertNotNull(dialog) } } diff --git a/app/src/test/java/com/amaze/filemanager/ui/dialogs/DecryptFingerprintDialogTest.kt b/app/src/test/java/com/amaze/filemanager/ui/dialogs/DecryptFingerprintDialogTest.kt index 22309c511e..838aa2ff65 100644 --- a/app/src/test/java/com/amaze/filemanager/ui/dialogs/DecryptFingerprintDialogTest.kt +++ b/app/src/test/java/com/amaze/filemanager/ui/dialogs/DecryptFingerprintDialogTest.kt @@ -59,10 +59,9 @@ import kotlin.random.Random */ @Config( shadows = [ShadowMultiDex::class, ShadowTabHandler::class, ShadowFingerprintManager::class], - sdk = [P] + sdk = [P], ) class DecryptFingerprintDialogTest : AbstractEncryptDialogTests() { - private lateinit var file: File /** @@ -71,13 +70,14 @@ class DecryptFingerprintDialogTest : AbstractEncryptDialogTests() { @Before override fun setUp() { super.setUp() - file = File( - Environment.getExternalStorageDirectory(), - RandomPathGenerator.generateRandomPath( - randomizer, - 16 - ) + CRYPT_EXTENSION - ) + file = + File( + Environment.getExternalStorageDirectory(), + RandomPathGenerator.generateRandomPath( + randomizer, + 16, + ) + CRYPT_EXTENSION, + ) initMockSecretKeygen() shadowOf(AppConfig.getInstance()).grantPermissions(USE_FINGERPRINT) } @@ -91,17 +91,19 @@ class DecryptFingerprintDialogTest : AbstractEncryptDialogTests() { performTest( testContent = { shadowOf( - AppConfig.getInstance().getSystemService(FingerprintManager::class.java) + AppConfig.getInstance().getSystemService(FingerprintManager::class.java), ).run { setDefaultFingerprints(1) setIsHardwareDetected(true) authenticationSucceeds() } }, - callback = object : EncryptDecryptUtils.DecryptButtonCallbackInterface { - override fun confirm(intent: Intent) = assertTrue(true) - override fun failed() = fail("Should never called") - } + callback = + object : EncryptDecryptUtils.DecryptButtonCallbackInterface { + override fun confirm(intent: Intent) = assertTrue(true) + + override fun failed() = fail("Should never called") + }, ) } @@ -114,24 +116,26 @@ class DecryptFingerprintDialogTest : AbstractEncryptDialogTests() { performTest( testContent = { shadowOf( - AppConfig.getInstance().getSystemService(FingerprintManager::class.java) + AppConfig.getInstance().getSystemService(FingerprintManager::class.java), ).run { setDefaultFingerprints(1) setIsHardwareDetected(true) authenticationFails() } }, - callback = object : EncryptDecryptUtils.DecryptButtonCallbackInterface { - override fun confirm(intent: Intent) = fail("Should never called") - override fun failed() = assertTrue(true) - } + callback = + object : EncryptDecryptUtils.DecryptButtonCallbackInterface { + override fun confirm(intent: Intent) = fail("Should never called") + + override fun failed() = assertTrue(true) + }, ) } private fun performTest( testContent: () -> Unit, callback: EncryptDecryptUtils.DecryptButtonCallbackInterface = - object : EncryptDecryptUtils.DecryptButtonCallbackInterface {} + object : EncryptDecryptUtils.DecryptButtonCallbackInterface {}, ) { scenario.onActivity { activity -> DecryptFingerprintDialog.show( @@ -141,10 +145,10 @@ class DecryptFingerprintDialogTest : AbstractEncryptDialogTests() { .putExtra(TAG_OPEN_MODE, OpenMode.FILE) .putExtra( TAG_DECRYPT_PATH, - Environment.getExternalStorageDirectory().absolutePath + Environment.getExternalStorageDirectory().absolutePath, ), activity.appTheme, - callback + callback, ) ShadowDialog.getLatestDialog()?.run { assertTrue(this is MaterialDialog) @@ -156,7 +160,6 @@ class DecryptFingerprintDialogTest : AbstractEncryptDialogTests() { } companion object { - private val randomizer = Random(System.currentTimeMillis()) private val key = SecretKeySpec(randomizer.nextBytes(16), "AES") diff --git a/app/src/test/java/com/amaze/filemanager/ui/dialogs/EncryptAuthenticateDialogTest.kt b/app/src/test/java/com/amaze/filemanager/ui/dialogs/EncryptAuthenticateDialogTest.kt index dfd3dea3a8..3a1b575de8 100644 --- a/app/src/test/java/com/amaze/filemanager/ui/dialogs/EncryptAuthenticateDialogTest.kt +++ b/app/src/test/java/com/amaze/filemanager/ui/dialogs/EncryptAuthenticateDialogTest.kt @@ -62,7 +62,6 @@ import kotlin.random.Random * Logic test for [EncryptAuthenticateDialog]. */ class EncryptAuthenticateDialogTest : AbstractEncryptDialogTests() { - private val randomizer = Random(System.currentTimeMillis()) private lateinit var file: File private lateinit var tilFileSaveAs: WarnableTextInputLayout @@ -81,13 +80,14 @@ class EncryptAuthenticateDialogTest : AbstractEncryptDialogTests() { @Before override fun setUp() { super.setUp() - file = File( - Environment.getExternalStorageDirectory(), - RandomPathGenerator.generateRandomPath( - randomizer, - 16 + file = + File( + Environment.getExternalStorageDirectory(), + RandomPathGenerator.generateRandomPath( + randomizer, + 16, + ), ) - ) } /** @@ -105,16 +105,19 @@ class EncryptAuthenticateDialogTest : AbstractEncryptDialogTests() { okButton.performClick() }, object : EncryptDecryptUtils.EncryptButtonCallbackInterface { - override fun onButtonPressed(intent: Intent, password: String) { + override fun onButtonPressed( + intent: Intent, + password: String, + ) { assertEquals(file.absolutePath, intent.getStringExtra(TAG_SOURCE)) assertTrue(intent.getBooleanExtra(TAG_AESCRYPT, false)) assertEquals( "${file.name}$AESCRYPT_EXTENSION", - intent.getStringExtra(TAG_ENCRYPT_TARGET) + intent.getStringExtra(TAG_ENCRYPT_TARGET), ) assertEquals("abcdefgh", password) } - } + }, ) } @@ -135,16 +138,19 @@ class EncryptAuthenticateDialogTest : AbstractEncryptDialogTests() { okButton.performClick() }, object : EncryptDecryptUtils.EncryptButtonCallbackInterface { - override fun onButtonPressed(intent: Intent, password: String) { + override fun onButtonPressed( + intent: Intent, + password: String, + ) { assertEquals(file.absolutePath, intent.getStringExtra(TAG_SOURCE)) assertFalse(intent.getBooleanExtra(TAG_AESCRYPT, true)) assertEquals( "testfile$CRYPT_EXTENSION", - intent.getStringExtra(TAG_ENCRYPT_TARGET) + intent.getStringExtra(TAG_ENCRYPT_TARGET), ) assertEquals("abcdefgh", password) } - } + }, ) } @@ -159,7 +165,7 @@ class EncryptAuthenticateDialogTest : AbstractEncryptDialogTests() { assertFalse(okButton.isEnabled) assertEquals( getString(R.string.password_no_match), - tilEncryptPasswordConfirm.error + tilEncryptPasswordConfirm.error, ) editTextEncryptPassword.setText("") editTextEncryptPasswordConfirm.setText("") @@ -189,13 +195,13 @@ class EncryptAuthenticateDialogTest : AbstractEncryptDialogTests() { assertFalse(okButton.isEnabled) assertEquals( getString(R.string.encrypt_file_must_end_with_aes), - tilFileSaveAs.error + tilFileSaveAs.error, ) editTextFileSaveAs.setText("${file.name}.aze") assertFalse(okButton.isEnabled) assertEquals( getString(R.string.encrypt_file_must_end_with_aes), - tilFileSaveAs.error + tilFileSaveAs.error, ) checkboxUseAze.isChecked = true assertTrue(okButton.isEnabled) @@ -204,25 +210,25 @@ class EncryptAuthenticateDialogTest : AbstractEncryptDialogTests() { assertFalse(okButton.isEnabled) assertEquals( getString(R.string.encrypt_file_must_end_with_aze), - tilFileSaveAs.error + tilFileSaveAs.error, ) editTextFileSaveAs.setText("${file.name}.aes") assertFalse(okButton.isEnabled) assertEquals( getString(R.string.encrypt_file_must_end_with_aze), - tilFileSaveAs.error + tilFileSaveAs.error, ) editTextFileSaveAs.setText("") assertFalse(okButton.isEnabled) assertEquals( getString(R.string.field_empty), - tilFileSaveAs.error + tilFileSaveAs.error, ) editTextFileSaveAs.setText(" ") assertFalse(okButton.isEnabled) assertEquals( getString(R.string.field_empty), - tilFileSaveAs.error + tilFileSaveAs.error, ) editTextFileSaveAs.setText("${file.name}.aze") assertTrue(okButton.isEnabled) @@ -240,10 +246,10 @@ class EncryptAuthenticateDialogTest : AbstractEncryptDialogTests() { assertEquals( HtmlCompat.fromHtml( getString(R.string.encrypt_option_use_azecrypt_desc), - FROM_HTML_MODE_COMPACT + FROM_HTML_MODE_COMPACT, ) .toString(), - textViewCryptInfo.text.toString() + textViewCryptInfo.text.toString(), ) assertTrue(ShadowDialog.getShownDialogs().size == 2) assertTrue(ShadowDialog.getLatestDialog() is MaterialDialog) @@ -252,11 +258,11 @@ class EncryptAuthenticateDialogTest : AbstractEncryptDialogTests() { assertEquals(getString(R.string.crypt_warning_key), contentView?.text.toString()) assertEquals( getString(R.string.warning_never_show), - getActionButton(DialogAction.NEGATIVE).text + getActionButton(DialogAction.NEGATIVE).text, ) assertEquals( getString(R.string.warning_confirm), - getActionButton(DialogAction.POSITIVE).text + getActionButton(DialogAction.POSITIVE).text, ) assertTrue(getActionButton(DialogAction.POSITIVE).performClick()) } @@ -267,10 +273,10 @@ class EncryptAuthenticateDialogTest : AbstractEncryptDialogTests() { assertEquals( HtmlCompat.fromHtml( getString(R.string.encrypt_option_use_aescrypt_desc), - FROM_HTML_MODE_COMPACT + FROM_HTML_MODE_COMPACT, ) .toString(), - textViewCryptInfo.text.toString() + textViewCryptInfo.text.toString(), ) assertEquals(2, ShadowDialog.getShownDialogs().size) assertFalse(ShadowDialog.getLatestDialog().isShowing) @@ -279,10 +285,10 @@ class EncryptAuthenticateDialogTest : AbstractEncryptDialogTests() { assertEquals( HtmlCompat.fromHtml( getString(R.string.encrypt_option_use_azecrypt_desc), - FROM_HTML_MODE_COMPACT + FROM_HTML_MODE_COMPACT, ) .toString(), - textViewCryptInfo.text.toString() + textViewCryptInfo.text.toString(), ) assertEquals(3, ShadowDialog.getShownDialogs().size) assertTrue(ShadowDialog.getLatestDialog().isShowing) @@ -293,7 +299,7 @@ class EncryptAuthenticateDialogTest : AbstractEncryptDialogTests() { assertFalse(ShadowDialog.getLatestDialog().isShowing) assertTrue( PreferenceManager.getDefaultSharedPreferences(AppConfig.getInstance()) - .getBoolean(PreferencesConstants.PREFERENCE_CRYPT_WARNING_REMEMBER, false) + .getBoolean(PreferencesConstants.PREFERENCE_CRYPT_WARNING_REMEMBER, false), ) checkboxUseAze.isChecked = false assertEquals(3, ShadowDialog.getShownDialogs().size) // no new dialog @@ -327,10 +333,10 @@ class EncryptAuthenticateDialogTest : AbstractEncryptDialogTests() { testContent: ( dialog: MaterialDialog, intent: Intent, - activity: MainActivity + activity: MainActivity, ) -> Unit, callback: EncryptDecryptUtils.EncryptButtonCallbackInterface = - object : EncryptDecryptUtils.EncryptButtonCallbackInterface {} + object : EncryptDecryptUtils.EncryptButtonCallbackInterface {}, ) { scenario.onActivity { activity -> Intent().putExtra(TAG_SOURCE, HybridFileParcelable(file.absolutePath)) @@ -340,33 +346,40 @@ class EncryptAuthenticateDialogTest : AbstractEncryptDialogTests() { intent, activity, activity.appTheme, - callback + callback, ) ShadowDialog.getLatestDialog()?.run { assertTrue(this is MaterialDialog) (this as MaterialDialog).let { - editTextFileSaveAs = findViewById( - R.id.edit_text_encrypt_save_as - ) - editTextEncryptPassword = findViewById( - R.id.edit_text_dialog_encrypt_password - ) - editTextEncryptPasswordConfirm = findViewById( - R.id.edit_text_dialog_encrypt_password_confirm - ) - tilFileSaveAs = findViewById( - R.id.til_encrypt_save_as - ) - tilEncryptPassword = findViewById( - R.id.til_encrypt_password - ) - tilEncryptPasswordConfirm = findViewById( - R.id.til_encrypt_password - ) + editTextFileSaveAs = + findViewById( + R.id.edit_text_encrypt_save_as, + ) + editTextEncryptPassword = + findViewById( + R.id.edit_text_dialog_encrypt_password, + ) + editTextEncryptPasswordConfirm = + findViewById( + R.id.edit_text_dialog_encrypt_password_confirm, + ) + tilFileSaveAs = + findViewById( + R.id.til_encrypt_save_as, + ) + tilEncryptPassword = + findViewById( + R.id.til_encrypt_password, + ) + tilEncryptPasswordConfirm = + findViewById( + R.id.til_encrypt_password, + ) checkboxUseAze = findViewById(R.id.checkbox_use_aze) - textViewCryptInfo = findViewById( - R.id.text_view_crypt_info - ) + textViewCryptInfo = + findViewById( + R.id.text_view_crypt_info, + ) okButton = getActionButton(DialogAction.POSITIVE) assertFalse(okButton.isEnabled) assertTrue(true == editTextFileSaveAs.text?.startsWith(file.name)) diff --git a/app/src/test/java/com/amaze/filemanager/ui/dialogs/EncryptWarningDialogTest.kt b/app/src/test/java/com/amaze/filemanager/ui/dialogs/EncryptWarningDialogTest.kt index 81f18d13a3..fe9985b806 100644 --- a/app/src/test/java/com/amaze/filemanager/ui/dialogs/EncryptWarningDialogTest.kt +++ b/app/src/test/java/com/amaze/filemanager/ui/dialogs/EncryptWarningDialogTest.kt @@ -37,7 +37,6 @@ import org.robolectric.shadows.ShadowDialog * Test [EncryptWarningDialog]. */ class EncryptWarningDialogTest : AbstractEncryptDialogTests() { - /** * Verify dialog behaviour. */ @@ -52,17 +51,17 @@ class EncryptWarningDialogTest : AbstractEncryptDialogTests() { assertEquals(getString(R.string.crypt_warning_key), contentView?.text.toString()) assertEquals( getString(R.string.warning_never_show), - getActionButton(DialogAction.NEGATIVE).text + getActionButton(DialogAction.NEGATIVE).text, ) assertEquals( getString(R.string.warning_confirm), - getActionButton(DialogAction.POSITIVE).text + getActionButton(DialogAction.POSITIVE).text, ) assertTrue(getActionButton(DialogAction.POSITIVE).performClick()) } assertFalse( PreferenceManager.getDefaultSharedPreferences(AppConfig.getInstance()) - .getBoolean(PreferencesConstants.PREFERENCE_CRYPT_WARNING_REMEMBER, false) + .getBoolean(PreferencesConstants.PREFERENCE_CRYPT_WARNING_REMEMBER, false), ) } } @@ -81,7 +80,7 @@ class EncryptWarningDialogTest : AbstractEncryptDialogTests() { } assertTrue( PreferenceManager.getDefaultSharedPreferences(AppConfig.getInstance()) - .getBoolean(PreferencesConstants.PREFERENCE_CRYPT_WARNING_REMEMBER, false) + .getBoolean(PreferencesConstants.PREFERENCE_CRYPT_WARNING_REMEMBER, false), ) } } diff --git a/app/src/test/java/com/amaze/filemanager/ui/dialogs/EncryptWithPresetPasswordSaveAsDialogTest.kt b/app/src/test/java/com/amaze/filemanager/ui/dialogs/EncryptWithPresetPasswordSaveAsDialogTest.kt index c0c5b02a50..76b1c50bad 100644 --- a/app/src/test/java/com/amaze/filemanager/ui/dialogs/EncryptWithPresetPasswordSaveAsDialogTest.kt +++ b/app/src/test/java/com/amaze/filemanager/ui/dialogs/EncryptWithPresetPasswordSaveAsDialogTest.kt @@ -62,7 +62,6 @@ import java.io.File import kotlin.random.Random class EncryptWithPresetPasswordSaveAsDialogTest : AbstractEncryptDialogTests() { - private val randomizer = Random(System.currentTimeMillis()) private lateinit var file: File private lateinit var tilFileSaveAs: WarnableTextInputLayout @@ -77,13 +76,14 @@ class EncryptWithPresetPasswordSaveAsDialogTest : AbstractEncryptDialogTests() { @Before override fun setUp() { super.setUp() - file = File( - Environment.getExternalStorageDirectory(), - RandomPathGenerator.generateRandomPath( - randomizer, - 16 + file = + File( + Environment.getExternalStorageDirectory(), + RandomPathGenerator.generateRandomPath( + randomizer, + 16, + ), ) - ) } /** @@ -95,7 +95,7 @@ class EncryptWithPresetPasswordSaveAsDialogTest : AbstractEncryptDialogTests() { PreferenceManager.getDefaultSharedPreferences(AppConfig.getInstance()) .edit().putBoolean( PREFERENCE_CRYPT_FINGERPRINT, - PREFERENCE_CRYPT_FINGERPRINT_DEFAULT + PREFERENCE_CRYPT_FINGERPRINT_DEFAULT, ).apply() } @@ -116,17 +116,21 @@ class EncryptWithPresetPasswordSaveAsDialogTest : AbstractEncryptDialogTests() { assertEquals(INVISIBLE, checkboxUseAze.visibility) assertEquals(INVISIBLE, textViewCryptInfo.visibility) }, - callback = object : EncryptDecryptUtils.EncryptButtonCallbackInterface { - override fun onButtonPressed(intent: Intent, password: String) { - assertEquals(ENCRYPT_PASSWORD_FINGERPRINT, password) - assertEquals(file.absolutePath, intent.getStringExtra(TAG_SOURCE)) - assertFalse(intent.getBooleanExtra(EncryptService.TAG_AESCRYPT, true)) - assertEquals( - "${file.name}$CRYPT_EXTENSION", - intent.getStringExtra(EncryptService.TAG_ENCRYPT_TARGET) - ) - } - } + callback = + object : EncryptDecryptUtils.EncryptButtonCallbackInterface { + override fun onButtonPressed( + intent: Intent, + password: String, + ) { + assertEquals(ENCRYPT_PASSWORD_FINGERPRINT, password) + assertEquals(file.absolutePath, intent.getStringExtra(TAG_SOURCE)) + assertFalse(intent.getBooleanExtra(EncryptService.TAG_AESCRYPT, true)) + assertEquals( + "${file.name}$CRYPT_EXTENSION", + intent.getStringExtra(EncryptService.TAG_ENCRYPT_TARGET), + ) + } + }, ) } @@ -145,13 +149,13 @@ class EncryptWithPresetPasswordSaveAsDialogTest : AbstractEncryptDialogTests() { assertFalse(okButton.isEnabled) assertEquals( getString(R.string.encrypt_file_must_end_with_aze), - tilFileSaveAs.error + tilFileSaveAs.error, ) editTextFileSaveAs.setText("${file.name}.aes") assertFalse(okButton.isEnabled) assertEquals( getString(R.string.encrypt_file_must_end_with_aze), - tilFileSaveAs.error + tilFileSaveAs.error, ) }) } @@ -173,18 +177,18 @@ class EncryptWithPresetPasswordSaveAsDialogTest : AbstractEncryptDialogTests() { assertFalse(okButton.isEnabled) assertEquals( getString(R.string.encrypt_file_must_end_with_aes), - tilFileSaveAs.error + tilFileSaveAs.error, ) editTextFileSaveAs.setText("${file.name}.aze") assertFalse(okButton.isEnabled) assertEquals( getString(R.string.encrypt_file_must_end_with_aes), - tilFileSaveAs.error + tilFileSaveAs.error, ) checkboxUseAze.isChecked = true assertTrue(okButton.isEnabled) assertNull(tilFileSaveAs.error) - } + }, ) } @@ -207,17 +211,21 @@ class EncryptWithPresetPasswordSaveAsDialogTest : AbstractEncryptDialogTests() { assertEquals(VISIBLE, checkboxUseAze.visibility) assertEquals(VISIBLE, textViewCryptInfo.visibility) }, - callback = object : EncryptDecryptUtils.EncryptButtonCallbackInterface { - override fun onButtonPressed(intent: Intent, password: String) { - assertEquals(ENCRYPT_PASSWORD_MASTER, password) - assertEquals(file.absolutePath, intent.getStringExtra(TAG_SOURCE)) - assertTrue(intent.getBooleanExtra(EncryptService.TAG_AESCRYPT, false)) - assertEquals( - "${file.name}$AESCRYPT_EXTENSION", - intent.getStringExtra(EncryptService.TAG_ENCRYPT_TARGET) - ) - } - } + callback = + object : EncryptDecryptUtils.EncryptButtonCallbackInterface { + override fun onButtonPressed( + intent: Intent, + password: String, + ) { + assertEquals(ENCRYPT_PASSWORD_MASTER, password) + assertEquals(file.absolutePath, intent.getStringExtra(TAG_SOURCE)) + assertTrue(intent.getBooleanExtra(EncryptService.TAG_AESCRYPT, false)) + assertEquals( + "${file.name}$AESCRYPT_EXTENSION", + intent.getStringExtra(EncryptService.TAG_ENCRYPT_TARGET), + ) + } + }, ) } @@ -232,7 +240,7 @@ class EncryptWithPresetPasswordSaveAsDialogTest : AbstractEncryptDialogTests() { .apply() performTest( password = "abcdefgh", - testContent = { _, _, _ -> } + testContent = { _, _, _ -> }, ) } @@ -248,10 +256,10 @@ class EncryptWithPresetPasswordSaveAsDialogTest : AbstractEncryptDialogTests() { assertEquals( HtmlCompat.fromHtml( getString(R.string.encrypt_option_use_azecrypt_desc), - HtmlCompat.FROM_HTML_MODE_COMPACT + HtmlCompat.FROM_HTML_MODE_COMPACT, ) .toString(), - textViewCryptInfo.text.toString() + textViewCryptInfo.text.toString(), ) assertTrue(ShadowDialog.getShownDialogs().size == 2) assertTrue(ShadowDialog.getLatestDialog() is MaterialDialog) @@ -259,15 +267,15 @@ class EncryptWithPresetPasswordSaveAsDialogTest : AbstractEncryptDialogTests() { assertEquals(getString(R.string.warning), titleView.text) assertEquals( getString(R.string.crypt_warning_key), - contentView?.text.toString() + contentView?.text.toString(), ) assertEquals( getString(R.string.warning_never_show), - getActionButton(DialogAction.NEGATIVE).text + getActionButton(DialogAction.NEGATIVE).text, ) assertEquals( getString(R.string.warning_confirm), - getActionButton(DialogAction.POSITIVE).text + getActionButton(DialogAction.POSITIVE).text, ) assertTrue(getActionButton(DialogAction.POSITIVE).performClick()) } @@ -278,10 +286,10 @@ class EncryptWithPresetPasswordSaveAsDialogTest : AbstractEncryptDialogTests() { assertEquals( HtmlCompat.fromHtml( getString(R.string.encrypt_option_use_aescrypt_desc), - HtmlCompat.FROM_HTML_MODE_COMPACT + HtmlCompat.FROM_HTML_MODE_COMPACT, ) .toString(), - textViewCryptInfo.text.toString() + textViewCryptInfo.text.toString(), ) assertEquals(2, ShadowDialog.getShownDialogs().size) assertFalse(ShadowDialog.getLatestDialog().isShowing) @@ -290,10 +298,10 @@ class EncryptWithPresetPasswordSaveAsDialogTest : AbstractEncryptDialogTests() { assertEquals( HtmlCompat.fromHtml( getString(R.string.encrypt_option_use_azecrypt_desc), - HtmlCompat.FROM_HTML_MODE_COMPACT + HtmlCompat.FROM_HTML_MODE_COMPACT, ) .toString(), - textViewCryptInfo.text.toString() + textViewCryptInfo.text.toString(), ) assertEquals(3, ShadowDialog.getShownDialogs().size) assertTrue(ShadowDialog.getLatestDialog().isShowing) @@ -304,13 +312,13 @@ class EncryptWithPresetPasswordSaveAsDialogTest : AbstractEncryptDialogTests() { assertFalse(ShadowDialog.getLatestDialog().isShowing) assertTrue( PreferenceManager.getDefaultSharedPreferences(AppConfig.getInstance()) - .getBoolean(PreferencesConstants.PREFERENCE_CRYPT_WARNING_REMEMBER, false) + .getBoolean(PreferencesConstants.PREFERENCE_CRYPT_WARNING_REMEMBER, false), ) checkboxUseAze.isChecked = false assertEquals(3, ShadowDialog.getShownDialogs().size) // no new dialog checkboxUseAze.isChecked = true assertEquals(3, ShadowDialog.getShownDialogs().size) - } + }, ) } @@ -318,7 +326,7 @@ class EncryptWithPresetPasswordSaveAsDialogTest : AbstractEncryptDialogTests() { testContent: (dialog: MaterialDialog, intent: Intent, activity: MainActivity) -> Unit, password: String = ENCRYPT_PASSWORD_FINGERPRINT, callback: EncryptDecryptUtils.EncryptButtonCallbackInterface = - object : EncryptDecryptUtils.EncryptButtonCallbackInterface {} + object : EncryptDecryptUtils.EncryptButtonCallbackInterface {}, ) { scenario.onActivity { activity -> Intent().putExtra(TAG_SOURCE, HybridFileParcelable(file.absolutePath)).let { intent -> @@ -327,21 +335,24 @@ class EncryptWithPresetPasswordSaveAsDialogTest : AbstractEncryptDialogTests() { intent, activity, password, - callback + callback, ) ShadowDialog.getLatestDialog()?.run { assertTrue(this is MaterialDialog) (this as MaterialDialog).let { - editTextFileSaveAs = findViewById( - R.id.edit_text_encrypt_save_as - ) - tilFileSaveAs = findViewById( - R.id.til_encrypt_save_as - ) + editTextFileSaveAs = + findViewById( + R.id.edit_text_encrypt_save_as, + ) + tilFileSaveAs = + findViewById( + R.id.til_encrypt_save_as, + ) checkboxUseAze = findViewById(R.id.checkbox_use_aze) - textViewCryptInfo = findViewById( - R.id.text_view_crypt_info - ) + textViewCryptInfo = + findViewById( + R.id.text_view_crypt_info, + ) okButton = getActionButton(DialogAction.POSITIVE) testContent.invoke(it, intent, activity) } diff --git a/app/src/test/java/com/amaze/filemanager/ui/dialogs/SftpConnectDialogTest.kt b/app/src/test/java/com/amaze/filemanager/ui/dialogs/SftpConnectDialogTest.kt index fc8db02b62..2bde0226a7 100644 --- a/app/src/test/java/com/amaze/filemanager/ui/dialogs/SftpConnectDialogTest.kt +++ b/app/src/test/java/com/amaze/filemanager/ui/dialogs/SftpConnectDialogTest.kt @@ -48,7 +48,6 @@ import java.util.concurrent.TimeUnit @Suppress("StringLiteralDuplication") class SftpConnectDialogTest : AbstractMainActivityTestBase() { - private lateinit var mc: MockedConstruction /** @@ -57,12 +56,13 @@ class SftpConnectDialogTest : AbstractMainActivityTestBase() { @Before override fun setUp() { super.setUp() - mc = mockConstruction( - SftpConnectDialog::class.java - ) { mock: SftpConnectDialog, _: MockedConstruction.Context? -> - doCallRealMethod().`when`(mock).arguments = any() - `when`(mock.arguments).thenCallRealMethod() - } + mc = + mockConstruction( + SftpConnectDialog::class.java, + ) { mock: SftpConnectDialog, _: MockedConstruction.Context? -> + doCallRealMethod().`when`(mock).arguments = any() + `when`(mock.arguments).thenCallRealMethod() + } } /** @@ -106,7 +106,7 @@ class SftpConnectDialogTest : AbstractMainActivityTestBase() { verify.putString( "password", PasswordUtil.encryptPassword(AppConfig.getInstance(), "12345678", Base64.URL_SAFE) - ?.replace("\n", "") + ?.replace("\n", ""), ) testOpenSftpConnectDialog(uri, verify) } @@ -116,9 +116,10 @@ class SftpConnectDialogTest : AbstractMainActivityTestBase() { */ @Test fun testInvokeSftpConnectionDialogWithPasswordAndDefaultPath() { - val uri = NetCopyClientUtils.encryptFtpPathAsNecessary( - "ssh://root:12345678@127.0.0.1:22/data/incoming" - ) + val uri = + NetCopyClientUtils.encryptFtpPathAsNecessary( + "ssh://root:12345678@127.0.0.1:22/data/incoming", + ) val verify = Bundle() verify.putString("address", "127.0.0.1") verify.putInt("port", 22) @@ -130,7 +131,7 @@ class SftpConnectDialogTest : AbstractMainActivityTestBase() { verify.putString( "password", PasswordUtil.encryptPassword(AppConfig.getInstance(), "12345678", Base64.URL_SAFE) - ?.replace("\n", "") + ?.replace("\n", ""), ) testOpenSftpConnectDialog(uri, verify) } @@ -138,14 +139,14 @@ class SftpConnectDialogTest : AbstractMainActivityTestBase() { /** * Test invoke [SftpConnectDialog] with arguments including password and URL encoded path. */ + @Suppress("ktlint:standard:max-line-length") @Test @Throws(GeneralSecurityException::class, IOException::class) fun testInvokeSftpConnectionDialogWithPasswordAndEncodedDefaultPath() { - /* ktlint-disable max-line-length */ - val uri = NetCopyClientUtils.encryptFtpPathAsNecessary( - "ssh://root:12345678@127.0.0.1:22/Users/TranceLove/My+Documents/%7BReference%7D%20Zobius%20Facro%20%24%24%20%23RFII1" - ) - /* ktlint-enable max-line-length */ + val uri = + NetCopyClientUtils.encryptFtpPathAsNecessary( + "ssh://root:12345678@127.0.0.1:22/Users/TranceLove/My+Documents/%7BReference%7D%20Zobius%20Facro%20%24%24%20%23RFII1", + ) val verify = Bundle() verify.putString("address", "127.0.0.1") verify.putInt("port", 22) @@ -155,18 +156,21 @@ class SftpConnectDialogTest : AbstractMainActivityTestBase() { verify.putBoolean("edit", true) verify.putString( "defaultPath", - "/Users/TranceLove/My Documents/{Reference} Zobius Facro $$ #RFII1" + "/Users/TranceLove/My Documents/{Reference} Zobius Facro $$ #RFII1", ) verify.putString( "password", PasswordUtil.encryptPassword(AppConfig.getInstance(), "12345678", Base64.URL_SAFE) - ?.replace("\n", "") + ?.replace("\n", ""), ) testOpenSftpConnectDialog(uri, verify) } @Throws(GeneralSecurityException::class, IOException::class) - private fun testOpenSftpConnectDialog(uri: String, verify: Bundle) { + private fun testOpenSftpConnectDialog( + uri: String, + verify: Bundle, + ) { val activity = mock(MainActivity::class.java) val utilsHandler = mock(UtilsHandler::class.java) `when`(utilsHandler.getSshAuthPrivateKeyName("ssh://root@127.0.0.1:22")) @@ -175,12 +179,12 @@ class SftpConnectDialogTest : AbstractMainActivityTestBase() { doCallRealMethod().`when`(activity).showSftpDialog( any(), any(), - anyBoolean() + anyBoolean(), ) activity.showSftpDialog( "SCP/SFTP Connection", NetCopyClientUtils.encryptFtpPathAsNecessary(uri), - true + true, ) assertEquals(1, mc.constructed().size) val mocked = mc.constructed()[0] @@ -195,8 +199,8 @@ class SftpConnectDialogTest : AbstractMainActivityTestBase() { PasswordUtil.decryptPassword( ApplicationProvider.getApplicationContext(), (mocked.arguments!![key] as String?)!!, - Base64.URL_SAFE - ) + Base64.URL_SAFE, + ), ) } } @@ -205,15 +209,16 @@ class SftpConnectDialogTest : AbstractMainActivityTestBase() { companion object { @JvmStatic - private val BUNDLE_KEYS = arrayOf( - "address", - "port", - "keypairName", - "name", - "username", - "password", - "edit", - "defaultPath" - ) + private val BUNDLE_KEYS = + arrayOf( + "address", + "port", + "keypairName", + "name", + "username", + "password", + "edit", + "defaultPath", + ) } } diff --git a/app/src/test/java/com/amaze/filemanager/ui/dialogs/SmbConnectDialogTest.kt b/app/src/test/java/com/amaze/filemanager/ui/dialogs/SmbConnectDialogTest.kt index dd76331050..72305b064a 100644 --- a/app/src/test/java/com/amaze/filemanager/ui/dialogs/SmbConnectDialogTest.kt +++ b/app/src/test/java/com/amaze/filemanager/ui/dialogs/SmbConnectDialogTest.kt @@ -45,7 +45,6 @@ import org.robolectric.shadows.ShadowLooper * Tests [SmbConnectDialog]. */ class SmbConnectDialogTest : AbstractMainActivityTestBase() { - /** * Test call to [SmbConnectionListener.addConnection] is encrypted path. */ @@ -54,16 +53,18 @@ class SmbConnectDialogTest : AbstractMainActivityTestBase() { val listener = spyk() doTestWithDialog( listener = listener, - arguments = Bundle().also { - it.putString(ARG_NAME, "") - it.putString(ARG_PATH, "") - it.putBoolean(ARG_EDIT, false) - }, + arguments = + Bundle().also { + it.putString(ARG_NAME, "") + it.putString(ARG_PATH, "") + it.putBoolean(ARG_EDIT, false) + }, withDialog = { dialog, materialDialog -> - val encryptedPath = SmbUtil.getSmbEncryptedPath( - AppConfig.getInstance(), - "smb://user:password@127.0.0.1/" - ) + val encryptedPath = + SmbUtil.getSmbEncryptedPath( + AppConfig.getInstance(), + "smb://user:password@127.0.0.1/", + ) dialog.binding.run { this.connectionET.setText("SMB Connection Test") this.usernameET.setText("user") @@ -77,18 +78,18 @@ class SmbConnectDialogTest : AbstractMainActivityTestBase() { "SMB Connection Test", encryptedPath, "", - "" + "", ) } confirmVerified(listener) - } + }, ) } private fun doTestWithDialog( arguments: Bundle, listener: SmbConnectionListener, - withDialog: (SmbConnectDialog, MaterialDialog) -> Unit + withDialog: (SmbConnectDialog, MaterialDialog) -> Unit, ) { val scenario = ActivityScenario.launch(MainActivity::class.java) ShadowLooper.idleMainLooper() diff --git a/app/src/test/java/com/amaze/filemanager/ui/fragments/CloudSheetFragmentTest.java b/app/src/test/java/com/amaze/filemanager/ui/fragments/CloudSheetFragmentTest.java index 2ae29be76a..e719ba8c60 100644 --- a/app/src/test/java/com/amaze/filemanager/ui/fragments/CloudSheetFragmentTest.java +++ b/app/src/test/java/com/amaze/filemanager/ui/fragments/CloudSheetFragmentTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/test/java/com/amaze/filemanager/ui/fragments/preferencefragments/UiPrefsFragmentTest.kt b/app/src/test/java/com/amaze/filemanager/ui/fragments/preferencefragments/UiPrefsFragmentTest.kt index d974fb57fa..69371b881c 100644 --- a/app/src/test/java/com/amaze/filemanager/ui/fragments/preferencefragments/UiPrefsFragmentTest.kt +++ b/app/src/test/java/com/amaze/filemanager/ui/fragments/preferencefragments/UiPrefsFragmentTest.kt @@ -57,11 +57,10 @@ import kotlin.random.Random ShadowStorageManager::class, ShadowPasswordUtil::class, ShadowSmbFile::class, - ShadowLocaleManager::class - ] + ShadowLocaleManager::class, + ], ) class UiPrefsFragmentTest : PreferencesActivityTestBase() { - /** * Test default behaviour. When no language is selected * [AppCompatDelegate.getApplicationLocales] should return an empty @@ -79,7 +78,7 @@ class UiPrefsFragmentTest : PreferencesActivityTestBase() { assertEquals(items?.size, activity.getLocaleListFromXml().size() + 1) assertEquals( getString(R.string.preference_language_system_default), - items?.get(0) + items?.get(0), ) assertEquals(0, this.selectedIndex) } @@ -103,13 +102,13 @@ class UiPrefsFragmentTest : PreferencesActivityTestBase() { assertEquals(items.size, activity.getLocaleListFromXml().size() + 1) assertEquals( getString(R.string.preference_language_system_default), - items[0] + items[0], ) assertEquals(0, this.selectedIndex) val wantTo = Random.nextInt(items.size - 1) this.selectedIndex = wantTo this.view.findViewById( - com.afollestad.materialdialogs.R.id.md_contentRecyclerView + com.afollestad.materialdialogs.R.id.md_contentRecyclerView, ).run { // Span out the RecyclerView as much as possible so all items are displayed. // Trick: https://bterczynski.medium.com/robolectric-tips-testing-recyclerviews-d6e79209a4b @@ -124,8 +123,8 @@ class UiPrefsFragmentTest : PreferencesActivityTestBase() { wantTo, // System Default is index 0 (top of list), hence index needs to + 1 activity.getLocaleListFromXml().indexOf( - AppCompatDelegate.getApplicationLocales()[0] - ) + 1 + AppCompatDelegate.getApplicationLocales()[0], + ) + 1, ) } ?: fail("Fail parsing locale list XML") } diff --git a/app/src/test/java/com/amaze/filemanager/ui/icons/IconsTest.java b/app/src/test/java/com/amaze/filemanager/ui/icons/IconsTest.java index bc377b3a30..add1f19ac7 100644 --- a/app/src/test/java/com/amaze/filemanager/ui/icons/IconsTest.java +++ b/app/src/test/java/com/amaze/filemanager/ui/icons/IconsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/test/java/com/amaze/filemanager/ui/notifications/NotificationConstantsTest.java b/app/src/test/java/com/amaze/filemanager/ui/notifications/NotificationConstantsTest.java index c2780642c3..aafa3fe106 100644 --- a/app/src/test/java/com/amaze/filemanager/ui/notifications/NotificationConstantsTest.java +++ b/app/src/test/java/com/amaze/filemanager/ui/notifications/NotificationConstantsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/test/java/com/amaze/filemanager/ui/theme/AppThemeTest.kt b/app/src/test/java/com/amaze/filemanager/ui/theme/AppThemeTest.kt index 2c4545f275..fd5423f72f 100644 --- a/app/src/test/java/com/amaze/filemanager/ui/theme/AppThemeTest.kt +++ b/app/src/test/java/com/amaze/filemanager/ui/theme/AppThemeTest.kt @@ -42,10 +42,9 @@ import java.util.* @RunWith(AndroidJUnit4::class) @Config( sdk = [KITKAT, P, Build.VERSION_CODES.R], - shadows = [ShadowMultiDex::class] + shadows = [ShadowMultiDex::class], ) class AppThemeTest { - /** * Test that the theme coincides with the index for [AppThemePreference.getTheme] */ @@ -53,27 +52,27 @@ class AppThemeTest { fun testGetTheme() { Assert.assertEquals( AppThemePreference.LIGHT, - AppThemePreference.getTheme(AppThemePreference.LIGHT_INDEX) + AppThemePreference.getTheme(AppThemePreference.LIGHT_INDEX), ) Assert.assertEquals( AppThemePreference.DARK, - AppThemePreference.getTheme(AppThemePreference.DARK_INDEX) + AppThemePreference.getTheme(AppThemePreference.DARK_INDEX), ) Assert.assertEquals( AppThemePreference.TIMED, - AppThemePreference.getTheme(AppThemePreference.TIME_INDEX) + AppThemePreference.getTheme(AppThemePreference.TIME_INDEX), ) Assert.assertEquals( AppThemePreference.BLACK, - AppThemePreference.getTheme(AppThemePreference.BLACK_INDEX) + AppThemePreference.getTheme(AppThemePreference.BLACK_INDEX), ) Assert.assertEquals( AppThemePreference.SYSTEM, - AppThemePreference.getTheme(AppThemePreference.SYSTEM_INDEX) + AppThemePreference.getTheme(AppThemePreference.SYSTEM_INDEX), ) } @@ -86,30 +85,30 @@ class AppThemeTest { Assert.assertEquals( Theme.LIGHT, - getMaterialDialogTheme(AppThemePreference.LIGHT_INDEX, context) + getMaterialDialogTheme(AppThemePreference.LIGHT_INDEX, context), ) Assert.assertEquals( Theme.DARK, - getMaterialDialogTheme(AppThemePreference.DARK_INDEX, context) + getMaterialDialogTheme(AppThemePreference.DARK_INDEX, context), ) val hour = Calendar.getInstance()[Calendar.HOUR_OF_DAY] if (hour <= 6 || hour >= 18) { Assert.assertEquals( Theme.DARK, - getMaterialDialogTheme(AppThemePreference.TIME_INDEX, context) + getMaterialDialogTheme(AppThemePreference.TIME_INDEX, context), ) } else { Assert.assertEquals( Theme.LIGHT, - getMaterialDialogTheme(AppThemePreference.TIME_INDEX, context) + getMaterialDialogTheme(AppThemePreference.TIME_INDEX, context), ) } Assert.assertEquals( Theme.DARK, - getMaterialDialogTheme(AppThemePreference.BLACK_INDEX, context) + getMaterialDialogTheme(AppThemePreference.BLACK_INDEX, context), ) } @@ -122,28 +121,30 @@ class AppThemeTest { Assert.assertEquals( AppTheme.LIGHT, - getSimpleTheme(AppThemePreference.LIGHT_INDEX, context) + getSimpleTheme(AppThemePreference.LIGHT_INDEX, context), ) Assert.assertEquals( AppTheme.DARK, - getSimpleTheme(AppThemePreference.DARK_INDEX, context) + getSimpleTheme(AppThemePreference.DARK_INDEX, context), ) val hour = Calendar.getInstance()[Calendar.HOUR_OF_DAY] if (hour <= 6 || hour >= 18) { Assert.assertEquals( AppTheme.DARK, - getSimpleTheme(AppThemePreference.TIME_INDEX, context) + getSimpleTheme(AppThemePreference.TIME_INDEX, context), ) - } else Assert.assertEquals( - AppTheme.LIGHT, - getSimpleTheme(AppThemePreference.TIME_INDEX, context) - ) + } else { + Assert.assertEquals( + AppTheme.LIGHT, + getSimpleTheme(AppThemePreference.TIME_INDEX, context), + ) + } Assert.assertEquals( AppTheme.BLACK, - getSimpleTheme(AppThemePreference.BLACK_INDEX, context) + getSimpleTheme(AppThemePreference.BLACK_INDEX, context), ) } @@ -168,7 +169,7 @@ class AppThemeTest { Assert.assertEquals( AppTheme.LIGHT, - getSimpleTheme(AppThemePreference.SYSTEM_INDEX, context) + getSimpleTheme(AppThemePreference.SYSTEM_INDEX, context), ) } @@ -179,7 +180,7 @@ class AppThemeTest { @Config( shadows = [ShadowPowerManager::class, ShadowMultiDex::class], qualifiers = "notnight", - minSdk = Build.VERSION_CODES.LOLLIPOP + minSdk = Build.VERSION_CODES.LOLLIPOP, ) fun testSimpleAppThemeWithFollowBatterySaverAndBatterySaverOn() { val context = ApplicationProvider.getApplicationContext() @@ -192,18 +193,18 @@ class AppThemeTest { Assert.assertEquals( "For $lightTheme: ", AppTheme.DARK, - getSimpleTheme(lightTheme.id, context) + getSimpleTheme(lightTheme.id, context), ) } Assert.assertEquals( AppTheme.DARK, - getSimpleTheme(AppThemePreference.DARK_INDEX, context) + getSimpleTheme(AppThemePreference.DARK_INDEX, context), ) Assert.assertEquals( AppTheme.BLACK, - getSimpleTheme(AppThemePreference.BLACK_INDEX, context) + getSimpleTheme(AppThemePreference.BLACK_INDEX, context), ) } @@ -214,7 +215,7 @@ class AppThemeTest { @Config( shadows = [ShadowPowerManager::class, ShadowMultiDex::class], qualifiers = "notnight", - minSdk = Build.VERSION_CODES.LOLLIPOP + minSdk = Build.VERSION_CODES.LOLLIPOP, ) fun testSimpleAppThemeWithFollowBatterySaverAndBatterySaverOff() { val context = ApplicationProvider.getApplicationContext() @@ -232,7 +233,7 @@ class AppThemeTest { @Config( shadows = [ShadowPowerManager::class, ShadowMultiDex::class], qualifiers = "notnight", - minSdk = Build.VERSION_CODES.LOLLIPOP + minSdk = Build.VERSION_CODES.LOLLIPOP, ) fun testMaterialDialogThemeWithFollowBatterySaverAndBatterySaverOn() { val context = ApplicationProvider.getApplicationContext() @@ -245,18 +246,18 @@ class AppThemeTest { Assert.assertEquals( "For $lightTheme: ", Theme.DARK, - getMaterialDialogTheme(lightTheme.id, context) + getMaterialDialogTheme(lightTheme.id, context), ) } Assert.assertEquals( Theme.DARK, - getMaterialDialogTheme(AppThemePreference.DARK_INDEX, context) + getMaterialDialogTheme(AppThemePreference.DARK_INDEX, context), ) Assert.assertEquals( Theme.DARK, - getMaterialDialogTheme(AppThemePreference.BLACK_INDEX, context) + getMaterialDialogTheme(AppThemePreference.BLACK_INDEX, context), ) } @@ -267,7 +268,7 @@ class AppThemeTest { @Config( shadows = [ShadowPowerManager::class, ShadowMultiDex::class], qualifiers = "notnight", - minSdk = Build.VERSION_CODES.LOLLIPOP + minSdk = Build.VERSION_CODES.LOLLIPOP, ) fun testMaterialDialogThemeWithFollowBatterySaverAndBatterySaverOff() { val context = ApplicationProvider.getApplicationContext() @@ -279,15 +280,22 @@ class AppThemeTest { } /** Shortcut to get the material dialog theme from the theme index */ - private fun getMaterialDialogTheme(apptheme: Int, context: Context): Theme = - AppThemePreference.getTheme(apptheme).getMaterialDialogTheme(context) + private fun getMaterialDialogTheme( + apptheme: Int, + context: Context, + ): Theme = AppThemePreference.getTheme(apptheme).getMaterialDialogTheme(context) /** Shortcut to get the simple theme from the theme index */ - private fun getSimpleTheme(index: Int, context: Context): AppTheme = - AppThemePreference.getTheme(index).getSimpleTheme(context) + private fun getSimpleTheme( + index: Int, + context: Context, + ): AppTheme = AppThemePreference.getTheme(index).getSimpleTheme(context) /** Sets the battery saver mode to [batterySaverOn] and the "Follow battery saver" option to true */ - private fun setUpForFollowBatterySaverMode(context: Context, batterySaverOn: Boolean) { + private fun setUpForFollowBatterySaverMode( + context: Context, + batterySaverOn: Boolean, + ) { // Set Battery saver mode to given state `batterySaverOn` val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager val shadowPowerManager = Shadows.shadowOf(powerManager) diff --git a/app/src/test/java/com/amaze/filemanager/ui/views/WarnableTextInputValidatorTest.java b/app/src/test/java/com/amaze/filemanager/ui/views/WarnableTextInputValidatorTest.java index 9c97ec536e..99970bb305 100644 --- a/app/src/test/java/com/amaze/filemanager/ui/views/WarnableTextInputValidatorTest.java +++ b/app/src/test/java/com/amaze/filemanager/ui/views/WarnableTextInputValidatorTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/test/java/com/amaze/filemanager/utils/AESCryptTest.kt b/app/src/test/java/com/amaze/filemanager/utils/AESCryptTest.kt index a1c7cbbcad..0ae810cc81 100644 --- a/app/src/test/java/com/amaze/filemanager/utils/AESCryptTest.kt +++ b/app/src/test/java/com/amaze/filemanager/utils/AESCryptTest.kt @@ -38,7 +38,6 @@ import kotlin.random.Random @RunWith(AndroidJUnit4::class) @Config(sdk = [KITKAT, P, Build.VERSION_CODES.R]) class AESCryptTest { - /** * Simple sanity test on [AESCrypt]. */ @@ -50,7 +49,7 @@ class AESCryptTest { crypter.encrypt( `in` = ByteArrayInputStream(contents), out = out, - progressHandler = ProgressHandler() + progressHandler = ProgressHandler(), ) out.close() val encrypted = out.toByteArray() @@ -73,7 +72,7 @@ class AESCryptTest { crypter.encrypt( `in` = ByteArrayInputStream(contents), out = out, - progressHandler = ProgressHandler() + progressHandler = ProgressHandler(), ) out.close() val encrypted = out.toByteArray() diff --git a/app/src/test/java/com/amaze/filemanager/utils/AnimUtilsTest.java b/app/src/test/java/com/amaze/filemanager/utils/AnimUtilsTest.java index b5cbfc2003..3cb7fe314b 100644 --- a/app/src/test/java/com/amaze/filemanager/utils/AnimUtilsTest.java +++ b/app/src/test/java/com/amaze/filemanager/utils/AnimUtilsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/test/java/com/amaze/filemanager/utils/BookSorterTest.java b/app/src/test/java/com/amaze/filemanager/utils/BookSorterTest.java index bc4b8a8fa2..9441f1c60b 100644 --- a/app/src/test/java/com/amaze/filemanager/utils/BookSorterTest.java +++ b/app/src/test/java/com/amaze/filemanager/utils/BookSorterTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/test/java/com/amaze/filemanager/utils/ComputerParcelableTest.java b/app/src/test/java/com/amaze/filemanager/utils/ComputerParcelableTest.java index 07a1abb70b..dd867c22ae 100644 --- a/app/src/test/java/com/amaze/filemanager/utils/ComputerParcelableTest.java +++ b/app/src/test/java/com/amaze/filemanager/utils/ComputerParcelableTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/test/java/com/amaze/filemanager/utils/CryptUtilTest.kt b/app/src/test/java/com/amaze/filemanager/utils/CryptUtilTest.kt index 21ddeec03b..ac364acfb6 100644 --- a/app/src/test/java/com/amaze/filemanager/utils/CryptUtilTest.kt +++ b/app/src/test/java/com/amaze/filemanager/utils/CryptUtilTest.kt @@ -48,10 +48,9 @@ import kotlin.random.Random @RunWith(AndroidJUnit4::class) @Config( - sdk = [KITKAT, P, Build.VERSION_CODES.R] + sdk = [KITKAT, P, Build.VERSION_CODES.R], ) class CryptUtilTest { - /** * Test AESCrypt function under CryptUtil. * @@ -63,12 +62,12 @@ class CryptUtilTest { performTest( useAescrypt = true, password = "abcdefgh1234567890", - targetExtension = "aes" + targetExtension = "aes", ) performFolderTest( useAescrypt = true, password = "abcdefgh1234567890", - targetExtension = "aes" + targetExtension = "aes", ) } @@ -87,7 +86,7 @@ class CryptUtilTest { private fun performTest( useAescrypt: Boolean, password: String? = null, - targetExtension: String + targetExtension: String, ) { val source = randomizer.nextBytes(117) val sourceFile = File(Environment.getExternalStorageDirectory(), "test.bin") @@ -99,12 +98,13 @@ class CryptUtilTest { ArrayList(), "test.bin.$targetExtension", useAescrypt, - password - ) - val targetFile = File( - Environment.getExternalStorageDirectory(), - "test.bin.$targetExtension" + password, ) + val targetFile = + File( + Environment.getExternalStorageDirectory(), + "test.bin.$targetExtension", + ) assertTrue(targetFile.length() > source.size) sourceFile.delete() CryptUtil( @@ -115,7 +115,7 @@ class CryptUtilTest { Environment.getExternalStorageDirectory().absolutePath, ProgressHandler(), ArrayList(), - password + password, ) File(Environment.getExternalStorageDirectory(), "test.bin").run { assertTrue(this.exists()) @@ -126,12 +126,13 @@ class CryptUtilTest { private fun performFolderTest( useAescrypt: Boolean, password: String? = null, - targetExtension: String + targetExtension: String, ) { val filesSize = randomizer.nextInt(10, 20) - val sourceData = Array(filesSize) { - randomizer.nextBytes(117) - } + val sourceData = + Array(filesSize) { + randomizer.nextBytes(117) + } val sourceFolder = File(Environment.getExternalStorageDirectory(), "test") sourceFolder.mkdirs() repeat(filesSize) { @@ -147,12 +148,13 @@ class CryptUtilTest { ArrayList(), "test.$targetExtension", useAescrypt, - password - ) - val targetFolder = File( - Environment.getExternalStorageDirectory(), - "test.$targetExtension" + password, ) + val targetFolder = + File( + Environment.getExternalStorageDirectory(), + "test.$targetExtension", + ) assertTrue(targetFolder.isDirectory) assertEquals(sourceData.size, targetFolder.listFiles()?.size) sourceFolder.deleteRecursively() @@ -164,7 +166,7 @@ class CryptUtilTest { Environment.getExternalStorageDirectory().absolutePath, ProgressHandler(), ArrayList(), - password + password, ) File(Environment.getExternalStorageDirectory(), "test").run { assertTrue(this.exists()) @@ -174,14 +176,15 @@ class CryptUtilTest { } this.listFiles()?.forEach { file: File? -> file?.run { - val index = file.name.substring( - "test".length, - file.name.indexOf('.') - ).toInt() + val index = + file.name.substring( + "test".length, + file.name.indexOf('.'), + ).toInt() assertArrayEquals( "Comparison broken at ${file.absolutePath}", sourceData[index], - file.readBytes() + file.readBytes(), ) } ?: fail("File not found") } ?: fail("No files found") @@ -189,7 +192,6 @@ class CryptUtilTest { } companion object { - private val randomizer = Random(System.currentTimeMillis()) private val key = SecretKeySpec(randomizer.nextBytes(16), "AES") diff --git a/app/src/test/java/com/amaze/filemanager/utils/MinMaxInputFilterTest.kt b/app/src/test/java/com/amaze/filemanager/utils/MinMaxInputFilterTest.kt index 9ecadd5fab..d16eb031f6 100644 --- a/app/src/test/java/com/amaze/filemanager/utils/MinMaxInputFilterTest.kt +++ b/app/src/test/java/com/amaze/filemanager/utils/MinMaxInputFilterTest.kt @@ -34,7 +34,6 @@ import org.robolectric.annotation.Config @RunWith(AndroidJUnit4::class) @Config(sdk = [KITKAT, P, Build.VERSION_CODES.R]) class MinMaxInputFilterTest { - /** * Test MinMaxInputFilter functioning */ diff --git a/app/src/test/java/com/amaze/filemanager/utils/OpenModeTest.java b/app/src/test/java/com/amaze/filemanager/utils/OpenModeTest.java index 1f0b67aec3..7e12bf9da0 100644 --- a/app/src/test/java/com/amaze/filemanager/utils/OpenModeTest.java +++ b/app/src/test/java/com/amaze/filemanager/utils/OpenModeTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/test/java/com/amaze/filemanager/utils/SmbUtilTest.kt b/app/src/test/java/com/amaze/filemanager/utils/SmbUtilTest.kt index 352eec1d06..ea1b3cb197 100644 --- a/app/src/test/java/com/amaze/filemanager/utils/SmbUtilTest.kt +++ b/app/src/test/java/com/amaze/filemanager/utils/SmbUtilTest.kt @@ -47,10 +47,9 @@ import org.robolectric.annotation.Config @RunWith(AndroidJUnit4::class) @Config( sdk = [KITKAT, P, Build.VERSION_CODES.R], - shadows = [ShadowPasswordUtil::class, ShadowSmbUtil::class] + shadows = [ShadowPasswordUtil::class, ShadowSmbUtil::class], ) class SmbUtilTest { - /** * Test encrypt/decrypt SMB URIs. */ @@ -87,7 +86,7 @@ class SmbUtilTest { val path = "smb://127.0.0.1" assertEquals( path, - getSmbEncryptedPath(ApplicationProvider.getApplicationContext(), path) + getSmbEncryptedPath(ApplicationProvider.getApplicationContext(), path), ) } @@ -99,7 +98,7 @@ class SmbUtilTest { val path = "smb://toor@127.0.0.1" assertEquals( path, - getSmbEncryptedPath(ApplicationProvider.getApplicationContext(), path) + getSmbEncryptedPath(ApplicationProvider.getApplicationContext(), path), ) } @@ -110,23 +109,23 @@ class SmbUtilTest { fun testCheckFolder() { assertEquals( DOESNT_EXIST, - checkFolder("smb://user:password@5.6.7.8/newfolder/DummyFolder") + checkFolder("smb://user:password@5.6.7.8/newfolder/DummyFolder"), ) assertEquals( DOESNT_EXIST, - checkFolder("smb://user:password@5.6.7.8/newfolder/resume.doc") + checkFolder("smb://user:password@5.6.7.8/newfolder/resume.doc"), ) assertEquals( WRITABLE_ON_REMOTE, - checkFolder("smb://user:password@5.6.7.8/newfolder/Documents") + checkFolder("smb://user:password@5.6.7.8/newfolder/Documents"), ) assertEquals( DOESNT_EXIST, - checkFolder("smb://user:password@5.6.7.8/newfolder/wirebroken.log") + checkFolder("smb://user:password@5.6.7.8/newfolder/wirebroken.log"), ) assertEquals( DOESNT_EXIST, - checkFolder("smb://user:password@5.6.7.8/newfolder/failcheck") + checkFolder("smb://user:password@5.6.7.8/newfolder/failcheck"), ) } diff --git a/app/src/test/java/com/amaze/filemanager/utils/TinyDBTest.java b/app/src/test/java/com/amaze/filemanager/utils/TinyDBTest.java index 67b03d58b2..530e2694c4 100644 --- a/app/src/test/java/com/amaze/filemanager/utils/TinyDBTest.java +++ b/app/src/test/java/com/amaze/filemanager/utils/TinyDBTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/test/java/com/amaze/filemanager/utils/UUIDv5Test.kt b/app/src/test/java/com/amaze/filemanager/utils/UUIDv5Test.kt index 6f4261978f..dcb9cd6553 100644 --- a/app/src/test/java/com/amaze/filemanager/utils/UUIDv5Test.kt +++ b/app/src/test/java/com/amaze/filemanager/utils/UUIDv5Test.kt @@ -27,7 +27,6 @@ import org.junit.Test * Test for [UUIDv5]. */ class UUIDv5Test { - /** * Test UUID generation. Value is based on SHA-1 hash, so it can be expected. * diff --git a/app/src/test/java/com/amaze/filemanager/utils/UtilsTest.java b/app/src/test/java/com/amaze/filemanager/utils/UtilsTest.java index 0c8d6dd710..52a5fbc687 100644 --- a/app/src/test/java/com/amaze/filemanager/utils/UtilsTest.java +++ b/app/src/test/java/com/amaze/filemanager/utils/UtilsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/app/src/test/java/com/amaze/filemanager/utils/X509CertificateUtilTest.kt b/app/src/test/java/com/amaze/filemanager/utils/X509CertificateUtilTest.kt index 9aebb4de92..35cf830f44 100644 --- a/app/src/test/java/com/amaze/filemanager/utils/X509CertificateUtilTest.kt +++ b/app/src/test/java/com/amaze/filemanager/utils/X509CertificateUtilTest.kt @@ -43,10 +43,9 @@ import javax.security.cert.X509Certificate @RunWith(AndroidJUnit4::class) @Config( shadows = [ShadowMultiDex::class], - sdk = [KITKAT, P, Build.VERSION_CODES.R] + sdk = [KITKAT, P, Build.VERSION_CODES.R], ) class X509CertificateUtilTest { - private lateinit var cert: X509Certificate /** @@ -54,13 +53,14 @@ class X509CertificateUtilTest { */ @Before fun setUp() { - val parser = PEMParser( - StringReader( - String( - javaClass.getResourceAsStream("/test.pem").readBytes() - ) + val parser = + PEMParser( + StringReader( + String( + javaClass.getResourceAsStream("/test.pem").readBytes(), + ), + ), ) - ) val a = parser.readObject() cert = X509Certificate.getInstance((a as X509CertificateHolder).encoded) } @@ -75,23 +75,23 @@ class X509CertificateUtilTest { assertTrue(verify.containsKey(SUBJECT)) assertEquals( "C=in,O=Team Amaze,CN=test.ftpsd.local", - verify[SUBJECT] + verify[SUBJECT], ) assertTrue(verify.containsKey(ISSUER)) assertEquals( "C=in,O=Team Amaze,CN=test.ftpsd.local", - verify[ISSUER] + verify[ISSUER], ) assertTrue(verify.containsKey(SERIAL)) assertEquals( "11:f5:7b:bf:1e:4f:da:f6:b9:e8:0c:e3:49:67:5e:f1:5f:b7:0a:1f", - verify[SERIAL] + verify[SERIAL], ) assertTrue(verify.containsKey(FINGERPRINT)) assertEquals( "a9:ab:de:6f:67:3a:f8:db:41:e0:30:81:f9:b7:36:cb:7a:2b:42:fc:cd:a9:af:a2:bc:" + "64:55:95:f2:c7:9a:74", - verify[FINGERPRINT] + verify[FINGERPRINT], ) } } diff --git a/app/src/test/java/com/amaze/filemanager/utils/smb/AbstractSubnetDiscoverDevicesStrategyTests.kt b/app/src/test/java/com/amaze/filemanager/utils/smb/AbstractSubnetDiscoverDevicesStrategyTests.kt index 3b44ccdc1e..b218c06ed9 100644 --- a/app/src/test/java/com/amaze/filemanager/utils/smb/AbstractSubnetDiscoverDevicesStrategyTests.kt +++ b/app/src/test/java/com/amaze/filemanager/utils/smb/AbstractSubnetDiscoverDevicesStrategyTests.kt @@ -40,7 +40,6 @@ import java.net.InetAddress @RunWith(AndroidJUnit4::class) @Config(sdk = [KITKAT, P, VERSION_CODES.R]) abstract class AbstractSubnetDiscoverDevicesStrategyTests { - /** * Post test cleanup. */ @@ -60,12 +59,16 @@ abstract class AbstractSubnetDiscoverDevicesStrategyTests { mockkStatic(NetworkUtil::class) every { NetworkUtil.isConnectedToWifi(any()) } returns true every { NetworkUtil.isConnectedToLocalNetwork(any()) } returns true - every { NetworkUtil.getLocalInetAddress(any()) } returns mockk().also { - every { it.hostName } returns "192.168.233.240" - } + every { NetworkUtil.getLocalInetAddress(any()) } returns + mockk().also { + every { it.hostName } returns "192.168.233.240" + } } - protected fun mockInetAddress(hostName: String, hostAddress: String): InetAddress { + protected fun mockInetAddress( + hostName: String, + hostAddress: String, + ): InetAddress { val upHost = mockk() every { upHost.hostName } returns hostName every { upHost.hostAddress } returns hostAddress diff --git a/app/src/test/java/com/amaze/filemanager/utils/smb/SameSubnetDiscoverDevicesStrategyTest.kt b/app/src/test/java/com/amaze/filemanager/utils/smb/SameSubnetDiscoverDevicesStrategyTest.kt index 1cd428f1f6..3ee68e0492 100644 --- a/app/src/test/java/com/amaze/filemanager/utils/smb/SameSubnetDiscoverDevicesStrategyTest.kt +++ b/app/src/test/java/com/amaze/filemanager/utils/smb/SameSubnetDiscoverDevicesStrategyTest.kt @@ -28,12 +28,12 @@ import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit class SameSubnetDiscoverDevicesStrategyTest : AbstractSubnetDiscoverDevicesStrategyTests() { - companion object { @JvmStatic - private val logger = LoggerFactory.getLogger( - SameSubnetDiscoverDevicesStrategyTest::class.java - ) + private val logger = + LoggerFactory.getLogger( + SameSubnetDiscoverDevicesStrategyTest::class.java, + ) } /** diff --git a/app/src/test/java/com/amaze/filemanager/utils/smb/WsddSubnetDiscoverDevicesStrategyTest.kt b/app/src/test/java/com/amaze/filemanager/utils/smb/WsddSubnetDiscoverDevicesStrategyTest.kt index 0212756d3b..d885ad2d7b 100644 --- a/app/src/test/java/com/amaze/filemanager/utils/smb/WsddSubnetDiscoverDevicesStrategyTest.kt +++ b/app/src/test/java/com/amaze/filemanager/utils/smb/WsddSubnetDiscoverDevicesStrategyTest.kt @@ -33,27 +33,28 @@ import kotlin.text.Charsets.UTF_8 */ @Suppress("StringLiteralDuplication") class WsddSubnetDiscoverDevicesStrategyTest : AbstractSubnetDiscoverDevicesStrategyTests() { + private val multicastResponseTemplate = + javaClass.classLoader!! + .getResourceAsStream("wsdd/multicast-response.txt") + .reader(UTF_8).readText() - private val multicastResponseTemplate = javaClass.classLoader!! - .getResourceAsStream("wsdd/multicast-response.txt") - .reader(UTF_8).readText() - - private val wsdResponseTemplate = javaClass.classLoader!! - .getResourceAsStream("wsdd/wsd-response.txt") - .reader(UTF_8).readText() + private val wsdResponseTemplate = + javaClass.classLoader!! + .getResourceAsStream("wsdd/wsd-response.txt") + .reader(UTF_8).readText() private val parseXmlForResponse: (WsddDiscoverDeviceStrategy, Any, Array) -> Map = - { instance, xml, tags -> - require((xml is ByteArray) or (xml is String)) - ReflectionHelpers.callInstanceMethod( - WsddDiscoverDeviceStrategy::class.java, - instance, - "parseXmlForResponse", - ReflectionHelpers.ClassParameter(xml.javaClass, xml), - ReflectionHelpers.ClassParameter(Array::class.java, tags) - ) - } + { instance, xml, tags -> + require((xml is ByteArray) or (xml is String)) + ReflectionHelpers.callInstanceMethod( + WsddDiscoverDeviceStrategy::class.java, + instance, + "parseXmlForResponse", + ReflectionHelpers.ClassParameter(xml.javaClass, xml), + ReflectionHelpers.ClassParameter(Array::class.java, tags), + ) + } private lateinit var wsdMulticastResponseMessageId: String private lateinit var deviceId: String @@ -64,11 +65,12 @@ class WsddSubnetDiscoverDevicesStrategyTest : AbstractSubnetDiscoverDevicesStrat @Test fun testParseMulticastResponse() { val instance = WsddDiscoverDeviceStrategy() - val result = parseXmlForResponse.invoke( - instance, - createMulticastResponse(), - arrayOf("wsd:Types", "wsa:Address") - ) + val result = + parseXmlForResponse.invoke( + instance, + createMulticastResponse(), + arrayOf("wsd:Types", "wsa:Address"), + ) assertTrue(result.isNotEmpty()) assertTrue(result.containsKey("wsd:Types")) assertTrue(result.containsKey("wsa:Address")) @@ -89,22 +91,22 @@ class WsddSubnetDiscoverDevicesStrategyTest : AbstractSubnetDiscoverDevicesStrat parseXmlForResponse.invoke( instance, ByteArray(0), - emptyArray() - ).isEmpty() + emptyArray(), + ).isEmpty(), ) assertTrue( parseXmlForResponse.invoke( instance, "foobar".toByteArray(), - emptyArray() - ).isEmpty() + emptyArray(), + ).isEmpty(), ) assertTrue( parseXmlForResponse.invoke( instance, randomBytes(), - emptyArray() - ).isEmpty() + emptyArray(), + ).isEmpty(), ) } @@ -119,38 +121,40 @@ class WsddSubnetDiscoverDevicesStrategyTest : AbstractSubnetDiscoverDevicesStrat parseXmlForResponse.invoke( instance, "", - arrayOf("foobar") - ).size + arrayOf("foobar"), + ).size, ) assertEquals( 0, parseXmlForResponse.invoke( instance, "", - arrayOf("test") - ).size + arrayOf("test"), + ).size, ) } private fun createMulticastResponse(): String { return multicastResponseTemplate.replace( "##DEVICE_UUID##", - UUID.randomUUID().toString() + UUID.randomUUID().toString(), ).replace( "##MESSAGE_ID##", - UUID.randomUUID().toString() + UUID.randomUUID().toString(), ).replace( "##SRC_MESSAGE_ID##", - UUID.randomUUID().toString() + UUID.randomUUID().toString(), ) } - private fun generateWsdResponse(deviceName: String, workgroupName: String = "WORKGROUP") = - wsdResponseTemplate - .replace("##THIS_DEVICE_ID##", deviceId) - .replace("##DEVICE_NAME##", deviceName) - .replace("##WORKGROUP_NAME##", workgroupName) - .replace("##PREV_MESSAGE_ID##", wsdMulticastResponseMessageId) - .replace("##THIS_MESSAGE_ID##", UUID.randomUUID().toString()) - .toByteArray(UTF_8) + private fun generateWsdResponse( + deviceName: String, + workgroupName: String = "WORKGROUP", + ) = wsdResponseTemplate + .replace("##THIS_DEVICE_ID##", deviceId) + .replace("##DEVICE_NAME##", deviceName) + .replace("##WORKGROUP_NAME##", workgroupName) + .replace("##PREV_MESSAGE_ID##", wsdMulticastResponseMessageId) + .replace("##THIS_MESSAGE_ID##", UUID.randomUUID().toString()) + .toByteArray(UTF_8) } diff --git a/app/src/testFdroid/java/com/amaze/filemanager/asynchronous/asynctasks/compress/CompressedHelperCallableTestSuite.kt b/app/src/testFdroid/java/com/amaze/filemanager/asynchronous/asynctasks/compress/CompressedHelperCallableTestSuite.kt index df1725cd88..a7d7e96a2b 100644 --- a/app/src/testFdroid/java/com/amaze/filemanager/asynchronous/asynctasks/compress/CompressedHelperCallableTestSuite.kt +++ b/app/src/testFdroid/java/com/amaze/filemanager/asynchronous/asynctasks/compress/CompressedHelperCallableTestSuite.kt @@ -40,6 +40,6 @@ import org.junit.runners.Suite.SuiteClasses EncryptedSevenZipHelperCallableTest::class, ListEncryptedSevenZipHelperCallableTest::class, UnknownCompressedHelperCallableTest::class, - CompressedHelperForBadArchiveTest::class + CompressedHelperForBadArchiveTest::class, ) class CompressedHelperCallableTestSuite diff --git a/app/src/testFdroid/java/com/amaze/filemanager/filesystem/compressed/extractcontents/ExtractorTestSuite.kt b/app/src/testFdroid/java/com/amaze/filemanager/filesystem/compressed/extractcontents/ExtractorTestSuite.kt index 5c07929125..7b2f41b6e9 100644 --- a/app/src/testFdroid/java/com/amaze/filemanager/filesystem/compressed/extractcontents/ExtractorTestSuite.kt +++ b/app/src/testFdroid/java/com/amaze/filemanager/filesystem/compressed/extractcontents/ExtractorTestSuite.kt @@ -42,6 +42,6 @@ import org.junit.runners.Suite.SuiteClasses SevenZipWithoutTimestampTest::class, PasswordProtectedZipTest::class, PasswordProtected7ZipTest::class, - ListPasswordProtected7ZipTest::class + ListPasswordProtected7ZipTest::class, ) class ExtractorTestSuite diff --git a/app/src/testPlay/java/com/amaze/filemanager/asynchronous/asynctasks/compress/CompressedHelperCallableTestSuite.kt b/app/src/testPlay/java/com/amaze/filemanager/asynchronous/asynctasks/compress/CompressedHelperCallableTestSuite.kt index 229c7b3fc2..e0709fc0d9 100644 --- a/app/src/testPlay/java/com/amaze/filemanager/asynchronous/asynctasks/compress/CompressedHelperCallableTestSuite.kt +++ b/app/src/testPlay/java/com/amaze/filemanager/asynchronous/asynctasks/compress/CompressedHelperCallableTestSuite.kt @@ -42,6 +42,6 @@ import org.junit.runners.Suite.SuiteClasses EncryptedSevenZipHelperCallableTest::class, ListEncryptedSevenZipHelperCallableTest::class, UnknownCompressedHelperCallableTest::class, - CompressedHelperForBadArchiveTest::class + CompressedHelperForBadArchiveTest::class, ) class CompressedHelperCallableTestSuite diff --git a/app/src/testPlay/java/com/amaze/filemanager/asynchronous/asynctasks/compress/EncryptedRarHelperCallableTest.kt b/app/src/testPlay/java/com/amaze/filemanager/asynchronous/asynctasks/compress/EncryptedRarHelperCallableTest.kt index 26c57dd709..a5b6b8b8b4 100644 --- a/app/src/testPlay/java/com/amaze/filemanager/asynchronous/asynctasks/compress/EncryptedRarHelperCallableTest.kt +++ b/app/src/testPlay/java/com/amaze/filemanager/asynchronous/asynctasks/compress/EncryptedRarHelperCallableTest.kt @@ -23,14 +23,16 @@ package com.amaze.filemanager.asynchronous.asynctasks.compress import java.io.File class EncryptedRarHelperCallableTest : AbstractCompressedHelperCallableArchiveTest() { - override val archiveFileName: String get() = "test-archive-encrypted.rar" - override fun doCreateCallable(archive: File, relativePath: String): CompressedHelperCallable = + override fun doCreateCallable( + archive: File, + relativePath: String, + ): CompressedHelperCallable = RarHelperCallable( archive.absolutePath, relativePath, - false + false, ) } diff --git a/app/src/testPlay/java/com/amaze/filemanager/asynchronous/asynctasks/compress/RarHelperCallableTest.kt b/app/src/testPlay/java/com/amaze/filemanager/asynchronous/asynctasks/compress/RarHelperCallableTest.kt index deb2a9f2d1..2ad71a5b7b 100644 --- a/app/src/testPlay/java/com/amaze/filemanager/asynchronous/asynctasks/compress/RarHelperCallableTest.kt +++ b/app/src/testPlay/java/com/amaze/filemanager/asynchronous/asynctasks/compress/RarHelperCallableTest.kt @@ -28,7 +28,6 @@ import org.junit.Test import java.io.File class RarHelperCallableTest : AbstractCompressedHelperCallableArchiveTest() { - override val archiveFileName: String get() = "test-archive.rar" @@ -37,15 +36,16 @@ class RarHelperCallableTest : AbstractCompressedHelperCallableArchiveTest() { */ @Test fun testMultiVolumeRar() { - val callable: CompressedHelperCallable = RarHelperCallable( - File( - Environment.getExternalStorageDirectory(), - "test-multipart-archive-v4.part1.rar" + val callable: CompressedHelperCallable = + RarHelperCallable( + File( + Environment.getExternalStorageDirectory(), + "test-multipart-archive-v4.part1.rar", + ) + .absolutePath, + "", + false, ) - .absolutePath, - "", - false - ) val result = callable.call() assertNotNull(result) assertNotNull(result) @@ -60,29 +60,34 @@ class RarHelperCallableTest : AbstractCompressedHelperCallableArchiveTest() { @Test @Suppress("Detekt.TooGenericExceptionCaught") fun testMultiVolumeRarV5() { - val callable: CompressedHelperCallable = RarHelperCallable( - File( - Environment.getExternalStorageDirectory(), - "test-multipart-archive-v5.part1.rar" + val callable: CompressedHelperCallable = + RarHelperCallable( + File( + Environment.getExternalStorageDirectory(), + "test-multipart-archive-v5.part1.rar", + ) + .absolutePath, + "", + false, ) - .absolutePath, - "", - false - ) - val result = try { - callable.call() - } catch (exception: Throwable) { - assertEquals(ArchiveException::class.java, exception.javaClass) - assertEquals(UnsupportedRarV5Exception::class.java, exception.cause!!.javaClass) - null - } + val result = + try { + callable.call() + } catch (exception: Throwable) { + assertEquals(ArchiveException::class.java, exception.javaClass) + assertEquals(UnsupportedRarV5Exception::class.java, exception.cause!!.javaClass) + null + } assertNull(result) } - override fun doCreateCallable(archive: File, relativePath: String): CompressedHelperCallable = + override fun doCreateCallable( + archive: File, + relativePath: String, + ): CompressedHelperCallable = RarHelperCallable( archive.absolutePath, relativePath, - false + false, ) } diff --git a/app/src/testPlay/java/com/amaze/filemanager/filesystem/compressed/extractcontents/ExtractorTestSuite.kt b/app/src/testPlay/java/com/amaze/filemanager/filesystem/compressed/extractcontents/ExtractorTestSuite.kt index 78054e5bd9..3088d1150a 100644 --- a/app/src/testPlay/java/com/amaze/filemanager/filesystem/compressed/extractcontents/ExtractorTestSuite.kt +++ b/app/src/testPlay/java/com/amaze/filemanager/filesystem/compressed/extractcontents/ExtractorTestSuite.kt @@ -46,6 +46,6 @@ import org.junit.runners.Suite.SuiteClasses PasswordProtected7ZipTest::class, ListPasswordProtected7ZipTest::class, ListPasswordProtectedRarTest::class, - MultipartRarExtractorTest::class + MultipartRarExtractorTest::class, ) class ExtractorTestSuite diff --git a/app/src/testPlay/java/com/amaze/filemanager/filesystem/compressed/extractcontents/ListPasswordProtectedRarTest.kt b/app/src/testPlay/java/com/amaze/filemanager/filesystem/compressed/extractcontents/ListPasswordProtectedRarTest.kt index 12d9ff3e03..46c6e1d549 100644 --- a/app/src/testPlay/java/com/amaze/filemanager/filesystem/compressed/extractcontents/ListPasswordProtectedRarTest.kt +++ b/app/src/testPlay/java/com/amaze/filemanager/filesystem/compressed/extractcontents/ListPasswordProtectedRarTest.kt @@ -24,9 +24,9 @@ import android.os.Environment import java.io.File class ListPasswordProtectedRarTest : PasswordProtectedRarTest() { - - override val archiveFile: File = File( - Environment.getExternalStorageDirectory(), - "test-archive-encrypted-list.$archiveType" - ) + override val archiveFile: File = + File( + Environment.getExternalStorageDirectory(), + "test-archive-encrypted-list.$archiveType", + ) } diff --git a/app/src/testPlay/java/com/amaze/filemanager/filesystem/compressed/extractcontents/MultipartRarExtractorTest.kt b/app/src/testPlay/java/com/amaze/filemanager/filesystem/compressed/extractcontents/MultipartRarExtractorTest.kt index e087520174..41e028ac14 100644 --- a/app/src/testPlay/java/com/amaze/filemanager/filesystem/compressed/extractcontents/MultipartRarExtractorTest.kt +++ b/app/src/testPlay/java/com/amaze/filemanager/filesystem/compressed/extractcontents/MultipartRarExtractorTest.kt @@ -44,16 +44,22 @@ import java.util.concurrent.CountDownLatch @RunWith(AndroidJUnit4::class) @Config( shadows = [ShadowMultiDex::class], - sdk = [Build.VERSION_CODES.KITKAT, Build.VERSION_CODES.P] + sdk = [Build.VERSION_CODES.KITKAT, Build.VERSION_CODES.P], ) class MultipartRarExtractorTest { + private val callback = + object : OnUpdate { + override fun onStart( + totalBytes: Long, + firstEntryName: String, + ) = Unit - private val callback = object : OnUpdate { - override fun onStart(totalBytes: Long, firstEntryName: String) = Unit - override fun onUpdate(entryPath: String) = Unit - override fun onFinish() = Unit - override fun isCancelled(): Boolean = false - } + override fun onUpdate(entryPath: String) = Unit + + override fun onFinish() = Unit + + override fun isCancelled(): Boolean = false + } /** * Test setup. @@ -74,7 +80,7 @@ class MultipartRarExtractorTest { ApplicationProvider.getApplicationContext(), File( Environment.getExternalStorageDirectory(), - "test-multipart-archive-v4.part1.rar" + "test-multipart-archive-v4.part1.rar", ).absolutePath, Environment.getExternalStorageDirectory().absolutePath, object : OnUpdate by callback { @@ -85,7 +91,7 @@ class MultipartRarExtractorTest { Assert.assertEquals((1024 * 128).toLong(), verify.length()) } }, - ServiceWatcherUtil.UPDATE_POSITION + ServiceWatcherUtil.UPDATE_POSITION, ).extractEverything() latch.await() } @@ -100,12 +106,12 @@ class MultipartRarExtractorTest { ApplicationProvider.getApplicationContext(), File( Environment.getExternalStorageDirectory(), - "test-multipart-archive-v5.part1.rar" + "test-multipart-archive-v5.part1.rar", ) .absolutePath, Environment.getExternalStorageDirectory().absolutePath, callback, - ServiceWatcherUtil.UPDATE_POSITION + ServiceWatcherUtil.UPDATE_POSITION, ).extractEverything() Assert.fail("No exception was thrown") } catch (expected: IOException) { diff --git a/app/src/testPlay/java/com/amaze/filemanager/filesystem/compressed/extractcontents/PasswordProtectedRarTest.kt b/app/src/testPlay/java/com/amaze/filemanager/filesystem/compressed/extractcontents/PasswordProtectedRarTest.kt index b1a93b89d2..bc43af985a 100644 --- a/app/src/testPlay/java/com/amaze/filemanager/filesystem/compressed/extractcontents/PasswordProtectedRarTest.kt +++ b/app/src/testPlay/java/com/amaze/filemanager/filesystem/compressed/extractcontents/PasswordProtectedRarTest.kt @@ -27,11 +27,9 @@ import org.junit.Test import java.io.IOException open class PasswordProtectedRarTest : AbstractExtractorPasswordProtectedArchivesTest() { - override fun extractorClass(): Class = RarExtractor::class.java - override fun expectedRootExceptionClass(): Array> = - arrayOf(IOException::class.java, PasswordRequiredException::class.java) + override fun expectedRootExceptionClass(): Array> = arrayOf(IOException::class.java, PasswordRequiredException::class.java) override val archiveType: String = "rar" diff --git a/app/src/testPlay/java/com/amaze/filemanager/filesystem/compressed/extractcontents/RarExtractorTest.kt b/app/src/testPlay/java/com/amaze/filemanager/filesystem/compressed/extractcontents/RarExtractorTest.kt index 657603789b..81b4d7c32a 100644 --- a/app/src/testPlay/java/com/amaze/filemanager/filesystem/compressed/extractcontents/RarExtractorTest.kt +++ b/app/src/testPlay/java/com/amaze/filemanager/filesystem/compressed/extractcontents/RarExtractorTest.kt @@ -32,7 +32,6 @@ import org.junit.Test import java.io.File class RarExtractorTest : AbstractArchiveExtractorTest() { - override val archiveType: String = "rar" override fun extractorClass(): Class = RarExtractor::class.java @@ -47,35 +46,43 @@ class RarExtractorTest : AbstractArchiveExtractorTest() { @Test fun testTryExtractSmallestFileInArchive() { val archiveFile = File(Environment.getExternalStorageDirectory(), "test-archive-sizes.rar") - val extractor = RarExtractor( - ApplicationProvider.getApplicationContext(), - archiveFile.absolutePath, - Environment.getExternalStorageDirectory().absolutePath, - object : Extractor.OnUpdate { - override fun onStart(totalBytes: Long, firstEntryName: String) = Unit - override fun onUpdate(entryPath: String) = Unit - override fun isCancelled(): Boolean = false - override fun onFinish() = Unit - }, - ServiceWatcherUtil.UPDATE_POSITION - ) - val verify = RarExtractor::class.java.getDeclaredMethod( - "tryExtractSmallestFileInArchive", - Context::class.java, - Archive::class.java - ).run { - isAccessible = true - invoke( - extractor, + val extractor = + RarExtractor( ApplicationProvider.getApplicationContext(), - Archive(archiveFile).also { - it.password = "123456" - } + archiveFile.absolutePath, + Environment.getExternalStorageDirectory().absolutePath, + object : Extractor.OnUpdate { + override fun onStart( + totalBytes: Long, + firstEntryName: String, + ) = Unit + + override fun onUpdate(entryPath: String) = Unit + + override fun isCancelled(): Boolean = false + + override fun onFinish() = Unit + }, + ServiceWatcherUtil.UPDATE_POSITION, ) - } + val verify = + RarExtractor::class.java.getDeclaredMethod( + "tryExtractSmallestFileInArchive", + Context::class.java, + Archive::class.java, + ).run { + isAccessible = true + invoke( + extractor, + ApplicationProvider.getApplicationContext(), + Archive(archiveFile).also { + it.password = "123456" + }, + ) + } File( ApplicationProvider.getApplicationContext().externalCacheDir!!, - "test-archive/1" + "test-archive/1", ).run { assertEquals(this.absolutePath, verify) assertEquals(2, this.length()) diff --git a/app/src/testPlayRelease/java/com/amaze/filemanager/utils/PackageInstallValidationTest.kt b/app/src/testPlayRelease/java/com/amaze/filemanager/utils/PackageInstallValidationTest.kt index 3f69dd66b1..b7c42503db 100644 --- a/app/src/testPlayRelease/java/com/amaze/filemanager/utils/PackageInstallValidationTest.kt +++ b/app/src/testPlayRelease/java/com/amaze/filemanager/utils/PackageInstallValidationTest.kt @@ -66,10 +66,9 @@ import java.util.concurrent.TimeUnit @RunWith(AndroidJUnit4::class) @Config( sdk = [KITKAT, P], - shadows = [ShadowPackageManager::class, ShadowMultiDex::class, ShadowTabHandler::class] + shadows = [ShadowPackageManager::class, ShadowMultiDex::class, ShadowTabHandler::class], ) class PackageInstallValidationTest { - companion object { private const val GOOD_PACKAGE = "/sdcard/good-package.apk" private const val MY_PACKAGE = "/sdcard/my-package.apk" @@ -86,17 +85,17 @@ class PackageInstallValidationTest { GOOD_PACKAGE, PackageInfo().also { it.packageName = "foo.bar.abc" - } + }, ) packageManager.setPackageArchiveInfo( MY_PACKAGE, PackageInfo().also { it.packageName = AppConfig.getInstance().packageName - } + }, ) packageManager.setPackageArchiveInfo( INVALID_PACKAGE, - null + null, ) if (SDK_INT >= N) initializeInternalStorage() RxJavaPlugins.reset() @@ -115,11 +114,13 @@ class PackageInstallValidationTest { */ @After fun tearDown() { - if (SDK_INT >= N) shadowOf( - ApplicationProvider.getApplicationContext().getSystemService( - StorageManager::class.java - ) - ).resetStorageVolumeList() + if (SDK_INT >= N) { + shadowOf( + ApplicationProvider.getApplicationContext().getSystemService( + StorageManager::class.java, + ), + ).resetStorageVolumeList() + } } /** @@ -128,7 +129,7 @@ class PackageInstallValidationTest { @Test fun testGoodPackage() { PackageInstallValidation.validatePackageInstallability( - File(GOOD_PACKAGE) + File(GOOD_PACKAGE), ) assertEquals(2, 1 + 1) } @@ -139,7 +140,7 @@ class PackageInstallValidationTest { @Test(expected = PackageInstallValidation.PackageCannotBeInstalledException::class) fun testMyPackage() { PackageInstallValidation.validatePackageInstallability( - File(MY_PACKAGE) + File(MY_PACKAGE), ) fail("PackageCannotBeInstalledException not thrown") } @@ -150,7 +151,7 @@ class PackageInstallValidationTest { @Test(expected = IllegalStateException::class) fun testInvalidPackage() { PackageInstallValidation.validatePackageInstallability( - File(INVALID_PACKAGE) + File(INVALID_PACKAGE), ) fail("PackageCannotBeInstalledException not thrown") } @@ -192,7 +193,7 @@ class PackageInstallValidationTest { } assertEquals( activity.getString(R.string.error_google_play_cannot_update_myself), - ShadowToast.getTextOfLatestToast() + ShadowToast.getTextOfLatestToast(), ) }.also { scenario.moveToState(Lifecycle.State.DESTROYED) @@ -216,7 +217,7 @@ class PackageInstallValidationTest { } assertEquals( activity.getString(R.string.error_cannot_get_package_info, INVALID_PACKAGE), - ShadowToast.getTextOfLatestToast() + ShadowToast.getTextOfLatestToast(), ) }.also { scenario.moveToState(Lifecycle.State.DESTROYED) diff --git a/build.gradle b/build.gradle index 515dc45fe0..81a125994c 100644 --- a/build.gradle +++ b/build.gradle @@ -62,7 +62,7 @@ buildscript { } plugins { - id "com.diffplug.spotless" version "6.5.0" + id "com.diffplug.spotless" version "6.25.0" } allprojects { @@ -83,22 +83,21 @@ allprojects { } spotless { + // update license header from first commit + // ratchetFrom='78b1a4cf3c0a9519be92ff8445f7dff2cd8722b1' java { - licenseHeaderFile 'spotless.license-java' - target 'app/src/**/*.java', 'commons_compress_7z/src/**/*.java', 'file_operations/src/**/*.java', 'portscanner/src/**/*.java' - googleJavaFormat('1.15.0') + licenseHeaderFile 'amaze.license.spotless.txt' + target '*/src/**/*.java' + googleJavaFormat('1.19.2') removeUnusedImports() // removes any unused imports importOrder 'java', 'javax', 'org', 'com', 'android', 'androidx', '' } kotlin { - licenseHeaderFile 'spotless.license-java' - target 'app/src/**/*.kt', 'file_operations/src/**/*.kt' - ktlint("0.44.0").setUseExperimental(true).userData(['disabled_rules': 'no-wildcard-imports', - 'kotlin_imports_layout': 'idea', 'indent_size': '4', - 'max_line_length': '100']) - trimTrailingWhitespace() - indentWithSpaces() - endWithNewline() + licenseHeaderFile 'amaze.license.spotless.txt' + target '*/src/**/*.kt' + ktlint("1.1.1") + .setEditorConfigPath("$projectDir/.editorconfig") + } } @@ -179,7 +178,7 @@ subprojects { it.dependsOn fetchRobolectricDependencies } } - if (project.plugins.hasPlugin("jacoco-android")){ + if (project.plugins.hasPlugin("jacoco-android")) { android { testOptions.unitTests.all { jacoco { diff --git a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/AES256SHA256Decoder.java b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/AES256SHA256Decoder.java index 146e672bfd..5f3db600c6 100644 --- a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/AES256SHA256Decoder.java +++ b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/AES256SHA256Decoder.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2022 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/Archive.java b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/Archive.java index 945e768a74..1d45033e44 100644 --- a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/Archive.java +++ b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/Archive.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2022 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/BindPair.java b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/BindPair.java index b653b77646..f03a0abc1c 100644 --- a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/BindPair.java +++ b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/BindPair.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2022 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/BoundedFileChannelInputStream.java b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/BoundedFileChannelInputStream.java index ee5c6fd86e..de78294ced 100644 --- a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/BoundedFileChannelInputStream.java +++ b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/BoundedFileChannelInputStream.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2022 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/Coder.java b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/Coder.java index f8e676ae00..d6e85dd958 100644 --- a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/Coder.java +++ b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/Coder.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2022 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/CoderBase.java b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/CoderBase.java index f43b19565f..2c27966a9e 100644 --- a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/CoderBase.java +++ b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/CoderBase.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2022 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. @@ -29,6 +29,7 @@ /** Base Codec class. */ abstract class CoderBase { private final Class[] acceptableOptions; + /** * @param acceptableOptions types that can be used as options for this codec. */ diff --git a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/Coders.java b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/Coders.java index f616a0bfa1..9f8a27c9dd 100644 --- a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/Coders.java +++ b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/Coders.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2022 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/DeltaDecoder.java b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/DeltaDecoder.java index 867e57f443..5053fdc98f 100644 --- a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/DeltaDecoder.java +++ b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/DeltaDecoder.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2022 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/Folder.java b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/Folder.java index 2f18f371e4..9cfe728ae6 100644 --- a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/Folder.java +++ b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/Folder.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2022 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/IOUtils.java b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/IOUtils.java index e576100271..ad6af2ab81 100644 --- a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/IOUtils.java +++ b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/IOUtils.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2022 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/LZMA2Decoder.java b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/LZMA2Decoder.java index ce8cc422ed..832d0787a7 100644 --- a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/LZMA2Decoder.java +++ b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/LZMA2Decoder.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2022 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/LZMADecoder.java b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/LZMADecoder.java index 6a2924bed1..404c5f7b9a 100644 --- a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/LZMADecoder.java +++ b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/LZMADecoder.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2022 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/NID.java b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/NID.java index 3a4f54e173..a75a020533 100644 --- a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/NID.java +++ b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/NID.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2022 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/SevenZArchiveEntry.java b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/SevenZArchiveEntry.java index 0f3e628bd7..92a99de33e 100644 --- a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/SevenZArchiveEntry.java +++ b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/SevenZArchiveEntry.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2022 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/SevenZFile.java b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/SevenZFile.java index 59126ac030..a504c7d3d2 100644 --- a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/SevenZFile.java +++ b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/SevenZFile.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2022 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/SevenZFileOptions.java b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/SevenZFileOptions.java index 77df73350a..c988c043c0 100644 --- a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/SevenZFileOptions.java +++ b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/SevenZFileOptions.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2022 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/SevenZMethod.java b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/SevenZMethod.java index aa5da65a6e..8dee04f101 100644 --- a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/SevenZMethod.java +++ b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/SevenZMethod.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2022 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/SevenZMethodConfiguration.java b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/SevenZMethodConfiguration.java index 1db39d9b35..5627dbd583 100644 --- a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/SevenZMethodConfiguration.java +++ b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/SevenZMethodConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2022 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/SevenZOutputFile.java b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/SevenZOutputFile.java index 13b3017c29..97b2a0ff72 100644 --- a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/SevenZOutputFile.java +++ b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/SevenZOutputFile.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2022 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/StartHeader.java b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/StartHeader.java index 06cedd6799..ea8a27397f 100644 --- a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/StartHeader.java +++ b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/StartHeader.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2022 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/StreamMap.java b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/StreamMap.java index 1856f0c572..816657cb6a 100644 --- a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/StreamMap.java +++ b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/StreamMap.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2022 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/SubStreamsInfo.java b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/SubStreamsInfo.java index 7915cf3800..1fddf99faa 100644 --- a/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/SubStreamsInfo.java +++ b/commons_compress_7z/src/main/java/com/amaze/filemanager/filesystem/compressed/sevenz/SubStreamsInfo.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2022 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/file_operations/src/main/java/com/amaze/filemanager/fileoperations/exceptions/CloudPluginException.java b/file_operations/src/main/java/com/amaze/filemanager/fileoperations/exceptions/CloudPluginException.java index a22f0aca8c..e95ede156f 100644 --- a/file_operations/src/main/java/com/amaze/filemanager/fileoperations/exceptions/CloudPluginException.java +++ b/file_operations/src/main/java/com/amaze/filemanager/fileoperations/exceptions/CloudPluginException.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/file_operations/src/main/java/com/amaze/filemanager/fileoperations/exceptions/ShellNotRunningException.java b/file_operations/src/main/java/com/amaze/filemanager/fileoperations/exceptions/ShellNotRunningException.java index 28b5503f05..5b9d77253c 100644 --- a/file_operations/src/main/java/com/amaze/filemanager/fileoperations/exceptions/ShellNotRunningException.java +++ b/file_operations/src/main/java/com/amaze/filemanager/fileoperations/exceptions/ShellNotRunningException.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/file_operations/src/main/java/com/amaze/filemanager/fileoperations/exceptions/StreamNotFoundException.java b/file_operations/src/main/java/com/amaze/filemanager/fileoperations/exceptions/StreamNotFoundException.java index fa82938ad0..b6cfb7e035 100644 --- a/file_operations/src/main/java/com/amaze/filemanager/fileoperations/exceptions/StreamNotFoundException.java +++ b/file_operations/src/main/java/com/amaze/filemanager/fileoperations/exceptions/StreamNotFoundException.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/OpenMode.java b/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/OpenMode.java index e154a69846..ebd2b1ec70 100644 --- a/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/OpenMode.java +++ b/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/OpenMode.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/StorageNaming.java b/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/StorageNaming.java index 9442017b07..006d003e89 100644 --- a/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/StorageNaming.java +++ b/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/StorageNaming.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/cloud/CloudStreamServer.java b/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/cloud/CloudStreamServer.java index 70ac980471..b13b84958b 100644 --- a/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/cloud/CloudStreamServer.java +++ b/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/cloud/CloudStreamServer.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/cloud/CloudStreamSource.java b/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/cloud/CloudStreamSource.java index 9d04cd80e5..b921d0ebc3 100644 --- a/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/cloud/CloudStreamSource.java +++ b/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/cloud/CloudStreamSource.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/cloud/CloudStreamer.java b/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/cloud/CloudStreamer.java index 547cc7f200..998c669205 100644 --- a/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/cloud/CloudStreamer.java +++ b/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/cloud/CloudStreamer.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/compressed/ArchivePasswordCache.java b/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/compressed/ArchivePasswordCache.java index 6ca7884d68..0a5c12c0c9 100644 --- a/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/compressed/ArchivePasswordCache.java +++ b/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/compressed/ArchivePasswordCache.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/smbstreamer/StreamServer.java b/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/smbstreamer/StreamServer.java index 05f0ae24f1..83242cacb8 100644 --- a/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/smbstreamer/StreamServer.java +++ b/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/smbstreamer/StreamServer.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/smbstreamer/StreamSource.java b/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/smbstreamer/StreamSource.java index d982ed45c8..d3c65022b8 100644 --- a/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/smbstreamer/StreamSource.java +++ b/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/smbstreamer/StreamSource.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/smbstreamer/Streamer.java b/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/smbstreamer/Streamer.java index 5e22368438..e24ad06eb2 100644 --- a/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/smbstreamer/Streamer.java +++ b/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/smbstreamer/Streamer.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/streams/RandomAccessStream.java b/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/streams/RandomAccessStream.java index d69179364c..ab39daede3 100644 --- a/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/streams/RandomAccessStream.java +++ b/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/streams/RandomAccessStream.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/usb/SingletonUsbOtg.java b/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/usb/SingletonUsbOtg.java index cb769a76b3..50b066785e 100644 --- a/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/usb/SingletonUsbOtg.java +++ b/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/usb/SingletonUsbOtg.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/usb/UsbOtgRepresentation.java b/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/usb/UsbOtgRepresentation.java index 4e1cd2001f..6c27ab84e2 100644 --- a/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/usb/UsbOtgRepresentation.java +++ b/file_operations/src/main/java/com/amaze/filemanager/fileoperations/filesystem/usb/UsbOtgRepresentation.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/file_operations/src/main/java/com/amaze/filemanager/fileoperations/utils/OnLowMemory.java b/file_operations/src/main/java/com/amaze/filemanager/fileoperations/utils/OnLowMemory.java index ae08769634..b0d0781bb3 100644 --- a/file_operations/src/main/java/com/amaze/filemanager/fileoperations/utils/OnLowMemory.java +++ b/file_operations/src/main/java/com/amaze/filemanager/fileoperations/utils/OnLowMemory.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2022 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/file_operations/src/main/java/com/amaze/filemanager/fileoperations/utils/UpdatePosition.java b/file_operations/src/main/java/com/amaze/filemanager/fileoperations/utils/UpdatePosition.java index 5e23fb0cf6..4638393a5d 100644 --- a/file_operations/src/main/java/com/amaze/filemanager/fileoperations/utils/UpdatePosition.java +++ b/file_operations/src/main/java/com/amaze/filemanager/fileoperations/utils/UpdatePosition.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2022 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/file_operations/src/test/java/com/amaze/filemanager/fileoperations/filesystem/cloud/CloudStreamSourceTest.java b/file_operations/src/test/java/com/amaze/filemanager/fileoperations/filesystem/cloud/CloudStreamSourceTest.java index d0e87e353f..c6d3bcee74 100644 --- a/file_operations/src/test/java/com/amaze/filemanager/fileoperations/filesystem/cloud/CloudStreamSourceTest.java +++ b/file_operations/src/test/java/com/amaze/filemanager/fileoperations/filesystem/cloud/CloudStreamSourceTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/file_operations/src/test/java/com/amaze/filemanager/fileoperations/filesystem/smbstreamer/StreamSourceTest.java b/file_operations/src/test/java/com/amaze/filemanager/fileoperations/filesystem/smbstreamer/StreamSourceTest.java index c8b012fa04..a9f972f5cd 100644 --- a/file_operations/src/test/java/com/amaze/filemanager/fileoperations/filesystem/smbstreamer/StreamSourceTest.java +++ b/file_operations/src/test/java/com/amaze/filemanager/fileoperations/filesystem/smbstreamer/StreamSourceTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/portscanner/src/main/java/com/stealthcopter/networktools/IPTools.kt b/portscanner/src/main/java/com/stealthcopter/networktools/IPTools.kt index 59fac0768e..8f022e0894 100644 --- a/portscanner/src/main/java/com/stealthcopter/networktools/IPTools.kt +++ b/portscanner/src/main/java/com/stealthcopter/networktools/IPTools.kt @@ -32,15 +32,18 @@ object IPTools { * https://examples.javacodegeeks.com/core-java/util/regex/regular-expressions-for-ip-v4-and-ip-v6-addresses/ * note that these patterns will match most but not all valid ips */ - private val IPV4_PATTERN = Pattern.compile( - "^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$" - ) - private val IPV6_STD_PATTERN = Pattern.compile( - "^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$" - ) - private val IPV6_HEX_COMPRESSED_PATTERN = Pattern.compile( - "^((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)$" - ) + private val IPV4_PATTERN = + Pattern.compile( + "^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$", + ) + private val IPV6_STD_PATTERN = + Pattern.compile( + "^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$", + ) + private val IPV6_HEX_COMPRESSED_PATTERN = + Pattern.compile( + "^((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)$", + ) /** * Answers if given string is valid IPv4 address. @@ -88,13 +91,14 @@ object IPTools { * Return The list of all IPv4 addresses found */ private val localIPv4Addresses: List - get() = runCatching { - NetworkInterface.getNetworkInterfaces().toList().flatMap { iface -> - iface.inetAddresses.asSequence().filter { addr -> - addr is Inet4Address && !addr.isLoopbackAddress() + get() = + runCatching { + NetworkInterface.getNetworkInterfaces().toList().flatMap { iface -> + iface.inetAddresses.asSequence().filter { addr -> + addr is Inet4Address && !addr.isLoopbackAddress() + } } - } - }.getOrDefault(emptyList()) + }.getOrDefault(emptyList()) /** * Check if the provided ip address refers to the localhost @@ -108,10 +112,14 @@ object IPTools { fun isIpAddressLocalhost(addr: InetAddress?): Boolean { return addr?.run { // Check if the address is a valid special local or loop back - if (addr.isAnyLocalAddress || addr.isLoopbackAddress) true else try { - NetworkInterface.getByInetAddress(addr) != null - } catch (e: SocketException) { - false + if (addr.isAnyLocalAddress || addr.isLoopbackAddress) { + true + } else { + try { + NetworkInterface.getByInetAddress(addr) != null + } catch (e: SocketException) { + false + } } } ?: false } @@ -125,6 +133,5 @@ object IPTools { * @return - true if ip address is self */ @JvmStatic - fun isIpAddressLocalNetwork(addr: InetAddress?): Boolean = - addr != null && addr.isSiteLocalAddress + fun isIpAddressLocalNetwork(addr: InetAddress?): Boolean = addr != null && addr.isSiteLocalAddress } diff --git a/portscanner/src/main/java/com/stealthcopter/networktools/PortScan.kt b/portscanner/src/main/java/com/stealthcopter/networktools/PortScan.kt index 0f9f9812ef..3d3ebb0ffa 100644 --- a/portscanner/src/main/java/com/stealthcopter/networktools/PortScan.kt +++ b/portscanner/src/main/java/com/stealthcopter/networktools/PortScan.kt @@ -29,287 +29,295 @@ import java.util.* /** Created by mat on 14/12/15. */ class PortScan // This class is not to be instantiated -private constructor() { + private constructor() { + private var method = METHOD_TCP + private var noThreads = 50 + private var address: InetAddress? = null + private var timeOutMillis = 1000 + private var cancelled = false + private var ports: MutableList = ArrayList() + private val openPortsFound: MutableList = ArrayList() + private var portListener: PortListener? = null + private lateinit var runningFlowable: Flowable - private var method = METHOD_TCP - private var noThreads = 50 - private var address: InetAddress? = null - private var timeOutMillis = 1000 - private var cancelled = false - private var ports: MutableList = ArrayList() - private val openPortsFound: MutableList = ArrayList() - private var portListener: PortListener? = null - private lateinit var runningFlowable: Flowable + interface PortListener { + /** + * Callback function for port scan result + */ + fun onResult( + portNo: Int, + open: Boolean, + ) + + /** + * Callback function for receiving the list of opened ports + */ + fun onFinished(openPorts: List?) + } - interface PortListener { /** - * Callback function for port scan result + * Sets the timeout for each port scanned + * + * If you raise the timeout you may want to consider increasing the thread count [ ][.setNoThreads] to compensate. We can afford to have quite a high thread count as most of + * the time the thread is just sitting idle and waiting for the socket to timeout. + * + * @param timeOutMillis - the timeout for each ping in milliseconds Recommendations: Local host: + * 20 - 500 ms - can be very fast as request doesn't need to go over network Local network 500 + * - 2500 ms Remote Scan 2500+ ms + * @return this object to allow chaining */ - fun onResult(portNo: Int, open: Boolean) + fun setTimeOutMillis(timeOutMillis: Int): PortScan { + require(timeOutMillis >= 0) { "Timeout cannot be less than 0" } + this.timeOutMillis = timeOutMillis + return this + } /** - * Callback function for receiving the list of opened ports + * Scan the ports to scan + * + * @param port - the port to scan + * @return this object to allow chaining */ - fun onFinished(openPorts: List?) - } - - /** - * Sets the timeout for each port scanned - * - * If you raise the timeout you may want to consider increasing the thread count [ ][.setNoThreads] to compensate. We can afford to have quite a high thread count as most of - * the time the thread is just sitting idle and waiting for the socket to timeout. - * - * @param timeOutMillis - the timeout for each ping in milliseconds Recommendations: Local host: - * 20 - 500 ms - can be very fast as request doesn't need to go over network Local network 500 - * - 2500 ms Remote Scan 2500+ ms - * @return this object to allow chaining - */ - fun setTimeOutMillis(timeOutMillis: Int): PortScan { - require(timeOutMillis >= 0) { "Timeout cannot be less than 0" } - this.timeOutMillis = timeOutMillis - return this - } - - /** - * Scan the ports to scan - * - * @param port - the port to scan - * @return this object to allow chaining - */ - fun setPort(port: Int): PortScan { - ports.clear() - validatePort(port) - ports.add(port) - return this - } - - /** - * Scan the ports to scan - * - * @param ports - the ports to scan - * @return this object to allow chaining - */ - fun setPorts(ports: MutableList): PortScan { - // Check all ports are valid - for (port in ports) { + fun setPort(port: Int): PortScan { + ports.clear() validatePort(port) + ports.add(port) + return this } - this.ports = ports - return this - } - /** - * Scan the ports to scan - * - * @param portString - the ports to scan (comma separated, hyphen denotes a range). For example: - * "21-23,25,45,53,80" - * @return this object to allow chaining - */ - fun setPorts(portString: String): PortScan { - var portString = portString - ports.clear() - val ports: MutableList = ArrayList() - portString = portString.substring(portString.indexOf(":") + 1, portString.length) - for (x in portString.split(",").toTypedArray()) { - if (x.contains("-")) { - val start = x.split("-").toTypedArray()[0].toInt() - val end = x.split("-").toTypedArray()[1].toInt() - validatePort(start) - validatePort(end) - require(end > start) { "Start port cannot be greater than or equal to the end port" } - for (j in start..end) { - ports.add(j) - } - } else { - val start = x.toInt() - validatePort(start) - ports.add(start) + /** + * Scan the ports to scan + * + * @param ports - the ports to scan + * @return this object to allow chaining + */ + fun setPorts(ports: MutableList): PortScan { + // Check all ports are valid + for (port in ports) { + validatePort(port) } + this.ports = ports + return this } - this.ports = ports - return this - } - - /** - * Checks and throws exception if port is not valid - * - * @param port - the port to validate - */ - private fun validatePort(port: Int) { - require(port >= 1) { "Start port cannot be less than 1" } - require(port <= 65535) { "Start cannot be greater than 65535" } - } - - private fun setAddress(address: InetAddress) { - this.address = address - } - private fun setDefaultThreadsAndTimeouts() { - // Try and work out automatically what kind of host we are scanning - // local host (this device) / local network / remote - if (isIpAddressLocalhost(address)) { - // If we are scanning a the localhost set the timeout to be very short so we get faster - // results - // This will be overridden if user calls setTimeoutMillis manually. - timeOutMillis = TIMEOUT_LOCALHOST - noThreads = DEFAULT_THREADS_LOCALHOST - } else if (isIpAddressLocalNetwork(address)) { - // Assume local network (not infallible) - timeOutMillis = TIMEOUT_LOCALNETWORK - noThreads = DEFAULT_THREADS_LOCALNETWORK - } else { - // Assume remote network timeouts - timeOutMillis = TIMEOUT_REMOTE - noThreads = DEFAULT_THREADS_REMOTE + /** + * Scan the ports to scan + * + * @param portString - the ports to scan (comma separated, hyphen denotes a range). For example: + * "21-23,25,45,53,80" + * @return this object to allow chaining + */ + fun setPorts(portString: String): PortScan { + var portString = portString + ports.clear() + val ports: MutableList = ArrayList() + portString = portString.substring(portString.indexOf(":") + 1, portString.length) + for (x in portString.split(",").toTypedArray()) { + if (x.contains("-")) { + val start = x.split("-").toTypedArray()[0].toInt() + val end = x.split("-").toTypedArray()[1].toInt() + validatePort(start) + validatePort(end) + require(end > start) { "Start port cannot be greater than or equal to the end port" } + for (j in start..end) { + ports.add(j) + } + } else { + val start = x.toInt() + validatePort(start) + ports.add(start) + } + } + this.ports = ports + return this } - } - /** - * @param noThreads set the number of threads to work with, note we default to a large number as - * these requests are network heavy not cpu heavy. - * @return self - * @throws IllegalArgumentException - if no threads is less than 1 - */ - @Throws(IllegalArgumentException::class) - fun setNoThreads(noThreads: Int): PortScan { - require(noThreads >= 1) { "Cannot have less than 1 thread" } - this.noThreads = noThreads - return this - } - - /** - * Set scan method, either TCP or UDP - * - * @param method - the transport method to use to scan, either PortScan.METHOD_UDP or - * PortScan.METHOD_TCP - * @return this object to allow chaining - * @throws IllegalArgumentException - if invalid method - */ - private fun setMethod(method: Int): PortScan { - when (method) { - METHOD_UDP, METHOD_TCP -> this.method = method - else -> throw IllegalArgumentException("Invalid method type $method") + /** + * Checks and throws exception if port is not valid + * + * @param port - the port to validate + */ + private fun validatePort(port: Int) { + require(port >= 1) { "Start port cannot be less than 1" } + require(port <= 65535) { "Start cannot be greater than 65535" } } - return this - } - - /** - * Set scan method to UDP - * - * @return this object to allow chaining - */ - fun setMethodUDP(): PortScan { - setMethod(METHOD_UDP) - return this - } - /** - * Set scan method to TCP - * - * @return this object to allow chaining - */ - fun setMethodTCP(): PortScan { - setMethod(METHOD_TCP) - return this - } - - /** Cancel a running ping */ - fun cancel() { - cancelled = true - runningFlowable.unsubscribeOn(Schedulers.computation()) - } - - /** - * Perform a synchronous (blocking) port scan and return a list of open ports - * - * @return - ping result - */ - fun doScan(): List { - cancelled = false - openPortsFound.clear() - runningFlowable = createPortScanFlowable().doOnComplete { - openPortsFound.sort() + private fun setAddress(address: InetAddress) { + this.address = address } - runningFlowable.blockingSubscribe() - return openPortsFound - } - private fun createPortScanFlowable(): Flowable { - return Flowable.fromIterable(ports) - .parallel(noThreads) - .runOn(Schedulers.io()) - .map { portNo -> - PortScanRunnable(address, portNo, timeOutMillis, method).run() - }.sequential() - .subscribeOn(Schedulers.computation()) - } + private fun setDefaultThreadsAndTimeouts() { + // Try and work out automatically what kind of host we are scanning + // local host (this device) / local network / remote + if (isIpAddressLocalhost(address)) { + // If we are scanning a the localhost set the timeout to be very short so we get faster + // results + // This will be overridden if user calls setTimeoutMillis manually. + timeOutMillis = TIMEOUT_LOCALHOST + noThreads = DEFAULT_THREADS_LOCALHOST + } else if (isIpAddressLocalNetwork(address)) { + // Assume local network (not infallible) + timeOutMillis = TIMEOUT_LOCALNETWORK + noThreads = DEFAULT_THREADS_LOCALNETWORK + } else { + // Assume remote network timeouts + timeOutMillis = TIMEOUT_REMOTE + noThreads = DEFAULT_THREADS_REMOTE + } + } - @Synchronized - private fun portScanned(port: Int, open: Boolean) { - if (open) { - openPortsFound.add(port) + /** + * @param noThreads set the number of threads to work with, note we default to a large number as + * these requests are network heavy not cpu heavy. + * @return self + * @throws IllegalArgumentException - if no threads is less than 1 + */ + @Throws(IllegalArgumentException::class) + fun setNoThreads(noThreads: Int): PortScan { + require(noThreads >= 1) { "Cannot have less than 1 thread" } + this.noThreads = noThreads + return this } - portListener?.onResult(port, open) - } - private inner class PortScanRunnable constructor( - private val address: InetAddress?, - private val portNo: Int, - private val timeOutMillis: Int, - private val method: Int - ) : Runnable { - override fun run() { - if (cancelled) return + /** + * Set scan method, either TCP or UDP + * + * @param method - the transport method to use to scan, either PortScan.METHOD_UDP or + * PortScan.METHOD_TCP + * @return this object to allow chaining + * @throws IllegalArgumentException - if invalid method + */ + private fun setMethod(method: Int): PortScan { when (method) { - METHOD_UDP -> portScanned( - portNo, - PortScanUDP.scanAddress(address, portNo, timeOutMillis) - ) - METHOD_TCP -> portScanned( - portNo, - PortScanTCP.scanAddress(address, portNo, timeOutMillis) - ) - else -> throw IllegalArgumentException("Invalid method") + METHOD_UDP, METHOD_TCP -> this.method = method + else -> throw IllegalArgumentException("Invalid method type $method") } + return this } - } - - companion object { - private const val TIMEOUT_LOCALHOST = 25 - private const val TIMEOUT_LOCALNETWORK = 1000 - private const val TIMEOUT_REMOTE = 2500 - private const val DEFAULT_THREADS_LOCALHOST = 7 - private const val DEFAULT_THREADS_LOCALNETWORK = 50 - private const val DEFAULT_THREADS_REMOTE = 50 - private const val METHOD_TCP = 0 - private const val METHOD_UDP = 1 /** - * Set the address to ping + * Set scan method to UDP * - * @param address - Address to be pinged * @return this object to allow chaining - * @throws UnknownHostException - if no IP address for the `host` could be found, or if a - * scope_id was specified for a global IPv6 address. */ - @JvmStatic - @Throws(UnknownHostException::class) - fun onAddress(address: String?): PortScan { - return onAddress(InetAddress.getByName(address)) + fun setMethodUDP(): PortScan { + setMethod(METHOD_UDP) + return this } /** - * Set the address to ping + * Set scan method to TCP * - * @param ia - Address to be pinged * @return this object to allow chaining */ - @JvmStatic - fun onAddress(ia: InetAddress): PortScan { - val portScan = PortScan() - portScan.setAddress(ia) - portScan.setDefaultThreadsAndTimeouts() - return portScan + fun setMethodTCP(): PortScan { + setMethod(METHOD_TCP) + return this + } + + /** Cancel a running ping */ + fun cancel() { + cancelled = true + runningFlowable.unsubscribeOn(Schedulers.computation()) + } + + /** + * Perform a synchronous (blocking) port scan and return a list of open ports + * + * @return - ping result + */ + fun doScan(): List { + cancelled = false + openPortsFound.clear() + runningFlowable = + createPortScanFlowable().doOnComplete { + openPortsFound.sort() + } + runningFlowable.blockingSubscribe() + return openPortsFound + } + + private fun createPortScanFlowable(): Flowable { + return Flowable.fromIterable(ports) + .parallel(noThreads) + .runOn(Schedulers.io()) + .map { portNo -> + PortScanRunnable(address, portNo, timeOutMillis, method).run() + }.sequential() + .subscribeOn(Schedulers.computation()) + } + + @Synchronized + private fun portScanned( + port: Int, + open: Boolean, + ) { + if (open) { + openPortsFound.add(port) + } + portListener?.onResult(port, open) + } + + private inner class PortScanRunnable constructor( + private val address: InetAddress?, + private val portNo: Int, + private val timeOutMillis: Int, + private val method: Int, + ) : Runnable { + override fun run() { + if (cancelled) return + when (method) { + METHOD_UDP -> + portScanned( + portNo, + PortScanUDP.scanAddress(address, portNo, timeOutMillis), + ) + METHOD_TCP -> + portScanned( + portNo, + PortScanTCP.scanAddress(address, portNo, timeOutMillis), + ) + else -> throw IllegalArgumentException("Invalid method") + } + } + } + + companion object { + private const val TIMEOUT_LOCALHOST = 25 + private const val TIMEOUT_LOCALNETWORK = 1000 + private const val TIMEOUT_REMOTE = 2500 + private const val DEFAULT_THREADS_LOCALHOST = 7 + private const val DEFAULT_THREADS_LOCALNETWORK = 50 + private const val DEFAULT_THREADS_REMOTE = 50 + private const val METHOD_TCP = 0 + private const val METHOD_UDP = 1 + + /** + * Set the address to ping + * + * @param address - Address to be pinged + * @return this object to allow chaining + * @throws UnknownHostException - if no IP address for the `host` could be found, or if a + * scope_id was specified for a global IPv6 address. + */ + @JvmStatic + @Throws(UnknownHostException::class) + fun onAddress(address: String?): PortScan { + return onAddress(InetAddress.getByName(address)) + } + + /** + * Set the address to ping + * + * @param ia - Address to be pinged + * @return this object to allow chaining + */ + @JvmStatic + fun onAddress(ia: InetAddress): PortScan { + val portScan = PortScan() + portScan.setAddress(ia) + portScan.setDefaultThreadsAndTimeouts() + return portScan + } } } -} diff --git a/portscanner/src/main/java/com/stealthcopter/networktools/portscanning/PortScanTCP.kt b/portscanner/src/main/java/com/stealthcopter/networktools/portscanning/PortScanTCP.kt index 8c816b155d..20a0ae39c4 100644 --- a/portscanner/src/main/java/com/stealthcopter/networktools/portscanning/PortScanTCP.kt +++ b/portscanner/src/main/java/com/stealthcopter/networktools/portscanning/PortScanTCP.kt @@ -35,7 +35,11 @@ object PortScanTCP { */ @JvmStatic @Suppress("LabeledExpression") - fun scanAddress(ia: InetAddress?, portNo: Int, timeoutMillis: Int): Boolean { + fun scanAddress( + ia: InetAddress?, + portNo: Int, + timeoutMillis: Int, + ): Boolean { return Socket().let { s -> runCatching { s.connect(InetSocketAddress(ia, portNo), timeoutMillis) diff --git a/portscanner/src/main/java/com/stealthcopter/networktools/portscanning/PortScanUDP.kt b/portscanner/src/main/java/com/stealthcopter/networktools/portscanning/PortScanUDP.kt index 286d6e7e01..86b26fd430 100644 --- a/portscanner/src/main/java/com/stealthcopter/networktools/portscanning/PortScanUDP.kt +++ b/portscanner/src/main/java/com/stealthcopter/networktools/portscanning/PortScanUDP.kt @@ -37,7 +37,11 @@ object PortScanUDP { * @return - true if port is open, false if not or unknown */ @JvmStatic - fun scanAddress(ia: InetAddress?, portNo: Int, timeoutMillis: Int): Boolean { + fun scanAddress( + ia: InetAddress?, + portNo: Int, + timeoutMillis: Int, + ): Boolean { try { val bytes = ByteArray(128) val dp = DatagramPacket(bytes, bytes.size) diff --git a/testShared/src/test/java/com/amaze/filemanager/shadows/ShadowContentResolver.kt b/testShared/src/test/java/com/amaze/filemanager/shadows/ShadowContentResolver.kt index 8677802878..d037413740 100644 --- a/testShared/src/test/java/com/amaze/filemanager/shadows/ShadowContentResolver.kt +++ b/testShared/src/test/java/com/amaze/filemanager/shadows/ShadowContentResolver.kt @@ -35,12 +35,14 @@ import java.io.OutputStream */ @Implements(ContentResolver::class) class ShadowContentResolver : ShadowContentResolver() { - /** * Implements [ContentResolver.openOutputStream] with open mode parameter. * * Simply delegate to one without open mode. */ @Implementation - fun openOutputStream(uri: Uri, mode: String): OutputStream? = super.openOutputStream(uri) + fun openOutputStream( + uri: Uri, + mode: String, + ): OutputStream? = super.openOutputStream(uri) } diff --git a/testShared/src/test/java/com/amaze/filemanager/shadows/ShadowMultiDex.java b/testShared/src/test/java/com/amaze/filemanager/shadows/ShadowMultiDex.java index 4eab02706f..6ac9f918d1 100644 --- a/testShared/src/test/java/com/amaze/filemanager/shadows/ShadowMultiDex.java +++ b/testShared/src/test/java/com/amaze/filemanager/shadows/ShadowMultiDex.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/testShared/src/test/java/com/amaze/filemanager/shadows/ShadowSmbUtil.kt b/testShared/src/test/java/com/amaze/filemanager/shadows/ShadowSmbUtil.kt index b141acd655..6acbd8bb59 100644 --- a/testShared/src/test/java/com/amaze/filemanager/shadows/ShadowSmbUtil.kt +++ b/testShared/src/test/java/com/amaze/filemanager/shadows/ShadowSmbUtil.kt @@ -34,10 +34,7 @@ import org.robolectric.util.ReflectionHelpers @Implements(SmbUtil::class) @Suppress() class ShadowSmbUtil { - companion object { - - /* ktlint-disable max-line-length */ const val PATH_CANNOT_DELETE_FILE = "smb://user:password@1.2.3.4/access/denied.file" const val PATH_CANNOT_MOVE_FILE = "smb://user:password@1.2.3.4/cannot/move.file" const val PATH_CANNOT_RENAME_OLDFILE = "smb://user:password@1.2.3.4/cannot/rename.file.old" @@ -61,60 +58,70 @@ class ShadowSmbUtil { var mockSmbExceptionOnIsFolder: SmbFile? = null init { - mockDeleteAccessDenied = createInternal(PATH_CANNOT_DELETE_FILE).also { - `when`(it.delete()).thenThrow(SmbException("Access is denied.")) - `when`(it.exists()).thenReturn(true) - } + mockDeleteAccessDenied = + createInternal(PATH_CANNOT_DELETE_FILE).also { + `when`(it.delete()).thenThrow(SmbException("Access is denied.")) + `when`(it.exists()).thenReturn(true) + } - mockDeleteDifferentNetwork = createInternal(PATH_CANNOT_MOVE_FILE).also { - `when`(it.delete()).thenThrow(SmbException("Cannot rename between different trees")) - `when`(it.exists()).thenReturn(true) - } + mockDeleteDifferentNetwork = + createInternal(PATH_CANNOT_MOVE_FILE).also { + `when`(it.delete()).thenThrow(SmbException("Cannot rename between different trees")) + `when`(it.exists()).thenReturn(true) + } - mockCanRename = createInternal(PATH_CAN_RENAME_OLDFILE).also { - doNothing().`when`(it).renameTo(any()) - } + mockCanRename = + createInternal(PATH_CAN_RENAME_OLDFILE).also { + doNothing().`when`(it).renameTo(any()) + } mockCannotRenameOld = createInternal(PATH_CANNOT_RENAME_OLDFILE) `when`(mockCannotRenameOld!!.renameTo(any())) .thenThrow(SmbException("Access is denied.")) `when`(mockCannotRenameOld!!.exists()).thenReturn(true) - mockPathDoesNotExist = createInternal(PATH_DOESNT_EXIST).also { - `when`(it.exists()).thenReturn(false) - } + mockPathDoesNotExist = + createInternal(PATH_DOESNT_EXIST).also { + `when`(it.exists()).thenReturn(false) + } - mockPathNotAFolder = createInternal(PATH_NOT_A_FOLDER).also { - `when`(it.exists()).thenReturn(true) - `when`(it.isDirectory).thenReturn(false) - } + mockPathNotAFolder = + createInternal(PATH_NOT_A_FOLDER).also { + `when`(it.exists()).thenReturn(true) + `when`(it.isDirectory).thenReturn(false) + } - mockPathExist = createInternal(PATH_EXIST).also { - `when`(it.exists()).thenReturn(true) - `when`(it.isDirectory).thenReturn(true) - } + mockPathExist = + createInternal(PATH_EXIST).also { + `when`(it.exists()).thenReturn(true) + `when`(it.isDirectory).thenReturn(true) + } - mockSmbExceptionOnExists = createInternal(PATH_INVOKE_SMBEXCEPTION_ON_EXISTS).also { - `when`(it.exists()).thenThrow(SmbException()) - } + mockSmbExceptionOnExists = + createInternal(PATH_INVOKE_SMBEXCEPTION_ON_EXISTS).also { + `when`(it.exists()).thenThrow(SmbException()) + } - mockSmbExceptionOnIsFolder = createInternal(PATH_INVOKE_SMBEXCEPTION_ON_ISFOLDER).also { - `when`(it.exists()).thenReturn(true) - `when`(it.isDirectory).thenThrow(SmbException()) - } + mockSmbExceptionOnIsFolder = + createInternal(PATH_INVOKE_SMBEXCEPTION_ON_ISFOLDER).also { + `when`(it.exists()).thenReturn(true) + `when`(it.isDirectory).thenThrow(SmbException()) + } } - /* ktlint-enable max-line-length */ /** * Delegate to [SmbUtil.getSmbEncryptedPath]. */ @JvmStatic @Implementation - fun getSmbEncryptedPath(context: Context, path: String): String { + fun getSmbEncryptedPath( + context: Context, + path: String, + ): String { return Shadow.directlyOn( SmbUtil::class.java, "getSmbEncryptedPath", ReflectionHelpers.ClassParameter(Context::class.java, context), - ReflectionHelpers.ClassParameter(String::class.java, path) + ReflectionHelpers.ClassParameter(String::class.java, path), ) } @@ -122,12 +129,15 @@ class ShadowSmbUtil { * Delegate to [SmbUtil.getSmbDecryptedPath]. */ @JvmStatic @Implementation - fun getSmbDecryptedPath(context: Context, path: String): String { + fun getSmbDecryptedPath( + context: Context, + path: String, + ): String { return Shadow.directlyOn( SmbUtil::class.java, "getSmbDecryptedPath", ReflectionHelpers.ClassParameter(Context::class.java, context), - ReflectionHelpers.ClassParameter(String::class.java, path) + ReflectionHelpers.ClassParameter(String::class.java, path), ) } @@ -139,7 +149,7 @@ class ShadowSmbUtil { return Shadow.directlyOn( SmbUtil::class.java, "checkFolder", - ReflectionHelpers.ClassParameter(String::class.java, path) + ReflectionHelpers.ClassParameter(String::class.java, path), ) } @@ -160,10 +170,11 @@ class ShadowSmbUtil { PATH_EXIST -> mockPathExist!! PATH_INVOKE_SMBEXCEPTION_ON_EXISTS -> mockSmbExceptionOnExists!! PATH_INVOKE_SMBEXCEPTION_ON_ISFOLDER -> mockSmbExceptionOnIsFolder!! - else -> createInternal(path).also { - doNothing().`when`(it).delete() - `when`(it.exists()).thenReturn(false) - } + else -> + createInternal(path).also { + doNothing().`when`(it).delete() + `when`(it.exists()).thenReturn(false) + } } } diff --git a/testShared/src/test/java/com/amaze/filemanager/shadows/jcifs/smb/ShadowSmbFile.java b/testShared/src/test/java/com/amaze/filemanager/shadows/jcifs/smb/ShadowSmbFile.java index 9a2f6a7c7c..d4b6568e7e 100644 --- a/testShared/src/test/java/com/amaze/filemanager/shadows/jcifs/smb/ShadowSmbFile.java +++ b/testShared/src/test/java/com/amaze/filemanager/shadows/jcifs/smb/ShadowSmbFile.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. @@ -21,7 +21,6 @@ package com.amaze.filemanager.shadows.jcifs.smb; import java.io.File; -import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; diff --git a/testShared/src/test/java/com/amaze/filemanager/test/DummyFileGenerator.java b/testShared/src/test/java/com/amaze/filemanager/test/DummyFileGenerator.java index df1fb60601..43f65912e4 100644 --- a/testShared/src/test/java/com/amaze/filemanager/test/DummyFileGenerator.java +++ b/testShared/src/test/java/com/amaze/filemanager/test/DummyFileGenerator.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/testShared/src/test/java/com/amaze/filemanager/test/ShadowNativeOperations.java b/testShared/src/test/java/com/amaze/filemanager/test/ShadowNativeOperations.java index a849f10eef..1f2e451fcd 100644 --- a/testShared/src/test/java/com/amaze/filemanager/test/ShadowNativeOperations.java +++ b/testShared/src/test/java/com/amaze/filemanager/test/ShadowNativeOperations.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2021 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/testShared/src/test/java/com/amaze/filemanager/test/ShadowPasswordUtil.kt b/testShared/src/test/java/com/amaze/filemanager/test/ShadowPasswordUtil.kt index e68b67db18..8e38681a01 100644 --- a/testShared/src/test/java/com/amaze/filemanager/test/ShadowPasswordUtil.kt +++ b/testShared/src/test/java/com/amaze/filemanager/test/ShadowPasswordUtil.kt @@ -34,7 +34,6 @@ import javax.crypto.spec.GCMParameterSpec @Implements(PasswordUtil::class) class ShadowPasswordUtil { - companion object { val INSTANCE = ShadowPasswordUtil() private const val ALGO_AES = "AES/GCM/NoPadding" @@ -49,7 +48,7 @@ class ShadowPasswordUtil { fun encryptPassword( context: Context?, plainText: String, - base64Options: Int = Base64.URL_SAFE + base64Options: Int = Base64.URL_SAFE, ): String { return aesEncryptPassword(plainText, base64Options) } @@ -60,14 +59,17 @@ class ShadowPasswordUtil { fun decryptPassword( context: Context?, cipherText: String, - base64Options: Int = Base64.URL_SAFE + base64Options: Int = Base64.URL_SAFE, ): String { return aesDecryptPassword(cipherText, base64Options) } /** Helper method to encrypt plain text password */ @Throws(GeneralSecurityException::class) - private fun aesEncryptPassword(plainTextPassword: String, base64Options: Int): String { + private fun aesEncryptPassword( + plainTextPassword: String, + base64Options: Int, + ): String { val cipher = Cipher.getInstance(ALGO_AES) val gcmParameterSpec = GCMParameterSpec(128, IV.toByteArray()) cipher.init(Cipher.ENCRYPT_MODE, secretKey, gcmParameterSpec) @@ -77,7 +79,10 @@ class ShadowPasswordUtil { /** Helper method to decrypt cipher text password */ @Throws(GeneralSecurityException::class) - private fun aesDecryptPassword(cipherPassword: String, base64Options: Int): String { + private fun aesDecryptPassword( + cipherPassword: String, + base64Options: Int, + ): String { val cipher = Cipher.getInstance(ALGO_AES) val gcmParameterSpec = GCMParameterSpec(128, IV.toByteArray()) cipher.init(Cipher.DECRYPT_MODE, secretKey, gcmParameterSpec) diff --git a/testShared/src/test/java/com/amaze/filemanager/test/ShadowPasswordUtilTest.java b/testShared/src/test/java/com/amaze/filemanager/test/ShadowPasswordUtilTest.java index 0f161a8256..1af6c0e167 100644 --- a/testShared/src/test/java/com/amaze/filemanager/test/ShadowPasswordUtilTest.java +++ b/testShared/src/test/java/com/amaze/filemanager/test/ShadowPasswordUtilTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2020 Arpit Khurana , Vishal Nehra , + * Copyright (C) 2014-2024 Arpit Khurana , Vishal Nehra , * Emmanuel Messulam, Raymond Lai and Contributors. * * This file is part of Amaze File Manager. diff --git a/testShared/src/test/java/com/amaze/filemanager/test/ShadowTabHandler.kt b/testShared/src/test/java/com/amaze/filemanager/test/ShadowTabHandler.kt index 6fefa1d230..082cc8cf0f 100644 --- a/testShared/src/test/java/com/amaze/filemanager/test/ShadowTabHandler.kt +++ b/testShared/src/test/java/com/amaze/filemanager/test/ShadowTabHandler.kt @@ -29,7 +29,6 @@ import org.robolectric.util.ReflectionHelpers @Implements(TabHandler::class) class ShadowTabHandler { - companion object { /** * Implements [TabHandler.getInstance] diff --git a/testShared/src/test/java/com/amaze/filemanager/test/TestUtils.kt b/testShared/src/test/java/com/amaze/filemanager/test/TestUtils.kt index e0ce8a764b..31418c804d 100644 --- a/testShared/src/test/java/com/amaze/filemanager/test/TestUtils.kt +++ b/testShared/src/test/java/com/amaze/filemanager/test/TestUtils.kt @@ -73,7 +73,9 @@ fun supportedArchiveExtensions(): List { * * @param id String resource ID */ -fun getString(@StringRes id: Int) = AppConfig.getInstance().getString(id) +fun getString( + @StringRes id: Int, +) = AppConfig.getInstance().getString(id) object TestUtils { /** @@ -146,14 +148,17 @@ object TestUtils { * compile. So we are injecting our mock copy using reflection. */ @JvmStatic - fun replaceObjectInstance(clazz: Class, newInstance: T?): T { + fun replaceObjectInstance( + clazz: Class, + newInstance: T?, + ): T { if (!clazz.declaredFields.any { - it.name == "INSTANCE" && it.type == clazz && Modifier.isStatic(it.modifiers) - } + it.name == "INSTANCE" && it.type == clazz && Modifier.isStatic(it.modifiers) + } ) { throw InstantiationException( "clazz ${clazz.canonicalName} does not have a static " + - "INSTANCE field, is it really a Kotlin \"object\"?" + "INSTANCE field, is it really a Kotlin \"object\"?", ) } @@ -170,11 +175,12 @@ object TestUtils { private fun addVolumeToStorageManager(parcel: Parcel) { parcel.setDataPosition(0) - val storageManager = Shadows.shadowOf( - ApplicationProvider.getApplicationContext().getSystemService( - StorageManager::class.java + val storageManager = + Shadows.shadowOf( + ApplicationProvider.getApplicationContext().getSystemService( + StorageManager::class.java, + ), ) - ) val volume = StorageVolume.CREATOR.createFromParcel(parcel) storageManager.addStorageVolume(volume) }