diff --git a/app/src/main/java/com/nextcloud/client/account/UserAccountManagerImpl.java b/app/src/main/java/com/nextcloud/client/account/UserAccountManagerImpl.java index 592b201810af..3a7f167709fd 100644 --- a/app/src/main/java/com/nextcloud/client/account/UserAccountManagerImpl.java +++ b/app/src/main/java/com/nextcloud/client/account/UserAccountManagerImpl.java @@ -66,8 +66,8 @@ public class UserAccountManagerImpl implements UserAccountManager { private static final String TAG = UserAccountManagerImpl.class.getSimpleName(); private static final String PREF_SELECT_OC_ACCOUNT = "select_oc_account"; - private Context context; - private AccountManager accountManager; + private final Context context; + private final AccountManager accountManager; public static UserAccountManagerImpl fromContext(Context context) { AccountManager am = (AccountManager)context.getSystemService(Context.ACCOUNT_SERVICE); @@ -166,7 +166,7 @@ public Account getCurrentAccount() { } } - if (defaultAccount == null && ocAccounts.length > 0) { + if (defaultAccount == null) { // take first which is not pending for removal account as fallback for (Account account: ocAccounts) { boolean pendingForRemoval = arbitraryDataProvider.getBooleanValue(account.name, @@ -262,7 +262,11 @@ public User getAnonymousUser() { public OwnCloudAccount getCurrentOwnCloudAccount() { try { Account currentPlatformAccount = getCurrentAccount(); - return new OwnCloudAccount(currentPlatformAccount, context); + if (currentPlatformAccount != null) { + return new OwnCloudAccount(currentPlatformAccount, context); + } else { + return null; + } } catch (AccountUtils.AccountNotFoundException | IllegalArgumentException ex) { return null; } diff --git a/app/src/main/java/com/owncloud/android/providers/FileContentProvider.java b/app/src/main/java/com/owncloud/android/providers/FileContentProvider.java index 3dea0102906c..233569884c23 100644 --- a/app/src/main/java/com/owncloud/android/providers/FileContentProvider.java +++ b/app/src/main/java/com/owncloud/android/providers/FileContentProvider.java @@ -262,23 +262,15 @@ public Uri insert(@NonNull Uri uri, ContentValues values) { private Uri insert(SupportSQLiteDatabase db, Uri uri, ContentValues values) { // verify only for those requests that are not internal (files table) switch (mUriMatcher.match(uri)) { - case ROOT_DIRECTORY: - case SINGLE_FILE: - case DIRECTORY: - VerificationUtils.verifyColumns(values); - break; + case ROOT_DIRECTORY, SINGLE_FILE, DIRECTORY -> VerificationUtils.verifyColumns(values); } - switch (mUriMatcher.match(uri)) { - case ROOT_DIRECTORY: - case SINGLE_FILE: + case ROOT_DIRECTORY, SINGLE_FILE -> { String where = ProviderTableMeta.FILE_PATH + "=? AND " + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?"; - String remotePath = values.getAsString(ProviderTableMeta.FILE_PATH); String accountName = values.getAsString(ProviderTableMeta.FILE_ACCOUNT_OWNER); String[] whereArgs = {remotePath, accountName}; - Cursor doubleCheck = query(db, uri, PROJECTION_FILE_PATH_AND_OWNER, where, whereArgs, null); // ugly patch; serious refactoring is needed to reduce work in // FileDataStorageManager and bring it to FileContentProvider @@ -295,13 +287,13 @@ private Uri insert(SupportSQLiteDatabase db, Uri uri, ContentValues values) { Uri insertedFileUri = ContentUris.withAppendedId( ProviderTableMeta.CONTENT_URI_FILE, doubleCheck.getLong(doubleCheck.getColumnIndexOrThrow(ProviderTableMeta._ID)) - ); + ); doubleCheck.close(); return insertedFileUri; } - - case SHARES: + } + case SHARES -> { Uri insertedShareUri; long idShares = db.insert(ProviderTableMeta.OCSHARES_TABLE_NAME, SQLiteDatabase.CONFLICT_REPLACE, values); if (idShares > 0) { @@ -311,10 +303,9 @@ private Uri insert(SupportSQLiteDatabase db, Uri uri, ContentValues values) { } updateFilesTableAccordingToShareInsertion(db, values); - return insertedShareUri; - - case CAPABILITIES: + } + case CAPABILITIES -> { Uri insertedCapUri; long idCapabilities = db.insert(ProviderTableMeta.CAPABILITIES_TABLE_NAME, SQLiteDatabase.CONFLICT_REPLACE, values); if (idCapabilities > 0) { @@ -323,8 +314,8 @@ private Uri insert(SupportSQLiteDatabase db, Uri uri, ContentValues values) { throw new SQLException(ERROR + uri); } return insertedCapUri; - - case UPLOADS: + } + case UPLOADS -> { Uri insertedUploadUri; long uploadId = db.insert(ProviderTableMeta.UPLOADS_TABLE_NAME, SQLiteDatabase.CONFLICT_REPLACE, values); if (uploadId > 0) { @@ -333,8 +324,8 @@ private Uri insert(SupportSQLiteDatabase db, Uri uri, ContentValues values) { throw new SQLException(ERROR + uri); } return insertedUploadUri; - - case SYNCED_FOLDERS: + } + case SYNCED_FOLDERS -> { Uri insertedSyncedFolderUri; long syncedFolderId = db.insert(ProviderTableMeta.SYNCED_FOLDERS_TABLE_NAME, SQLiteDatabase.CONFLICT_REPLACE, values); if (syncedFolderId > 0) { @@ -344,8 +335,8 @@ private Uri insert(SupportSQLiteDatabase db, Uri uri, ContentValues values) { throw new SQLException("ERROR " + uri); } return insertedSyncedFolderUri; - - case EXTERNAL_LINKS: + } + case EXTERNAL_LINKS -> { Uri insertedExternalLinkUri; long externalLinkId = db.insert(ProviderTableMeta.EXTERNAL_LINKS_TABLE_NAME, SQLiteDatabase.CONFLICT_REPLACE, values); if (externalLinkId > 0) { @@ -355,19 +346,18 @@ private Uri insert(SupportSQLiteDatabase db, Uri uri, ContentValues values) { throw new SQLException("ERROR " + uri); } return insertedExternalLinkUri; - - case VIRTUAL: + } + case VIRTUAL -> { Uri insertedVirtualUri; long virtualId = db.insert(ProviderTableMeta.VIRTUAL_TABLE_NAME, SQLiteDatabase.CONFLICT_REPLACE, values); - if (virtualId > 0) { insertedVirtualUri = ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_VIRTUAL, virtualId); } else { throw new SQLException("ERROR " + uri); } - return insertedVirtualUri; - case FILESYSTEM: + } + case FILESYSTEM -> { Uri insertedFilesystemUri; long filesystemId = db.insert(ProviderTableMeta.FILESYSTEM_TABLE_NAME, SQLiteDatabase.CONFLICT_REPLACE, values); if (filesystemId > 0) { @@ -377,8 +367,8 @@ private Uri insert(SupportSQLiteDatabase db, Uri uri, ContentValues values) { throw new SQLException("ERROR " + uri); } return insertedFilesystemUri; - default: - throw new IllegalArgumentException("Unknown uri id: " + uri); + } + default -> throw new IllegalArgumentException("Unknown uri id: " + uri); } } @@ -387,24 +377,12 @@ private void updateFilesTableAccordingToShareInsertion(SupportSQLiteDatabase db, ShareType newShareType = ShareType.fromValue(newShare.getAsInteger(ProviderTableMeta.OCSHARES_SHARE_TYPE)); switch (newShareType) { - case PUBLIC_LINK: - fileValues.put(ProviderTableMeta.FILE_SHARED_VIA_LINK, 1); - break; - - case USER: - case GROUP: - case EMAIL: - case FEDERATED: - case FEDERATED_GROUP: - case ROOM: - case CIRCLE: - case DECK: - case GUEST: + case PUBLIC_LINK -> fileValues.put(ProviderTableMeta.FILE_SHARED_VIA_LINK, 1); + case USER, GROUP, EMAIL, FEDERATED, FEDERATED_GROUP, ROOM, CIRCLE, DECK, GUEST -> fileValues.put(ProviderTableMeta.FILE_SHARED_WITH_SHAREE, 1); - break; - - default: - // everything should be handled + default -> { + } + // everything should be handled } String where = ProviderTableMeta.FILE_PATH + "=? AND " + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?"; diff --git a/app/src/main/java/com/owncloud/android/ui/activity/DrawerActivity.java b/app/src/main/java/com/owncloud/android/ui/activity/DrawerActivity.java index 2484b4d22a8e..ef6f6b191282 100644 --- a/app/src/main/java/com/owncloud/android/ui/activity/DrawerActivity.java +++ b/app/src/main/java/com/owncloud/android/ui/activity/DrawerActivity.java @@ -536,7 +536,7 @@ private void onNavigationItemClicked(final MenuItem menuItem) { MainApp.showOnlyFilesOnDevice(false); Intent intent = new Intent(getApplicationContext(), FileDisplayActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); - intent.setAction(FileDisplayActivity.LIST_GROUPFOLDERS); + intent.setAction(FileDisplayActivity.LIST_GROUP_FOLDERS); intent.putExtra(FileDisplayActivity.DRAWER_MENU_ID, menuItem.getItemId()); startActivity(intent); } else { diff --git a/app/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.java b/app/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.java index 16478cd5b628..fb22160552b5 100644 --- a/app/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.java +++ b/app/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.java @@ -142,8 +142,11 @@ import java.io.File; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; +import java.util.HashSet; import java.util.List; +import java.util.Set; import javax.inject.Inject; @@ -172,12 +175,10 @@ public class FileDisplayActivity extends FileActivity public static final String RESTART = "RESTART"; public static final String ALL_FILES = "ALL_FILES"; - public static final String LIST_GROUPFOLDERS = "LIST_GROUPFOLDERS"; - public static final String PHOTO_SEARCH = "PHOTO_SEARCH"; + public static final String LIST_GROUP_FOLDERS = "LIST_GROUPFOLDERS"; public static final int SINGLE_USER_SIZE = 1; public static final String OPEN_FILE = "NC_OPEN_FILE"; - private FilesBinding binding; private SyncBroadcastReceiver mSyncBroadcastReceiver; @@ -205,7 +206,6 @@ public class FileDisplayActivity extends FileActivity public static final int REQUEST_CODE__SELECT_FILES_FROM_FILE_SYSTEM = REQUEST_CODE__LAST_SHARED + 2; public static final int REQUEST_CODE__MOVE_OR_COPY_FILES = REQUEST_CODE__LAST_SHARED + 3; public static final int REQUEST_CODE__UPLOAD_FROM_CAMERA = REQUEST_CODE__LAST_SHARED + 5; - public static final int REQUEST_CODE__UPLOAD_SCAN_DOC_FROM_CAMERA = REQUEST_CODE__LAST_SHARED + 6; protected static final long DELAY_TO_REQUEST_REFRESH_OPERATION_LATER = DELAY_TO_REQUEST_OPERATIONS_LATER + 350; @@ -232,7 +232,6 @@ public class FileDisplayActivity extends FileActivity private SearchView searchView; private PlayerServiceConnection mPlayerConnection; private Optional lastDisplayedUser = Optional.empty(); - private int menuItemId = -1; @Inject AppPreferences preferences; @@ -448,12 +447,11 @@ private void checkOutdatedServer() { public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { - case PermissionUtil.PERMISSIONS_POST_NOTIFICATIONS: + case PermissionUtil.PERMISSIONS_POST_NOTIFICATIONS -> // handle notification permission on API level >= 33 // dialogue was dismissed -> prompt for storage permissions PermissionUtil.requestExternalStoragePermission(this, viewThemeUtils); - break; - case PermissionUtil.PERMISSIONS_EXTERNAL_STORAGE: + case PermissionUtil.PERMISSIONS_EXTERNAL_STORAGE -> { // If request is cancelled, result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { @@ -462,17 +460,16 @@ public void onRequestPermissionsResult(int requestCode, @NonNull String[] permis syncAndUpdateFolder(true); // toggle on is save since this is the only scenario this code gets accessed } - break; - case PermissionUtil.PERMISSIONS_CAMERA: + } + case PermissionUtil.PERMISSIONS_CAMERA -> { // If request is cancelled, result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permission was granted getFileOperationsHelper() .uploadFromCamera(this, FileDisplayActivity.REQUEST_CODE__UPLOAD_FROM_CAMERA); } - break; - default: - super.onRequestPermissionsResult(requestCode, permissions, grantResults); + } + default -> super.onRequestPermissionsResult(requestCode, permissions, grantResults); } } @@ -522,6 +519,7 @@ private void initFragments() { } // Is called with the flag FLAG_ACTIVITY_SINGLE_TOP and set the new file and intent + @SuppressLint("UnsafeIntentLaunch") @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); @@ -577,7 +575,7 @@ protected void onNewIntent(Intent intent) { setLeftFragment(new OCFileListFragment()); getSupportFragmentManager().executePendingTransactions(); browseToRoot(); - } else if (LIST_GROUPFOLDERS.equals(intent.getAction())) { + } else if (LIST_GROUP_FOLDERS.equals(intent.getAction())) { Log_OC.d(this, "Switch to list groupfolders fragment"); setLeftFragment(new GroupfolderListFragment()); @@ -620,11 +618,7 @@ private void setLeftFragment(Fragment fragment) { transaction.replace(R.id.left_fragment_container, fragment, TAG_LIST_OF_FILES); transaction.commit(); - if (fragment instanceof UnifiedSearchFragment || fragment instanceof PreviewMediaFragment) { - showSortListGroup(false); - } else { - showSortListGroup(true); - } + showSortListGroup(!(fragment instanceof UnifiedSearchFragment) && !(fragment instanceof PreviewMediaFragment)); } @@ -669,10 +663,9 @@ public void resetSearchView() { protected void refreshDetailsFragmentIfVisible(String downloadEvent, String downloadedRemotePath, boolean success) { Fragment leftFragment = getLeftFragment(); - if (leftFragment instanceof FileDetailFragment) { + if (leftFragment instanceof FileDetailFragment detailsFragment) { boolean waitedPreview = mWaitingToPreview != null && mWaitingToPreview.getRemotePath().equals(downloadedRemotePath); - FileDetailFragment detailsFragment = (FileDetailFragment) leftFragment; OCFile fileInFragment = detailsFragment.getFile(); if (fileInFragment != null && !downloadedRemotePath.equals(fileInFragment.getRemotePath())) { @@ -764,7 +757,11 @@ public boolean onCreateOptionsMenu(Menu menu) { if (TextUtils.isEmpty(searchView.getQuery().toString())) { searchView.onActionViewCollapsed(); setDrawerIndicatorEnabled(isDrawerIndicatorAvailable()); // order matters - getSupportActionBar().setDisplayHomeAsUpEnabled(true); + + if (getSupportActionBar() != null) { + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + } + mDrawerToggle.syncState(); OCFileListFragment ocFileListFragment = getListOfFilesFragment(); @@ -840,24 +837,28 @@ public boolean onOptionsItemSelected(MenuItem item) { */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { + Set resultCodesForUploadFromApps = new HashSet<>(Arrays.asList( + RESULT_OK, + UploadFilesActivity.RESULT_OK_AND_MOVE)); - if (requestCode == REQUEST_CODE__SELECT_CONTENT_FROM_APPS && - (resultCode == RESULT_OK || - resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) { + Set resultCodesForUploadFromFileSystem = new HashSet<>(Arrays.asList( + RESULT_OK, + UploadFilesActivity.RESULT_OK_AND_MOVE, + UploadFilesActivity.RESULT_OK_AND_DO_NOTHING, + UploadFilesActivity.RESULT_OK_AND_DELETE)); - requestUploadOfContentFromApps(data, resultCode); + Set resultCodesForUploadFromCamera = new HashSet<>(Arrays.asList( + RESULT_OK, + UploadFilesActivity.RESULT_OK_AND_DELETE)); + if (requestCode == REQUEST_CODE__SELECT_CONTENT_FROM_APPS && + resultCodesForUploadFromApps.contains(resultCode)) { + requestUploadOfContentFromApps(data, resultCode); } else if (requestCode == REQUEST_CODE__SELECT_FILES_FROM_FILE_SYSTEM && - (resultCode == RESULT_OK || - resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE || - resultCode == UploadFilesActivity.RESULT_OK_AND_DO_NOTHING || - resultCode == UploadFilesActivity.RESULT_OK_AND_DELETE)) { - + resultCodesForUploadFromFileSystem.contains(resultCode)) { requestUploadOfFilesFromFileSystem(data, resultCode); - } else if (requestCode == REQUEST_CODE__UPLOAD_FROM_CAMERA && - (resultCode == RESULT_OK || resultCode == UploadFilesActivity.RESULT_OK_AND_DELETE)) { - + resultCodesForUploadFromCamera.contains(resultCode)) { new CheckAvailableSpaceTask(new CheckAvailableSpaceTask.CheckAvailableSpaceListener() { @Override public void onCheckAvailableSpaceStart() { @@ -882,10 +883,10 @@ public void onCheckAvailableSpaceFinish(boolean hasEnoughSpaceAvailable, String. FileUploader.LOCAL_BEHAVIOUR_DELETE); } } - }, new String[] { FileOperationsHelper.createImageFile(getActivity()).getAbsolutePath() }).execute(); + }, new String[]{FileOperationsHelper.createImageFile(getActivity()).getAbsolutePath()}).execute(); } else if (requestCode == REQUEST_CODE__MOVE_OR_COPY_FILES && resultCode == RESULT_OK) { exitSelectionMode(); - } else if (requestCode == PermissionUtil.REQUEST_CODE_MANAGE_ALL_FILES) { + } else if (requestCode == PermissionUtil.REQUEST_CODE_MANAGE_ALL_FILES && resultCode == RESULT_OK) { syncAndUpdateFolder(true); } else { super.onActivityResult(requestCode, resultCode, data); @@ -918,24 +919,11 @@ private void requestUploadOfFilesFromFileSystem(String localBasePath, String[] f remotePaths[j] = remotePathBase + relativePath; } - int behaviour; - switch (resultCode) { - case UploadFilesActivity.RESULT_OK_AND_MOVE: - behaviour = FileUploader.LOCAL_BEHAVIOUR_MOVE; - break; - - case UploadFilesActivity.RESULT_OK_AND_DELETE: - behaviour = FileUploader.LOCAL_BEHAVIOUR_DELETE; - break; - - case UploadFilesActivity.RESULT_OK_AND_DO_NOTHING: - behaviour = FileUploader.LOCAL_BEHAVIOUR_FORGET; - break; - - default: - behaviour = FileUploader.LOCAL_BEHAVIOUR_FORGET; - break; - } + int behaviour = switch (resultCode) { + case UploadFilesActivity.RESULT_OK_AND_MOVE -> FileUploader.LOCAL_BEHAVIOUR_MOVE; + case UploadFilesActivity.RESULT_OK_AND_DELETE -> FileUploader.LOCAL_BEHAVIOUR_DELETE; + default -> FileUploader.LOCAL_BEHAVIOUR_FORGET; + }; FileUploader.uploadNewFile( this, @@ -948,8 +936,7 @@ private void requestUploadOfFilesFromFileSystem(String localBasePath, String[] f UploadFileOperation.CREATED_BY_USER, false, false, - NameCollisionPolicy.ASK_USER - ); + NameCollisionPolicy.ASK_USER); } else { Log_OC.d(TAG, "User clicked on 'Update' with no selection"); @@ -1015,8 +1002,7 @@ public void onBackPressed() { final Fragment leftFragment = getLeftFragment(); - if (leftFragment instanceof OCFileListFragment) { - OCFileListFragment listOfFiles = (OCFileListFragment) leftFragment; + if (leftFragment instanceof OCFileListFragment listOfFiles) { if (isSearchOpen && searchView != null) { searchView.setQuery("", true); @@ -1068,7 +1054,7 @@ protected void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW, mWaitingToPreview); outState.putBoolean(FileDisplayActivity.KEY_SYNC_IN_PROGRESS, mSyncInProgress); - //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, + // outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, // mRefreshSharesInProgress); outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_SEND, mWaitingToSend); if (searchView != null) { @@ -1091,15 +1077,13 @@ protected void onResume() { initSyncBroadcastReceiver(); } - if (!(leftFragment instanceof OCFileListFragment)) { + if (!(leftFragment instanceof OCFileListFragment ocFileListFragment)) { if (leftFragment instanceof FileFragment) { super.updateActionBarTitleAndHomeButton(((FileFragment) leftFragment).getFile()); } return; } - OCFileListFragment ocFileListFragment = (OCFileListFragment) leftFragment; - ocFileListFragment.setLoading(mSyncInProgress); syncAndUpdateFolder(false, true); @@ -1132,7 +1116,7 @@ protected void onResume() { localBroadcastManager.registerReceiver(mDownloadFinishReceiver, downloadIntentFilter); // setup drawer - menuItemId = getIntent().getIntExtra(FileDisplayActivity.DRAWER_MENU_ID, -1); + int menuItemId = getIntent().getIntExtra(FileDisplayActivity.DRAWER_MENU_ID, -1); if (menuItemId == -1) { setDrawerAllFiles(); @@ -1179,6 +1163,7 @@ public void initSyncBroadcastReceiver() { @Override protected void onPause() { Log_OC.v(TAG, "onPause() start"); + if (mSyncBroadcastReceiver != null) { localBroadcastManager.unregisterReceiver(mSyncBroadcastReceiver); mSyncBroadcastReceiver = null; @@ -1222,9 +1207,9 @@ public void onReceive(Context context, Intent intent) { Log_OC.d(TAG, "Received broadcast " + event); String accountName = intent.getStringExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME); - String synchFolderRemotePath = + String syncFolderRemotePath = intent.getStringExtra(FileSyncAdapter.EXTRA_FOLDER_PATH); - RemoteOperationResult synchResult = (RemoteOperationResult) + RemoteOperationResult syncResult = (RemoteOperationResult) DataHolderUtil.getInstance().retrieve(intent.getStringExtra(FileSyncAdapter.EXTRA_RESULT)); boolean sameAccount = getAccount() != null && accountName.equals(getAccount().name) && getStorageManager() != null; @@ -1236,17 +1221,16 @@ public void onReceive(Context context, Intent intent) { } else { OCFile currentFile = (getFile() == null) ? null : - getStorageManager().getFileByPath(getFile().getRemotePath()); + getStorageManager().getFileByEncryptedRemotePath(getFile().getRemotePath()); OCFile currentDir = (getCurrentDir() == null) ? null : - getStorageManager().getFileByPath(getCurrentDir().getRemotePath()); + getStorageManager().getFileByEncryptedRemotePath(getCurrentDir().getRemotePath()); if (currentDir == null) { // current folder was removed from the server DisplayUtils.showSnackMessage( getActivity(), R.string.sync_current_folder_was_removed, - synchFolderRemotePath - ); + syncFolderRemotePath); browseToRoot(); @@ -1258,7 +1242,7 @@ public void onReceive(Context context, Intent intent) { currentFile = currentDir; } - if (currentDir.getRemotePath().equals(synchFolderRemotePath)) { + if (currentDir.getRemotePath().equals(syncFolderRemotePath)) { OCFileListFragment fileListFragment = getListOfFilesFragment(); if (fileListFragment != null) { fileListFragment.listDirectory(currentDir, MainApp.isOnlyOnDevice(), false); @@ -1271,35 +1255,22 @@ public void onReceive(Context context, Intent intent) { !RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED.equals(event); if (RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED.equals(event) && - synchResult != null) { + syncResult != null) { - if (synchResult.isSuccess()) { + if (syncResult.isSuccess()) { hideInfoBox(); } else { // TODO refactor and make common - if (checkForRemoteOperationError(synchResult)) { + if (checkForRemoteOperationError(syncResult)) { requestCredentialsUpdate(context); } else { - switch (synchResult.getCode()) { - case SSL_RECOVERABLE_PEER_UNVERIFIED: - showUntrustedCertDialog(synchResult); - break; - - case MAINTENANCE_MODE: - showInfoBox(R.string.maintenance_mode); - break; - - case NO_NETWORK_CONNECTION: - showInfoBox(R.string.offline_mode); - break; - - case HOST_NOT_AVAILABLE: - showInfoBox(R.string.host_not_available); - break; - - default: - // nothing to do - break; + switch (syncResult.getCode()) { + case SSL_RECOVERABLE_PEER_UNVERIFIED -> showUntrustedCertDialog(syncResult); + case MAINTENANCE_MODE -> showInfoBox(R.string.maintenance_mode); + case NO_NETWORK_CONNECTION -> showInfoBox(R.string.offline_mode); + case HOST_NOT_AVAILABLE -> showInfoBox(R.string.host_not_available); + default -> { + } } } } @@ -1325,8 +1296,8 @@ public void onReceive(Context context, Intent intent) { } } - if (synchResult != null && synchResult.getCode() == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) { - mLastSslUntrustedServerResult = synchResult; + if (syncResult != null && syncResult.getCode() == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) { + mLastSslUntrustedServerResult = syncResult; } } catch (RuntimeException e) { // avoid app crashes after changing the serial id of RemoteOperationResult @@ -1410,7 +1381,7 @@ public void onReceive(Context context, Intent intent) { if (sameAccount && sameFile && details instanceof FileDetailFragment) { if (uploadWasFine) { - setFile(getStorageManager().getFileByPath(uploadedRemotePath)); + setFile(getStorageManager().getFileByEncryptedRemotePath(uploadedRemotePath)); } else { //TODO remove upload progress bar after upload failed. Log_OC.d(TAG, "Remove upload progress bar after upload failed"); @@ -1420,8 +1391,7 @@ public void onReceive(Context context, Intent intent) { DisplayUtils.showSnackMessage( getActivity(), R.string.filedetails_renamed_in_upload_msg, - newName - ); + newName); } if (uploadWasFine || getFile().fileExists()) { ((FileDetailFragment) details).updateFileDetails(false, true); @@ -1523,7 +1493,7 @@ private boolean isSameAccount(Intent intent) { public void browseToRoot() { OCFileListFragment listOfFiles = getListOfFilesFragment(); if (listOfFiles != null) { // should never be null, indeed - OCFile root = getStorageManager().getFileByPath(OCFile.ROOT_PATH); + OCFile root = getStorageManager().getFileByEncryptedRemotePath(OCFile.ROOT_PATH); listOfFiles.listDirectory(root, MainApp.isOnlyOnDevice(), false); setFile(listOfFiles.getCurrentFile()); startSyncFolderOperation(root, false); @@ -1642,8 +1612,7 @@ public void onServiceConnected(ComponentName component, IBinder service) { listOfFiles.listDirectory(MainApp.isOnlyOnDevice(), false); } Fragment leftFragment = getLeftFragment(); - if (leftFragment instanceof FileDetailFragment) { - FileDetailFragment detailFragment = (FileDetailFragment) leftFragment; + if (leftFragment instanceof FileDetailFragment detailFragment) { detailFragment.listenForTransferProgress(); detailFragment.updateFileDetails(false, false); } @@ -1694,12 +1663,11 @@ private void refreshShowDetails() { if (details instanceof FileFragment) { OCFile file = ((FileFragment) details).getFile(); if (file != null) { - file = getStorageManager().getFileByPath(file.getRemotePath()); + file = getStorageManager().getFileByEncryptedRemotePath(file.getRemotePath()); + if (details instanceof PreviewMediaFragment) { - // Refresh OCFile of the fragment ((PreviewMediaFragment) details).updateFile(file); } else if (details instanceof PreviewTextFragment) { - // Refresh OCFile of the fragment ((PreviewTextFileFragment) details).updateFile(file); } else { showDetails(file); @@ -1772,8 +1740,7 @@ private void onRestoreFileVersionOperationFinish(RemoteOperationResult result) { startSyncFolderOperation(parent, true, true); Fragment leftFragment = getLeftFragment(); - if (leftFragment instanceof FileDetailFragment) { - FileDetailFragment fileDetailFragment = (FileDetailFragment) leftFragment; + if (leftFragment instanceof FileDetailFragment fileDetailFragment) { fileDetailFragment.getFileDetailActivitiesFragment().reload(); } @@ -1846,8 +1813,7 @@ private void onRenameFileOperationFinish(RenameFileOperation operation, if (result.isSuccess() && optionalUser.isPresent()) { final User currentUser = optionalUser.get(); Fragment leftFragment = getLeftFragment(); - if (leftFragment instanceof FileFragment) { - final FileFragment fileFragment = (FileFragment) leftFragment; + if (leftFragment instanceof final FileFragment fileFragment) { if (fileFragment instanceof FileDetailFragment && renamedFile.equals(fileFragment.getFile())) { ((FileDetailFragment) fileFragment).updateFileDetails(renamedFile, currentUser); @@ -2254,7 +2220,7 @@ public void startDownloadForPreview(OCFile file, OCFile parentFolder) { * Opens EditImageActivity with given file loaded. If file is not available locally, it will be synced before * opening the image editor. * - * @param file {@link OCFile} (image) to be loaded into image editor + * @param file {@link OCFile} (image) to be loaded into image editor */ public void startImageEditor(OCFile file) { if (file.isDown()) { @@ -2263,7 +2229,7 @@ public void startImageEditor(OCFile file) { startActivity(editImageIntent); } else { mWaitingToPreview = file; - requestForDownload(file,EditImageActivity.OPEN_IMAGE_EDITOR, getPackageName(), + requestForDownload(file, EditImageActivity.OPEN_IMAGE_EDITOR, getPackageName(), this.getClass().getSimpleName()); updateActionBarTitleAndHomeButton(file); setFile(file); @@ -2349,6 +2315,7 @@ public void onMessageEvent(final SearchEvent event) { } } + // Do not delete these functions @Subscribe(threadMode = ThreadMode.MAIN) public void onMessageEvent(SyncEventFinished event) { Bundle bundle = event.getIntent().getExtras(); @@ -2386,24 +2353,27 @@ public void onStart() { // current Account OCFile file = getFile(); // get parent from path - String parentPath = ""; if (file != null) { if (file.isDown() && file.getLastSyncDateForProperties() == 0) { // upload in progress - right now, files are not inserted in the local // cache until the upload is successful get parent from path - parentPath = file.getRemotePath().substring(0, - file.getRemotePath().lastIndexOf(file.getFileName())); - if (storageManager.getFileByPath(parentPath) == null) { + // Retrieve the full remote path of the file. + + String fullRemotePath = file.getRemotePath(); + int fileNameIndex = fullRemotePath.lastIndexOf(file.getFileName()); + String parentPath = fullRemotePath.substring(0, fileNameIndex); + + if (storageManager.getFileByEncryptedRemotePath(parentPath) == null) { file = null; // not able to know the directory where the file is uploading } } else { - file = storageManager.getFileByPath(file.getRemotePath()); + file = storageManager.getFileByEncryptedRemotePath(file.getRemotePath()); // currentDir = null if not in the current Account } } if (file == null) { // fall back to root folder - file = storageManager.getFileByPath(OCFile.ROOT_PATH); // never returns null + file = storageManager.getFileByEncryptedRemotePath(OCFile.ROOT_PATH); // never returns null } setFile(file); @@ -2591,7 +2561,8 @@ public void showFile(String message) { dismissLoadingDialog(); final Fragment leftFragment = getLeftFragment(); - OCFileListFragment listOfFiles = null; + OCFileListFragment listOfFiles; + if (leftFragment instanceof OCFileListFragment) { listOfFiles = (OCFileListFragment) leftFragment; } else {