From 8d845c8d0fe0817c66c395844bbe873d1b0ad48d Mon Sep 17 00:00:00 2001 From: alperozturk Date: Thu, 28 Dec 2023 12:55:29 +0100 Subject: [PATCH] Code cleanup Signed-off-by: alperozturk --- .../ui/activity/FolderPickerActivity.kt | 416 +++++++++--------- 1 file changed, 211 insertions(+), 205 deletions(-) diff --git a/app/src/main/java/com/owncloud/android/ui/activity/FolderPickerActivity.kt b/app/src/main/java/com/owncloud/android/ui/activity/FolderPickerActivity.kt index 3f97b65a4cf2..c07e145caaca 100644 --- a/app/src/main/java/com/owncloud/android/ui/activity/FolderPickerActivity.kt +++ b/app/src/main/java/com/owncloud/android/ui/activity/FolderPickerActivity.kt @@ -34,8 +34,6 @@ import android.view.MenuItem import android.view.View import androidx.activity.OnBackPressedCallback import androidx.localbroadcastmanager.content.LocalBroadcastManager -import androidx.viewbinding.ViewBinding -import com.google.android.material.button.MaterialButton import com.nextcloud.client.di.Injectable import com.owncloud.android.R import com.owncloud.android.databinding.FilesFolderPickerBinding @@ -63,11 +61,10 @@ import com.owncloud.android.utils.PathUtils import java.io.File import javax.inject.Inject -@Suppress("Detekt.TooManyFunctions") // legacy code +@Suppress("Detekt.TooManyFunctions") open class FolderPickerActivity : FileActivity(), FileFragment.ContainerActivity, - View.OnClickListener, OnEnforceableRefreshListener, Injectable, OnSortingOrderListener { @@ -78,11 +75,6 @@ open class FolderPickerActivity : var isDoNotEnterEncryptedFolder = false private set - private var mCancelBtn: MaterialButton? = null - private var mCopyBtn: MaterialButton? = null - private var mChooseBtn: MaterialButton? = null - private var mMoveBtn: MaterialButton? = null - private var captionText: String? = null private var action: String? = null @@ -97,16 +89,10 @@ open class FolderPickerActivity : private fun initBinding() { if (this is FilePickerActivity) { filesPickerBinding = FilesPickerBinding.inflate(layoutInflater) + setContentView(filesPickerBinding.root) } else { folderPickerBinding = FilesFolderPickerBinding.inflate(layoutInflater) - } - } - - private fun binding(): ViewBinding { - return if (this is FilePickerActivity) { - filesPickerBinding - } else { - folderPickerBinding + setContentView(folderPickerBinding.root) } } @@ -116,7 +102,6 @@ open class FolderPickerActivity : super.onCreate(savedInstanceState) initBinding() - setContentView(binding().root) initControls() setupToolbar() setupActionBar() @@ -158,15 +143,15 @@ open class FolderPickerActivity : mSearchOnlyFolders = true isDoNotEnterEncryptedFolder = true - mCopyBtn?.visibility = View.GONE - mMoveBtn?.visibility = View.GONE - mChooseBtn?.visibility = View.VISIBLE - - val chooseButtonSpacer = findViewById(R.id.choose_button_spacer) - val moveOrCopyButtonSpacer = findViewById(R.id.move_or_copy_button_spacer) - - chooseButtonSpacer.visibility = View.VISIBLE - moveOrCopyButtonSpacer.visibility = View.GONE + if (this is FilePickerActivity) { + filesPickerBinding.folderPickerBtnCancel.visibility = View.GONE + } else { + folderPickerBinding.folderPickerBtnCancel.visibility = View.GONE + folderPickerBinding.folderPickerBtnMove.visibility = View.GONE + folderPickerBinding.folderPickerBtnChoose.visibility = View.VISIBLE + folderPickerBinding.chooseButtonSpacer.visibility = View.VISIBLE + folderPickerBinding.moveOrCopyButtonSpacer.visibility = View.GONE + } } private fun handleOnBackPressed() { @@ -174,15 +159,15 @@ open class FolderPickerActivity : this, object : OnBackPressedCallback(true) { override fun handleOnBackPressed() { - val listOfFiles = listOfFilesFragment - if (listOfFiles != null) { - // should never be null, indeed - val levelsUp = listOfFiles.onBrowseUp() + listOfFilesFragment?.let { + val levelsUp = it.onBrowseUp() + if (levelsUp == 0) { finish() return } - file = listOfFiles.currentFile + + file = it.currentFile updateUiElements() } } @@ -192,19 +177,21 @@ open class FolderPickerActivity : override fun onActionModeStarted(mode: ActionMode) { super.onActionModeStarted(mode) - if (account != null) { - updateFileFromDB() - var folder = file - if (folder == null || !folder.isFolder) { - // fall back to root folder - file = storageManager.getFileByPath(OCFile.ROOT_PATH) - folder = file - } - val listOfFolders = listOfFilesFragment - listOfFolders!!.listDirectory(folder, false, false) - startSyncFolderOperation(folder, false) - updateUiElements() + + if (action == null) { + return + } + + updateFileFromDB() + var folder = file + if (folder == null || !folder.isFolder) { + file = storageManager.getFileByEncryptedRemotePath(OCFile.ROOT_PATH) + folder = file } + + listOfFilesFragment?.listDirectory(folder, false, false) + startSyncFolderOperation(folder, false) + updateUiElements() } private val activity: Activity @@ -212,12 +199,16 @@ open class FolderPickerActivity : protected open fun createFragments() { val listOfFiles = OCFileListFragment() - val args = Bundle() - args.putBoolean(OCFileListFragment.ARG_ONLY_FOLDERS_CLICKABLE, true) - args.putBoolean(OCFileListFragment.ARG_HIDE_FAB, true) - args.putBoolean(OCFileListFragment.ARG_HIDE_ITEM_OPTIONS, true) - args.putBoolean(OCFileListFragment.ARG_SEARCH_ONLY_FOLDER, mSearchOnlyFolders) - listOfFiles.arguments = args + + val bundle = Bundle().apply { + putBoolean(OCFileListFragment.ARG_ONLY_FOLDERS_CLICKABLE, true) + putBoolean(OCFileListFragment.ARG_HIDE_FAB, true) + putBoolean(OCFileListFragment.ARG_HIDE_ITEM_OPTIONS, true) + putBoolean(OCFileListFragment.ARG_SEARCH_ONLY_FOLDER, mSearchOnlyFolders) + } + + listOfFiles.arguments = bundle + val transaction = supportFragmentManager.beginTransaction() transaction.add(R.id.fragment_container, listOfFiles, TAG_LIST_OF_FOLDERS) transaction.commit() @@ -228,30 +219,35 @@ open class FolderPickerActivity : */ private fun setBackgroundText() { val listFragment = listOfFilesFragment - if (listFragment != null) { + + if (listFragment == null) { + Log_OC.e(TAG, "OCFileListFragment is null") + } + + listFragment?.let { if (!mSyncInProgress) { - listFragment.setMessageForEmptyList( + it.setMessageForEmptyList( R.string.folder_list_empty_headline, R.string.file_list_empty_moving, R.drawable.ic_list_empty_create_folder, true ) } else { - listFragment.setEmptyListLoadingMessage() + it.setEmptyListLoadingMessage() } - } else { - Log_OC.e(TAG, "OCFileListFragment is null") } } protected val listOfFilesFragment: OCFileListFragment? - protected get() { + get() { val listOfFiles = supportFragmentManager.findFragmentByTag(TAG_LIST_OF_FOLDERS) - if (listOfFiles != null) { + + return if (listOfFiles != null) { return listOfFiles as OCFileListFragment? + } else { + Log_OC.e(TAG, "Access to non existing list of files fragment!!") + null } - Log_OC.e(TAG, "Access to non existing list of files fragment!!") - return null } /** @@ -263,7 +259,6 @@ open class FolderPickerActivity : override fun onBrowsedDownTo(directory: OCFile) { file = directory updateUiElements() - // Sync Folder startSyncFolderOperation(directory, false) } @@ -275,8 +270,7 @@ open class FolderPickerActivity : val currentSyncTime = System.currentTimeMillis() mSyncInProgress = true - // perform folder synchronization - val refreshFolderOperation: RemoteOperation<*> = RefreshFolderOperation( + RefreshFolderOperation( folder, currentSyncTime, false, @@ -284,53 +278,62 @@ open class FolderPickerActivity : storageManager, user.orElseThrow { RuntimeException("User not set") }, applicationContext - ) - refreshFolderOperation.execute(account, this, null, null) - listOfFilesFragment!!.isLoading = true + ).also { + it.execute(account, this, null, null) + } + + listOfFilesFragment?.isLoading = true setBackgroundText() } override fun onResume() { super.onResume() Log_OC.e(TAG, "onResume() start") - listOfFilesFragment!!.isLoading = mSyncInProgress - // refresh list of files + listOfFilesFragment?.isLoading = mSyncInProgress refreshListOfFilesFragment(false) - file = listOfFilesFragment?.currentFile updateUiElements() - // Listen for sync messages - val syncIntentFilter = IntentFilter(FileSyncAdapter.EVENT_FULL_SYNC_START) - syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_END) - syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED) - syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED) - syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED) + val intentFilter = getSyncIntentFilter() mSyncBroadcastReceiver = SyncBroadcastReceiver() - localBroadcastManager.registerReceiver(mSyncBroadcastReceiver!!, syncIntentFilter) + mSyncBroadcastReceiver?.let { + localBroadcastManager.registerReceiver(it, intentFilter) + } + Log_OC.d(TAG, "onResume() end") } + private fun getSyncIntentFilter(): IntentFilter { + return IntentFilter(FileSyncAdapter.EVENT_FULL_SYNC_START).apply { + addAction(FileSyncAdapter.EVENT_FULL_SYNC_END) + addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED) + addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED) + addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED) + } + } + override fun onPause() { Log_OC.e(TAG, "onPause() start") + if (mSyncBroadcastReceiver != null) { localBroadcastManager.unregisterReceiver(mSyncBroadcastReceiver!!) mSyncBroadcastReceiver = null } + Log_OC.d(TAG, "onPause() end") super.onPause() } override fun onCreateOptionsMenu(menu: Menu): Boolean { - val inflater = menuInflater - inflater.inflate(R.menu.activity_folder_picker, menu) + menuInflater.inflate(R.menu.activity_folder_picker, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { var retval = true val itemId = item.itemId + if (itemId == R.id.action_create_dir) { val dialog = CreateFolderDialogFragment.newInstance(currentFolder) dialog.show(supportFragmentManager, CreateFolderDialogFragment.CREATE_FOLDER_FRAGMENT) @@ -342,6 +345,7 @@ open class FolderPickerActivity : } else { retval = super.onOptionsItemSelected(item) } + return retval } @@ -349,35 +353,31 @@ open class FolderPickerActivity : val currentFolder: OCFile? get() { val currentFile = file - var finalFolder: OCFile? = null val storageManager = storageManager - // If the file is null, take the root folder to avoid any error in functions depending on this one - if (currentFile != null) { + return if (currentFile != null) { if (currentFile.isFolder) { - finalFolder = currentFile + currentFile } else if (currentFile.remotePath != null) { val parentPath = File(currentFile.remotePath).parent - finalFolder = storageManager.getFileByPath(parentPath) + storageManager.getFileByEncryptedRemotePath(parentPath) + } else { + null } } else { - finalFolder = storageManager.getFileByPath(OCFile.ROOT_PATH) + storageManager.getFileByEncryptedRemotePath(OCFile.ROOT_PATH) } - return finalFolder } private fun refreshListOfFilesFragment(fromSearch: Boolean) { - val fileListFragment = listOfFilesFragment - fileListFragment?.listDirectory(false, fromSearch) + listOfFilesFragment?.listDirectory(false, fromSearch) } fun browseToRoot() { - val listOfFiles = listOfFilesFragment - if (listOfFiles != null) { - // should never be null, indeed - val root = storageManager.getFileByPath(OCFile.ROOT_PATH) - listOfFiles.listDirectory(root, false, false) - file = listOfFiles.currentFile + listOfFilesFragment?.let { + val root = storageManager.getFileByEncryptedRemotePath(OCFile.ROOT_PATH) + it.listDirectory(root, false, false) + file = it.currentFile updateUiElements() startSyncFolderOperation(root, false) } @@ -389,8 +389,12 @@ open class FolderPickerActivity : } private fun toggleChooseEnabled() { - mCopyBtn?.isEnabled = checkFolderSelectable() - mMoveBtn?.isEnabled = checkFolderSelectable() + if (this is FilePickerActivity) { + return + } else { + folderPickerBinding.folderPickerBtnCopy.isEnabled = checkFolderSelectable() + folderPickerBinding.folderPickerBtnMove.isEnabled = checkFolderSelectable() + } } // for copy and move, disable selecting parent folder of target files @@ -399,70 +403,57 @@ open class FolderPickerActivity : action != MOVE_OR_COPY -> true targetFilePaths.isNullOrEmpty() -> true file?.isFolder != true -> true + // all of the target files are already in the selected directory - targetFilePaths!!.all { PathUtils.isDirectParent(file.remotePath, it) } -> false + targetFilePaths?.all { PathUtils.isDirectParent(file.remotePath, it) } == true -> false + // some of the target files are parents of the selected folder - targetFilePaths!!.any { PathUtils.isAncestor(it, file.remotePath) } -> false + targetFilePaths?.any { PathUtils.isAncestor(it, file.remotePath) } == true -> false else -> true } } private fun updateNavigationElementsInActionBar() { val currentDir = currentFolder - val actionBar = supportActionBar - if (actionBar != null) { - val atRoot = currentDir == null || currentDir.parentId == 0L + supportActionBar?.let { actionBar -> + val atRoot = (currentDir == null || currentDir.parentId == 0L) actionBar.setDisplayHomeAsUpEnabled(!atRoot) actionBar.setHomeButtonEnabled(!atRoot) - val title = if (atRoot) captionText ?: "" else currentDir!!.fileName - viewThemeUtils.files.themeActionBar(this, actionBar, title) + val title = if (atRoot) captionText ?: "" else currentDir?.fileName + title?.let { + viewThemeUtils.files.themeActionBar(this, actionBar, title) + } } } - /** - * Set per-view controllers - */ private fun initControls() { - mCancelBtn = findViewById(R.id.folder_picker_btn_cancel) - mCopyBtn = findViewById(R.id.folder_picker_btn_copy) - mMoveBtn = findViewById(R.id.folder_picker_btn_move) - mChooseBtn = findViewById(R.id.folder_picker_btn_choose) - - mCopyBtn?.let { - viewThemeUtils.material.colorMaterialButtonPrimaryFilled(it) - it.setOnClickListener(this) - } - - mMoveBtn?.let { - viewThemeUtils.material.colorMaterialButtonPrimaryTonal(it) - it.setOnClickListener(this) - } + if (this is FilePickerActivity) { + viewThemeUtils.material.colorMaterialButtonPrimaryFilled(filesPickerBinding.folderPickerBtnCancel) + filesPickerBinding.folderPickerBtnCancel.setOnClickListener { finish() } + } else { + viewThemeUtils.material.colorMaterialButtonText(folderPickerBinding.folderPickerBtnCancel) + folderPickerBinding.folderPickerBtnCancel.setOnClickListener { finish() } - mChooseBtn?.let { - viewThemeUtils.material.colorMaterialButtonPrimaryTonal(it) - it.setOnClickListener(this) - } + viewThemeUtils.material.colorMaterialButtonPrimaryTonal(folderPickerBinding.folderPickerBtnChoose) + folderPickerBinding.folderPickerBtnChoose.setOnClickListener { processOperation(null) } - mCancelBtn?.let { - if (this is FilePickerActivity) { - viewThemeUtils.material.colorMaterialButtonPrimaryFilled(it) - } else { - viewThemeUtils.material.colorMaterialButtonText(it) + viewThemeUtils.material.colorMaterialButtonPrimaryFilled(folderPickerBinding.folderPickerBtnCopy) + folderPickerBinding.folderPickerBtnCopy.setOnClickListener { + processOperation( + OperationsService.ACTION_COPY_FILE + ) } - it.setOnClickListener(this) - } - } - - override fun onClick(v: View) { - when (v) { - mChooseBtn -> processOperation(v) - mCancelBtn -> finish() - mCopyBtn, mMoveBtn -> processOperation(v) + viewThemeUtils.material.colorMaterialButtonPrimaryTonal(folderPickerBinding.folderPickerBtnMove) + folderPickerBinding.folderPickerBtnMove.setOnClickListener { + processOperation( + OperationsService.ACTION_MOVE_FILE + ) + } } } - private fun processOperation(v: View) { + private fun processOperation(action: String?) { val i = intent val resultData = Intent() resultData.putExtra(EXTRA_FOLDER, listOfFilesFragment?.currentFile) @@ -471,28 +462,18 @@ open class FolderPickerActivity : resultData.putParcelableArrayListExtra(EXTRA_FILES, targetFiles) } - targetFilePaths?.let { - if (v == mCopyBtn || v == mMoveBtn) { - moveOrCopyFiles(v, it) + targetFilePaths?.let { filePaths -> + action?.let { action -> + fileOperationsHelper.moveOrCopyFiles(action, filePaths, file) } - resultData.putStringArrayListExtra(EXTRA_FILE_PATHS, it) + resultData.putStringArrayListExtra(EXTRA_FILE_PATHS, filePaths) } setResult(RESULT_OK, resultData) finish() } - private fun moveOrCopyFiles(v: View, filePathList: ArrayList) { - val action = if (v == mCopyBtn) { - OperationsService.ACTION_COPY_FILE - } else { - OperationsService.ACTION_MOVE_FILE - } - - fileOperationsHelper.moveOrCopyFiles(action, filePathList, file) - } - override fun onRemoteOperationFinish(operation: RemoteOperation<*>?, result: RemoteOperationResult<*>) { super.onRemoteOperationFinish(operation, result) if (operation is CreateFolderOperation) { @@ -526,10 +507,13 @@ open class FolderPickerActivity : } fun search(query: String?) { - val fileListFragment = listOfFilesFragment - fileListFragment?.onMessageEvent( + if (query == null) { + return + } + + listOfFilesFragment?.onMessageEvent( SearchEvent( - query!!, + query, SearchRemoteOperation.SearchType.FILE_SEARCH ) ) @@ -551,60 +535,45 @@ open class FolderPickerActivity : Log_OC.d(TAG, "Received broadcast $event") val accountName = intent.getStringExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME) val syncFolderRemotePath = intent.getStringExtra(FileSyncAdapter.EXTRA_FOLDER_PATH) + val syncResult = DataHolderUtil.getInstance() .retrieve(intent.getStringExtra(FileSyncAdapter.EXTRA_RESULT)) as RemoteOperationResult<*> - val sameAccount = account != null && accountName == account.name && storageManager != null - if (sameAccount) { - if (FileSyncAdapter.EVENT_FULL_SYNC_START == event) { - mSyncInProgress = true + val sameAccount = (account != null && accountName == account.name && storageManager != null) + + if (!sameAccount) { + return + } + + if (FileSyncAdapter.EVENT_FULL_SYNC_START == event) { + mSyncInProgress = true + } else { + var (currentFile, currentDir) = getCurrentFileAndDirectory() + + if (currentDir == null) { + browseRootForRemovedFolder() } else { - var currentFile = if (file == null) null else storageManager.getFileByPath(file.remotePath) - val currentDir = if (currentFolder == null) { - null - } else { - storageManager.getFileByPath( - currentFolder!!.remotePath - ) + if (currentFile == null && !file.isFolder) { + // currently selected file was removed in the server, and now we know it + currentFile = currentDir } - if (currentDir == null) { - // current folder was removed from the server - DisplayUtils.showSnackMessage( - activity, - R.string.sync_current_folder_was_removed, - currentFolder!!.fileName - ) - browseToRoot() - } else { - if (currentFile == null && !file.isFolder) { - // currently selected file was removed in the server, and now we know it - currentFile = currentDir - } - if (currentDir.remotePath == syncFolderRemotePath) { - val fileListFragment = listOfFilesFragment - fileListFragment?.listDirectory(currentDir, false, false) - } - file = currentFile - } - mSyncInProgress = FileSyncAdapter.EVENT_FULL_SYNC_END != event && - RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED != event - if (RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED == event && !syncResult.isSuccess - ) { - if (ResultCode.UNAUTHORIZED == syncResult.code || ( - syncResult.isException && - syncResult.exception is AuthenticatorException - ) - ) { - requestCredentialsUpdate(context) - } else if (ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED == syncResult.code) { - showUntrustedCertDialog(syncResult) - } + if (currentDir.remotePath == syncFolderRemotePath) { + listOfFilesFragment?.listDirectory(currentDir, false, false) } + file = currentFile } - DataHolderUtil.getInstance().delete(intent.getStringExtra(FileSyncAdapter.EXTRA_RESULT)) - Log_OC.d(TAG, "Setting progress visibility to $mSyncInProgress") - listOfFilesFragment!!.isLoading = mSyncInProgress - setBackgroundText() + + mSyncInProgress = ( + FileSyncAdapter.EVENT_FULL_SYNC_END != event && + RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED != event + ) + + checkCredentials(syncResult, context, event) } + + DataHolderUtil.getInstance().delete(intent.getStringExtra(FileSyncAdapter.EXTRA_RESULT)) + Log_OC.d(TAG, "Setting progress visibility to $mSyncInProgress") + listOfFilesFragment?.isLoading = mSyncInProgress + setBackgroundText() } catch (e: RuntimeException) { Log_OC.e(TAG, "Error on broadcast receiver", e) // avoid app crashes after changing the serial id of RemoteOperationResult @@ -612,6 +581,45 @@ open class FolderPickerActivity : DataHolderUtil.getInstance().delete(intent.getStringExtra(FileSyncAdapter.EXTRA_RESULT)) } } + + private fun getCurrentFileAndDirectory(): Pair { + val currentFile = + if (file == null) null else storageManager.getFileByEncryptedRemotePath(file.remotePath) + + val currentDir = if (currentFolder == null) { + null + } else { + storageManager.getFileByEncryptedRemotePath( + currentFolder?.remotePath + ) + } + + return Pair(currentFile, currentDir) + } + + private fun browseRootForRemovedFolder() { + DisplayUtils.showSnackMessage( + activity, + R.string.sync_current_folder_was_removed, + currentFolder?.fileName + ) + browseToRoot() + } + + private fun checkCredentials(syncResult: RemoteOperationResult<*>, context: Context, event: String?) { + if (RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED == event && !syncResult.isSuccess + ) { + if (ResultCode.UNAUTHORIZED == syncResult.code || ( + syncResult.isException && + syncResult.exception is AuthenticatorException + ) + ) { + requestCredentialsUpdate(context) + } else if (ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED == syncResult.code) { + showUntrustedCertDialog(syncResult) + } + } + } } override fun showDetails(file: OCFile) { @@ -638,10 +646,8 @@ open class FolderPickerActivity : } private fun refreshList(ignoreETag: Boolean) { - val listOfFiles = listOfFilesFragment - if (listOfFiles != null) { - val folder = listOfFiles.currentFile - folder?.let { startSyncFolderOperation(it, ignoreETag) } + listOfFilesFragment?.currentFile?.let { + startSyncFolderOperation(it, ignoreETag) } }