From a7eb7148fa0ceb42981366eb2ddcf0ff921e6a55 Mon Sep 17 00:00:00 2001 From: Chris Narkiewicz Date: Mon, 18 Nov 2019 19:08:54 +0000 Subject: [PATCH 1/2] Migrate simple cases of getCurrentAccount() to getUser() Migrate trivially convertible uses of getCurrentAccount() to new user model - getUser(). Signed-off-by: Chris Narkiewicz --- .../nextcloud/client/account/AnonymousUser.kt | 1 + .../client/account/RegisteredUser.kt | 1 + .../java/com/nextcloud/client/account/User.kt | 1 + .../client/account/UserAccountManager.java | 14 +++ .../com/nextcloud/client/di/AppModule.java | 5 +- .../client/network/ClientFactory.java | 22 ++++ .../client/network/ClientFactoryImpl.java | 13 ++ .../preferences/AppPreferencesImpl.java | 42 +++---- .../authentication/AuthenticatorActivity.java | 5 +- .../datamodel/FileDataStorageManager.java | 12 +- .../DiskLruImageCacheFileProvider.java | 5 +- .../UsersAndGroupsSearchProvider.java | 15 ++- .../ui/activities/ActivitiesActivity.java | 3 +- .../activities/ActivitiesServiceApiImpl.java | 8 +- .../data/files/FilesServiceApiImpl.java | 52 +++----- .../android/ui/activity/BaseActivity.java | 17 ++- .../android/ui/activity/DrawerActivity.java | 74 ++++++----- .../ui/activity/FileDisplayActivity.java | 18 ++- .../ui/activity/ManageAccountsActivity.java | 10 +- .../ui/activity/NotificationsActivity.java | 53 ++++---- .../ui/activity/RichDocumentsWebView.java | 8 +- .../android/ui/activity/SettingsActivity.java | 26 ++-- .../ui/activity/SyncedFoldersActivity.java | 23 ++-- .../ui/activity/UploadListActivity.java | 8 +- .../ui/adapter/ActivityListAdapter.java | 15 ++- .../android/ui/adapter/TemplateAdapter.java | 9 +- .../ui/adapter/TrashbinListAdapter.java | 12 +- .../ui/asynctasks/PhotoSearchTask.java | 10 +- .../dialog/ChooseTemplateDialogFragment.java | 15 ++- .../ui/fragment/ExtendedListFragment.java | 4 +- .../FileDetailActivitiesFragment.java | 30 ++--- .../ui/fragment/OCFileListFragment.java | 54 +++----- .../android/ui/fragment/PhotoFragment.java | 2 +- .../contactsbackup/ContactListFragment.java | 10 +- .../ui/helpers/FileOperationsHelper.java | 13 +- .../ui/preview/PreviewImageActivity.java | 5 +- .../ui/trashbin/RemoteTrashbinRepository.java | 115 +++++++++++------- .../android/ui/trashbin/TrashbinActivity.java | 21 ++-- .../owncloud/android/utils/DisplayUtils.java | 8 +- .../utils/glide/CustomGlideStreamLoader.java | 7 +- .../utils/glide/CustomGlideUriLoader.java | 7 +- .../utils/glide/HttpStreamFetcher.java | 18 +-- src/main/res/values/strings.xml | 3 - 43 files changed, 445 insertions(+), 349 deletions(-) diff --git a/src/main/java/com/nextcloud/client/account/AnonymousUser.kt b/src/main/java/com/nextcloud/client/account/AnonymousUser.kt index d949cf5bf393..ec2a284e2cbc 100644 --- a/src/main/java/com/nextcloud/client/account/AnonymousUser.kt +++ b/src/main/java/com/nextcloud/client/account/AnonymousUser.kt @@ -46,6 +46,7 @@ internal class AnonymousUser(private val accountType: String) : User { override val accountName: String = "anonymous" override val server = Server(URI.create(""), MainApp.MINIMUM_SUPPORTED_SERVER_VERSION) + override val isAnonymous = true override fun toPlatformAccount(): Account { return Account(accountName, accountType) diff --git a/src/main/java/com/nextcloud/client/account/RegisteredUser.kt b/src/main/java/com/nextcloud/client/account/RegisteredUser.kt index 7a8a5f6314ab..4ba956552137 100644 --- a/src/main/java/com/nextcloud/client/account/RegisteredUser.kt +++ b/src/main/java/com/nextcloud/client/account/RegisteredUser.kt @@ -31,6 +31,7 @@ internal class RegisteredUser( private val ownCloudAccount: OwnCloudAccount, override val server: Server ) : User { + override val isAnonymous = false override val accountName: String get() { return account.name diff --git a/src/main/java/com/nextcloud/client/account/User.kt b/src/main/java/com/nextcloud/client/account/User.kt index 408797d07965..0500d8358a9a 100644 --- a/src/main/java/com/nextcloud/client/account/User.kt +++ b/src/main/java/com/nextcloud/client/account/User.kt @@ -26,6 +26,7 @@ import com.owncloud.android.lib.common.OwnCloudAccount interface User { val accountName: String val server: Server + val isAnonymous: Boolean /** * This is temporary helper method created to facilitate incremental refactoring. diff --git a/src/main/java/com/nextcloud/client/account/UserAccountManager.java b/src/main/java/com/nextcloud/client/account/UserAccountManager.java index 0b217073e24c..d4394423a564 100644 --- a/src/main/java/com/nextcloud/client/account/UserAccountManager.java +++ b/src/main/java/com/nextcloud/client/account/UserAccountManager.java @@ -97,10 +97,24 @@ public interface UserAccountManager extends CurrentAccountProvider { * @return Version of the OC server corresponding to account, according to the data saved * in the system AccountManager */ + @Deprecated @NonNull OwnCloudVersion getServerVersion(Account account); + @Deprecated boolean isSearchSupported(@Nullable Account account); + + /** + * Check if user's account supports media streaming. This is a property of server where user has his account. + * + * @deprecated Please use {@link OwnCloudVersion#isMediaStreamingSupported()} directly, + * obtainable from {@link User#getServer()} and {@link Server#getVersion()} + * + * @param account Account used to perform {@link android.accounts.AccountManager} lookup. + * + * @return true is server supports media streaming, false otherwise + */ + @Deprecated boolean isMediaStreamingSupported(@Nullable Account account); void resetOwnCloudAccount(); diff --git a/src/main/java/com/nextcloud/client/di/AppModule.java b/src/main/java/com/nextcloud/client/di/AppModule.java index f9199705240c..64c96123b448 100644 --- a/src/main/java/com/nextcloud/client/di/AppModule.java +++ b/src/main/java/com/nextcloud/client/di/AppModule.java @@ -41,6 +41,7 @@ import com.nextcloud.client.logger.Logger; import com.nextcloud.client.logger.LoggerImpl; import com.nextcloud.client.logger.LogsRepository; +import com.nextcloud.client.network.ClientFactory; import com.owncloud.android.datamodel.ArbitraryDataProvider; import com.owncloud.android.datamodel.UploadsStorageManager; import com.owncloud.android.ui.activities.data.activities.ActivitiesRepository; @@ -106,8 +107,8 @@ ActivitiesRepository activitiesRepository(ActivitiesServiceApi api) { } @Provides - FilesRepository filesRepository(UserAccountManager accountManager) { - return new RemoteFilesRepository(new FilesServiceApiImpl(accountManager)); + FilesRepository filesRepository(UserAccountManager accountManager, ClientFactory clientFactory) { + return new RemoteFilesRepository(new FilesServiceApiImpl(accountManager, clientFactory)); } @Provides diff --git a/src/main/java/com/nextcloud/client/network/ClientFactory.java b/src/main/java/com/nextcloud/client/network/ClientFactory.java index affbb34c79bc..9f8694bab25f 100644 --- a/src/main/java/com/nextcloud/client/network/ClientFactory.java +++ b/src/main/java/com/nextcloud/client/network/ClientFactory.java @@ -26,6 +26,7 @@ import android.app.Activity; import android.net.Uri; +import com.nextcloud.client.account.User; import com.owncloud.android.lib.common.OwnCloudClient; import com.owncloud.android.lib.common.accounts.AccountUtils; @@ -35,10 +36,31 @@ public interface ClientFactory { + /** + * This exception wraps all possible errors thrown by trigger-happy + * OwnCloudClient constructor, making try-catch blocks manageable. + * + * This is a temporary refactoring measure, until a better + * error handling method can be procured. + */ + @Deprecated + class CreationException extends Exception { + + private static final long serialVersionUID = 0L; + + CreationException(Throwable t) { + super(t); + } + } + + OwnCloudClient create(User user) throws CreationException; + + @Deprecated OwnCloudClient create(Account account) throws OperationCanceledException, AuthenticatorException, IOException, AccountUtils.AccountNotFoundException; + @Deprecated OwnCloudClient create(Account account, Activity currentActivity) throws OperationCanceledException, AuthenticatorException, IOException, AccountUtils.AccountNotFoundException; diff --git a/src/main/java/com/nextcloud/client/network/ClientFactoryImpl.java b/src/main/java/com/nextcloud/client/network/ClientFactoryImpl.java index 467d98ebc0b6..ff88a8487f9b 100644 --- a/src/main/java/com/nextcloud/client/network/ClientFactoryImpl.java +++ b/src/main/java/com/nextcloud/client/network/ClientFactoryImpl.java @@ -27,6 +27,7 @@ import android.content.Context; import android.net.Uri; +import com.nextcloud.client.account.User; import com.owncloud.android.lib.common.OwnCloudClient; import com.owncloud.android.lib.common.OwnCloudClientFactory; import com.owncloud.android.lib.common.accounts.AccountUtils; @@ -41,6 +42,18 @@ class ClientFactoryImpl implements ClientFactory { this.context = context; } + @Override + public OwnCloudClient create(User user) throws CreationException { + try { + return OwnCloudClientFactory.createOwnCloudClient(user.toPlatformAccount(), context); + } catch (OperationCanceledException| + AuthenticatorException| + IOException| + AccountUtils.AccountNotFoundException e) { + throw new CreationException(e); + } + } + @Override public OwnCloudClient create(Account account) throws OperationCanceledException, AuthenticatorException, IOException, diff --git a/src/main/java/com/nextcloud/client/preferences/AppPreferencesImpl.java b/src/main/java/com/nextcloud/client/preferences/AppPreferencesImpl.java index 1ac83f887386..60867fabf047 100644 --- a/src/main/java/com/nextcloud/client/preferences/AppPreferencesImpl.java +++ b/src/main/java/com/nextcloud/client/preferences/AppPreferencesImpl.java @@ -27,6 +27,7 @@ import android.content.SharedPreferences; import com.nextcloud.client.account.CurrentAccountProvider; +import com.nextcloud.client.account.User; import com.nextcloud.client.account.UserAccountManagerImpl; import com.owncloud.android.datamodel.ArbitraryDataProvider; import com.owncloud.android.datamodel.FileDataStorageManager; @@ -282,7 +283,7 @@ public boolean isFingerprintUnlockEnabled() { @Override public String getFolderLayout(OCFile folder) { return getFolderPreference(context, - currentAccountProvider.getCurrentAccount(), + currentAccountProvider.getUser(), PREF__FOLDER_LAYOUT, folder, FOLDER_LAYOUT_LIST); @@ -291,7 +292,7 @@ public String getFolderLayout(OCFile folder) { @Override public void setFolderLayout(OCFile folder, String layout_name) { setFolderPreference(context, - currentAccountProvider.getCurrentAccount(), + currentAccountProvider.getUser(), PREF__FOLDER_LAYOUT, folder, layout_name); @@ -300,7 +301,7 @@ public void setFolderLayout(OCFile folder, String layout_name) { @Override public FileSortOrder getSortOrderByFolder(OCFile folder) { return FileSortOrder.sortOrders.get(getFolderPreference(context, - currentAccountProvider.getCurrentAccount(), + currentAccountProvider.getUser(), PREF__FOLDER_SORT_ORDER, folder, FileSortOrder.sort_a_to_z.name)); @@ -309,7 +310,7 @@ public FileSortOrder getSortOrderByFolder(OCFile folder) { @Override public void setSortOrder(OCFile folder, FileSortOrder sortOrder) { setFolderPreference(context, - currentAccountProvider.getCurrentAccount(), + currentAccountProvider.getUser(), PREF__FOLDER_SORT_ORDER, folder, sortOrder.name); @@ -322,28 +323,23 @@ public FileSortOrder getSortOrderByType(FileSortOrder.Type type) { @Override public FileSortOrder getSortOrderByType(FileSortOrder.Type type, FileSortOrder defaultOrder) { - Account account = currentAccountProvider.getCurrentAccount(); - if (account == null) { + User user = currentAccountProvider.getUser(); + if (user.isAnonymous()) { return defaultOrder; } ArbitraryDataProvider dataProvider = new ArbitraryDataProvider(context.getContentResolver()); - String value = dataProvider.getValue(account.name, PREF__FOLDER_SORT_ORDER + "_" + type); + String value = dataProvider.getValue(user.getAccountName(), PREF__FOLDER_SORT_ORDER + "_" + type); return value.isEmpty() ? defaultOrder : FileSortOrder.sortOrders.get(value); } @Override public void setSortOrder(FileSortOrder.Type type, FileSortOrder sortOrder) { - Account account = currentAccountProvider.getCurrentAccount(); - - if (account == null) { - throw new IllegalArgumentException("Account may not be null!"); - } - + User user = currentAccountProvider.getUser(); ArbitraryDataProvider dataProvider = new ArbitraryDataProvider(context.getContentResolver()); - dataProvider.storeOrUpdateKeyValue(account.name, PREF__FOLDER_SORT_ORDER + "_" + type, sortOrder.name); + dataProvider.storeOrUpdateKeyValue(user.getAccountName(), PREF__FOLDER_SORT_ORDER + "_" + type, sortOrder.name); } @Override @@ -576,22 +572,22 @@ public long getPhotoSearchTimestamp() { * @return Preference value */ private static String getFolderPreference(final Context context, - final Account account, + final User user, final String preferenceName, final OCFile folder, final String defaultValue) { - if (account == null) { + if (user.isAnonymous()) { return defaultValue; } ArbitraryDataProvider dataProvider = new ArbitraryDataProvider(context.getContentResolver()); - FileDataStorageManager storageManager = new FileDataStorageManager(account, context.getContentResolver()); + FileDataStorageManager storageManager = new FileDataStorageManager(user.toPlatformAccount(), context.getContentResolver()); - String value = dataProvider.getValue(account.name, getKeyFromFolder(preferenceName, folder)); + String value = dataProvider.getValue(user.getAccountName(), getKeyFromFolder(preferenceName, folder)); OCFile prefFolder = folder; while (prefFolder != null && value.isEmpty()) { prefFolder = storageManager.getFileById(prefFolder.getParentId()); - value = dataProvider.getValue(account.name, getKeyFromFolder(preferenceName, prefFolder)); + value = dataProvider.getValue(user.getAccountName(), getKeyFromFolder(preferenceName, prefFolder)); } return value.isEmpty() ? defaultValue : value; } @@ -605,16 +601,12 @@ private static String getFolderPreference(final Context context, * @param value Preference value to set. */ private static void setFolderPreference(final Context context, - final Account account, + final User user, final String preferenceName, final OCFile folder, final String value) { - if (account == null) { - throw new IllegalArgumentException("Account may not be null!"); - } - ArbitraryDataProvider dataProvider = new ArbitraryDataProvider(context.getContentResolver()); - dataProvider.storeOrUpdateKeyValue(account.name, getKeyFromFolder(preferenceName, folder), value); + dataProvider.storeOrUpdateKeyValue(user.getAccountName(), getKeyFromFolder(preferenceName, folder), value); } private static String getKeyFromFolder(String preferenceName, OCFile folder) { diff --git a/src/main/java/com/owncloud/android/authentication/AuthenticatorActivity.java b/src/main/java/com/owncloud/android/authentication/AuthenticatorActivity.java index a83d1bb7a919..de9551e416b8 100644 --- a/src/main/java/com/owncloud/android/authentication/AuthenticatorActivity.java +++ b/src/main/java/com/owncloud/android/authentication/AuthenticatorActivity.java @@ -92,6 +92,7 @@ import com.blikoon.qrcodescanner.QrCodeActivity; import com.google.android.material.snackbar.Snackbar; +import com.nextcloud.client.account.User; import com.nextcloud.client.account.UserAccountManager; import com.nextcloud.client.device.DeviceInfo; import com.nextcloud.client.di.Injectable; @@ -1735,8 +1736,8 @@ protected boolean createAccount(RemoteOperationResult authResult) { } /// add the new account as default in preferences, if there is none already - Account defaultAccount = accountManager.getCurrentAccount(); - if (defaultAccount == null) { + User defaultAccount = accountManager.getUser(); + if (defaultAccount.isAnonymous()) { SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit(); editor.putString("select_oc_account", accountName); editor.apply(); diff --git a/src/main/java/com/owncloud/android/datamodel/FileDataStorageManager.java b/src/main/java/com/owncloud/android/datamodel/FileDataStorageManager.java index aca96b5ff3f4..28bd0e5411ba 100644 --- a/src/main/java/com/owncloud/android/datamodel/FileDataStorageManager.java +++ b/src/main/java/com/owncloud/android/datamodel/FileDataStorageManager.java @@ -1259,8 +1259,8 @@ private OCShare createShareInstance(Cursor c) { private void resetShareFlagsInAllFiles() { ContentValues cv = new ContentValues(); - cv.put(ProviderTableMeta.FILE_SHARED_VIA_LINK, false); - cv.put(ProviderTableMeta.FILE_SHARED_WITH_SHAREE, false); + cv.put(ProviderTableMeta.FILE_SHARED_VIA_LINK, Boolean.FALSE); + cv.put(ProviderTableMeta.FILE_SHARED_WITH_SHAREE, Boolean.FALSE); cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, ""); String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?"; String[] whereArgs = new String[]{account.name}; @@ -1279,8 +1279,8 @@ private void resetShareFlagsInAllFiles() { private void resetShareFlagsInFolder(OCFile folder) { ContentValues cv = new ContentValues(); - cv.put(ProviderTableMeta.FILE_SHARED_VIA_LINK, false); - cv.put(ProviderTableMeta.FILE_SHARED_WITH_SHAREE, false); + cv.put(ProviderTableMeta.FILE_SHARED_VIA_LINK, Boolean.FALSE); + cv.put(ProviderTableMeta.FILE_SHARED_WITH_SHAREE, Boolean.FALSE); cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, ""); String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + AND + ProviderTableMeta.FILE_PARENT + "=?"; String[] whereArgs = new String[]{account.name, String.valueOf(folder.getFileId())}; @@ -1299,8 +1299,8 @@ private void resetShareFlagsInFolder(OCFile folder) { private void resetShareFlagInAFile(String filePath) { ContentValues cv = new ContentValues(); - cv.put(ProviderTableMeta.FILE_SHARED_VIA_LINK, false); - cv.put(ProviderTableMeta.FILE_SHARED_WITH_SHAREE, false); + cv.put(ProviderTableMeta.FILE_SHARED_VIA_LINK, Boolean.FALSE); + cv.put(ProviderTableMeta.FILE_SHARED_WITH_SHAREE, Boolean.FALSE); cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, ""); String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + AND + ProviderTableMeta.FILE_PATH + "=?"; String[] whereArgs = new String[]{account.name, filePath}; diff --git a/src/main/java/com/owncloud/android/providers/DiskLruImageCacheFileProvider.java b/src/main/java/com/owncloud/android/providers/DiskLruImageCacheFileProvider.java index 0c17aeb4df87..cf398a425cbf 100644 --- a/src/main/java/com/owncloud/android/providers/DiskLruImageCacheFileProvider.java +++ b/src/main/java/com/owncloud/android/providers/DiskLruImageCacheFileProvider.java @@ -31,6 +31,7 @@ import android.os.ParcelFileDescriptor; import android.provider.OpenableColumns; +import com.nextcloud.client.account.User; import com.nextcloud.client.account.UserAccountManager; import com.owncloud.android.MainApp; import com.owncloud.android.datamodel.FileDataStorageManager; @@ -61,8 +62,8 @@ public boolean onCreate() { } private OCFile getFile(Uri uri) { - Account account = accountManager.getCurrentAccount(); - FileDataStorageManager fileDataStorageManager = new FileDataStorageManager(account, + User user = accountManager.getUser(); + FileDataStorageManager fileDataStorageManager = new FileDataStorageManager(user.toPlatformAccount(), MainApp.getAppContext().getContentResolver()); return fileDataStorageManager.getFileByPath(uri.getPath()); diff --git a/src/main/java/com/owncloud/android/providers/UsersAndGroupsSearchProvider.java b/src/main/java/com/owncloud/android/providers/UsersAndGroupsSearchProvider.java index acc79b695ade..0daa551ab90a 100644 --- a/src/main/java/com/owncloud/android/providers/UsersAndGroupsSearchProvider.java +++ b/src/main/java/com/owncloud/android/providers/UsersAndGroupsSearchProvider.java @@ -34,6 +34,7 @@ import android.provider.BaseColumns; import android.widget.Toast; +import com.nextcloud.client.account.User; import com.nextcloud.client.account.UserAccountManager; import com.owncloud.android.R; import com.owncloud.android.datamodel.FileDataStorageManager; @@ -180,18 +181,14 @@ private Cursor searchForUsersOrGroups(Uri uri) { // need to trust on the AccountUtils to get the current account since the query in the client side is not // directly started by our code, but from SearchView implementation - Account account = accountManager.getCurrentAccount(); - - if (account == null) { - throw new IllegalArgumentException("Account may not be null!"); - } + User user = accountManager.getUser(); String userQuery = lastPathSegment.toLowerCase(Locale.ROOT); // request to the OC server about users and groups matching userQuery GetShareesRemoteOperation searchRequest = new GetShareesRemoteOperation(userQuery, REQUESTED_PAGE, RESULTS_PER_PAGE); - RemoteOperationResult result = searchRequest.execute(account, getContext()); + RemoteOperationResult result = searchRequest.execute(user.toPlatformAccount(), getContext()); List names = new ArrayList<>(); if (result.isSuccess()) { @@ -217,8 +214,10 @@ private Cursor searchForUsersOrGroups(Uri uri) { Uri remoteBaseUri = new Uri.Builder().scheme(CONTENT).authority(DATA_REMOTE).build(); Uri emailBaseUri = new Uri.Builder().scheme(CONTENT).authority(DATA_EMAIL).build(); - FileDataStorageManager manager = new FileDataStorageManager(account, getContext().getContentResolver()); - boolean federatedShareAllowed = manager.getCapability(account.name).getFilesSharingFederationOutgoing() + FileDataStorageManager manager = new FileDataStorageManager(user.toPlatformAccount(), + getContext().getContentResolver()); + boolean federatedShareAllowed = manager.getCapability(user.getAccountName()) + .getFilesSharingFederationOutgoing() .isTrue(); try { diff --git a/src/main/java/com/owncloud/android/ui/activities/ActivitiesActivity.java b/src/main/java/com/owncloud/android/ui/activities/ActivitiesActivity.java index 7d06866c6ef9..4c36bce115b8 100644 --- a/src/main/java/com/owncloud/android/ui/activities/ActivitiesActivity.java +++ b/src/main/java/com/owncloud/android/ui/activities/ActivitiesActivity.java @@ -169,7 +169,8 @@ private void setupContent() { PorterDuff.Mode.SRC_IN); FileDataStorageManager storageManager = new FileDataStorageManager(getAccount(), getContentResolver()); - adapter = new ActivityListAdapter(this, getUserAccountManager(), this, storageManager, getCapabilities(), false); + adapter = new ActivityListAdapter(this, getUserAccountManager(), this, storageManager, + getCapabilities(), false); recyclerView.setAdapter(adapter); LinearLayoutManager layoutManager = new LinearLayoutManager(this); diff --git a/src/main/java/com/owncloud/android/ui/activities/data/activities/ActivitiesServiceApiImpl.java b/src/main/java/com/owncloud/android/ui/activities/data/activities/ActivitiesServiceApiImpl.java index 450fbcc9cc40..360c2458881e 100644 --- a/src/main/java/com/owncloud/android/ui/activities/data/activities/ActivitiesServiceApiImpl.java +++ b/src/main/java/com/owncloud/android/ui/activities/data/activities/ActivitiesServiceApiImpl.java @@ -28,6 +28,7 @@ import android.content.Context; import android.os.AsyncTask; +import com.nextcloud.client.account.User; import com.nextcloud.client.account.UserAccountManager; import com.owncloud.android.MainApp; import com.owncloud.android.R; @@ -58,8 +59,11 @@ public ActivitiesServiceApiImpl(UserAccountManager accountManager) { @Override public void getAllActivities(int lastGiven, ActivitiesServiceCallback> callback) { - Account account = accountManager.getCurrentAccount(); - GetActivityListTask getActivityListTask = new GetActivityListTask(account, accountManager, lastGiven, callback); + User user = accountManager.getUser(); + GetActivityListTask getActivityListTask = new GetActivityListTask(user.toPlatformAccount(), + accountManager, + lastGiven, + callback); getActivityListTask.execute(); } diff --git a/src/main/java/com/owncloud/android/ui/activities/data/files/FilesServiceApiImpl.java b/src/main/java/com/owncloud/android/ui/activities/data/files/FilesServiceApiImpl.java index 892d05a4cf25..8492a0751a4f 100644 --- a/src/main/java/com/owncloud/android/ui/activities/data/files/FilesServiceApiImpl.java +++ b/src/main/java/com/owncloud/android/ui/activities/data/files/FilesServiceApiImpl.java @@ -22,19 +22,16 @@ */ package com.owncloud.android.ui.activities.data.files; -import android.accounts.Account; -import android.accounts.AuthenticatorException; -import android.accounts.OperationCanceledException; import android.content.Context; import android.os.AsyncTask; +import com.nextcloud.client.account.User; import com.nextcloud.client.account.UserAccountManager; +import com.nextcloud.client.network.ClientFactory; import com.owncloud.android.MainApp; import com.owncloud.android.R; import com.owncloud.android.datamodel.OCFile; -import com.owncloud.android.lib.common.OwnCloudAccount; import com.owncloud.android.lib.common.OwnCloudClient; -import com.owncloud.android.lib.common.OwnCloudClientManagerFactory; import com.owncloud.android.lib.common.operations.RemoteOperation; import com.owncloud.android.lib.common.operations.RemoteOperationResult; import com.owncloud.android.lib.common.utils.Log_OC; @@ -44,8 +41,6 @@ import com.owncloud.android.ui.activity.BaseActivity; import com.owncloud.android.utils.FileStorageUtils; -import java.io.IOException; - /** * Implementation of the Files service API that communicates with the NextCloud remote server. */ @@ -54,15 +49,18 @@ public class FilesServiceApiImpl implements FilesServiceApi { private static final String TAG = FilesServiceApiImpl.class.getSimpleName(); private UserAccountManager accountManager; + private ClientFactory clientFactory; - public FilesServiceApiImpl(UserAccountManager accountManager) { + public FilesServiceApiImpl(UserAccountManager accountManager, ClientFactory clientFactory) { this.accountManager = accountManager; + this.clientFactory = clientFactory; } @Override public void readRemoteFile(String fileUrl, BaseActivity activity, FilesServiceCallback callback) { ReadRemoteFileTask readRemoteFileTask = new ReadRemoteFileTask( accountManager, + clientFactory, fileUrl, activity, callback @@ -77,30 +75,29 @@ private static class ReadRemoteFileTask extends AsyncTask // TODO: Figure out a better way to do this than passing a BaseActivity reference. private final BaseActivity baseActivity; private final String fileUrl; - private final Account account; + private final User user; private final UserAccountManager accountManager; + private final ClientFactory clientFactory; private ReadRemoteFileTask(UserAccountManager accountManager, + ClientFactory clientFactory, String fileUrl, BaseActivity baseActivity, FilesServiceCallback callback) { this.callback = callback; this.baseActivity = baseActivity; this.fileUrl = fileUrl; - this.account = accountManager.getCurrentAccount(); + this.user = accountManager.getUser(); this.accountManager = accountManager; + this.clientFactory = clientFactory; } @Override protected Boolean doInBackground(Void... voids) { final Context context = MainApp.getAppContext(); - OwnCloudAccount ocAccount; - OwnCloudClient ownCloudClient; try { - ocAccount = new OwnCloudAccount(account, context); - ownCloudClient = OwnCloudClientManagerFactory.getDefaultSingleton(). - getClientFor(ocAccount, MainApp.getAppContext()); - ownCloudClient.setOwnCloudVersion(accountManager.getServerVersion(account)); + OwnCloudClient ownCloudClient = clientFactory.create(user); + ownCloudClient.setOwnCloudVersion(user.getServer().getVersion()); // always update file as it could be an old state saved in database RemoteOperationResult resultRemoteFileOp = new ReadFileRemoteOperation(fileUrl).execute(ownCloudClient); @@ -111,28 +108,19 @@ protected Boolean doInBackground(Void... voids) { if (remoteOcFile.isFolder()) { // perform folder synchronization RemoteOperation synchFolderOp = new RefreshFolderOperation(remoteOcFile, - System.currentTimeMillis(), - false, - true, - baseActivity.getStorageManager(), - baseActivity.getAccount(), - context); + System.currentTimeMillis(), + false, + true, + baseActivity.getStorageManager(), + baseActivity.getAccount(), + context); synchFolderOp.execute(ownCloudClient); } } return true; - } catch (com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException e) { + } catch (ClientFactory.CreationException e) { Log_OC.e(TAG, "Account not found", e); errorMessage = baseActivity.getString(R.string.account_not_found); - } catch (IOException e) { - Log_OC.e(TAG, "IO error", e); - errorMessage = baseActivity.getString(R.string.io_error); - } catch (OperationCanceledException e) { - Log_OC.e(TAG, "Operation has been canceled", e); - errorMessage = baseActivity.getString(R.string.operation_canceled); - } catch (AuthenticatorException e) { - Log_OC.e(TAG, "Authentication Exception", e); - errorMessage = baseActivity.getString(R.string.authentication_exception); } return false; diff --git a/src/main/java/com/owncloud/android/ui/activity/BaseActivity.java b/src/main/java/com/owncloud/android/ui/activity/BaseActivity.java index 92cda745b2cd..327bb103873d 100644 --- a/src/main/java/com/owncloud/android/ui/activity/BaseActivity.java +++ b/src/main/java/com/owncloud/android/ui/activity/BaseActivity.java @@ -6,17 +6,16 @@ import android.accounts.AccountManagerFuture; import android.accounts.OperationCanceledException; import android.content.Intent; -import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.os.PersistableBundle; +import com.nextcloud.client.account.User; import com.nextcloud.client.account.UserAccountManager; import com.nextcloud.client.di.Injectable; import com.nextcloud.client.preferences.AppPreferences; -import com.nextcloud.client.preferences.AppPreferencesImpl; +import com.nextcloud.java.util.Optional; import com.owncloud.android.MainApp; -import com.owncloud.android.R; import com.owncloud.android.datamodel.FileDataStorageManager; import com.owncloud.android.datamodel.OCFile; import com.owncloud.android.lib.common.utils.Log_OC; @@ -161,6 +160,10 @@ protected void setAccount(Account account, boolean savedAccount) { } } + protected void setUser(User user) { + setAccount(user.toPlatformAccount(), false); + } + /** * Tries to swap the current ownCloud {@link Account} for other valid and existing. * @@ -215,6 +218,14 @@ public OCCapability getCapabilities() { public Account getAccount() { return currentAccount; } + + public Optional getUser() { + if (currentAccount != null) { + return accountManager.getUser(currentAccount.name); + } else { + return Optional.empty(); + } + } public FileDataStorageManager getStorageManager() { return storageManager; diff --git a/src/main/java/com/owncloud/android/ui/activity/DrawerActivity.java b/src/main/java/com/owncloud/android/ui/activity/DrawerActivity.java index 18e368137ae6..5984380b1f6a 100644 --- a/src/main/java/com/owncloud/android/ui/activity/DrawerActivity.java +++ b/src/main/java/com/owncloud/android/ui/activity/DrawerActivity.java @@ -56,8 +56,10 @@ import com.bumptech.glide.request.animation.GlideAnimation; import com.bumptech.glide.request.target.SimpleTarget; import com.google.android.material.navigation.NavigationView; +import com.nextcloud.client.account.User; import com.nextcloud.client.account.UserAccountManager; import com.nextcloud.client.di.Injectable; +import com.nextcloud.client.network.ClientFactory; import com.nextcloud.client.onboarding.FirstRunActivity; import com.nextcloud.client.preferences.AppPreferences; import com.owncloud.android.MainApp; @@ -217,6 +219,9 @@ public abstract class DrawerActivity extends ToolbarActivity @Inject AppPreferences preferences; + @Inject + ClientFactory clientFactory; + /** * Initializes the drawer, its content and highlights the menu item with the given id. * This method needs to be called after the content view has been set. @@ -357,21 +362,19 @@ public void run() { navigationView.getMenu().setGroupVisible(R.id.drawer_menu_accounts, false); } - Account account = accountManager.getCurrentAccount(); + User account = accountManager.getUser(); filterDrawerMenu(navigationView.getMenu(), account); } - private void filterDrawerMenu(Menu menu, Account account) { - OCCapability capability = null; - if (account != null) { - FileDataStorageManager storageManager = new FileDataStorageManager(account, getContentResolver()); - capability = storageManager.getCapability(account.name); - } + private void filterDrawerMenu(final Menu menu, @NonNull final User user) { + FileDataStorageManager storageManager = new FileDataStorageManager(user.toPlatformAccount(), + getContentResolver()); + OCCapability capability = storageManager.getCapability(user.getAccountName()); - boolean hasSearchSupport = accountManager.getServerVersion(account).isSearchSupported(); + boolean hasSearchSupport = user.getServer().getVersion().isSearchSupported(); - DrawerMenuUtil.filterSearchMenuItems(menu, account, getResources(), hasSearchSupport); - DrawerMenuUtil.filterTrashbinMenuItem(menu, account, capability, accountManager); + DrawerMenuUtil.filterSearchMenuItems(menu, user.toPlatformAccount(), getResources(), hasSearchSupport); + DrawerMenuUtil.filterTrashbinMenuItem(menu, user.toPlatformAccount(), capability, accountManager); DrawerMenuUtil.filterActivityMenuItem(menu, capability); DrawerMenuUtil.setupHomeMenuItem(menu, getResources()); @@ -685,7 +688,7 @@ public void updateAccountList() { if (mNavigationView != null && mDrawerLayout != null) { if (persistingAccounts.size() > 0) { repopulateAccountList(persistingAccounts); - setAccountInDrawer(accountManager.getCurrentAccount()); + setAccountInDrawer(accountManager.getUser()); populateDrawerOwnCloudAccounts(); // activate second/end account avatar @@ -791,30 +794,25 @@ protected void updateActionBarTitleAndHomeButton(OCFile chosenFile) { * sets the given account name in the drawer in case the drawer is available. The account name is shortened * beginning from the @-sign in the username. * - * @param account the account to be set in the drawer + * @param user the account to be set in the drawer */ - protected void setAccountInDrawer(Account account) { - if (mDrawerLayout != null && account != null) { + protected void setAccountInDrawer(User user) { + if (mDrawerLayout != null && user != null) { TextView username = (TextView) findNavigationViewChildById(R.id.drawer_username); TextView usernameFull = (TextView) findNavigationViewChildById(R.id.drawer_username_full); - usernameFull.setText(DisplayUtils.convertIdn(account.name.substring(account.name.lastIndexOf('@') + 1), + String name = user.getAccountName(); + usernameFull.setText(DisplayUtils.convertIdn(name.substring(name.lastIndexOf('@') + 1), false)); usernameFull.setTextColor(ThemeUtils.fontColor(this)); - try { - OwnCloudAccount oca = new OwnCloudAccount(account, this); - username.setText(oca.getDisplayName()); - username.setTextColor(ThemeUtils.fontColor(this)); - } catch (com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException e) { - Log_OC.w(TAG, "Couldn't read display name of account fallback to account name"); - username.setText(UserAccountManager.getUsername(account)); - } + username.setText(user.toOwnCloudAccount().getDisplayName()); + username.setTextColor(ThemeUtils.fontColor(this)); View currentAccountView = findNavigationViewChildById(R.id.drawer_current_account); - currentAccountView.setTag(account.name); + currentAccountView.setTag(name); - DisplayUtils.setAvatar(account, this, mCurrentAccountAvatarRadiusDimension, getResources(), + DisplayUtils.setAvatar(user.toPlatformAccount(), this, mCurrentAccountAvatarRadiusDimension, getResources(), currentAccountView, this); // check and show quota info if available @@ -958,6 +956,7 @@ public void onLoadFailed(Exception e, Drawable errorDrawable) { }; DisplayUtils.downloadIcon(getUserAccountManager(), + clientFactory, this, firstQuota.iconUrl, target, @@ -1024,14 +1023,14 @@ private void getAndDisplayUserQuota() { // set user space information Thread t = new Thread(new Runnable() { public void run() { - final Account currentAccount = accountManager.getCurrentAccount(); + final User user = accountManager.getUser(); - if (currentAccount == null) { + if (user.isAnonymous()) { return; } final Context context = MainApp.getAppContext(); - RemoteOperationResult result = new GetUserInfoRemoteOperation().execute(currentAccount, context); + RemoteOperationResult result = new GetUserInfoRemoteOperation().execute(user.toPlatformAccount(), context); if (result.isSuccess() && result.getData() != null) { final UserInfo userInfo = (UserInfo) result.getData().get(0); @@ -1101,6 +1100,7 @@ public void onLoadFailed(Exception e, Drawable errorDrawable) { }; DisplayUtils.downloadIcon(getUserAccountManager(), + clientFactory, this, link.iconUrl, target, @@ -1375,12 +1375,11 @@ private void populateDrawerOwnCloudAccounts() { } } - Account currentAccount = accountManager.getCurrentAccount(); - - mAvatars[0] = currentAccount; + User user = accountManager.getUser(); + mAvatars[0] = user.toPlatformAccount(); int j = 0; for (int i = 1; i <= 2 && i < persistingAccounts.size() && j < persistingAccounts.size(); j++) { - if (!currentAccount.equals(persistingAccounts.get(j))) { + if (!user.equals(persistingAccounts.get(j))) { mAvatars[i] = persistingAccounts.get(j); i++; } @@ -1462,11 +1461,10 @@ && getStorageManager() != null) { getCapabilities.execute(getStorageManager(), getBaseContext()); } - Account account = accountManager.getCurrentAccount(); - - if (account != null && getStorageManager() != null && - getStorageManager().getCapability(account.name) != null && - getStorageManager().getCapability(account.name).getExternalLinks().isTrue()) { + User user = accountManager.getUser(); + String name = user.getAccountName(); + if (getStorageManager() != null && getStorageManager().getCapability(name) != null && + getStorageManager().getCapability(name).getExternalLinks().isTrue()) { int count = arbitraryDataProvider.getIntegerValue(FilesSyncHelper.GLOBAL, FileActivity.APP_OPENED_COUNT); @@ -1481,7 +1479,7 @@ && getStorageManager() != null) { Log_OC.d("ExternalLinks", "update via api"); RemoteOperation getExternalLinksOperation = new ExternalLinksOperation(); - RemoteOperationResult result = getExternalLinksOperation.execute(account, this); + RemoteOperationResult result = getExternalLinksOperation.execute(user.toPlatformAccount(), this); if (result.isSuccess() && result.getData() != null) { externalLinksProvider.deleteAllExternalLinks(); diff --git a/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.java b/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.java index f083396db1a3..84df7e4fd4db 100644 --- a/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.java +++ b/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.java @@ -54,11 +54,13 @@ import android.view.ViewTreeObserver; import com.google.android.material.snackbar.Snackbar; +import com.nextcloud.client.account.User; import com.nextcloud.client.appinfo.AppInfo; import com.nextcloud.client.di.Injectable; import com.nextcloud.client.media.PlayerServiceConnection; import com.nextcloud.client.network.ConnectivityService; import com.nextcloud.client.preferences.AppPreferences; +import com.nextcloud.java.util.Optional; import com.owncloud.android.MainApp; import com.owncloud.android.R; import com.owncloud.android.datamodel.FileDataStorageManager; @@ -2545,8 +2547,8 @@ public void onMessageEvent(TokenPushEvent event) { @Override public void onStart() { super.onStart(); - final Account account = getAccount(); - if (account != null) { + Optional optionalUser = getUser(); + if (optionalUser.isPresent()) { /// Check whether the 'main' OCFile handled by the Activity is contained in the // current Account OCFile file = getFile(); @@ -2572,10 +2574,12 @@ public void onStart() { } setFile(file); - setAccountInDrawer(account); + User user = optionalUser.get(); + setAccountInDrawer(user); setupDrawer(); - final boolean accountChanged = !account.equals(mLastDisplayedAccount); + final String lastDisplayedAccountName = mLastDisplayedAccount != null ? mLastDisplayedAccount.name : null; + final boolean accountChanged = !user.getAccountName().equals(lastDisplayedAccountName); if (accountChanged) { Log_OC.d(TAG, "Initializing Fragments in onAccountChanged.."); initFragmentsWithFile(); @@ -2587,7 +2591,11 @@ public void onStart() { updateActionBarTitleAndHomeButton(file.isFolder() ? null : file); } } - mLastDisplayedAccount = account; + if (optionalUser.isPresent()) { + mLastDisplayedAccount = optionalUser.get().toPlatformAccount(); + } else { + mLastDisplayedAccount = null; + } EventBus.getDefault().post(new TokenPushEvent()); checkForNewDevVersionNecessary(findViewById(R.id.root_layout), getApplicationContext()); diff --git a/src/main/java/com/owncloud/android/ui/activity/ManageAccountsActivity.java b/src/main/java/com/owncloud/android/ui/activity/ManageAccountsActivity.java index 4108c000735e..531f448900e7 100644 --- a/src/main/java/com/owncloud/android/ui/activity/ManageAccountsActivity.java +++ b/src/main/java/com/owncloud/android/ui/activity/ManageAccountsActivity.java @@ -38,6 +38,7 @@ import com.evernote.android.job.JobRequest; import com.evernote.android.job.util.support.PersistableBundleCompat; +import com.nextcloud.client.account.User; import com.nextcloud.client.account.UserAccountManager; import com.nextcloud.client.onboarding.FirstRunActivity; import com.owncloud.android.MainApp; @@ -198,11 +199,11 @@ private boolean hasAccountListChanged() { * @return true if account list has changed, false if not */ private boolean hasCurrentAccountChanged() { - Account account = getUserAccountManager().getCurrentAccount(); - if (account == null) { + User account = getUserAccountManager().getUser(); + if (account.isAnonymous()) { return true; } else { - return !account.name.equals(originalCurrentAccount); + return !account.getAccountName().equals(originalCurrentAccount); } } @@ -320,7 +321,8 @@ public void run(AccountManagerFuture future) { } } - if (getUserAccountManager().getCurrentAccount() == null) { + User user = getUserAccountManager().getUser(); + if (user.isAnonymous()) { String accountName = ""; Account[] accounts = AccountManager.get(this).getAccountsByType(MainApp.getAccountType(this)); if (accounts.length != 0) { diff --git a/src/main/java/com/owncloud/android/ui/activity/NotificationsActivity.java b/src/main/java/com/owncloud/android/ui/activity/NotificationsActivity.java index 46792c86afbc..261d12497aee 100644 --- a/src/main/java/com/owncloud/android/ui/activity/NotificationsActivity.java +++ b/src/main/java/com/owncloud/android/ui/activity/NotificationsActivity.java @@ -24,9 +24,6 @@ package com.owncloud.android.ui.activity; -import android.accounts.Account; -import android.accounts.AuthenticatorException; -import android.accounts.OperationCanceledException; import android.content.Intent; import android.graphics.PorterDuff; import android.os.Bundle; @@ -39,13 +36,14 @@ import android.widget.TextView; import com.google.android.material.snackbar.Snackbar; +import com.nextcloud.client.account.User; import com.nextcloud.client.account.UserAccountManager; +import com.nextcloud.client.network.ClientFactory; +import com.nextcloud.java.util.Optional; import com.owncloud.android.R; import com.owncloud.android.datamodel.ArbitraryDataProvider; import com.owncloud.android.jobs.NotificationJob; -import com.owncloud.android.lib.common.OwnCloudAccount; import com.owncloud.android.lib.common.OwnCloudClient; -import com.owncloud.android.lib.common.OwnCloudClientManagerFactory; import com.owncloud.android.lib.common.operations.RemoteOperation; import com.owncloud.android.lib.common.operations.RemoteOperationResult; import com.owncloud.android.lib.common.utils.Log_OC; @@ -58,9 +56,10 @@ import com.owncloud.android.utils.PushUtils; import com.owncloud.android.utils.ThemeUtils; -import java.io.IOException; import java.util.List; +import javax.inject.Inject; + import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; @@ -109,7 +108,9 @@ public class NotificationsActivity extends FileActivity implements Notifications private NotificationListAdapter adapter; private Snackbar snackbar; private OwnCloudClient client; - private Account currentAccount; + private Optional optionalUser; + + @Inject ClientFactory clientFactory; @Override protected void onCreate(Bundle savedInstanceState) { @@ -119,16 +120,18 @@ protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.notifications_layout); unbinder = ButterKnife.bind(this); - currentAccount = getAccount(); + optionalUser = getUser(); // use account from intent (opened via android notification can have a different account than current one) if (getIntent() != null && getIntent().getExtras() != null) { - String account = getIntent().getExtras().getString(NotificationJob.KEY_NOTIFICATION_ACCOUNT); - - if (account != null && (currentAccount == null || !account.equalsIgnoreCase(currentAccount.name))) { - accountManager.setCurrentOwnCloudAccount(account); - setAccount(getUserAccountManager().getCurrentAccount(), false); - currentAccount = getAccount(); + String accountName = getIntent().getExtras().getString(NotificationJob.KEY_NOTIFICATION_ACCOUNT); + if(accountName != null && optionalUser.isPresent()) { + User user = optionalUser.get(); + if (user.getAccountName().equalsIgnoreCase(accountName)) { + accountManager.setCurrentOwnCloudAccount(accountName); + setUser(getUserAccountManager().getUser()); + optionalUser = getUser(); + } } } @@ -142,7 +145,7 @@ protected void onCreate(Bundle savedInstanceState) { setupDrawer(R.id.nav_notifications); ThemeUtils.setColoredTitle(getSupportActionBar(), getString(R.string.drawer_item_notifications), this); - if (currentAccount == null) { + if (!optionalUser.isPresent()) { // show error runOnUiThread(() -> setEmptyContent(noResultsHeadline, getString(R.string.account_not_found))); return; @@ -156,7 +159,6 @@ protected void onCreate(Bundle savedInstanceState) { swipeEmptyListRefreshLayout.setOnRefreshListener(() -> { setLoadingMessage(); fetchAndSetData(); - }); setupPushWarning(); @@ -175,16 +177,16 @@ private void setupPushWarning() { snackbar = Snackbar.make(emptyContentContainer, R.string.push_notifications_not_implemented, Snackbar.LENGTH_INDEFINITE); } else { - ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(getContentResolver()); - - boolean usesOldLogin = arbitraryDataProvider.getBooleanValue(currentAccount.name, + final ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(getContentResolver()); + final String accountName = optionalUser.isPresent() ? optionalUser.get().getAccountName() : ""; + final boolean usesOldLogin = arbitraryDataProvider.getBooleanValue(accountName, UserAccountManager.ACCOUNT_USES_STANDARD_PASSWORD); if (usesOldLogin) { snackbar = Snackbar.make(emptyContentContainer, R.string.push_notifications_old_login, Snackbar.LENGTH_INDEFINITE); } else { - String pushValue = arbitraryDataProvider.getValue(currentAccount.name, PushUtils.KEY_PUSH); + String pushValue = arbitraryDataProvider.getValue(accountName, PushUtils.KEY_PUSH); if (pushValue == null || pushValue.isEmpty()) { snackbar = Snackbar.make(emptyContentContainer, R.string.push_notifications_temp_error, @@ -250,13 +252,12 @@ private void populateList(List notifications) { private void fetchAndSetData() { Thread t = new Thread(() -> { - if (client == null) { + if (client == null && optionalUser.isPresent()) { try { - OwnCloudAccount ocAccount = new OwnCloudAccount(currentAccount, this); - client = OwnCloudClientManagerFactory.getDefaultSingleton().getClientFor(ocAccount, this); - client.setOwnCloudVersion(accountManager.getServerVersion(currentAccount)); - } catch (com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException | - IOException | OperationCanceledException | AuthenticatorException e) { + User user = optionalUser.get(); + client = clientFactory.create(user); + client.setOwnCloudVersion(user.getServer().getVersion()); + } catch (ClientFactory.CreationException e) { Log_OC.e(TAG, "Error initializing client", e); } } diff --git a/src/main/java/com/owncloud/android/ui/activity/RichDocumentsWebView.java b/src/main/java/com/owncloud/android/ui/activity/RichDocumentsWebView.java index 9f0188569b3c..e72182bcd93b 100644 --- a/src/main/java/com/owncloud/android/ui/activity/RichDocumentsWebView.java +++ b/src/main/java/com/owncloud/android/ui/activity/RichDocumentsWebView.java @@ -49,6 +49,7 @@ import com.bumptech.glide.Glide; import com.google.android.material.snackbar.Snackbar; import com.nextcloud.client.account.CurrentAccountProvider; +import com.nextcloud.client.account.User; import com.nextcloud.client.network.ClientFactory; import com.owncloud.android.R; import com.owncloud.android.datamodel.OCFile; @@ -155,7 +156,8 @@ protected void onCreate(Bundle savedInstanceState) { break; } - Glide.with(this).using(new CustomGlideStreamLoader(currentAccountProvider)).load(template.getThumbnailLink()) + Glide.with(this).using(new CustomGlideStreamLoader(currentAccountProvider, clientFactory)) + .load(template.getThumbnailLink()) .placeholder(placeholder) .error(placeholder) .into(thumbnail); @@ -314,9 +316,9 @@ private void handleRemoteFile(Intent data) { OCFile file = data.getParcelableExtra(FolderPickerActivity.EXTRA_FILES); new Thread(() -> { - Account account = currentAccountProvider.getCurrentAccount(); + User user = currentAccountProvider.getUser(); RichDocumentsCreateAssetOperation operation = new RichDocumentsCreateAssetOperation(file.getRemotePath()); - RemoteOperationResult result = operation.execute(account, this); + RemoteOperationResult result = operation.execute(user.toPlatformAccount(), this); if (result.isSuccess()) { String asset = (String) result.getSingleData(); diff --git a/src/main/java/com/owncloud/android/ui/activity/SettingsActivity.java b/src/main/java/com/owncloud/android/ui/activity/SettingsActivity.java index e51d028e5fb8..03563a730460 100644 --- a/src/main/java/com/owncloud/android/ui/activity/SettingsActivity.java +++ b/src/main/java/com/owncloud/android/ui/activity/SettingsActivity.java @@ -25,7 +25,6 @@ */ package com.owncloud.android.ui.activity; -import android.accounts.Account; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; @@ -52,10 +51,12 @@ import android.view.Window; import android.webkit.URLUtil; +import com.nextcloud.client.account.User; import com.nextcloud.client.account.UserAccountManager; import com.nextcloud.client.di.Injectable; import com.nextcloud.client.etm.EtmActivity; import com.nextcloud.client.logger.ui.LogsActivity; +import com.nextcloud.client.network.ClientFactory; import com.nextcloud.client.preferences.AppPreferences; import com.nextcloud.client.preferences.AppPreferencesImpl; import com.owncloud.android.BuildConfig; @@ -69,8 +70,6 @@ import com.owncloud.android.datastorage.StoragePoint; import com.owncloud.android.lib.common.ExternalLink; import com.owncloud.android.lib.common.ExternalLinkType; -import com.owncloud.android.lib.common.OwnCloudAccount; -import com.owncloud.android.lib.common.OwnCloudClientManagerFactory; import com.owncloud.android.lib.common.utils.Log_OC; import com.owncloud.android.ui.asynctasks.LoadingVersionNumberTask; import com.owncloud.android.utils.DeviceCredentialUtils; @@ -130,10 +129,11 @@ public class SettingsActivity extends ThemedPreferenceActivity private String storagePath; private String pendingLock; - private Account account; + private User user; @Inject ArbitraryDataProvider arbitraryDataProvider; @Inject AppPreferences preferences; @Inject UserAccountManager accountManager; + @Inject ClientFactory clientFactory; @SuppressWarnings("deprecation") @Override @@ -156,7 +156,7 @@ public void onCreate(Bundle savedInstanceState) { String appVersion = getAppVersion(); PreferenceScreen preferenceScreen = (PreferenceScreen) findPreference("preference_screen"); - account = accountManager.getCurrentAccount(); + user = accountManager.getUser(); // retrieve user's base uri setupBaseUri(); @@ -408,7 +408,7 @@ private void setupRecommendPreference(PreferenceCategory preferenceCategoryMore) } private void setupE2EMnemonicPreference(PreferenceCategory preferenceCategoryMore) { - String mnemonic = arbitraryDataProvider.getValue(account.name, EncryptionUtils.MNEMONIC); + String mnemonic = arbitraryDataProvider.getValue(user.getAccountName(), EncryptionUtils.MNEMONIC); Preference pMnemonic = findPreference("mnemonic"); if (pMnemonic != null) { @@ -603,11 +603,11 @@ private void setupAutoUploadCategory(int accentColor, PreferenceScreen preferenc final SwitchPreference pUploadOnWifiCheckbox = (SwitchPreference) findPreference("synced_folder_on_wifi"); pUploadOnWifiCheckbox.setChecked( - arbitraryDataProvider.getBooleanValue(account, SYNCED_FOLDER_LIGHT_UPLOAD_ON_WIFI)); + arbitraryDataProvider.getBooleanValue(user.toPlatformAccount(), SYNCED_FOLDER_LIGHT_UPLOAD_ON_WIFI)); pUploadOnWifiCheckbox.setOnPreferenceClickListener(preference -> { - arbitraryDataProvider.storeOrUpdateKeyValue(account.name, SYNCED_FOLDER_LIGHT_UPLOAD_ON_WIFI, - String.valueOf(pUploadOnWifiCheckbox.isChecked())); + arbitraryDataProvider.storeOrUpdateKeyValue(user.getAccountName(), SYNCED_FOLDER_LIGHT_UPLOAD_ON_WIFI, + String.valueOf(pUploadOnWifiCheckbox.isChecked())); return true; }); @@ -764,7 +764,7 @@ private void launchDavDroidLogin() { davDroidLoginIntent.setData(Uri.parse(serverBaseUri.toString() + AuthenticatorActivity.WEB_LOGIN)); davDroidLoginIntent.putExtra("davPath", DAV_PATH); } - davDroidLoginIntent.putExtra("username", UserAccountManager.getUsername(account)); + davDroidLoginIntent.putExtra("username", UserAccountManager.getUsername(user.toPlatformAccount())); startActivityForResult(davDroidLoginIntent, ACTION_REQUEST_CODE_DAVDROID_SETUP); } else { @@ -789,9 +789,7 @@ private void setupBaseUri() { // retrieve and set user's base URI Thread t = new Thread(() -> { try { - OwnCloudAccount ocAccount = new OwnCloudAccount(account, MainApp.getAppContext()); - serverBaseUri = OwnCloudClientManagerFactory.getDefaultSingleton().getClientFor(ocAccount, - getApplicationContext()).getBaseUri(); + serverBaseUri = clientFactory.create(user).getBaseUri(); } catch (Exception e) { Log_OC.e(TAG, "Error retrieving user's base URI", e); } @@ -857,7 +855,7 @@ protected void onActivityResult(int requestCode, int resultCode, Intent data) { RequestCredentialsActivity.KEY_CHECK_RESULT_TRUE) { ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(getContentResolver()); - String mnemonic = arbitraryDataProvider.getValue(account.name, EncryptionUtils.MNEMONIC); + String mnemonic = arbitraryDataProvider.getValue(user.getAccountName(), EncryptionUtils.MNEMONIC); int accentColor = ThemeUtils.primaryAccentColor(this); diff --git a/src/main/java/com/owncloud/android/ui/activity/SyncedFoldersActivity.java b/src/main/java/com/owncloud/android/ui/activity/SyncedFoldersActivity.java index 85506e065250..972522d6336f 100644 --- a/src/main/java/com/owncloud/android/ui/activity/SyncedFoldersActivity.java +++ b/src/main/java/com/owncloud/android/ui/activity/SyncedFoldersActivity.java @@ -41,10 +41,12 @@ import android.widget.LinearLayout; import android.widget.TextView; +import com.nextcloud.client.account.User; import com.nextcloud.client.core.Clock; import com.nextcloud.client.device.PowerManagementService; import com.nextcloud.client.di.Injectable; import com.nextcloud.client.preferences.AppPreferences; +import com.nextcloud.java.util.Optional; import com.owncloud.android.BuildConfig; import com.owncloud.android.MainApp; import com.owncloud.android.R; @@ -125,15 +127,15 @@ protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.synced_folders_layout); - String account; - Account currentAccount; if (getIntent() != null && getIntent().getExtras() != null) { - account = getIntent().getExtras().getString(NotificationJob.KEY_NOTIFICATION_ACCOUNT); - currentAccount = getAccount(); - - if (account != null && currentAccount != null && !account.equalsIgnoreCase(currentAccount.name)) { - accountManager.setCurrentOwnCloudAccount(account); - setAccount(getUserAccountManager().getCurrentAccount(), false); + final String accountName = getIntent().getExtras().getString(NotificationJob.KEY_NOTIFICATION_ACCOUNT); + Optional optionalUser = getUser(); + if (optionalUser.isPresent() && accountName != null) { + User user = optionalUser.get(); + if (!accountName.equalsIgnoreCase(user.getAccountName())) { + accountManager.setCurrentOwnCloudAccount(accountName); + setUser(getUserAccountManager().getUser()); + } } path = getIntent().getStringExtra(MediaFoldersDetectionJob.KEY_MEDIA_FOLDER_PATH); @@ -254,10 +256,9 @@ private void load(final int perFolderMediaItemLimit, boolean force) { List syncedFolderArrayList = mSyncedFolderProvider.getSyncedFolders(); List currentAccountSyncedFoldersList = new ArrayList<>(); - Account currentAccount = getUserAccountManager().getCurrentAccount(); + User user = getUserAccountManager().getUser(); for (SyncedFolder syncedFolder : syncedFolderArrayList) { - if (currentAccount != null && syncedFolder.getAccount().equals(currentAccount.name)) { - + if (syncedFolder.getAccount().equals(user.getAccountName())) { // delete non-existing & disabled synced folders if (!new File(syncedFolder.getLocalPath()).exists() && !syncedFolder.isEnabled()) { mSyncedFolderProvider.deleteSyncedFolder(syncedFolder.getId()); diff --git a/src/main/java/com/owncloud/android/ui/activity/UploadListActivity.java b/src/main/java/com/owncloud/android/ui/activity/UploadListActivity.java index 606cc7db24c7..2ca1520000e1 100755 --- a/src/main/java/com/owncloud/android/ui/activity/UploadListActivity.java +++ b/src/main/java/com/owncloud/android/ui/activity/UploadListActivity.java @@ -43,9 +43,11 @@ import com.evernote.android.job.JobManager; import com.evernote.android.job.JobRequest; import com.evernote.android.job.util.support.PersistableBundleCompat; +import com.nextcloud.client.account.User; import com.nextcloud.client.account.UserAccountManager; import com.nextcloud.client.device.PowerManagementService; import com.nextcloud.client.network.ConnectivityService; +import com.nextcloud.java.util.Optional; import com.owncloud.android.R; import com.owncloud.android.datamodel.UploadsStorageManager; import com.owncloud.android.files.services.FileUploader; @@ -230,9 +232,9 @@ private void refresh() { protected void onStart() { super.onStart(); ThemeUtils.setColoredTitle(getSupportActionBar(), R.string.uploads_view_title, this); - final Account account = getAccount(); - if (account != null) { - setAccountInDrawer(account); + final Optional optionalUser = getUser(); + if (optionalUser.isPresent()) { + setAccountInDrawer(optionalUser.get()); } } diff --git a/src/main/java/com/owncloud/android/ui/adapter/ActivityListAdapter.java b/src/main/java/com/owncloud/android/ui/adapter/ActivityListAdapter.java index 5a5275ced0ed..018dd33fb24d 100644 --- a/src/main/java/com/owncloud/android/ui/adapter/ActivityListAdapter.java +++ b/src/main/java/com/owncloud/android/ui/adapter/ActivityListAdapter.java @@ -51,6 +51,7 @@ import com.bumptech.glide.load.resource.file.FileToStreamDecoder; import com.caverock.androidsvg.SVG; import com.nextcloud.client.account.CurrentAccountProvider; +import com.nextcloud.client.network.ClientFactory; import com.owncloud.android.MainApp; import com.owncloud.android.R; import com.owncloud.android.datamodel.FileDataStorageManager; @@ -94,6 +95,7 @@ public class ActivityListAdapter extends RecyclerView.Adapter values; @@ -246,8 +248,11 @@ private ImageView createThumbnailNew(PreviewObject previewObject) { if (MimeTypeUtil.isImageOrVideo(previewObject.getMimeType())) { int placeholder = R.drawable.file; - Glide.with(context).using(new CustomGlideStreamLoader(currentAccountProvider)).load(previewObject.getSource()). - placeholder(placeholder).error(placeholder).into(imageView); + Glide.with(context).using(new CustomGlideStreamLoader(currentAccountProvider, clientFactory)) + .load(previewObject.getSource()) + .placeholder(placeholder) + .error(placeholder) + .into(imageView); } else { if (MimeTypeUtil.isFolder(previewObject.getMimeType())) { imageView.setImageDrawable( @@ -297,8 +302,10 @@ private void setBitmap(OCFile file, ImageView fileIcon, boolean isDetailView) { String uri = client.getBaseUri() + "/index.php/apps/files/api/v1/thumbnail/" + px + "/" + px + Uri.encode(file.getRemotePath(), "/"); - Glide.with(context).using(new CustomGlideStreamLoader(currentAccountProvider)).load(uri).placeholder(placeholder) - .error(placeholder).into(fileIcon); // using custom fetcher + Glide.with(context).using(new CustomGlideStreamLoader(currentAccountProvider, clientFactory)) + .load(uri).placeholder(placeholder) + .error(placeholder) + .into(fileIcon); // using custom fetcher } else { if (isDetailView) { diff --git a/src/main/java/com/owncloud/android/ui/adapter/TemplateAdapter.java b/src/main/java/com/owncloud/android/ui/adapter/TemplateAdapter.java index 40a42bf5a067..6769d5b53033 100644 --- a/src/main/java/com/owncloud/android/ui/adapter/TemplateAdapter.java +++ b/src/main/java/com/owncloud/android/ui/adapter/TemplateAdapter.java @@ -33,6 +33,7 @@ import com.bumptech.glide.Glide; import com.nextcloud.client.account.CurrentAccountProvider; +import com.nextcloud.client.network.ClientFactory; import com.owncloud.android.R; import com.owncloud.android.datamodel.Template; import com.owncloud.android.ui.dialog.ChooseTemplateDialogFragment; @@ -56,17 +57,20 @@ public class TemplateAdapter extends RecyclerView.Adapter files; private final Context context; - private final Account account; + private final User user; private final FileDataStorageManager storageManager; private final AppPreferences preferences; @@ -76,11 +76,11 @@ public TrashbinListAdapter( FileDataStorageManager storageManager, AppPreferences preferences, Context context, - Account account + User user ) { this.files = new ArrayList<>(); this.trashbinActivityInterface = trashbinActivityInterface; - this.account = account; + this.user = user; this.storageManager = storageManager; this.preferences = preferences; this.context = context; @@ -237,7 +237,7 @@ private void setThumbnail(TrashbinFile file, ImageView thumbnailView) { try { final ThumbnailsCacheManager.ThumbnailGenerationTask task = new ThumbnailsCacheManager.ThumbnailGenerationTask(thumbnailView, storageManager, - account, asyncTasks); + user.toPlatformAccount(), asyncTasks); final ThumbnailsCacheManager.AsyncThumbnailDrawable asyncDrawable = new ThumbnailsCacheManager.AsyncThumbnailDrawable(context.getResources(), @@ -257,7 +257,7 @@ private void setThumbnail(TrashbinFile file, ImageView thumbnailView) { } } else { thumbnailView.setImageDrawable(MimeTypeUtil.getFileTypeIcon(file.getMimeType(), file.getFileName(), - account, context)); + user.toPlatformAccount(), context)); } } } diff --git a/src/main/java/com/owncloud/android/ui/asynctasks/PhotoSearchTask.java b/src/main/java/com/owncloud/android/ui/asynctasks/PhotoSearchTask.java index a300ac0ca975..e388d96380d8 100644 --- a/src/main/java/com/owncloud/android/ui/asynctasks/PhotoSearchTask.java +++ b/src/main/java/com/owncloud/android/ui/asynctasks/PhotoSearchTask.java @@ -21,9 +21,9 @@ package com.owncloud.android.ui.asynctasks; -import android.accounts.Account; import android.os.AsyncTask; +import com.nextcloud.client.account.User; import com.owncloud.android.datamodel.FileDataStorageManager; import com.owncloud.android.lib.common.operations.RemoteOperationResult; import com.owncloud.android.lib.common.utils.Log_OC; @@ -38,18 +38,18 @@ public class PhotoSearchTask extends AsyncTask { private int columnCount; - private Account account; + private User user; private WeakReference photoFragmentWeakReference; private SearchRemoteOperation searchRemoteOperation; private FileDataStorageManager storageManager; public PhotoSearchTask(int columnsCount, PhotoFragment photoFragment, - Account account, + User user, SearchRemoteOperation searchRemoteOperation, FileDataStorageManager storageManager) { this.columnCount = columnsCount; - this.account = account; + this.user = user; this.photoFragmentWeakReference = new WeakReference<>(photoFragment); this.searchRemoteOperation = searchRemoteOperation; this.storageManager = storageManager; @@ -88,7 +88,7 @@ protected RemoteOperationResult doInBackground(Void... voids) { searchRemoteOperation.setTimestamp(timestamp); if (photoFragment.getContext() != null) { - return searchRemoteOperation.execute(account, photoFragment.getContext()); + return searchRemoteOperation.execute(user.toPlatformAccount(), photoFragment.getContext()); } else { return new RemoteOperationResult(new IllegalStateException("No context available")); } diff --git a/src/main/java/com/owncloud/android/ui/dialog/ChooseTemplateDialogFragment.java b/src/main/java/com/owncloud/android/ui/dialog/ChooseTemplateDialogFragment.java index 044932479085..90bffa6dc35f 100644 --- a/src/main/java/com/owncloud/android/ui/dialog/ChooseTemplateDialogFragment.java +++ b/src/main/java/com/owncloud/android/ui/dialog/ChooseTemplateDialogFragment.java @@ -24,7 +24,6 @@ package com.owncloud.android.ui.dialog; -import android.accounts.Account; import android.annotation.SuppressLint; import android.app.Activity; import android.app.Dialog; @@ -40,16 +39,16 @@ import android.widget.EditText; import com.nextcloud.client.account.CurrentAccountProvider; +import com.nextcloud.client.account.User; import com.nextcloud.client.di.Injectable; +import com.nextcloud.client.network.ClientFactory; import com.owncloud.android.MainApp; import com.owncloud.android.R; import com.owncloud.android.datamodel.OCFile; import com.owncloud.android.datamodel.Template; import com.owncloud.android.files.CreateFileFromTemplateOperation; import com.owncloud.android.files.FetchTemplateOperation; -import com.owncloud.android.lib.common.OwnCloudAccount; import com.owncloud.android.lib.common.OwnCloudClient; -import com.owncloud.android.lib.common.OwnCloudClientManagerFactory; import com.owncloud.android.lib.common.operations.RemoteOperationResult; import com.owncloud.android.lib.common.utils.Log_OC; import com.owncloud.android.ui.activity.ExternalSiteWebView; @@ -88,7 +87,8 @@ public class ChooseTemplateDialogFragment extends DialogFragment implements Dial private TemplateAdapter adapter; private OCFile parentFolder; private OwnCloudClient client; - @Inject CurrentAccountProvider currentAccount; + @Inject CurrentAccountProvider currentUser; + @Inject ClientFactory clientFactory; public enum Type { DOCUMENT, @@ -151,9 +151,8 @@ public Dialog onCreateDialog(Bundle savedInstanceState) { fileName.getBackground().setColorFilter(accentColor, PorterDuff.Mode.SRC_ATOP); try { - Account account = currentAccount.getCurrentAccount(); - OwnCloudAccount ocAccount = new OwnCloudAccount(account, activity); - client = OwnCloudClientManagerFactory.getDefaultSingleton().getClientFor(ocAccount, getContext()); + User user = currentUser.getUser(); + client = clientFactory.create(user); new FetchTemplateTask(this, client).execute(type); } catch (Exception e) { @@ -162,7 +161,7 @@ public Dialog onCreateDialog(Bundle savedInstanceState) { listView.setHasFixedSize(true); listView.setLayoutManager(new GridLayoutManager(activity, 2)); - adapter = new TemplateAdapter(type, this, getContext(), currentAccount); + adapter = new TemplateAdapter(type, this, getContext(), currentUser, clientFactory); listView.setAdapter(adapter); // Build the dialog diff --git a/src/main/java/com/owncloud/android/ui/fragment/ExtendedListFragment.java b/src/main/java/com/owncloud/android/ui/fragment/ExtendedListFragment.java index a1032b363b56..165bc9d0e4db 100644 --- a/src/main/java/com/owncloud/android/ui/fragment/ExtendedListFragment.java +++ b/src/main/java/com/owncloud/android/ui/fragment/ExtendedListFragment.java @@ -53,6 +53,7 @@ import android.widget.TextView; import com.google.android.material.floatingactionbutton.FloatingActionButton; +import com.nextcloud.client.account.User; import com.nextcloud.client.account.UserAccountManager; import com.nextcloud.client.di.Injectable; import com.nextcloud.client.preferences.AppPreferences; @@ -304,7 +305,8 @@ private void performSearch(final String query, boolean isSubmit) { handler.postDelayed(new Runnable() { @Override public void run() { - if (accountManager.isSearchSupported(accountManager.getCurrentAccount())) { + User user = accountManager.getUser(); + if (user.getServer().getVersion().isSearchSupported()) { EventBus.getDefault().post(new SearchEvent(query, SearchRemoteOperation.SearchType.FILE_SEARCH, SearchEvent.UnsetType.NO_UNSET)); } else { diff --git a/src/main/java/com/owncloud/android/ui/fragment/FileDetailActivitiesFragment.java b/src/main/java/com/owncloud/android/ui/fragment/FileDetailActivitiesFragment.java index 60886c3f7fd3..ce4d1e37c202 100644 --- a/src/main/java/com/owncloud/android/ui/fragment/FileDetailActivitiesFragment.java +++ b/src/main/java/com/owncloud/android/ui/fragment/FileDetailActivitiesFragment.java @@ -24,9 +24,6 @@ package com.owncloud.android.ui.fragment; import android.accounts.Account; -import android.accounts.AuthenticatorException; -import android.accounts.OperationCanceledException; -import android.content.Context; import android.graphics.PorterDuff; import android.os.AsyncTask; import android.os.Bundle; @@ -41,15 +38,14 @@ import com.google.android.material.snackbar.Snackbar; import com.google.android.material.textfield.TextInputEditText; +import com.nextcloud.client.account.User; import com.nextcloud.client.account.UserAccountManager; import com.nextcloud.client.di.Injectable; -import com.owncloud.android.MainApp; +import com.nextcloud.client.network.ClientFactory; import com.owncloud.android.R; import com.owncloud.android.datamodel.FileDataStorageManager; import com.owncloud.android.datamodel.OCFile; -import com.owncloud.android.lib.common.OwnCloudAccount; import com.owncloud.android.lib.common.OwnCloudClient; -import com.owncloud.android.lib.common.OwnCloudClientManagerFactory; import com.owncloud.android.lib.common.operations.RemoteOperationResult; import com.owncloud.android.lib.common.utils.Log_OC; import com.owncloud.android.lib.resources.activities.GetActivitiesRemoteOperation; @@ -72,7 +68,6 @@ import org.apache.commons.httpclient.HttpStatus; import org.greenrobot.eventbus.EventBus; -import java.io.IOException; import java.util.ArrayList; import java.util.List; @@ -149,6 +144,7 @@ public class FileDetailActivitiesFragment extends Fragment implements private VersionListInterface.CommentCallback callback; @Inject UserAccountManager accountManager; + @Inject ClientFactory clientFactory; public static FileDetailActivitiesFragment newInstance(OCFile file, Account account) { FileDetailActivitiesFragment fragment = new FileDetailActivitiesFragment(); @@ -258,7 +254,9 @@ private void setupView() { PorterDuff.Mode.SRC_IN); emptyContentIcon.setImageDrawable(getResources().getDrawable(R.drawable.ic_activity_light_grey)); - adapter = new ActivityAndVersionListAdapter(getContext(), accountManager, this, this, storageManager, capability); + adapter = new ActivityAndVersionListAdapter(getContext(), accountManager, this, this, + storageManager, + capability); recyclerView.setAdapter(adapter); LinearLayoutManager layoutManager = new LinearLayoutManager(getContext()); @@ -301,9 +299,9 @@ private void fetchAndSetData(int lastGiven) { final SwipeRefreshLayout empty = swipeEmptyListRefreshLayout; final SwipeRefreshLayout list = swipeListRefreshLayout; - final Account currentAccount = accountManager.getCurrentAccount(); + final User user = accountManager.getUser(); - if (currentAccount == null) { + if (user.isAnonymous()) { activity.runOnUiThread(() -> { setEmptyContent(getString(R.string.common_error), getString(R.string.file_detail_activity_error)); list.setVisibility(View.GONE); @@ -312,15 +310,10 @@ private void fetchAndSetData(int lastGiven) { return; } - final Context context = MainApp.getAppContext(); - Thread t = new Thread(() -> { - OwnCloudAccount ocAccount; try { - ocAccount = new OwnCloudAccount(currentAccount, context); - ownCloudClient = OwnCloudClientManagerFactory.getDefaultSingleton(). - getClientFor(ocAccount, MainApp.getAppContext()); - ownCloudClient.setOwnCloudVersion(accountManager.getServerVersion(currentAccount)); + ownCloudClient = clientFactory.create(user); + ownCloudClient.setOwnCloudVersion(user.getServer().getVersion()); isLoadingActivities = true; GetActivitiesRemoteOperation getRemoteNotificationOperation; @@ -385,8 +378,7 @@ private void fetchAndSetData(int lastGiven) { } hideRefreshLayoutLoader(activity); - } catch (com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException | IOException | - OperationCanceledException | AuthenticatorException | NullPointerException e) { + } catch (ClientFactory.CreationException e) { Log_OC.e(TAG, "Error fetching file details activities", e); } }); diff --git a/src/main/java/com/owncloud/android/ui/fragment/OCFileListFragment.java b/src/main/java/com/owncloud/android/ui/fragment/OCFileListFragment.java index 4fc993e3003c..3d3b85aaa591 100644 --- a/src/main/java/com/owncloud/android/ui/fragment/OCFileListFragment.java +++ b/src/main/java/com/owncloud/android/ui/fragment/OCFileListFragment.java @@ -47,9 +47,11 @@ import android.widget.PopupMenu; import com.google.android.material.snackbar.Snackbar; +import com.nextcloud.client.account.User; import com.nextcloud.client.account.UserAccountManager; import com.nextcloud.client.device.DeviceInfo; import com.nextcloud.client.di.Injectable; +import com.nextcloud.client.network.ClientFactory; import com.nextcloud.client.preferences.AppPreferences; import com.owncloud.android.MainApp; import com.owncloud.android.R; @@ -169,6 +171,7 @@ public class OCFileListFragment extends ExtendedListFragment implements @Inject AppPreferences preferences; @Inject UserAccountManager accountManager; + @Inject ClientFactory clientFactory; protected FileFragment.ContainerActivity mContainerActivity; protected OCFile mFile; @@ -942,10 +945,11 @@ public void onItemClicked(OCFile file) { mContainerActivity.getFileOperationsHelper().openFile(file); } } else { - Account account = accountManager.getCurrentAccount(); - OCCapability capability = mContainerActivity.getStorageManager().getCapability(account.name); + User account = accountManager.getUser(); + OCCapability capability = mContainerActivity.getStorageManager() + .getCapability(account.getAccountName()); - if (PreviewMediaFragment.canBePreviewed(file) && accountManager.getServerVersion(account) + if (PreviewMediaFragment.canBePreviewed(file) && account.getServer().getVersion() .isMediaStreamingSupported()) { // stream media preview on >= NC14 ((FileDisplayActivity) mContainerActivity).startMediaPreview(file, 0, true, true, true); @@ -1430,26 +1434,19 @@ public void onMessageEvent(CommentsEvent event) { @Subscribe(threadMode = ThreadMode.BACKGROUND) public void onMessageEvent(FavoriteEvent event) { - Account currentAccount = accountManager.getCurrentAccount(); - - OwnCloudAccount ocAccount; - try { - ocAccount = new OwnCloudAccount(currentAccount, MainApp.getAppContext()); - - OwnCloudClient mClient = OwnCloudClientManagerFactory.getDefaultSingleton(). - getClientFor(ocAccount, MainApp.getAppContext()); + User user = accountManager.getUser(); + OwnCloudClient client = clientFactory.create(user); ToggleFavoriteRemoteOperation toggleFavoriteOperation = new ToggleFavoriteRemoteOperation( event.shouldFavorite, event.remotePath); - RemoteOperationResult remoteOperationResult = toggleFavoriteOperation.execute(mClient); + RemoteOperationResult remoteOperationResult = toggleFavoriteOperation.execute(client); if (remoteOperationResult.isSuccess()) { mAdapter.setFavoriteAttributeForItemID(event.remoteId, event.shouldFavorite); } - } catch (com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException | AuthenticatorException - | IOException | OperationCanceledException e) { + } catch (ClientFactory.CreationException e) { Log_OC.e(TAG, "Error processing event", e); } } @@ -1483,7 +1480,7 @@ public void onMessageEvent(final SearchEvent event) { new Handler(Looper.getMainLooper()).post(switchViewsRunnable); - final Account currentAccount = accountManager.getCurrentAccount(); + final User currentAccount = accountManager.getUser(); final RemoteOperation remoteOperation; if (currentSearchType != SearchType.SHARED_FILTER) { @@ -1503,7 +1500,8 @@ public void onMessageEvent(final SearchEvent event) { protected Object doInBackground(Object[] params) { setTitle(); if (getContext() != null && !isCancelled()) { - RemoteOperationResult remoteOperationResult = remoteOperation.execute(currentAccount, getContext()); + RemoteOperationResult remoteOperationResult = remoteOperation.execute( + currentAccount.toPlatformAccount(), getContext()); FileDataStorageManager storageManager = null; if (mContainerActivity != null && mContainerActivity.getStorageManager() != null) { @@ -1555,18 +1553,12 @@ protected void onPostExecute(Object o) { @Subscribe(threadMode = ThreadMode.BACKGROUND) public void onMessageEvent(EncryptionEvent event) { - Account currentAccount = accountManager.getCurrentAccount(); - - OwnCloudAccount ocAccount; try { - ocAccount = new OwnCloudAccount(currentAccount, MainApp.getAppContext()); - - OwnCloudClient mClient = OwnCloudClientManagerFactory.getDefaultSingleton(). - getClientFor(ocAccount, MainApp.getAppContext()); - - ToggleEncryptionRemoteOperation toggleEncryptionOperation = new ToggleEncryptionRemoteOperation( + final User user = accountManager.getUser(); + final OwnCloudClient client = clientFactory.create(user); + final ToggleEncryptionRemoteOperation toggleEncryptionOperation = new ToggleEncryptionRemoteOperation( event.localId, event.remotePath, event.shouldBeEncrypted); - RemoteOperationResult remoteOperationResult = toggleEncryptionOperation.execute(mClient); + final RemoteOperationResult remoteOperationResult = toggleEncryptionOperation.execute(client); if (remoteOperationResult.isSuccess()) { mAdapter.setEncryptionAttributeForItemID(event.remoteId, event.shouldBeEncrypted); @@ -1576,14 +1568,8 @@ public void onMessageEvent(EncryptionEvent event) { Snackbar.make(getRecyclerView(), R.string.common_error_unknown, Snackbar.LENGTH_LONG).show(); } - } catch (com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException e) { - Log_OC.e(TAG, "Account not found", e); - } catch (AuthenticatorException e) { - Log_OC.e(TAG, "Authentication failed", e); - } catch (IOException e) { - Log_OC.e(TAG, "IO error", e); - } catch (OperationCanceledException e) { - Log_OC.e(TAG, "Operation has been canceled", e); + } catch (ClientFactory.CreationException e) { + Log_OC.e(TAG, "Cannot create client", e); } } diff --git a/src/main/java/com/owncloud/android/ui/fragment/PhotoFragment.java b/src/main/java/com/owncloud/android/ui/fragment/PhotoFragment.java index e405e2947bc0..a6bc85eff1b3 100644 --- a/src/main/java/com/owncloud/android/ui/fragment/PhotoFragment.java +++ b/src/main/java/com/owncloud/android/ui/fragment/PhotoFragment.java @@ -161,7 +161,7 @@ private void searchAndDisplay() { if (!photoSearchQueryRunning && !photoSearchNoNew) { photoSearchTask = new PhotoSearchTask(getColumnsCount(), this, - accountManager.getCurrentAccount(), + accountManager.getUser(), searchRemoteOperation, mContainerActivity.getStorageManager()) .execute(); diff --git a/src/main/java/com/owncloud/android/ui/fragment/contactsbackup/ContactListFragment.java b/src/main/java/com/owncloud/android/ui/fragment/contactsbackup/ContactListFragment.java index 2f6597e8378f..540c9646b647 100644 --- a/src/main/java/com/owncloud/android/ui/fragment/contactsbackup/ContactListFragment.java +++ b/src/main/java/com/owncloud/android/ui/fragment/contactsbackup/ContactListFragment.java @@ -61,6 +61,7 @@ import com.google.android.material.snackbar.Snackbar; import com.nextcloud.client.account.UserAccountManager; import com.nextcloud.client.di.Injectable; +import com.nextcloud.client.network.ClientFactory; import com.owncloud.android.R; import com.owncloud.android.datamodel.FileDataStorageManager; import com.owncloud.android.datamodel.OCFile; @@ -149,6 +150,7 @@ public class ContactListFragment extends FileFragment implements Injectable { private List vCards = new ArrayList<>(); private OCFile ocFile; @Inject UserAccountManager accountManager; + @Inject ClientFactory clientFactory; public static ContactListFragment newInstance(OCFile file, Account account) { ContactListFragment frag = new ContactListFragment(); @@ -191,7 +193,7 @@ public View onCreateView(@NonNull final LayoutInflater inflater, ViewGroup conta recyclerView = view.findViewById(R.id.contactlist_recyclerview); if (savedInstanceState == null) { - contactListAdapter = new ContactListAdapter(accountManager, getContext(), vCards); + contactListAdapter = new ContactListAdapter(accountManager, clientFactory, getContext(), vCards); } else { Set checkedItems = new HashSet<>(); int[] itemsArray = savedInstanceState.getIntArray(CHECKED_ITEMS_ARRAY_KEY); @@ -589,12 +591,15 @@ class ContactListAdapter extends RecyclerView.Adapter vCards) { + ContactListAdapter(UserAccountManager accountManager, ClientFactory clientFactory, Context context, + List vCards) { this.vCards = vCards; this.context = context; this.checkedVCards = new HashSet<>(); this.accountManager = accountManager; + this.clientFactory = clientFactory; } ContactListAdapter(UserAccountManager accountManager, @@ -699,6 +704,7 @@ public void onLoadFailed(Exception e, Drawable errorDrawable) { } }; DisplayUtils.downloadIcon(accountManager, + clientFactory, context, url, target, diff --git a/src/main/java/com/owncloud/android/ui/helpers/FileOperationsHelper.java b/src/main/java/com/owncloud/android/ui/helpers/FileOperationsHelper.java index 0c6c0d1115c6..387125c67c72 100755 --- a/src/main/java/com/owncloud/android/ui/helpers/FileOperationsHelper.java +++ b/src/main/java/com/owncloud/android/ui/helpers/FileOperationsHelper.java @@ -46,6 +46,7 @@ import com.evernote.android.job.JobRequest; import com.nextcloud.client.account.CurrentAccountProvider; +import com.nextcloud.client.account.User; import com.nextcloud.client.network.ConnectivityService; import com.owncloud.android.MainApp; import com.owncloud.android.R; @@ -291,14 +292,14 @@ public void openFile(OCFile file) { new Thread(new Runnable() { @Override public void run() { - Account account = currentAccount.getCurrentAccount(); + User user = currentAccount.getUser(); FileDataStorageManager storageManager = - new FileDataStorageManager(account, fileActivity.getContentResolver()); + new FileDataStorageManager(user.toPlatformAccount(), fileActivity.getContentResolver()); // a fresh object is needed; many things could have occurred to the file // since it was registered to observe again, assuming that local files // are linked to a remote file AT MOST, SOMETHING TO BE DONE; SynchronizeFileOperation sfo = - new SynchronizeFileOperation(file, null, account, true, fileActivity); + new SynchronizeFileOperation(file, null, user.toPlatformAccount(), true, fileActivity); RemoteOperationResult result = sfo.execute(storageManager, fileActivity); fileActivity.dismissLoadingDialog(); if (result.getCode() == RemoteOperationResult.ResultCode.SYNC_CONFLICT) { @@ -307,7 +308,7 @@ public void run() { Intent i = new Intent(fileActivity, ConflictsResolveActivity.class); i.setFlags(i.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK); i.putExtra(ConflictsResolveActivity.EXTRA_FILE, file); - i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, account); + i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, user.toPlatformAccount()); fileActivity.startActivity(i); } else { if (!launchables.isEmpty()) { @@ -397,10 +398,10 @@ private Uri getFileUri(OCFile file, String... officeExtensions) { public void streamMediaFile(OCFile file) { fileActivity.showLoadingDialog(fileActivity.getString(R.string.wait_a_moment)); - final Account account = currentAccount.getCurrentAccount(); + final User user = currentAccount.getUser(); new Thread(() -> { StreamMediaFileOperation sfo = new StreamMediaFileOperation(file.getLocalId()); - RemoteOperationResult result = sfo.execute(account, fileActivity); + RemoteOperationResult result = sfo.execute(user.toPlatformAccount(), fileActivity); fileActivity.dismissLoadingDialog(); diff --git a/src/main/java/com/owncloud/android/ui/preview/PreviewImageActivity.java b/src/main/java/com/owncloud/android/ui/preview/PreviewImageActivity.java index d956b2462c82..81f7d4d3b0bc 100644 --- a/src/main/java/com/owncloud/android/ui/preview/PreviewImageActivity.java +++ b/src/main/java/com/owncloud/android/ui/preview/PreviewImageActivity.java @@ -37,6 +37,7 @@ import android.view.View; import com.google.android.material.snackbar.Snackbar; +import com.nextcloud.client.account.User; import com.nextcloud.client.di.Injectable; import com.nextcloud.client.preferences.AppPreferences; import com.owncloud.android.MainApp; @@ -385,11 +386,11 @@ private void backToDisplayActivity() { @SuppressFBWarnings("DLS") @Override public void showDetails(OCFile file) { - final Account currentAccount = getUserAccountManager().getCurrentAccount(); + final User currentUser = getUserAccountManager().getUser(); final Intent showDetailsIntent = new Intent(this, FileDisplayActivity.class); showDetailsIntent.setAction(FileDisplayActivity.ACTION_DETAILS); showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, file); - showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, currentAccount); + showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, currentUser.toPlatformAccount()); showDetailsIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); startActivity(showDetailsIntent); finish(); diff --git a/src/main/java/com/owncloud/android/ui/trashbin/RemoteTrashbinRepository.java b/src/main/java/com/owncloud/android/ui/trashbin/RemoteTrashbinRepository.java index a10646f6e525..fcf9ad155bc9 100644 --- a/src/main/java/com/owncloud/android/ui/trashbin/RemoteTrashbinRepository.java +++ b/src/main/java/com/owncloud/android/ui/trashbin/RemoteTrashbinRepository.java @@ -27,6 +27,8 @@ import android.content.Context; import android.os.AsyncTask; +import com.nextcloud.client.account.User; +import com.nextcloud.client.network.ClientFactory; import com.owncloud.android.R; import com.owncloud.android.lib.common.OwnCloudAccount; import com.owncloud.android.lib.common.OwnCloudClient; @@ -47,39 +49,46 @@ public class RemoteTrashbinRepository implements TrashbinRepository { private static final String TAG = RemoteTrashbinRepository.class.getSimpleName(); - private OwnCloudClient client; + private final User user; + private final ClientFactory clientFactory; - RemoteTrashbinRepository(final Context context, final Account account) { - try { - OwnCloudAccount nextcloudAccount = new OwnCloudAccount(account, context); - client = OwnCloudClientManagerFactory.getDefaultSingleton().getClientFor(nextcloudAccount, context); - } catch (Exception e) { - Log_OC.e(TAG, e.getMessage()); - } + RemoteTrashbinRepository(User user, ClientFactory clientFactory) { + this.user = user; + this.clientFactory = clientFactory; } public void removeTrashbinFile(TrashbinFile file, OperationCallback callback) { - new RemoveTrashbinFileTask(client, file, callback).execute(); + new RemoveTrashbinFileTask(user, clientFactory, file, callback).execute(); } private static class RemoveTrashbinFileTask extends AsyncTask { - private OwnCloudClient client; + private User user; + private ClientFactory clientFactory; private TrashbinFile file; private OperationCallback callback; - private RemoveTrashbinFileTask(OwnCloudClient client, TrashbinFile file, OperationCallback callback) { - this.client = client; + private RemoveTrashbinFileTask(User user, + ClientFactory clientFactory, + TrashbinFile file, + OperationCallback callback) { + this.user = user; + this.clientFactory = clientFactory; this.file = file; this.callback = callback; } @Override protected Boolean doInBackground(Void... voids) { - RemoteOperationResult result = new RemoveTrashbinFileRemoteOperation(file.getFullRemotePath()) - .execute(client); - - return result.isSuccess(); + try { + OwnCloudClient client = clientFactory.create(user); + RemoteOperationResult result = new RemoveTrashbinFileRemoteOperation(file.getFullRemotePath()) + .execute(client); + return result.isSuccess(); + } catch (ClientFactory.CreationException e) { + Log_OC.e(this, "Cannot create client", e); + return false; + } } @Override @@ -91,25 +100,32 @@ protected void onPostExecute(Boolean success) { } public void emptyTrashbin(OperationCallback callback) { - new EmptyTrashbinTask(client, callback).execute(); + new EmptyTrashbinTask(user, clientFactory, callback).execute(); } private static class EmptyTrashbinTask extends AsyncTask { - private OwnCloudClient client; + private User user; + private ClientFactory clientFactory; private OperationCallback callback; - private EmptyTrashbinTask(OwnCloudClient client, OperationCallback callback) { - this.client = client; + private EmptyTrashbinTask(User user, ClientFactory clientFactory, OperationCallback callback) { + this.user = user; + this.clientFactory = clientFactory; this.callback = callback; } @Override protected Boolean doInBackground(Void... voids) { - EmptyTrashbinRemoteOperation emptyTrashbinFileOperation = new EmptyTrashbinRemoteOperation(); - RemoteOperationResult result = emptyTrashbinFileOperation.execute(client); - - return result.isSuccess(); + try { + OwnCloudClient client = clientFactory.create(user); + EmptyTrashbinRemoteOperation emptyTrashbinFileOperation = new EmptyTrashbinRemoteOperation(); + RemoteOperationResult result = emptyTrashbinFileOperation.execute(client); + return result.isSuccess(); + } catch (ClientFactory.CreationException e) { + Log_OC.e(this, "Cannot create client", e); + return false; + } } @Override @@ -122,28 +138,36 @@ protected void onPostExecute(Boolean success) { @Override public void restoreFile(TrashbinFile file, OperationCallback callback) { - new RestoreTrashbinFileTask(file, client, callback).execute(); + new RestoreTrashbinFileTask(file, user, clientFactory, callback).execute(); } private static class RestoreTrashbinFileTask extends AsyncTask { private TrashbinFile file; - private OwnCloudClient client; + private User user; + private ClientFactory clientFactory; private TrashbinRepository.OperationCallback callback; - private RestoreTrashbinFileTask(TrashbinFile file, OwnCloudClient client, + private RestoreTrashbinFileTask(TrashbinFile file, User user, ClientFactory clientFactory, TrashbinRepository.OperationCallback callback) { this.file = file; - this.client = client; + this.user = user; + this.clientFactory = clientFactory; this.callback = callback; } @Override protected Boolean doInBackground(Void... voids) { - RemoteOperationResult result = new RestoreTrashbinFileRemoteOperation(file.getFullRemotePath(), - file.getFileName()).execute(client); - - return result.isSuccess(); + try { + OwnCloudClient client = clientFactory.create(user); + RemoteOperationResult result = new RestoreTrashbinFileRemoteOperation(file.getFullRemotePath(), + file.getFileName()).execute(client); + + return result.isSuccess(); + } catch (ClientFactory.CreationException e) { + Log_OC.e(this, "Cannot create client", e); + return false; + } } @Override @@ -156,30 +180,37 @@ protected void onPostExecute(Boolean success) { @Override public void getFolder(String remotePath, @NonNull LoadFolderCallback callback) { - new ReadRemoteTrashbinFolderTask(remotePath, client, callback).execute(); + new ReadRemoteTrashbinFolderTask(remotePath, user, clientFactory, callback).execute(); } private static class ReadRemoteTrashbinFolderTask extends AsyncTask { private String remotePath; - private OwnCloudClient client; + private User user; + private ClientFactory clientFactory; private List trashbinFiles; private LoadFolderCallback callback; - private ReadRemoteTrashbinFolderTask(String remotePath, OwnCloudClient client, LoadFolderCallback callback) { + private ReadRemoteTrashbinFolderTask(String remotePath, User user, ClientFactory clientFactory, + LoadFolderCallback callback) { this.remotePath = remotePath; - this.client = client; + this.user = user; + this.clientFactory = clientFactory; this.callback = callback; } @Override protected Boolean doInBackground(Void... voids) { - RemoteOperationResult result = new ReadTrashbinFolderRemoteOperation(remotePath).execute(client); - - if (result.isSuccess()) { - trashbinFiles = result.getData(); - return true; - } else { + try { + OwnCloudClient client = clientFactory.create(user); + RemoteOperationResult result = new ReadTrashbinFolderRemoteOperation(remotePath).execute(client); + if (result.isSuccess()) { + trashbinFiles = result.getData(); + return true; + } else { + return false; + } + } catch (ClientFactory.CreationException e) { return false; } } diff --git a/src/main/java/com/owncloud/android/ui/trashbin/TrashbinActivity.java b/src/main/java/com/owncloud/android/ui/trashbin/TrashbinActivity.java index a6aac5ac08d4..e43a46bcb1bf 100644 --- a/src/main/java/com/owncloud/android/ui/trashbin/TrashbinActivity.java +++ b/src/main/java/com/owncloud/android/ui/trashbin/TrashbinActivity.java @@ -23,7 +23,6 @@ */ package com.owncloud.android.ui.trashbin; -import android.accounts.Account; import android.content.Intent; import android.os.Bundle; import android.view.Menu; @@ -34,7 +33,10 @@ import android.widget.TextView; import com.google.android.material.snackbar.Snackbar; +import com.nextcloud.client.account.CurrentAccountProvider; +import com.nextcloud.client.account.User; import com.nextcloud.client.di.Injectable; +import com.nextcloud.client.network.ClientFactory; import com.nextcloud.client.preferences.AppPreferences; import com.owncloud.android.R; import com.owncloud.android.lib.resources.trashbin.model.TrashbinFile; @@ -92,6 +94,8 @@ public class TrashbinActivity extends FileActivity implements public String noResultsMessage; @Inject AppPreferences preferences; + @Inject CurrentAccountProvider accountProvider; + @Inject ClientFactory clientFactory; private Unbinder unbinder; private TrashbinListAdapter trashbinListAdapter; private TrashbinPresenter trashbinPresenter; @@ -101,29 +105,20 @@ public class TrashbinActivity extends FileActivity implements @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - - final Account currentAccount = getUserAccountManager().getCurrentAccount(); - final RemoteTrashbinRepository trashRepository = new RemoteTrashbinRepository(this, currentAccount); + final User user = accountProvider.getUser(); + final RemoteTrashbinRepository trashRepository = new RemoteTrashbinRepository(user, clientFactory); trashbinPresenter = new TrashbinPresenter(trashRepository, this); - setContentView(R.layout.trashbin_activity); unbinder = ButterKnife.bind(this); - - // setup toolbar setupToolbar(); - - // setup drawer setupDrawer(R.id.nav_trashbin); - ThemeUtils.setColoredTitle(getSupportActionBar(), R.string.trashbin_activity_title, this); } @Override protected void onStart() { super.onStart(); - active = true; - setupContent(); } @@ -142,7 +137,7 @@ private void setupContent() { getStorageManager(), preferences, this, - getUserAccountManager().getCurrentAccount() + getUserAccountManager().getUser() ); recyclerView.setAdapter(trashbinListAdapter); recyclerView.setHasFixedSize(true); diff --git a/src/main/java/com/owncloud/android/utils/DisplayUtils.java b/src/main/java/com/owncloud/android/utils/DisplayUtils.java index 047268759979..9fa2ee6a040f 100644 --- a/src/main/java/com/owncloud/android/utils/DisplayUtils.java +++ b/src/main/java/com/owncloud/android/utils/DisplayUtils.java @@ -55,6 +55,7 @@ import com.caverock.androidsvg.SVG; import com.google.android.material.snackbar.Snackbar; import com.nextcloud.client.account.CurrentAccountProvider; +import com.nextcloud.client.network.ClientFactory; import com.owncloud.android.MainApp; import com.owncloud.android.R; import com.owncloud.android.datamodel.ArbitraryDataProvider; @@ -515,6 +516,7 @@ public static void setAvatar(@NonNull Account account, } public static void downloadIcon(CurrentAccountProvider currentAccountProvider, + ClientFactory clientFactory, Context context, String iconUrl, SimpleTarget imageView, @@ -523,7 +525,8 @@ public static void downloadIcon(CurrentAccountProvider currentAccountProvider, int height) { try { if (iconUrl.endsWith(".svg")) { - downloadSVGIcon(currentAccountProvider, context, iconUrl, imageView, placeholder, width, height); + downloadSVGIcon(currentAccountProvider, clientFactory, context, iconUrl, imageView, placeholder, width, + height); } else { downloadPNGIcon(context, iconUrl, imageView, placeholder); } @@ -544,6 +547,7 @@ private static void downloadPNGIcon(Context context, String iconUrl, SimpleTarge } private static void downloadSVGIcon(CurrentAccountProvider currentAccountProvider, + ClientFactory clientFactory, Context context, String iconUrl, SimpleTarget imageView, @@ -551,7 +555,7 @@ private static void downloadSVGIcon(CurrentAccountProvider currentAccountProvide int width, int height) { GenericRequestBuilder requestBuilder = Glide.with(context) - .using(new CustomGlideUriLoader(currentAccountProvider), InputStream.class) + .using(new CustomGlideUriLoader(currentAccountProvider, clientFactory), InputStream.class) .from(Uri.class) .as(SVG.class) .transcode(new SvgDrawableTranscoder(), PictureDrawable.class) diff --git a/src/main/java/com/owncloud/android/utils/glide/CustomGlideStreamLoader.java b/src/main/java/com/owncloud/android/utils/glide/CustomGlideStreamLoader.java index 51345864b054..196b882af1bd 100644 --- a/src/main/java/com/owncloud/android/utils/glide/CustomGlideStreamLoader.java +++ b/src/main/java/com/owncloud/android/utils/glide/CustomGlideStreamLoader.java @@ -25,6 +25,7 @@ import com.bumptech.glide.load.data.DataFetcher; import com.bumptech.glide.load.model.stream.StreamModelLoader; import com.nextcloud.client.account.CurrentAccountProvider; +import com.nextcloud.client.network.ClientFactory; import java.io.InputStream; @@ -34,13 +35,15 @@ public class CustomGlideStreamLoader implements StreamModelLoader { private final CurrentAccountProvider currentAccount; + private final ClientFactory clientFactory; - public CustomGlideStreamLoader(CurrentAccountProvider currentAccount) { + public CustomGlideStreamLoader(CurrentAccountProvider currentAccount, ClientFactory clientFactory) { this.currentAccount = currentAccount; + this.clientFactory = clientFactory; } @Override public DataFetcher getResourceFetcher(String url, int width, int height) { - return new HttpStreamFetcher(currentAccount, url); + return new HttpStreamFetcher(currentAccount, clientFactory, url); } } diff --git a/src/main/java/com/owncloud/android/utils/glide/CustomGlideUriLoader.java b/src/main/java/com/owncloud/android/utils/glide/CustomGlideUriLoader.java index 48694c0180c4..5216aea35b16 100644 --- a/src/main/java/com/owncloud/android/utils/glide/CustomGlideUriLoader.java +++ b/src/main/java/com/owncloud/android/utils/glide/CustomGlideUriLoader.java @@ -25,6 +25,7 @@ import com.bumptech.glide.load.data.DataFetcher; import com.bumptech.glide.load.model.stream.StreamModelLoader; import com.nextcloud.client.account.CurrentAccountProvider; +import com.nextcloud.client.network.ClientFactory; import java.io.InputStream; @@ -34,13 +35,15 @@ public class CustomGlideUriLoader implements StreamModelLoader { private final CurrentAccountProvider currentAccount; + private final ClientFactory clientFactory; - public CustomGlideUriLoader(CurrentAccountProvider currentAccount) { + public CustomGlideUriLoader(CurrentAccountProvider currentAccount, ClientFactory clientFactory) { this.currentAccount = currentAccount; + this.clientFactory = clientFactory; } @Override public DataFetcher getResourceFetcher(Uri url, int width, int height) { - return new HttpStreamFetcher(currentAccount, url.toString()); + return new HttpStreamFetcher(currentAccount, clientFactory, url.toString()); } } diff --git a/src/main/java/com/owncloud/android/utils/glide/HttpStreamFetcher.java b/src/main/java/com/owncloud/android/utils/glide/HttpStreamFetcher.java index 3af6e41838e2..ae12ac31f3c6 100644 --- a/src/main/java/com/owncloud/android/utils/glide/HttpStreamFetcher.java +++ b/src/main/java/com/owncloud/android/utils/glide/HttpStreamFetcher.java @@ -27,6 +27,8 @@ import com.bumptech.glide.Priority; import com.bumptech.glide.load.data.DataFetcher; import com.nextcloud.client.account.CurrentAccountProvider; +import com.nextcloud.client.account.User; +import com.nextcloud.client.network.ClientFactory; import com.owncloud.android.MainApp; import com.owncloud.android.lib.common.OwnCloudAccount; import com.owncloud.android.lib.common.OwnCloudClient; @@ -47,30 +49,30 @@ public class HttpStreamFetcher implements DataFetcher { private static final String TAG = HttpStreamFetcher.class.getName(); private final String url; private final CurrentAccountProvider currentAccount; + private final ClientFactory clientFactory; - HttpStreamFetcher(final CurrentAccountProvider currentAccount, final String url) { + HttpStreamFetcher(final CurrentAccountProvider currentAccount, ClientFactory clientFactory, final String url) { this.currentAccount = currentAccount; + this.clientFactory = clientFactory; this.url = url; } @Override public InputStream loadData(Priority priority) throws Exception { - Account account = currentAccount.getCurrentAccount(); - OwnCloudAccount ocAccount = new OwnCloudAccount(account, MainApp.getAppContext()); - OwnCloudClient mClient = OwnCloudClientManagerFactory.getDefaultSingleton(). - getClientFor(ocAccount, MainApp.getAppContext()); + User user = currentAccount.getUser(); + OwnCloudClient client = clientFactory.create(user); - if (mClient != null) { + if (client != null) { GetMethod get; try { get = new GetMethod(url); get.setRequestHeader("Cookie", "nc_sameSiteCookielax=true;nc_sameSiteCookiestrict=true"); get.setRequestHeader(RemoteOperation.OCS_API_HEADER, RemoteOperation.OCS_API_HEADER_VALUE); - int status = mClient.executeMethod(get); + int status = client.executeMethod(get); if (status == HttpStatus.SC_OK) { return get.getResponseBodyAsStream(); } else { - mClient.exhaustResponse(get.getResponseBodyAsStream()); + client.exhaustResponse(get.getResponseBodyAsStream()); } } catch (Exception e) { Log_OC.e(TAG, e.getMessage(), e); diff --git a/src/main/res/values/strings.xml b/src/main/res/values/strings.xml index 4aac77165312..185272de0e65 100644 --- a/src/main/res/values/strings.xml +++ b/src/main/res/values/strings.xml @@ -868,9 +868,6 @@ Music Documents Downloads - IO error - Operation has been canceled - Authentication Exception Avatar from shared user Shared with you by %1$s Resharing is not allowed From 11687c65cb2c1745bca5c8b4896cca55f7f8cb6e Mon Sep 17 00:00:00 2001 From: nextcloud-android-bot Date: Mon, 25 Nov 2019 12:22:26 +0000 Subject: [PATCH 2/2] Drone: update FindBugs results to reflect reduced error/warning count [skip ci] Signed-off-by: nextcloud-android-bot --- scripts/analysis/findbugs-results.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/analysis/findbugs-results.txt b/scripts/analysis/findbugs-results.txt index 97964b3fde64..2da56739379b 100644 --- a/scripts/analysis/findbugs-results.txt +++ b/scripts/analysis/findbugs-results.txt @@ -1 +1 @@ -422 \ No newline at end of file +418 \ No newline at end of file