Migrate current account getter from AccountUtils to UserAccountManager

The implementation delegates calls to the old code, so there should
be no regressions in functionality.

Signed-off-by: Chris Narkiewicz <hello@ezaquarii.com>
This commit is contained in:
Chris Narkiewicz 2019-04-13 18:50:53 +01:00
parent 4442d5a338
commit 442394f949
No known key found for this signature in database
GPG Key ID: 30D28CA4CCC665C6
61 changed files with 724 additions and 294 deletions

View File

@ -5,3 +5,4 @@ NC_TEST_SERVER_PASSWORD=test
android.enableJetifier=true android.enableJetifier=true
android.useAndroidX=true android.useAndroidX=true
android.debug.obsoleteApi=true android.debug.obsoleteApi=true

View File

@ -38,22 +38,22 @@ public abstract class AbstractIT {
protected static OwnCloudClient client; protected static OwnCloudClient client;
static Account account; static Account account;
protected static Context context; protected static Context targetContext;
@BeforeClass @BeforeClass
public static void beforeAll() { public static void beforeAll() {
try { try {
context = InstrumentationRegistry.getInstrumentation().getTargetContext(); targetContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
Bundle arguments = androidx.test.platform.app.InstrumentationRegistry.getArguments(); Bundle arguments = androidx.test.platform.app.InstrumentationRegistry.getArguments();
Uri baseUrl = Uri.parse(arguments.getString("TEST_SERVER_URL")); Uri baseUrl = Uri.parse(arguments.getString("TEST_SERVER_URL"));
String username = arguments.getString("TEST_SERVER_USERNAME"); String username = arguments.getString("TEST_SERVER_USERNAME");
String password = arguments.getString("TEST_SERVER_PASSWORD"); String password = arguments.getString("TEST_SERVER_PASSWORD");
Account temp = new Account(username + "@" + baseUrl, MainApp.getAccountType(context)); Account temp = new Account(username + "@" + baseUrl, MainApp.getAccountType(targetContext));
if (!com.owncloud.android.authentication.AccountUtils.exists(temp, context)) { if (!com.owncloud.android.authentication.AccountUtils.exists(temp, targetContext)) {
AccountManager accountManager = AccountManager.get(context); AccountManager accountManager = AccountManager.get(targetContext);
accountManager.addAccountExplicitly(temp, password, null); accountManager.addAccountExplicitly(temp, password, null);
accountManager.setUserData(temp, AccountUtils.Constants.KEY_OC_ACCOUNT_VERSION, accountManager.setUserData(temp, AccountUtils.Constants.KEY_OC_ACCOUNT_VERSION,
Integer.toString(com.owncloud.android.authentication.AccountUtils.ACCOUNT_VERSION)); Integer.toString(com.owncloud.android.authentication.AccountUtils.ACCOUNT_VERSION));
@ -62,14 +62,14 @@ public abstract class AbstractIT {
accountManager.setUserData(temp, AccountUtils.Constants.KEY_USER_ID, username); accountManager.setUserData(temp, AccountUtils.Constants.KEY_USER_ID, username);
} }
account = com.owncloud.android.authentication.AccountUtils.getOwnCloudAccountByName(context, account = com.owncloud.android.authentication.AccountUtils.getOwnCloudAccountByName(targetContext,
username + "@" + baseUrl); username + "@" + baseUrl);
if (account == null) { if (account == null) {
throw new ActivityNotFoundException(); throw new ActivityNotFoundException();
} }
client = OwnCloudClientFactory.createOwnCloudClient(account, context); client = OwnCloudClientFactory.createOwnCloudClient(account, targetContext);
createDummyFiles(); createDummyFiles();
@ -86,7 +86,7 @@ public abstract class AbstractIT {
} }
FileDataStorageManager getStorageManager() { FileDataStorageManager getStorageManager() {
return new FileDataStorageManager(account, context.getContentResolver()); return new FileDataStorageManager(account, targetContext.getContentResolver());
} }
private static void createDummyFiles() throws IOException { private static void createDummyFiles() throws IOException {

View File

@ -35,7 +35,7 @@ public class FileIT extends AbstractIT {
assertTrue(getStorageManager().getFileByPath(path).isFolder()); assertTrue(getStorageManager().getFileByPath(path).isFolder());
// cleanup // cleanup
new RemoveFileOperation(path, false, account, false, context).execute(client, getStorageManager()); new RemoveFileOperation(path, false, account, false, targetContext).execute(client, getStorageManager());
} }
@Test @Test
@ -52,6 +52,6 @@ public class FileIT extends AbstractIT {
assertTrue(getStorageManager().getFileByPath(path).isFolder()); assertTrue(getStorageManager().getFileByPath(path).isFolder());
// cleanup // cleanup
new RemoveFileOperation("/testFolder/", false, account, false, context).execute(client, getStorageManager()); new RemoveFileOperation("/testFolder/", false, account, false, targetContext).execute(client, getStorageManager());
} }
} }

View File

@ -1,5 +1,10 @@
package com.owncloud.android; package com.owncloud.android;
import android.content.ContentResolver;
import com.nextcloud.client.account.CurrentAccountProvider;
import com.owncloud.android.authentication.AccountUtils;
import com.owncloud.android.datamodel.UploadsStorageManager;
import com.owncloud.android.db.OCUpload; import com.owncloud.android.db.OCUpload;
import com.owncloud.android.files.services.FileUploader; import com.owncloud.android.files.services.FileUploader;
import com.owncloud.android.lib.common.operations.RemoteOperationResult; import com.owncloud.android.lib.common.operations.RemoteOperationResult;
@ -7,6 +12,7 @@ import com.owncloud.android.operations.RemoveFileOperation;
import com.owncloud.android.operations.UploadFileOperation; import com.owncloud.android.operations.UploadFileOperation;
import com.owncloud.android.utils.FileStorageUtils; import com.owncloud.android.utils.FileStorageUtils;
import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@ -21,6 +27,16 @@ import static junit.framework.TestCase.assertTrue;
@RunWith(AndroidJUnit4.class) @RunWith(AndroidJUnit4.class)
public class UploadIT extends AbstractIT { public class UploadIT extends AbstractIT {
private UploadsStorageManager storageManager;
@Before
public void setUp() {
final ContentResolver contentResolver = targetContext.getContentResolver();
final CurrentAccountProvider currentAccountProvider = () -> AccountUtils.getCurrentOwnCloudAccount(targetContext);
storageManager = new UploadsStorageManager(currentAccountProvider, contentResolver, targetContext);
}
@Test @Test
public void testEmptyUpload() { public void testEmptyUpload() {
OCUpload ocUpload = new OCUpload(FileStorageUtils.getSavePath(account.name) + "/empty.txt", OCUpload ocUpload = new OCUpload(FileStorageUtils.getSavePath(account.name) + "/empty.txt",
@ -31,7 +47,7 @@ public class UploadIT extends AbstractIT {
assertTrue(result.toString(), result.isSuccess()); assertTrue(result.toString(), result.isSuccess());
// cleanup // cleanup
new RemoveFileOperation("/testUpload/", false, account, false, context).execute(client, getStorageManager()); new RemoveFileOperation("/testUpload/", false, account, false, targetContext).execute(client, getStorageManager());
} }
@Test @Test
@ -44,7 +60,7 @@ public class UploadIT extends AbstractIT {
assertTrue(result.toString(), result.isSuccess()); assertTrue(result.toString(), result.isSuccess());
// cleanup // cleanup
new RemoveFileOperation("/testUpload/", false, account, false, context).execute(client, getStorageManager()); new RemoveFileOperation("/testUpload/", false, account, false, targetContext).execute(client, getStorageManager());
} }
@Test @Test
@ -57,17 +73,18 @@ public class UploadIT extends AbstractIT {
assertTrue(result.toString(), result.isSuccess()); assertTrue(result.toString(), result.isSuccess());
// cleanup // cleanup
new RemoveFileOperation("/testUpload/", false, account, false, context).execute(client, getStorageManager()); new RemoveFileOperation("/testUpload/", false, account, false, targetContext).execute(client, getStorageManager());
} }
public RemoteOperationResult testUpload(OCUpload ocUpload) { public RemoteOperationResult testUpload(OCUpload ocUpload) {
UploadFileOperation newUpload = new UploadFileOperation( UploadFileOperation newUpload = new UploadFileOperation(
storageManager,
account, account,
null, null,
ocUpload, ocUpload,
false, false,
FileUploader.LOCAL_BEHAVIOUR_COPY, FileUploader.LOCAL_BEHAVIOUR_COPY,
context, targetContext,
false, false,
false false
); );
@ -85,12 +102,13 @@ public class UploadIT extends AbstractIT {
OCUpload ocUpload = new OCUpload(FileStorageUtils.getSavePath(account.name) + "/empty.txt", OCUpload ocUpload = new OCUpload(FileStorageUtils.getSavePath(account.name) + "/empty.txt",
"/testUpload/2/3/4/1.txt", account.name); "/testUpload/2/3/4/1.txt", account.name);
UploadFileOperation newUpload = new UploadFileOperation( UploadFileOperation newUpload = new UploadFileOperation(
storageManager,
account, account,
null, null,
ocUpload, ocUpload,
false, false,
FileUploader.LOCAL_BEHAVIOUR_COPY, FileUploader.LOCAL_BEHAVIOUR_COPY,
context, targetContext,
false, false,
false false
); );
@ -104,6 +122,6 @@ public class UploadIT extends AbstractIT {
assertTrue(result.toString(), result.isSuccess()); assertTrue(result.toString(), result.isSuccess());
// cleanup // cleanup
new RemoveFileOperation("/testUpload/", false, account, false, context).execute(client, getStorageManager()); new RemoveFileOperation("/testUpload/", false, account, false, targetContext).execute(client, getStorageManager());
} }
} }

View File

@ -4,6 +4,7 @@ import android.accounts.Account;
import android.content.ContentResolver; import android.content.ContentResolver;
import android.content.Context; import android.content.Context;
import com.nextcloud.client.account.CurrentAccountProvider;
import com.owncloud.android.db.OCUpload; import com.owncloud.android.db.OCUpload;
import org.junit.After; import org.junit.After;
@ -14,6 +15,7 @@ import org.junit.runner.RunWith;
import java.io.File; import java.io.File;
import androidx.annotation.Nullable;
import androidx.test.InstrumentationRegistry; import androidx.test.InstrumentationRegistry;
import androidx.test.filters.SmallTest; import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4; import androidx.test.runner.AndroidJUnit4;
@ -28,12 +30,13 @@ public class UploadStorageManagerTest {
private Account[] Accounts; private Account[] Accounts;
private UploadsStorageManager uploadsStorageManager; private UploadsStorageManager uploadsStorageManager;
private CurrentAccountProvider currentAccountProvider = () -> null;
@Before @Before
public void setUp() { public void setUp() {
Context instrumentationCtx = InstrumentationRegistry.getTargetContext(); Context instrumentationCtx = InstrumentationRegistry.getTargetContext();
ContentResolver contentResolver = instrumentationCtx.getContentResolver(); ContentResolver contentResolver = instrumentationCtx.getContentResolver();
uploadsStorageManager = new UploadsStorageManager(contentResolver, instrumentationCtx); uploadsStorageManager = new UploadsStorageManager(currentAccountProvider, contentResolver, instrumentationCtx);
Accounts = new Account[]{new Account("A", "A"), new Account("B", "B")}; Accounts = new Account[]{new Account("A", "A"), new Account("B", "B")};
} }

View File

@ -0,0 +1,20 @@
package com.nextcloud.client.account;
import android.accounts.Account;
import androidx.annotation.Nullable;
/**
* This interface provides access to currently selected user Account.
* @see UserAccountManager
*/
@FunctionalInterface
public interface CurrentAccountProvider {
/**
* Get currently active account.
*
* @return Currently selected {@link Account} or first valid {@link Account} registered in OS or null, if not available at all.
*/
@Nullable
Account getCurrentAccount();
}

View File

@ -23,7 +23,7 @@ import android.accounts.Account;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
public interface UserAccountManager { public interface UserAccountManager extends CurrentAccountProvider {
int ACCOUNT_VERSION = 1; int ACCOUNT_VERSION = 1;
int ACCOUNT_VERSION_WITH_PROPER_ID = 2; int ACCOUNT_VERSION_WITH_PROPER_ID = 2;

View File

@ -39,6 +39,7 @@ import com.owncloud.android.lib.resources.users.GetRemoteUserInfoOperation;
import javax.inject.Inject; import javax.inject.Inject;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
public class UserAccountManagerImpl implements UserAccountManager { public class UserAccountManagerImpl implements UserAccountManager {
@ -49,7 +50,10 @@ public class UserAccountManagerImpl implements UserAccountManager {
private AccountManager accountManager; private AccountManager accountManager;
@Inject @Inject
public UserAccountManagerImpl(Context context, AccountManager accountManager) { public UserAccountManagerImpl(
Context context,
AccountManager accountManager
) {
this.context = context; this.context = context;
this.accountManager = accountManager; this.accountManager = accountManager;
} }
@ -60,6 +64,11 @@ public class UserAccountManagerImpl implements UserAccountManager {
return accountManager.getAccountsByType(getAccountType()); return accountManager.getAccountsByType(getAccountType());
} }
@Nullable
public Account getCurrentAccount() {
return AccountUtils.getCurrentOwnCloudAccount(context);
}
public void updateAccountVersion() { public void updateAccountVersion() {
Account currentAccount = AccountUtils.getCurrentOwnCloudAccount(context); Account currentAccount = AccountUtils.getCurrentOwnCloudAccount(context);

View File

@ -22,12 +22,23 @@ package com.nextcloud.client.di;
import android.accounts.AccountManager; import android.accounts.AccountManager;
import android.app.Application; import android.app.Application;
import android.content.ContentResolver;
import android.content.Context; import android.content.Context;
import com.nextcloud.client.account.CurrentAccountProvider;
import com.nextcloud.client.account.UserAccountManager; import com.nextcloud.client.account.UserAccountManager;
import com.nextcloud.client.account.UserAccountManagerImpl; import com.nextcloud.client.account.UserAccountManagerImpl;
import com.nextcloud.client.preferences.AppPreferences; import com.nextcloud.client.preferences.AppPreferences;
import com.nextcloud.client.preferences.AppPreferencesImpl; import com.nextcloud.client.preferences.AppPreferencesImpl;
import com.owncloud.android.datamodel.ArbitraryDataProvider;
import com.owncloud.android.datamodel.UploadsStorageManager;
import com.owncloud.android.ui.activities.data.activities.ActivitiesRepository;
import com.owncloud.android.ui.activities.data.activities.ActivitiesServiceApi;
import com.owncloud.android.ui.activities.data.activities.ActivitiesServiceApiImpl;
import com.owncloud.android.ui.activities.data.activities.RemoteActivitiesRepository;
import com.owncloud.android.ui.activities.data.files.FilesRepository;
import com.owncloud.android.ui.activities.data.files.FilesServiceApiImpl;
import com.owncloud.android.ui.activities.data.files.RemoteFilesRepository;
import dagger.Module; import dagger.Module;
import dagger.Provides; import dagger.Provides;
@ -51,7 +62,39 @@ class AppModule {
} }
@Provides @Provides
UserAccountManager userAccountManager(Context context, AccountManager accountManager) { UserAccountManager userAccountManager(
Context context,
AccountManager accountManager
) {
return new UserAccountManagerImpl(context, accountManager); return new UserAccountManagerImpl(context, accountManager);
} }
@Provides
ArbitraryDataProvider arbitraryDataProvider(Context context) {
final ContentResolver resolver = context.getContentResolver();
return new ArbitraryDataProvider(resolver);
}
@Provides
ActivitiesServiceApi activitiesServiceApi(UserAccountManager accountManager) {
return new ActivitiesServiceApiImpl(accountManager);
}
@Provides
ActivitiesRepository activitiesRepository(ActivitiesServiceApi api) {
return new RemoteActivitiesRepository(api);
}
@Provides
FilesRepository filesRepository(UserAccountManager accountManager) {
return new RemoteFilesRepository(new FilesServiceApiImpl(accountManager));
}
@Provides UploadsStorageManager uploadsStorageManager(Context context, CurrentAccountProvider currentAccountProvider) {
return new UploadsStorageManager(currentAccountProvider, context.getContentResolver(), context);
}
@Provides CurrentAccountProvider currentAccountProvider(UserAccountManager accountManager) {
return accountManager;
}
} }

View File

@ -23,8 +23,12 @@ package com.nextcloud.client.di;
import com.owncloud.android.authentication.AuthenticatorActivity; import com.owncloud.android.authentication.AuthenticatorActivity;
import com.owncloud.android.authentication.DeepLinkLoginActivity; import com.owncloud.android.authentication.DeepLinkLoginActivity;
import com.owncloud.android.files.BootupBroadcastReceiver; import com.owncloud.android.files.BootupBroadcastReceiver;
import com.owncloud.android.files.services.FileUploader;
import com.owncloud.android.providers.DiskLruImageCacheFileProvider;
import com.owncloud.android.providers.DocumentsStorageProvider; import com.owncloud.android.providers.DocumentsStorageProvider;
import com.owncloud.android.providers.UsersAndGroupsSearchProvider;
import com.owncloud.android.ui.activities.ActivitiesActivity; import com.owncloud.android.ui.activities.ActivitiesActivity;
import com.owncloud.android.ui.activity.BaseActivity;
import com.owncloud.android.ui.activity.ConflictsResolveActivity; import com.owncloud.android.ui.activity.ConflictsResolveActivity;
import com.owncloud.android.ui.activity.ContactsPreferenceActivity; import com.owncloud.android.ui.activity.ContactsPreferenceActivity;
import com.owncloud.android.ui.activity.CopyToClipboardActivity; import com.owncloud.android.ui.activity.CopyToClipboardActivity;
@ -53,8 +57,10 @@ import com.owncloud.android.ui.activity.UploadListActivity;
import com.owncloud.android.ui.activity.UploadPathActivity; import com.owncloud.android.ui.activity.UploadPathActivity;
import com.owncloud.android.ui.activity.UserInfoActivity; import com.owncloud.android.ui.activity.UserInfoActivity;
import com.owncloud.android.ui.activity.WhatsNewActivity; import com.owncloud.android.ui.activity.WhatsNewActivity;
import com.owncloud.android.ui.dialog.ChooseTemplateDialogFragment;
import com.owncloud.android.ui.errorhandling.ErrorShowActivity; import com.owncloud.android.ui.errorhandling.ErrorShowActivity;
import com.owncloud.android.ui.fragment.ExtendedListFragment; import com.owncloud.android.ui.fragment.ExtendedListFragment;
import com.owncloud.android.ui.fragment.FileDetailActivitiesFragment;
import com.owncloud.android.ui.fragment.FileDetailFragment; import com.owncloud.android.ui.fragment.FileDetailFragment;
import com.owncloud.android.ui.fragment.LocalFileListFragment; import com.owncloud.android.ui.fragment.LocalFileListFragment;
import com.owncloud.android.ui.fragment.OCFileListFragment; import com.owncloud.android.ui.fragment.OCFileListFragment;
@ -73,6 +79,7 @@ import dagger.android.ContributesAndroidInjector;
abstract class ComponentsModule { abstract class ComponentsModule {
@ContributesAndroidInjector abstract ActivitiesActivity activitiesActivity(); @ContributesAndroidInjector abstract ActivitiesActivity activitiesActivity();
@ContributesAndroidInjector abstract AuthenticatorActivity authenticatorActivity(); @ContributesAndroidInjector abstract AuthenticatorActivity authenticatorActivity();
@ContributesAndroidInjector abstract BaseActivity baseActivity();
@ContributesAndroidInjector abstract ConflictsResolveActivity conflictsResolveActivity(); @ContributesAndroidInjector abstract ConflictsResolveActivity conflictsResolveActivity();
@ContributesAndroidInjector abstract ContactsPreferenceActivity contactsPreferenceActivity(); @ContributesAndroidInjector abstract ContactsPreferenceActivity contactsPreferenceActivity();
@ContributesAndroidInjector abstract CopyToClipboardActivity copyToClipboardActivity(); @ContributesAndroidInjector abstract CopyToClipboardActivity copyToClipboardActivity();
@ -111,8 +118,14 @@ abstract class ComponentsModule {
@ContributesAndroidInjector abstract FileDetailFragment fileDetailFragment(); @ContributesAndroidInjector abstract FileDetailFragment fileDetailFragment();
@ContributesAndroidInjector abstract LocalFileListFragment localFileListFragment(); @ContributesAndroidInjector abstract LocalFileListFragment localFileListFragment();
@ContributesAndroidInjector abstract OCFileListFragment ocFileListFragment(); @ContributesAndroidInjector abstract OCFileListFragment ocFileListFragment();
@ContributesAndroidInjector abstract FileDetailActivitiesFragment fileDetailActivitiesFragment();
@ContributesAndroidInjector abstract ChooseTemplateDialogFragment chooseTemplateDialogFragment();
@ContributesAndroidInjector abstract FileUploader fileUploader();
@ContributesAndroidInjector abstract BootupBroadcastReceiver bootupBroadcastReceiver(); @ContributesAndroidInjector abstract BootupBroadcastReceiver bootupBroadcastReceiver();
@ContributesAndroidInjector abstract DocumentsStorageProvider documentsStorageProvider(); @ContributesAndroidInjector abstract DocumentsStorageProvider documentsStorageProvider();
@ContributesAndroidInjector abstract UsersAndGroupsSearchProvider usersAndGroupsSearchProvider();
@ContributesAndroidInjector abstract DiskLruImageCacheFileProvider diskLruImageCacheFileProvider();
} }

View File

@ -280,4 +280,7 @@ public interface AppPreferences {
void setStoragePath(String path); void setStoragePath(String path);
void removeKeysMigrationPreference(); void removeKeysMigrationPreference();
String getCurrentAccountName();
void setCurrentAccountName(String accountName);
} }

View File

@ -25,6 +25,7 @@ import android.accounts.Account;
import android.annotation.SuppressLint; import android.annotation.SuppressLint;
import android.content.Context; import android.content.Context;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import com.owncloud.android.authentication.AccountUtils; import com.owncloud.android.authentication.AccountUtils;
import com.owncloud.android.datamodel.ArbitraryDataProvider; import com.owncloud.android.datamodel.ArbitraryDataProvider;
import com.owncloud.android.datamodel.FileDataStorageManager; import com.owncloud.android.datamodel.FileDataStorageManager;
@ -68,6 +69,7 @@ public final class AppPreferencesImpl implements AppPreferences {
private static final String PREF__LOCK_TIMESTAMP = "lock_timestamp"; private static final String PREF__LOCK_TIMESTAMP = "lock_timestamp";
private static final String PREF__SHOW_MEDIA_SCAN_NOTIFICATIONS = "show_media_scan_notifications"; private static final String PREF__SHOW_MEDIA_SCAN_NOTIFICATIONS = "show_media_scan_notifications";
private static final String PREF__LOCK = SettingsActivity.PREFERENCE_LOCK; private static final String PREF__LOCK = SettingsActivity.PREFERENCE_LOCK;
private static final String PREF__SELECTED_ACCOUNT_NAME = "select_oc_account";
private final Context context; private final Context context;
private final SharedPreferences preferences; private final SharedPreferences preferences;
@ -424,6 +426,16 @@ public final class AppPreferencesImpl implements AppPreferences {
preferences.edit().remove(AppPreferencesImpl.PREF__KEYS_MIGRATION).commit(); // commit synchronously preferences.edit().remove(AppPreferencesImpl.PREF__KEYS_MIGRATION).commit(); // commit synchronously
} }
@Override
public String getCurrentAccountName() {
return preferences.getString(PREF__SELECTED_ACCOUNT_NAME, null);
}
@Override
public void setCurrentAccountName(String accountName) {
preferences.edit().putString(PREF__SELECTED_ACCOUNT_NAME, accountName).apply();
}
/** /**
* Get preference value for a folder. * Get preference value for a folder.
* If folder is not set itself, it finds an ancestor that is set. * If folder is not set itself, it finds an ancestor that is set.

View File

@ -58,6 +58,7 @@ import com.owncloud.android.datamodel.MediaProvider;
import com.owncloud.android.datamodel.SyncedFolder; import com.owncloud.android.datamodel.SyncedFolder;
import com.owncloud.android.datamodel.SyncedFolderProvider; import com.owncloud.android.datamodel.SyncedFolderProvider;
import com.owncloud.android.datamodel.ThumbnailsCacheManager; import com.owncloud.android.datamodel.ThumbnailsCacheManager;
import com.owncloud.android.datamodel.UploadsStorageManager;
import com.owncloud.android.datastorage.DataStorageProvider; import com.owncloud.android.datastorage.DataStorageProvider;
import com.owncloud.android.datastorage.StoragePoint; import com.owncloud.android.datastorage.StoragePoint;
import com.owncloud.android.jobs.MediaFoldersDetectionJob; import com.owncloud.android.jobs.MediaFoldersDetectionJob;
@ -135,25 +136,28 @@ public class MainApp extends MultiDexApplication implements
private static boolean mOnlyOnDevice; private static boolean mOnlyOnDevice;
@Inject @Inject
AppPreferences preferences; protected AppPreferences preferences;
@Inject @Inject
DispatchingAndroidInjector<Activity> dispatchingActivityInjector; protected DispatchingAndroidInjector<Activity> dispatchingActivityInjector;
@Inject @Inject
DispatchingAndroidInjector<Fragment> dispatchingFragmentInjector; protected DispatchingAndroidInjector<Fragment> dispatchingFragmentInjector;
@Inject @Inject
DispatchingAndroidInjector<Service> dispatchingServiceInjector; protected DispatchingAndroidInjector<Service> dispatchingServiceInjector;
@Inject @Inject
DispatchingAndroidInjector<ContentProvider> dispatchingContentProviderInjector; protected DispatchingAndroidInjector<ContentProvider> dispatchingContentProviderInjector;
@Inject @Inject
DispatchingAndroidInjector<BroadcastReceiver> dispatchingBroadcastReceiverInjector; protected DispatchingAndroidInjector<BroadcastReceiver> dispatchingBroadcastReceiverInjector;
@Inject @Inject
UserAccountManager accountManager; protected UserAccountManager accountManager;
@Inject
protected UploadsStorageManager uploadsStorageManager;
private PassCodeManager passCodeManager; private PassCodeManager passCodeManager;
@ -176,7 +180,14 @@ public class MainApp extends MultiDexApplication implements
registerActivityLifecycleCallbacks(new ActivityInjector()); registerActivityLifecycleCallbacks(new ActivityInjector());
JobManager.create(this).addJobCreator(new NCJobCreator(getApplicationContext(), accountManager, preferences)); JobManager.create(this).addJobCreator(
new NCJobCreator(
getApplicationContext(),
accountManager,
preferences,
uploadsStorageManager
)
);
MainApp.mContext = getApplicationContext(); MainApp.mContext = getApplicationContext();
new SecurityUtils(); new SecurityUtils();
@ -217,7 +228,7 @@ public class MainApp extends MultiDexApplication implements
} }
} }
initSyncOperations(accountManager); initSyncOperations(uploadsStorageManager, accountManager);
initContactsBackup(accountManager); initContactsBackup(accountManager);
notificationChannels(); notificationChannels();
@ -342,7 +353,10 @@ public class MainApp extends MultiDexApplication implements
} }
} }
public static void initSyncOperations(UserAccountManager accountManager) { public static void initSyncOperations(
final UploadsStorageManager uploadsStorageManager,
final UserAccountManager accountManager
) {
updateToAutoUpload(); updateToAutoUpload();
cleanOldEntries(); cleanOldEntries();
updateAutoUploadEntries(); updateAutoUploadEntries();
@ -360,18 +374,17 @@ public class MainApp extends MultiDexApplication implements
initiateExistingAutoUploadEntries(); initiateExistingAutoUploadEntries();
FilesSyncHelper.scheduleFilesSyncIfNeeded(mContext); FilesSyncHelper.scheduleFilesSyncIfNeeded(mContext);
FilesSyncHelper.restartJobsIfNeeded(accountManager); FilesSyncHelper.restartJobsIfNeeded(uploadsStorageManager, accountManager);
FilesSyncHelper.scheduleOfflineSyncIfNeeded(); FilesSyncHelper.scheduleOfflineSyncIfNeeded();
ReceiversHelper.registerNetworkChangeReceiver(accountManager); ReceiversHelper.registerNetworkChangeReceiver(uploadsStorageManager, accountManager);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
ReceiversHelper.registerPowerChangeReceiver(accountManager ReceiversHelper.registerPowerChangeReceiver(uploadsStorageManager, accountManager);
);
} }
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ReceiversHelper.registerPowerSaveReceiver(accountManager); ReceiversHelper.registerPowerSaveReceiver(uploadsStorageManager, accountManager);
} }
} }

View File

@ -88,6 +88,7 @@ import android.widget.TextView.OnEditorActionListener;
import com.blikoon.qrcodescanner.QrCodeActivity; import com.blikoon.qrcodescanner.QrCodeActivity;
import com.google.android.material.snackbar.Snackbar; import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.textfield.TextInputLayout; import com.google.android.material.textfield.TextInputLayout;
import com.nextcloud.client.account.UserAccountManager;
import com.owncloud.android.MainApp; import com.owncloud.android.MainApp;
import com.owncloud.android.R; import com.owncloud.android.R;
import com.owncloud.android.authentication.SsoWebViewClient.SsoWebViewClientListener; import com.owncloud.android.authentication.SsoWebViewClient.SsoWebViewClientListener;
@ -133,6 +134,8 @@ import java.util.HashMap;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import javax.inject.Inject;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment; import androidx.fragment.app.DialogFragment;
@ -262,6 +265,9 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
private TextInputLayout mPasswordInputLayout; private TextInputLayout mPasswordInputLayout;
private boolean forceOldLoginMethod; private boolean forceOldLoginMethod;
@Inject
protected UserAccountManager accountManager;
/** /**
* {@inheritDoc} * {@inheritDoc}
* *
@ -1976,7 +1982,7 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
} }
/// add the new account as default in preferences, if there is none already /// add the new account as default in preferences, if there is none already
Account defaultAccount = AccountUtils.getCurrentOwnCloudAccount(this); Account defaultAccount = accountManager.getCurrentAccount();
if (defaultAccount == null) { if (defaultAccount == null) {
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit(); SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putString("select_oc_account", accountName); editor.putString("select_oc_account", accountName);

View File

@ -4,7 +4,10 @@
* @author LukeOwncloud * @author LukeOwncloud
* @author David A. Velasco * @author David A. Velasco
* @author masensio * @author masensio
* @author Chris Narkiewicz
*
* Copyright (C) 2016 ownCloud Inc. * Copyright (C) 2016 ownCloud Inc.
* Copyright (C) 2019 Chris Narkiewicz <hello@ezaquarii.com>
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2, * it under the terms of the GNU General Public License version 2,
@ -27,7 +30,7 @@ import android.content.Context;
import android.database.Cursor; import android.database.Cursor;
import android.net.Uri; import android.net.Uri;
import com.owncloud.android.authentication.AccountUtils; import com.nextcloud.client.account.CurrentAccountProvider;
import com.owncloud.android.db.OCUpload; import com.owncloud.android.db.OCUpload;
import com.owncloud.android.db.ProviderMeta.ProviderTableMeta; import com.owncloud.android.db.ProviderMeta.ProviderTableMeta;
import com.owncloud.android.db.UploadResult; import com.owncloud.android.db.UploadResult;
@ -53,13 +56,19 @@ public class UploadsStorageManager extends Observable {
private ContentResolver mContentResolver; private ContentResolver mContentResolver;
private Context mContext; private Context mContext;
private CurrentAccountProvider currentAccountProvider;
public UploadsStorageManager(ContentResolver contentResolver, Context context) { public UploadsStorageManager(
CurrentAccountProvider currentAccountProvider,
ContentResolver contentResolver,
Context context
) {
if (contentResolver == null) { if (contentResolver == null) {
throw new IllegalArgumentException("Cannot create an instance with a NULL contentResolver"); throw new IllegalArgumentException("Cannot create an instance with a NULL contentResolver");
} }
mContentResolver = contentResolver; mContentResolver = contentResolver;
mContext = context; mContext = context;
this.currentAccountProvider = currentAccountProvider;
} }
/** /**
@ -340,7 +349,7 @@ public class UploadsStorageManager extends Observable {
} }
public OCUpload[] getCurrentAndPendingUploadsForCurrentAccount() { public OCUpload[] getCurrentAndPendingUploadsForCurrentAccount() {
Account account = AccountUtils.getCurrentOwnCloudAccount(mContext); Account account = currentAccountProvider.getCurrentAccount();
if (account != null) { if (account != null) {
return getUploads( return getUploads(
@ -379,7 +388,7 @@ public class UploadsStorageManager extends Observable {
} }
public OCUpload[] getFinishedUploadsForCurrentAccount() { public OCUpload[] getFinishedUploadsForCurrentAccount() {
Account account = AccountUtils.getCurrentOwnCloudAccount(mContext); Account account = currentAccountProvider.getCurrentAccount();
if (account != null) { if (account != null) {
return getUploads(ProviderTableMeta.UPLOADS_STATUS + "==" + UploadStatus.UPLOAD_SUCCEEDED.value + AND + return getUploads(ProviderTableMeta.UPLOADS_STATUS + "==" + UploadStatus.UPLOAD_SUCCEEDED.value + AND +
@ -398,7 +407,7 @@ public class UploadsStorageManager extends Observable {
} }
public OCUpload[] getFailedButNotDelayedUploadsForCurrentAccount() { public OCUpload[] getFailedButNotDelayedUploadsForCurrentAccount() {
Account account = AccountUtils.getCurrentOwnCloudAccount(mContext); Account account = currentAccountProvider.getCurrentAccount();
if (account != null) { if (account != null) {
return getUploads(ProviderTableMeta.UPLOADS_STATUS + "==" + UploadStatus.UPLOAD_FAILED.value + return getUploads(ProviderTableMeta.UPLOADS_STATUS + "==" + UploadStatus.UPLOAD_FAILED.value +
@ -441,7 +450,7 @@ public class UploadsStorageManager extends Observable {
} }
public long clearFailedButNotDelayedUploads() { public long clearFailedButNotDelayedUploads() {
Account account = AccountUtils.getCurrentOwnCloudAccount(mContext); Account account = currentAccountProvider.getCurrentAccount();
long result = 0; long result = 0;
if (account != null) { if (account != null) {
@ -469,7 +478,7 @@ public class UploadsStorageManager extends Observable {
} }
public long clearSuccessfulUploads() { public long clearSuccessfulUploads() {
Account account = AccountUtils.getCurrentOwnCloudAccount(mContext); Account account = currentAccountProvider.getCurrentAccount();
long result = 0; long result = 0;
if (account != null) { if (account != null) {

View File

@ -29,6 +29,7 @@ import android.content.Intent;
import com.nextcloud.client.account.UserAccountManager; import com.nextcloud.client.account.UserAccountManager;
import com.owncloud.android.MainApp; import com.owncloud.android.MainApp;
import com.owncloud.android.datamodel.UploadsStorageManager;
import com.owncloud.android.lib.common.utils.Log_OC; import com.owncloud.android.lib.common.utils.Log_OC;
import javax.inject.Inject; import javax.inject.Inject;
@ -44,8 +45,8 @@ public class BootupBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = BootupBroadcastReceiver.class.getSimpleName(); private static final String TAG = BootupBroadcastReceiver.class.getSimpleName();
@Inject @Inject UserAccountManager accountManager;
UserAccountManager accountManager; @Inject UploadsStorageManager uploadsStorageManager;
/** /**
* Receives broadcast intent reporting that the system was just boot up. * Receives broadcast intent reporting that the system was just boot up.
@ -58,7 +59,7 @@ public class BootupBroadcastReceiver extends BroadcastReceiver {
AndroidInjection.inject(this, context); AndroidInjection.inject(this, context);
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) { if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
MainApp.initSyncOperations(accountManager); MainApp.initSyncOperations(uploadsStorageManager, accountManager);
MainApp.initContactsBackup(accountManager); MainApp.initContactsBackup(accountManager);
} else { } else {
Log_OC.d(TAG, "Getting wrong intent: " + intent.getAction()); Log_OC.d(TAG, "Getting wrong intent: " + intent.getAction());

View File

@ -5,9 +5,11 @@
* @author masensio * @author masensio
* @author LukeOwnCloud * @author LukeOwnCloud
* @author David A. Velasco * @author David A. Velasco
* @author Chris Narkiewicz
* *
* Copyright (C) 2012 Bartek Przybylski * Copyright (C) 2012 Bartek Przybylski
* Copyright (C) 2012-2016 ownCloud Inc. * Copyright (C) 2012-2016 ownCloud Inc.
* Copyright (C) 2019 Chris Narkiewicz <hello@ezaquarii.com>
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2, * it under the terms of the GNU General Public License version 2,
@ -46,6 +48,7 @@ import android.util.Pair;
import com.evernote.android.job.JobRequest; import com.evernote.android.job.JobRequest;
import com.evernote.android.job.util.Device; import com.evernote.android.job.util.Device;
import com.nextcloud.client.account.UserAccountManager;
import com.owncloud.android.MainApp; import com.owncloud.android.MainApp;
import com.owncloud.android.R; import com.owncloud.android.R;
import com.owncloud.android.authentication.AccountUtils; import com.owncloud.android.authentication.AccountUtils;
@ -74,6 +77,8 @@ import com.owncloud.android.utils.ErrorMessageAdapter;
import com.owncloud.android.utils.PowerUtils; import com.owncloud.android.utils.PowerUtils;
import com.owncloud.android.utils.ThemeUtils; import com.owncloud.android.utils.ThemeUtils;
import org.jetbrains.annotations.NotNull;
import java.io.File; import java.io.File;
import java.util.AbstractList; import java.util.AbstractList;
import java.util.HashMap; import java.util.HashMap;
@ -82,8 +87,11 @@ import java.util.Map;
import java.util.Vector; import java.util.Vector;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import javax.inject.Inject;
import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationCompat;
import dagger.android.AndroidInjection;
/** /**
* Service for uploading files. Invoke using context.startService(...). * Service for uploading files. Invoke using context.startService(...).
@ -121,6 +129,9 @@ public class FileUploader extends Service
private Notification mNotification; private Notification mNotification;
@Inject
protected UserAccountManager accountManager;
/** /**
* Call this Service with only this Intent key if all pending uploads are to be retried. * Call this Service with only this Intent key if all pending uploads are to be retried.
*/ */
@ -174,7 +185,7 @@ public class FileUploader extends Service
private Account mCurrentAccount; private Account mCurrentAccount;
private FileDataStorageManager mStorageManager; private FileDataStorageManager mStorageManager;
//since there can be only one instance of an Android service, there also just one db connection. //since there can be only one instance of an Android service, there also just one db connection.
private UploadsStorageManager mUploadsStorageManager; @Inject UploadsStorageManager mUploadsStorageManager;
private IndexedForest<UploadFileOperation> mPendingUploads = new IndexedForest<>(); private IndexedForest<UploadFileOperation> mPendingUploads = new IndexedForest<>();
@ -386,8 +397,12 @@ public class FileUploader extends Service
* @param uploadResult If not null, only failed uploads with the result specified will be retried; * @param uploadResult If not null, only failed uploads with the result specified will be retried;
* otherwise, failed uploads due to any result will be retried. * otherwise, failed uploads due to any result will be retried.
*/ */
public void retryFailedUploads(Context context, Account account, UploadResult uploadResult) { public void retryFailedUploads(
UploadsStorageManager uploadsStorageManager = new UploadsStorageManager(context.getContentResolver(), context); @NonNull final Context context,
@Nullable Account account,
@NotNull final UploadsStorageManager uploadsStorageManager,
@Nullable final UploadResult uploadResult
) {
OCUpload[] failedUploads = uploadsStorageManager.getFailedUploads(); OCUpload[] failedUploads = uploadsStorageManager.getFailedUploads();
Account currentAccount = null; Account currentAccount = null;
boolean resultMatch; boolean resultMatch;
@ -451,6 +466,7 @@ public class FileUploader extends Service
@Override @Override
public void onCreate() { public void onCreate() {
super.onCreate(); super.onCreate();
AndroidInjection.inject(this);
Log_OC.d(TAG, "Creating service"); Log_OC.d(TAG, "Creating service");
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
HandlerThread thread = new HandlerThread("FileUploaderThread", HandlerThread thread = new HandlerThread("FileUploaderThread",
@ -460,8 +476,6 @@ public class FileUploader extends Service
mServiceHandler = new ServiceHandler(mServiceLooper, this); mServiceHandler = new ServiceHandler(mServiceLooper, this);
mBinder = new FileUploaderBinder(); mBinder = new FileUploaderBinder();
mUploadsStorageManager = new UploadsStorageManager(getContentResolver(), getApplicationContext());
NotificationCompat.Builder builder = new NotificationCompat.Builder(this).setContentTitle( NotificationCompat.Builder builder = new NotificationCompat.Builder(this).setContentTitle(
getApplicationContext().getResources().getString(R.string.app_name)) getApplicationContext().getResources().getString(R.string.app_name))
.setContentText(getApplicationContext().getResources().getString(R.string.foreground_service_upload)) .setContentText(getApplicationContext().getResources().getString(R.string.foreground_service_upload))
@ -627,6 +641,7 @@ public class FileUploader extends Service
newUpload = new UploadFileOperation( newUpload = new UploadFileOperation(
mUploadsStorageManager,
account, account,
file, file,
ocUpload, ocUpload,
@ -685,6 +700,7 @@ public class FileUploader extends Service
whileChargingOnly = upload.isWhileChargingOnly(); whileChargingOnly = upload.isWhileChargingOnly();
UploadFileOperation newUpload = new UploadFileOperation( UploadFileOperation newUpload = new UploadFileOperation(
mUploadsStorageManager,
account, account,
null, null,
upload, upload,

View File

@ -2,8 +2,11 @@
* Nextcloud Android client application * Nextcloud Android client application
* *
* @author Tobias Kaminsky * @author Tobias Kaminsky
* @author Chris Narkiewicz
*
* Copyright (C) 2017 Tobias Kaminsky * Copyright (C) 2017 Tobias Kaminsky
* Copyright (C) 2017 Nextcloud GmbH. * Copyright (C) 2017 Nextcloud GmbH.
* Copyright (C) 2019 Chris Narkiewicz <hello@ezaquarii.com>
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by * it under the terms of the GNU Affero General Public License as published by
@ -63,6 +66,13 @@ public class AccountRemovalJob extends Job implements AccountManagerCallback<Boo
public static final String TAG = "AccountRemovalJob"; public static final String TAG = "AccountRemovalJob";
public static final String ACCOUNT = "account"; public static final String ACCOUNT = "account";
private UploadsStorageManager uploadsStorageManager;
public AccountRemovalJob(UploadsStorageManager uploadStorageManager) {
this.uploadsStorageManager = uploadStorageManager;
}
@NonNull @NonNull
@Override @Override
protected Result onRunJob(Params params) { protected Result onRunJob(Params params) {
@ -109,8 +119,6 @@ public class AccountRemovalJob extends Job implements AccountManagerCallback<Boo
syncedFolderProvider.deleteSyncFoldersForAccount(account); syncedFolderProvider.deleteSyncFoldersForAccount(account);
UploadsStorageManager uploadsStorageManager = new UploadsStorageManager(context.getContentResolver(),
context);
uploadsStorageManager.removeAccountUploads(account); uploadsStorageManager.removeAccountUploads(account);
FilesystemDataProvider filesystemDataProvider = new FilesystemDataProvider(context.getContentResolver()); FilesystemDataProvider filesystemDataProvider = new FilesystemDataProvider(context.getContentResolver());

View File

@ -43,6 +43,7 @@ import com.owncloud.android.datamodel.FilesystemDataProvider;
import com.owncloud.android.datamodel.MediaFolderType; import com.owncloud.android.datamodel.MediaFolderType;
import com.owncloud.android.datamodel.SyncedFolder; import com.owncloud.android.datamodel.SyncedFolder;
import com.owncloud.android.datamodel.SyncedFolderProvider; import com.owncloud.android.datamodel.SyncedFolderProvider;
import com.owncloud.android.datamodel.UploadsStorageManager;
import com.owncloud.android.files.services.FileUploader; import com.owncloud.android.files.services.FileUploader;
import com.owncloud.android.lib.common.utils.Log_OC; import com.owncloud.android.lib.common.utils.Log_OC;
import com.owncloud.android.operations.UploadFileOperation; import com.owncloud.android.operations.UploadFileOperation;
@ -77,10 +78,16 @@ public class FilesSyncJob extends Job {
private UserAccountManager userAccountManager; private UserAccountManager userAccountManager;
private AppPreferences preferences; private AppPreferences preferences;
private UploadsStorageManager uploadsStorageManager;
public FilesSyncJob(UserAccountManager userAccountManager, AppPreferences preferences) { public FilesSyncJob(
final UserAccountManager userAccountManager,
final AppPreferences preferences,
final UploadsStorageManager uploadsStorageManager
) {
this.userAccountManager = userAccountManager; this.userAccountManager = userAccountManager;
this.preferences = preferences; this.preferences = preferences;
this.uploadsStorageManager = uploadsStorageManager;
} }
@NonNull @NonNull
@ -109,7 +116,7 @@ public class FilesSyncJob extends Job {
boolean lightVersion = resources.getBoolean(R.bool.syncedFolder_light); boolean lightVersion = resources.getBoolean(R.bool.syncedFolder_light);
final boolean skipCustom = bundle.getBoolean(SKIP_CUSTOM, false); final boolean skipCustom = bundle.getBoolean(SKIP_CUSTOM, false);
FilesSyncHelper.restartJobsIfNeeded(userAccountManager); FilesSyncHelper.restartJobsIfNeeded(uploadsStorageManager, userAccountManager);
FilesSyncHelper.insertAllDBEntries(preferences, skipCustom); FilesSyncHelper.insertAllDBEntries(preferences, skipCustom);
// Create all the providers we'll need // Create all the providers we'll need

View File

@ -1,11 +1,13 @@
/** /*
* Nextcloud Android client application * Nextcloud Android client application
* *
* @author Mario Danic * @author Mario Danic
* @author Chris Narkiewicz * @author Chris Narkiewicz
*
* Copyright (C) 2017 Mario Danic * Copyright (C) 2017 Mario Danic
* Copyright (C) 2017 Nextcloud GmbH * Copyright (C) 2017 Nextcloud GmbH
* Copyright (C) 2019 Chris Narkiewicz <hello@ezaquarii.com> * Copyright (C) 2019 Chris Narkiewicz <hello@ezaquarii.com>
*
* <p> * <p>
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by * it under the terms of the GNU Affero General Public License as published by
@ -28,6 +30,7 @@ import com.evernote.android.job.Job;
import com.evernote.android.job.JobCreator; import com.evernote.android.job.JobCreator;
import com.nextcloud.client.account.UserAccountManager; import com.nextcloud.client.account.UserAccountManager;
import com.nextcloud.client.preferences.AppPreferences; import com.nextcloud.client.preferences.AppPreferences;
import com.owncloud.android.datamodel.UploadsStorageManager;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
@ -40,11 +43,18 @@ public class NCJobCreator implements JobCreator {
private final Context context; private final Context context;
private final UserAccountManager accountManager; private final UserAccountManager accountManager;
private final AppPreferences preferences; private final AppPreferences preferences;
private final UploadsStorageManager uploadsStorageManager;
public NCJobCreator(Context context, UserAccountManager accountManager, AppPreferences preferences) { public NCJobCreator(
Context context,
UserAccountManager accountManager,
AppPreferences preferences,
UploadsStorageManager uploadsStorageManager
) {
this.context = context; this.context = context;
this.accountManager = accountManager; this.accountManager = accountManager;
this.preferences = preferences; this.preferences = preferences;
this.uploadsStorageManager = uploadsStorageManager;
} }
@Override @Override
@ -55,9 +65,9 @@ public class NCJobCreator implements JobCreator {
case ContactsImportJob.TAG: case ContactsImportJob.TAG:
return new ContactsImportJob(); return new ContactsImportJob();
case AccountRemovalJob.TAG: case AccountRemovalJob.TAG:
return new AccountRemovalJob(); return new AccountRemovalJob(uploadsStorageManager);
case FilesSyncJob.TAG: case FilesSyncJob.TAG:
return new FilesSyncJob(accountManager, preferences); return new FilesSyncJob(accountManager, preferences, uploadsStorageManager);
case OfflineSyncJob.TAG: case OfflineSyncJob.TAG:
return new OfflineSyncJob(accountManager); return new OfflineSyncJob(accountManager);
case NotificationJob.TAG: case NotificationJob.TAG:

View File

@ -2,7 +2,9 @@
* ownCloud Android client application * ownCloud Android client application
* *
* @author David A. Velasco * @author David A. Velasco
* @author Chris Narkiewicz
* Copyright (C) 2016 ownCloud GmbH. * Copyright (C) 2016 ownCloud GmbH.
* Copyright (C) 2019 Chris Narkiewicz <hello@ezaquarii.com>
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2, * it under the terms of the GNU General Public License version 2,
@ -142,9 +144,9 @@ public class UploadFileOperation extends SyncOperation {
private RequestEntity mEntity; private RequestEntity mEntity;
private Account mAccount; final private Account mAccount;
private OCUpload mUpload; final private OCUpload mUpload;
private UploadsStorageManager uploadsStorageManager; final private UploadsStorageManager uploadsStorageManager;
private boolean encryptedAncestor; private boolean encryptedAncestor;
@ -174,7 +176,8 @@ public class UploadFileOperation extends SyncOperation {
return newFile; return newFile;
} }
public UploadFileOperation(Account account, public UploadFileOperation(UploadsStorageManager uploadsStorageManager,
Account account,
OCFile file, OCFile file,
OCUpload upload, OCUpload upload,
boolean forceOverwrite, boolean forceOverwrite,
@ -195,6 +198,7 @@ public class UploadFileOperation extends SyncOperation {
+ upload.getLocalPath()); + upload.getLocalPath());
} }
this.uploadsStorageManager = uploadsStorageManager;
mAccount = account; mAccount = account;
mUpload = upload; mUpload = upload;
if (file == null) { if (file == null) {
@ -352,8 +356,6 @@ public class UploadFileOperation extends SyncOperation {
mCancellationRequested.set(false); mCancellationRequested.set(false);
mUploadStarted.set(true); mUploadStarted.set(true);
uploadsStorageManager = new UploadsStorageManager(mContext.getContentResolver(), mContext);
for (OCUpload ocUpload : uploadsStorageManager.getAllStoredUploads()) { for (OCUpload ocUpload : uploadsStorageManager.getAllStoredUploads()) {
if (ocUpload.getUploadId() == getOCUploadId()) { if (ocUpload.getUploadId() == getOCUploadId()) {
ocUpload.setFileSize(0); ocUpload.setFileSize(0);

View File

@ -31,6 +31,7 @@ import android.net.Uri;
import android.os.ParcelFileDescriptor; import android.os.ParcelFileDescriptor;
import android.provider.OpenableColumns; import android.provider.OpenableColumns;
import com.nextcloud.client.account.UserAccountManager;
import com.owncloud.android.MainApp; import com.owncloud.android.MainApp;
import com.owncloud.android.authentication.AccountUtils; import com.owncloud.android.authentication.AccountUtils;
import com.owncloud.android.datamodel.FileDataStorageManager; import com.owncloud.android.datamodel.FileDataStorageManager;
@ -43,18 +44,25 @@ import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import javax.inject.Inject;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import dagger.android.AndroidInjection;
public class DiskLruImageCacheFileProvider extends ContentProvider { public class DiskLruImageCacheFileProvider extends ContentProvider {
public static final String TAG = DiskLruImageCacheFileProvider.class.getSimpleName(); public static final String TAG = DiskLruImageCacheFileProvider.class.getSimpleName();
@Inject
protected UserAccountManager accountManager;
@Override @Override
public boolean onCreate() { public boolean onCreate() {
AndroidInjection.inject(this);
return true; return true;
} }
private OCFile getFile(Uri uri) { private OCFile getFile(Uri uri) {
Account account = AccountUtils.getCurrentOwnCloudAccount(MainApp.getAppContext()); Account account = accountManager.getCurrentAccount();
FileDataStorageManager fileDataStorageManager = new FileDataStorageManager(account, FileDataStorageManager fileDataStorageManager = new FileDataStorageManager(account,
MainApp.getAppContext().getContentResolver()); MainApp.getAppContext().getContentResolver());

View File

@ -34,6 +34,7 @@ import android.os.Looper;
import android.provider.BaseColumns; import android.provider.BaseColumns;
import android.widget.Toast; import android.widget.Toast;
import com.nextcloud.client.account.UserAccountManager;
import com.owncloud.android.R; import com.owncloud.android.R;
import com.owncloud.android.authentication.AccountUtils; import com.owncloud.android.authentication.AccountUtils;
import com.owncloud.android.datamodel.FileDataStorageManager; import com.owncloud.android.datamodel.FileDataStorageManager;
@ -53,8 +54,11 @@ import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import javax.inject.Inject;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import dagger.android.AndroidInjection;
/** /**
@ -89,6 +93,9 @@ public class UsersAndGroupsSearchProvider extends ContentProvider {
private UriMatcher mUriMatcher; private UriMatcher mUriMatcher;
@Inject
protected UserAccountManager accountManager;
private static Map<String, ShareType> sShareTypes = new HashMap<>(); private static Map<String, ShareType> sShareTypes = new HashMap<>();
public static ShareType getShareType(String authority) { public static ShareType getShareType(String authority) {
@ -96,6 +103,10 @@ public class UsersAndGroupsSearchProvider extends ContentProvider {
return sShareTypes.get(authority); return sShareTypes.get(authority);
} }
private static void setActionShareWith(@NonNull Context context) {
ACTION_SHARE_WITH = context.getResources().getString(R.string.users_and_groups_share_with);
}
@Nullable @Nullable
@Override @Override
public String getType(@NonNull Uri uri) { public String getType(@NonNull Uri uri) {
@ -105,12 +116,14 @@ public class UsersAndGroupsSearchProvider extends ContentProvider {
@Override @Override
public boolean onCreate() { public boolean onCreate() {
AndroidInjection.inject(this);
if (getContext() == null) { if (getContext() == null) {
return false; return false;
} }
String AUTHORITY = getContext().getResources().getString(R.string.users_and_groups_search_authority); String AUTHORITY = getContext().getResources().getString(R.string.users_and_groups_search_authority);
ACTION_SHARE_WITH = getContext().getResources().getString(R.string.users_and_groups_share_with); setActionShareWith(getContext());
DATA_USER = AUTHORITY + ".data.user"; DATA_USER = AUTHORITY + ".data.user";
DATA_GROUP = AUTHORITY + ".data.group"; DATA_GROUP = AUTHORITY + ".data.group";
DATA_ROOM = AUTHORITY + ".data.room"; DATA_ROOM = AUTHORITY + ".data.room";
@ -168,7 +181,7 @@ public class UsersAndGroupsSearchProvider extends ContentProvider {
// need to trust on the AccountUtils to get the current account since the query in the client side is not // 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 // directly started by our code, but from SearchView implementation
Account account = AccountUtils.getCurrentOwnCloudAccount(getContext()); Account account = accountManager.getCurrentAccount();
if (account == null) { if (account == null) {
throw new IllegalArgumentException("Account may not be null!"); throw new IllegalArgumentException("Account may not be null!");

View File

@ -37,7 +37,8 @@ import com.owncloud.android.lib.common.OwnCloudClient;
import com.owncloud.android.lib.common.utils.Log_OC; import com.owncloud.android.lib.common.utils.Log_OC;
import com.owncloud.android.lib.resources.activities.model.RichObject; import com.owncloud.android.lib.resources.activities.model.RichObject;
import com.owncloud.android.lib.resources.files.FileUtils; import com.owncloud.android.lib.resources.files.FileUtils;
import com.owncloud.android.ui.activities.data.Injection; import com.owncloud.android.ui.activities.data.activities.ActivitiesRepository;
import com.owncloud.android.ui.activities.data.files.FilesRepository;
import com.owncloud.android.ui.activity.FileActivity; import com.owncloud.android.ui.activity.FileActivity;
import com.owncloud.android.ui.activity.FileDisplayActivity; import com.owncloud.android.ui.activity.FileDisplayActivity;
import com.owncloud.android.ui.adapter.ActivityListAdapter; import com.owncloud.android.ui.adapter.ActivityListAdapter;
@ -49,6 +50,8 @@ import com.owncloud.android.utils.ThemeUtils;
import java.util.List; import java.util.List;
import javax.inject.Inject;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.ActionBar;
import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.LinearLayoutManager;
@ -99,15 +102,15 @@ public class ActivitiesActivity extends FileActivity implements ActivityListInte
private boolean isLoadingActivities; private boolean isLoadingActivities;
private ActivitiesContract.ActionListener mActionListener; private ActivitiesContract.ActionListener mActionListener;
@Inject ActivitiesRepository activitiesRepository;
@Inject FilesRepository filesRepository;
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
Log_OC.v(TAG, "onCreate() start"); Log_OC.v(TAG, "onCreate() start");
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
mActionListener = new ActivitiesPresenter(Injection.provideActivitiesRepository(), mActionListener = new ActivitiesPresenter(activitiesRepository, filesRepository, this);
Injection.provideFilesRepository(),
this);
setContentView(R.layout.activity_list_layout); setContentView(R.layout.activity_list_layout);
unbinder = ButterKnife.bind(this); unbinder = ButterKnife.bind(this);
@ -171,7 +174,7 @@ public class ActivitiesActivity extends FileActivity implements ActivityListInte
PorterDuff.Mode.SRC_IN); PorterDuff.Mode.SRC_IN);
FileDataStorageManager storageManager = new FileDataStorageManager(getAccount(), getContentResolver()); FileDataStorageManager storageManager = new FileDataStorageManager(getAccount(), getContentResolver());
adapter = new ActivityListAdapter(this, this, storageManager, getCapabilities(), false); adapter = new ActivityListAdapter(this, getUserAccountManager(), this, storageManager, getCapabilities(), false);
recyclerView.setAdapter(adapter); recyclerView.setAdapter(adapter);
LinearLayoutManager layoutManager = new LinearLayoutManager(this); LinearLayoutManager layoutManager = new LinearLayoutManager(this);
@ -198,7 +201,13 @@ public class ActivitiesActivity extends FileActivity implements ActivityListInte
if (getResources().getBoolean(R.bool.bottom_toolbar_enabled)) { if (getResources().getBoolean(R.bool.bottom_toolbar_enabled)) {
bottomNavigationView.setVisibility(View.VISIBLE); bottomNavigationView.setVisibility(View.VISIBLE);
DisplayUtils.setupBottomBar(bottomNavigationView, getResources(), this, -1); DisplayUtils.setupBottomBar(
getUserAccountManager().getCurrentAccount(),
bottomNavigationView,
getResources(),
this,
-1
);
} }
mActionListener.loadActivities(null); mActionListener.loadActivities(null);

View File

@ -1,41 +0,0 @@
/**
* Nextcloud Android client application
*
* Copyright (C) 2018 Edvard Holst
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.owncloud.android.ui.activities.data;
import com.owncloud.android.ui.activities.data.activities.ActivitiesRepository;
import com.owncloud.android.ui.activities.data.activities.ActivitiesServiceApiImpl;
import com.owncloud.android.ui.activities.data.activities.ActivityRepositories;
import com.owncloud.android.ui.activities.data.files.FileRepositories;
import com.owncloud.android.ui.activities.data.files.FilesRepository;
import com.owncloud.android.ui.activities.data.files.FilesServiceApiImpl;
public class Injection {
private Injection () {
// Required empty constructor
}
public static ActivitiesRepository provideActivitiesRepository() {
return ActivityRepositories.getRepository(new ActivitiesServiceApiImpl());
}
public static FilesRepository provideFilesRepository() {
return FileRepositories.getRepository(new FilesServiceApiImpl());
}
}

View File

@ -1,7 +1,11 @@
/* /*
* Nextcloud Android client application * Nextcloud Android client application
* *
* @author Edvard Holst
* @author Chris Narkiewicz
*
* Copyright (C) 2018 Edvard Holst * Copyright (C) 2018 Edvard Holst
* Copyright (C) 2019 Chris Narkiewicz <hello@ezaquarii.com>
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
@ -24,6 +28,7 @@ import android.accounts.OperationCanceledException;
import android.content.Context; import android.content.Context;
import android.os.AsyncTask; import android.os.AsyncTask;
import com.nextcloud.client.account.UserAccountManager;
import com.owncloud.android.MainApp; import com.owncloud.android.MainApp;
import com.owncloud.android.R; import com.owncloud.android.R;
import com.owncloud.android.authentication.AccountUtils; import com.owncloud.android.authentication.AccountUtils;
@ -46,10 +51,16 @@ import java.util.List;
public class ActivitiesServiceApiImpl implements ActivitiesServiceApi { public class ActivitiesServiceApiImpl implements ActivitiesServiceApi {
private static final String TAG = ActivitiesServiceApiImpl.class.getSimpleName(); private static final String TAG = ActivitiesServiceApiImpl.class.getSimpleName();
private UserAccountManager accountManager;
public ActivitiesServiceApiImpl(UserAccountManager accountManager) {
this.accountManager = accountManager;
}
@Override @Override
public void getAllActivities(String pageUrl, ActivitiesServiceCallback<List<Object>> callback) { public void getAllActivities(String pageUrl, ActivitiesServiceCallback<List<Object>> callback) {
GetActivityListTask getActivityListTask = new GetActivityListTask(pageUrl, callback); Account account = accountManager.getCurrentAccount();
GetActivityListTask getActivityListTask = new GetActivityListTask(account, pageUrl, callback);
getActivityListTask.execute(); getActivityListTask.execute();
} }
@ -57,11 +68,13 @@ public class ActivitiesServiceApiImpl implements ActivitiesServiceApi {
private final ActivitiesServiceCallback<List<Object>> callback; private final ActivitiesServiceCallback<List<Object>> callback;
private List<Object> activities; private List<Object> activities;
private Account account;
private String pageUrl; private String pageUrl;
private String errorMessage; private String errorMessage;
private OwnCloudClient ownCloudClient; private OwnCloudClient ownCloudClient;
private GetActivityListTask(String pageUrl, ActivitiesServiceCallback<List<Object>> callback) { private GetActivityListTask(Account account, String pageUrl, ActivitiesServiceCallback<List<Object>> callback) {
this.account = account;
this.pageUrl = pageUrl; this.pageUrl = pageUrl;
this.callback = callback; this.callback = callback;
activities = new ArrayList<>(); activities = new ArrayList<>();
@ -71,13 +84,12 @@ public class ActivitiesServiceApiImpl implements ActivitiesServiceApi {
@Override @Override
protected Boolean doInBackground(Void... voids) { protected Boolean doInBackground(Void... voids) {
final Context context = MainApp.getAppContext(); final Context context = MainApp.getAppContext();
final Account currentAccount = AccountUtils.getCurrentOwnCloudAccount(context);
OwnCloudAccount ocAccount; OwnCloudAccount ocAccount;
try { try {
ocAccount = new OwnCloudAccount(currentAccount, context); ocAccount = new OwnCloudAccount(account, context);
ownCloudClient = OwnCloudClientManagerFactory.getDefaultSingleton(). ownCloudClient = OwnCloudClientManagerFactory.getDefaultSingleton().
getClientFor(ocAccount, MainApp.getAppContext()); getClientFor(ocAccount, MainApp.getAppContext());
ownCloudClient.setOwnCloudVersion(AccountUtils.getServerVersion(currentAccount)); ownCloudClient.setOwnCloudVersion(AccountUtils.getServerVersion(account));
GetActivitiesRemoteOperation getRemoteNotificationOperation = new GetActivitiesRemoteOperation(); GetActivitiesRemoteOperation getRemoteNotificationOperation = new GetActivitiesRemoteOperation();
if (pageUrl != null) { if (pageUrl != null) {

View File

@ -1,7 +1,11 @@
/* /*
* Nextcloud Android client application * Nextcloud Android client application
* *
* @author Chris Narkiewicz
* @author Edvard Holst
*
* Copyright (C) 2018 Edvard Holst * Copyright (C) 2018 Edvard Holst
* Copyright (C) 2019 Chris Narkiewicz <hello@ezaquarii.com>
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
@ -24,6 +28,7 @@ import android.accounts.OperationCanceledException;
import android.content.Context; import android.content.Context;
import android.os.AsyncTask; import android.os.AsyncTask;
import com.nextcloud.client.account.UserAccountManager;
import com.owncloud.android.MainApp; import com.owncloud.android.MainApp;
import com.owncloud.android.R; import com.owncloud.android.R;
import com.owncloud.android.authentication.AccountUtils; import com.owncloud.android.authentication.AccountUtils;
@ -49,9 +54,20 @@ public class FilesServiceApiImpl implements FilesServiceApi {
private static final String TAG = FilesServiceApiImpl.class.getSimpleName(); private static final String TAG = FilesServiceApiImpl.class.getSimpleName();
private UserAccountManager accountManager;
public FilesServiceApiImpl(UserAccountManager accountManager) {
this.accountManager = accountManager;
}
@Override @Override
public void readRemoteFile(String fileUrl, BaseActivity activity, FilesServiceCallback<OCFile> callback) { public void readRemoteFile(String fileUrl, BaseActivity activity, FilesServiceCallback<OCFile> callback) {
ReadRemoteFileTask readRemoteFileTask = new ReadRemoteFileTask(fileUrl, activity, callback); ReadRemoteFileTask readRemoteFileTask = new ReadRemoteFileTask(
accountManager.getCurrentAccount(),
fileUrl,
activity,
callback
);
readRemoteFileTask.execute(); readRemoteFileTask.execute();
} }
@ -62,24 +78,25 @@ public class FilesServiceApiImpl implements FilesServiceApi {
// TODO: Figure out a better way to do this than passing a BaseActivity reference. // TODO: Figure out a better way to do this than passing a BaseActivity reference.
private final BaseActivity baseActivity; private final BaseActivity baseActivity;
private final String fileUrl; private final String fileUrl;
private final Account account;
private ReadRemoteFileTask(String fileUrl, BaseActivity baseActivity, FilesServiceCallback<OCFile> callback) { private ReadRemoteFileTask(Account account, String fileUrl, BaseActivity baseActivity, FilesServiceCallback<OCFile> callback) {
this.callback = callback; this.callback = callback;
this.baseActivity = baseActivity; this.baseActivity = baseActivity;
this.fileUrl = fileUrl; this.fileUrl = fileUrl;
this.account = account;
} }
@Override @Override
protected Boolean doInBackground(Void... voids) { protected Boolean doInBackground(Void... voids) {
final Account currentAccount = AccountUtils.getCurrentOwnCloudAccount(MainApp.getAppContext());
final Context context = MainApp.getAppContext(); final Context context = MainApp.getAppContext();
OwnCloudAccount ocAccount; OwnCloudAccount ocAccount;
OwnCloudClient ownCloudClient; OwnCloudClient ownCloudClient;
try { try {
ocAccount = new OwnCloudAccount(currentAccount, context); ocAccount = new OwnCloudAccount(account, context);
ownCloudClient = OwnCloudClientManagerFactory.getDefaultSingleton(). ownCloudClient = OwnCloudClientManagerFactory.getDefaultSingleton().
getClientFor(ocAccount, MainApp.getAppContext()); getClientFor(ocAccount, MainApp.getAppContext());
ownCloudClient.setOwnCloudVersion(AccountUtils.getServerVersion(currentAccount)); ownCloudClient.setOwnCloudVersion(AccountUtils.getServerVersion(account));
// always update file as it could be an old state saved in database // always update file as it could be an old state saved in database
RemoteOperationResult resultRemoteFileOp = new ReadFileRemoteOperation(fileUrl).execute(ownCloudClient); RemoteOperationResult resultRemoteFileOp = new ReadFileRemoteOperation(fileUrl).execute(ownCloudClient);

View File

@ -23,7 +23,7 @@ import com.owncloud.android.ui.activity.BaseActivity;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
class RemoteFilesRepository implements FilesRepository { public class RemoteFilesRepository implements FilesRepository {
private final FilesServiceApi filesServiceApi; private final FilesServiceApi filesServiceApi;

View File

@ -9,6 +9,8 @@ import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler; import android.os.Handler;
import com.nextcloud.client.account.UserAccountManager;
import com.nextcloud.client.di.Injectable;
import com.owncloud.android.MainApp; import com.owncloud.android.MainApp;
import com.owncloud.android.authentication.AccountUtils; import com.owncloud.android.authentication.AccountUtils;
import com.owncloud.android.datamodel.FileDataStorageManager; import com.owncloud.android.datamodel.FileDataStorageManager;
@ -16,12 +18,14 @@ import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.lib.common.utils.Log_OC; import com.owncloud.android.lib.common.utils.Log_OC;
import com.owncloud.android.lib.resources.status.OCCapability; import com.owncloud.android.lib.resources.status.OCCapability;
import javax.inject.Inject;
import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatActivity;
/** /**
* Base activity with common behaviour for activities dealing with ownCloud {@link Account}s . * Base activity with common behaviour for activities dealing with ownCloud {@link Account}s .
*/ */
public abstract class BaseActivity extends AppCompatActivity { public abstract class BaseActivity extends AppCompatActivity implements Injectable {
private static final String TAG = BaseActivity.class.getSimpleName(); private static final String TAG = BaseActivity.class.getSimpleName();
/** /**
@ -49,10 +53,16 @@ public abstract class BaseActivity extends AppCompatActivity {
*/ */
private FileDataStorageManager mStorageManager; private FileDataStorageManager mStorageManager;
@Inject UserAccountManager accountManager;
public UserAccountManager getUserAccountManager() {
return accountManager;
}
@Override @Override
protected void onNewIntent (Intent intent) { protected void onNewIntent (Intent intent) {
Log_OC.v(TAG, "onNewIntent() start"); Log_OC.v(TAG, "onNewIntent() start");
Account current = AccountUtils.getCurrentOwnCloudAccount(this); Account current = accountManager.getCurrentAccount();
if (current != null && mCurrentAccount != null && !mCurrentAccount.name.equals(current.name)) { if (current != null && mCurrentAccount != null && !mCurrentAccount.name.equals(current.name)) {
mCurrentAccount = current; mCurrentAccount = current;
} }
@ -108,7 +118,7 @@ public abstract class BaseActivity extends AppCompatActivity {
*/ */
protected void swapToDefaultAccount() { protected void swapToDefaultAccount() {
// default to the most recently used account // default to the most recently used account
Account newAccount = AccountUtils.getCurrentOwnCloudAccount(getApplicationContext()); Account newAccount = accountManager.getCurrentAccount();
if (newAccount == null) { if (newAccount == null) {
/// no account available: force account creation /// no account available: force account creation
createAccount(true); createAccount(true);

View File

@ -109,7 +109,13 @@ public class ContactsPreferenceActivity extends FileActivity implements FileFrag
if (getResources().getBoolean(R.bool.bottom_toolbar_enabled)) { if (getResources().getBoolean(R.bool.bottom_toolbar_enabled)) {
bottomNavigationView.setVisibility(View.VISIBLE); bottomNavigationView.setVisibility(View.VISIBLE);
DisplayUtils.setupBottomBar(bottomNavigationView, getResources(), this, -1); DisplayUtils.setupBottomBar(
getUserAccountManager().getCurrentAccount(),
bottomNavigationView,
getResources(),
this,
-1
);
} }
} }

View File

@ -356,7 +356,7 @@ public abstract class DrawerActivity extends ToolbarActivity
navigationView.getMenu().setGroupVisible(R.id.drawer_menu_accounts, false); navigationView.getMenu().setGroupVisible(R.id.drawer_menu_accounts, false);
} }
Account account = AccountUtils.getCurrentOwnCloudAccount(this); Account account = accountManager.getCurrentAccount();
filterDrawerMenu(navigationView.getMenu(), account); filterDrawerMenu(navigationView.getMenu(), account);
} }
@ -545,11 +545,10 @@ public abstract class DrawerActivity extends ToolbarActivity
* @param accountName The account name to be set * @param accountName The account name to be set
*/ */
private void accountClicked(String accountName) { private void accountClicked(String accountName) {
if (!AccountUtils.getCurrentOwnCloudAccount(getApplicationContext()).name.equals(accountName)) { final Account currentAccount = accountManager.getCurrentAccount();
if (currentAccount != null && !TextUtils.equals(currentAccount.name, accountName)) {
AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), accountName); AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), accountName);
fetchExternalLinks(true); fetchExternalLinks(true);
restart(); restart();
} }
} }
@ -654,7 +653,7 @@ public abstract class DrawerActivity extends ToolbarActivity
if (mNavigationView != null && mDrawerLayout != null) { if (mNavigationView != null && mDrawerLayout != null) {
if (persistingAccounts.size() > 0) { if (persistingAccounts.size() > 0) {
repopulateAccountList(persistingAccounts); repopulateAccountList(persistingAccounts);
setAccountInDrawer(AccountUtils.getCurrentOwnCloudAccount(this)); setAccountInDrawer(accountManager.getCurrentAccount());
populateDrawerOwnCloudAccounts(); populateDrawerOwnCloudAccounts();
// activate second/end account avatar // activate second/end account avatar
@ -974,15 +973,15 @@ public abstract class DrawerActivity extends ToolbarActivity
// set user space information // set user space information
Thread t = new Thread(new Runnable() { Thread t = new Thread(new Runnable() {
public void run() { public void run() {
Context context = MainApp.getAppContext(); final Account currentAccount = accountManager.getCurrentAccount();
Account account = AccountUtils.getCurrentOwnCloudAccount(context);
if (account == null) { if (currentAccount == null) {
return; return;
} }
final Context context = MainApp.getAppContext();
AccountManager mAccountMgr = AccountManager.get(context); AccountManager mAccountMgr = AccountManager.get(context);
String userId = mAccountMgr.getUserData(account, String userId = mAccountMgr.getUserData(currentAccount,
com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_USER_ID); com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_USER_ID);
RemoteOperation getQuotaInfoOperation; RemoteOperation getQuotaInfoOperation;
@ -992,7 +991,7 @@ public abstract class DrawerActivity extends ToolbarActivity
getQuotaInfoOperation = new GetRemoteUserInfoOperation(userId); getQuotaInfoOperation = new GetRemoteUserInfoOperation(userId);
} }
RemoteOperationResult result = getQuotaInfoOperation.execute(account, context); RemoteOperationResult result = getQuotaInfoOperation.execute(currentAccount, context);
if (result.isSuccess() && result.getData() != null) { if (result.isSuccess() && result.getData() != null) {
final UserInfo userInfo = (UserInfo) result.getData().get(0); final UserInfo userInfo = (UserInfo) result.getData().get(0);
@ -1000,7 +999,7 @@ public abstract class DrawerActivity extends ToolbarActivity
// Since we always call this method, might as well put it here // Since we always call this method, might as well put it here
if (userInfo.getId() != null) { if (userInfo.getId() != null) {
mAccountMgr.setUserData(account, mAccountMgr.setUserData(currentAccount,
com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_USER_ID, com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_USER_ID,
userInfo.getId()); userInfo.getId());
} }
@ -1252,7 +1251,7 @@ public abstract class DrawerActivity extends ToolbarActivity
// current account has changed // current account has changed
if (data.getBooleanExtra(ManageAccountsActivity.KEY_CURRENT_ACCOUNT_CHANGED, false)) { if (data.getBooleanExtra(ManageAccountsActivity.KEY_CURRENT_ACCOUNT_CHANGED, false)) {
setAccount(AccountUtils.getCurrentOwnCloudAccount(this)); setAccount(accountManager.getCurrentAccount());
updateAccountList(); updateAccountList();
restart(); restart();
} else { } else {
@ -1334,7 +1333,7 @@ public abstract class DrawerActivity extends ToolbarActivity
} }
} }
Account currentAccount = AccountUtils.getCurrentOwnCloudAccount(this); Account currentAccount = accountManager.getCurrentAccount();
mAvatars[0] = currentAccount; mAvatars[0] = currentAccount;
int j = 0; int j = 0;
@ -1416,7 +1415,7 @@ public abstract class DrawerActivity extends ToolbarActivity
getCapabilities.execute(getStorageManager(), getBaseContext()); getCapabilities.execute(getStorageManager(), getBaseContext());
} }
Account account = AccountUtils.getCurrentOwnCloudAccount(this); Account account = accountManager.getCurrentAccount();
if (account != null && getStorageManager() != null && if (account != null && getStorageManager() != null &&
getStorageManager().getCapability(account.name) != null && getStorageManager().getCapability(account.name) != null &&

View File

@ -141,7 +141,8 @@ public abstract class FileActivity extends DrawerActivity
private ServiceConnection mDownloadServiceConnection; private ServiceConnection mDownloadServiceConnection;
private ServiceConnection mUploadServiceConnection; private ServiceConnection mUploadServiceConnection;
@Inject UserAccountManager accountManager; @Inject
protected UserAccountManager accountManager;
@Override @Override
public void showFiles(boolean onDeviceOnly) { public void showFiles(boolean onDeviceOnly) {
@ -160,7 +161,7 @@ public abstract class FileActivity extends DrawerActivity
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
mHandler = new Handler(); mHandler = new Handler();
mFileOperationsHelper = new FileOperationsHelper(this); mFileOperationsHelper = new FileOperationsHelper(this, getUserAccountManager());
Account account = null; Account account = null;
if (savedInstanceState != null) { if (savedInstanceState != null) {

View File

@ -58,16 +58,15 @@ import android.widget.ImageView;
import com.google.android.material.bottomnavigation.BottomNavigationView; import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.snackbar.Snackbar; import com.google.android.material.snackbar.Snackbar;
import com.nextcloud.client.account.UserAccountManager;
import com.nextcloud.client.di.Injectable; import com.nextcloud.client.di.Injectable;
import com.nextcloud.client.preferences.AppPreferences;
import com.nextcloud.client.preferences.AppPreferencesImpl;
import com.owncloud.android.MainApp; import com.owncloud.android.MainApp;
import com.owncloud.android.R; import com.owncloud.android.R;
import com.owncloud.android.datamodel.ArbitraryDataProvider; import com.owncloud.android.datamodel.ArbitraryDataProvider;
import com.owncloud.android.datamodel.FileDataStorageManager; import com.owncloud.android.datamodel.FileDataStorageManager;
import com.owncloud.android.datamodel.OCFile; import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.datamodel.VirtualFolderType; import com.owncloud.android.datamodel.VirtualFolderType;
import com.nextcloud.client.preferences.AppPreferences;
import com.nextcloud.client.preferences.AppPreferencesImpl;
import com.owncloud.android.files.services.FileDownloader; import com.owncloud.android.files.services.FileDownloader;
import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder; import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
import com.owncloud.android.files.services.FileUploader; import com.owncloud.android.files.services.FileUploader;
@ -214,7 +213,6 @@ public class FileDisplayActivity extends FileActivity
private SearchView searchView; private SearchView searchView;
@Inject AppPreferences preferences; @Inject AppPreferences preferences;
@Inject UserAccountManager accountManager;
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
@ -2367,7 +2365,7 @@ public class FileDisplayActivity extends FileActivity
if (showPreview) { if (showPreview) {
startActivity(showDetailsIntent); startActivity(showDetailsIntent);
} else { } else {
FileOperationsHelper fileOperationsHelper = new FileOperationsHelper(this); FileOperationsHelper fileOperationsHelper = new FileOperationsHelper(this, getUserAccountManager());
fileOperationsHelper.startSyncForFileAndIntent(file, showDetailsIntent); fileOperationsHelper.startSyncForFileAndIntent(file, showDetailsIntent);
} }
} }
@ -2386,7 +2384,7 @@ public class FileDisplayActivity extends FileActivity
if (showPreview) { if (showPreview) {
startActivity(showDetailsIntent); startActivity(showDetailsIntent);
} else { } else {
FileOperationsHelper fileOperationsHelper = new FileOperationsHelper(this); FileOperationsHelper fileOperationsHelper = new FileOperationsHelper(this, getUserAccountManager());
fileOperationsHelper.startSyncForFileAndIntent(file, showDetailsIntent); fileOperationsHelper.startSyncForFileAndIntent(file, showDetailsIntent);
} }
} }
@ -2413,7 +2411,7 @@ public class FileDisplayActivity extends FileActivity
previewIntent.putExtra(EXTRA_FILE, file); previewIntent.putExtra(EXTRA_FILE, file);
previewIntent.putExtra(PreviewVideoActivity.EXTRA_START_POSITION, startPlaybackPosition); previewIntent.putExtra(PreviewVideoActivity.EXTRA_START_POSITION, startPlaybackPosition);
previewIntent.putExtra(PreviewVideoActivity.EXTRA_AUTOPLAY, autoplay); previewIntent.putExtra(PreviewVideoActivity.EXTRA_AUTOPLAY, autoplay);
FileOperationsHelper fileOperationsHelper = new FileOperationsHelper(this); FileOperationsHelper fileOperationsHelper = new FileOperationsHelper(this, getUserAccountManager());
fileOperationsHelper.startSyncForFileAndIntent(file, previewIntent); fileOperationsHelper.startSyncForFileAndIntent(file, previewIntent);
} }
} }
@ -2440,7 +2438,7 @@ public class FileDisplayActivity extends FileActivity
Intent previewIntent = new Intent(); Intent previewIntent = new Intent();
previewIntent.putExtra(EXTRA_FILE, file); previewIntent.putExtra(EXTRA_FILE, file);
previewIntent.putExtra(TEXT_PREVIEW, true); previewIntent.putExtra(TEXT_PREVIEW, true);
FileOperationsHelper fileOperationsHelper = new FileOperationsHelper(this); FileOperationsHelper fileOperationsHelper = new FileOperationsHelper(this, getUserAccountManager());
fileOperationsHelper.startSyncForFileAndIntent(file, previewIntent); fileOperationsHelper.startSyncForFileAndIntent(file, previewIntent);
} }
} }
@ -2570,9 +2568,9 @@ public class FileDisplayActivity extends FileActivity
@Subscribe(threadMode = ThreadMode.BACKGROUND) @Subscribe(threadMode = ThreadMode.BACKGROUND)
public void onMessageEvent(TokenPushEvent event) { public void onMessageEvent(TokenPushEvent event) {
if (!preferences.isKeysReInitEnabled()) { if (!preferences.isKeysReInitEnabled()) {
PushUtils.reinitKeys(accountManager); PushUtils.reinitKeys(getUserAccountManager());
} else { } else {
PushUtils.pushRegistrationToServer(accountManager, preferences.getPushToken()); PushUtils.pushRegistrationToServer(getUserAccountManager(), preferences.getPushToken());
} }
} }

View File

@ -2,7 +2,9 @@
* ownCloud Android client application * ownCloud Android client application
* *
* @author Andy Scherzinger * @author Andy Scherzinger
* @author Chris Narkiewicz
* Copyright (C) 2016 ownCloud Inc. * Copyright (C) 2016 ownCloud Inc.
* Copyright (C) 2019 Chris Narkiewicz <hello@ezaquarii.com>
* <p/> * <p/>
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2, * it under the terms of the GNU General Public License version 2,
@ -117,7 +119,7 @@ public class ManageAccountsActivity extends FileActivity
Account[] accountList = AccountManager.get(this).getAccountsByType(MainApp.getAccountType(this)); Account[] accountList = AccountManager.get(this).getAccountsByType(MainApp.getAccountType(this));
mOriginalAccounts = DisplayUtils.toAccountNameSet(Arrays.asList(accountList)); mOriginalAccounts = DisplayUtils.toAccountNameSet(Arrays.asList(accountList));
Account currentAccount = AccountUtils.getCurrentOwnCloudAccount(this); Account currentAccount = getUserAccountManager().getCurrentAccount();
if (currentAccount != null) { if (currentAccount != null) {
mOriginalCurrentAccount = currentAccount.name; mOriginalCurrentAccount = currentAccount.name;
@ -128,7 +130,7 @@ public class ManageAccountsActivity extends FileActivity
arbitraryDataProvider = new ArbitraryDataProvider(getContentResolver()); arbitraryDataProvider = new ArbitraryDataProvider(getContentResolver());
mAccountListAdapter = new AccountListAdapter(this, getAccountListItems(), mTintedCheck); mAccountListAdapter = new AccountListAdapter(this, getUserAccountManager(), getAccountListItems(), mTintedCheck);
mListView.setAdapter(mAccountListAdapter); mListView.setAdapter(mAccountListAdapter);
@ -213,7 +215,7 @@ public class ManageAccountsActivity extends FileActivity
* @return true if account list has changed, false if not * @return true if account list has changed, false if not
*/ */
private boolean hasCurrentAccountChanged() { private boolean hasCurrentAccountChanged() {
Account account = AccountUtils.getCurrentOwnCloudAccount(this); Account account = getUserAccountManager().getCurrentAccount();
if (account == null) { if (account == null) {
return true; return true;
} else { } else {
@ -297,6 +299,7 @@ public class ManageAccountsActivity extends FileActivity
AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), name); AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), name);
mAccountListAdapter = new AccountListAdapter( mAccountListAdapter = new AccountListAdapter(
ManageAccountsActivity.this, ManageAccountsActivity.this,
getUserAccountManager(),
getAccountListItems(), getAccountListItems(),
mTintedCheck mTintedCheck
); );
@ -340,7 +343,7 @@ public class ManageAccountsActivity extends FileActivity
} }
} }
if (AccountUtils.getCurrentOwnCloudAccount(this) == null) { if (getUserAccountManager().getCurrentAccount() == null) {
String accountName = ""; String accountName = "";
Account[] accounts = AccountManager.get(this).getAccountsByType(MainApp.getAccountType(this)); Account[] accounts = AccountManager.get(this).getAccountsByType(MainApp.getAccountType(this));
if (accounts.length != 0) { if (accounts.length != 0) {
@ -351,7 +354,7 @@ public class ManageAccountsActivity extends FileActivity
List<AccountListItem> accountListItemArray = getAccountListItems(); List<AccountListItem> accountListItemArray = getAccountListItems();
if (accountListItemArray.size() > SINGLE_ACCOUNT) { if (accountListItemArray.size() > SINGLE_ACCOUNT) {
mAccountListAdapter = new AccountListAdapter(this, accountListItemArray, mTintedCheck); mAccountListAdapter = new AccountListAdapter(this, getUserAccountManager(), accountListItemArray, mTintedCheck);
mListView.setAdapter(mAccountListAdapter); mListView.setAdapter(mAccountListAdapter);
} else { } else {
onBackPressed(); onBackPressed();

View File

@ -3,8 +3,10 @@
* *
* @author Andy Scherzinger * @author Andy Scherzinger
* @author Mario Danic * @author Mario Danic
* @author Chris Narkiewicz
* Copyright (C) 2017 Andy Scherzinger * Copyright (C) 2017 Andy Scherzinger
* Copyright (C) 2017 Mario Danic * Copyright (C) 2017 Mario Danic
* Copyright (C) 2019 Chris Narkiewicz <hello@ezaquarii.com>
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by * it under the terms of the GNU Affero General Public License as published by
@ -126,7 +128,7 @@ public class NotificationsActivity extends FileActivity implements Notifications
if (account != null && (currentAccount == null || !account.equalsIgnoreCase(currentAccount.name))) { if (account != null && (currentAccount == null || !account.equalsIgnoreCase(currentAccount.name))) {
AccountUtils.setCurrentOwnCloudAccount(this, account); AccountUtils.setCurrentOwnCloudAccount(this, account);
setAccount(AccountUtils.getCurrentOwnCloudAccount(this)); setAccount(getUserAccountManager().getCurrentAccount());
currentAccount = getAccount(); currentAccount = getAccount();
} }
} }
@ -244,7 +246,12 @@ public class NotificationsActivity extends FileActivity implements Notifications
if (getResources().getBoolean(R.bool.bottom_toolbar_enabled)) { if (getResources().getBoolean(R.bool.bottom_toolbar_enabled)) {
bottomNavigationView.setVisibility(View.VISIBLE); bottomNavigationView.setVisibility(View.VISIBLE);
DisplayUtils.setupBottomBar(bottomNavigationView, getResources(), this, -1); DisplayUtils.setupBottomBar(
getUserAccountManager().getCurrentAccount(),
bottomNavigationView,
getResources(),
this,
-1);
} }
fetchAndSetData(); fetchAndSetData();

View File

@ -5,8 +5,10 @@
* @author masensio * @author masensio
* @author Juan Carlos González Cabrero * @author Juan Carlos González Cabrero
* @author David A. Velasco * @author David A. Velasco
* @author Chris Narkiewicz
* Copyright (C) 2012 Bartek Przybylski * Copyright (C) 2012 Bartek Przybylski
* Copyright (C) 2016 ownCloud Inc. * Copyright (C) 2016 ownCloud Inc.
* Copyright (C) 2019 Chris Narkiewicz <hello@ezaquarii.com>
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2, * it under the terms of the GNU General Public License version 2,
@ -73,6 +75,7 @@ import androidx.core.view.MenuItemCompat;
import androidx.fragment.app.DialogFragment; import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentManager;
import com.nextcloud.client.account.UserAccountManager;
import com.nextcloud.client.di.Injectable; import com.nextcloud.client.di.Injectable;
import com.nextcloud.client.preferences.AppPreferences; import com.nextcloud.client.preferences.AppPreferences;
import com.owncloud.android.MainApp; import com.owncloud.android.MainApp;
@ -285,10 +288,12 @@ public class ReceiveExternalFilesActivity extends FileActivity
} }
} }
public static class DialogMultipleAccount extends DialogFragment { public static class DialogMultipleAccount extends DialogFragment implements Injectable {
private AccountListAdapter mAccountListAdapter; private AccountListAdapter mAccountListAdapter;
private Drawable mTintedCheck; private Drawable mTintedCheck;
@Inject UserAccountManager accountManager;
@NonNull @NonNull
@Override @Override
public Dialog onCreateDialog(Bundle savedInstanceState) { public Dialog onCreateDialog(Bundle savedInstanceState) {
@ -299,14 +304,14 @@ public class ReceiveExternalFilesActivity extends FileActivity
int tint = ThemeUtils.primaryColor(getContext()); int tint = ThemeUtils.primaryColor(getContext());
DrawableCompat.setTint(mTintedCheck, tint); DrawableCompat.setTint(mTintedCheck, tint);
mAccountListAdapter = new AccountListAdapter(parent, getAccountListItems(parent), mTintedCheck); mAccountListAdapter = new AccountListAdapter(parent, accountManager, getAccountListItems(parent), mTintedCheck);
builder.setTitle(R.string.common_choose_account); builder.setTitle(R.string.common_choose_account);
builder.setAdapter(mAccountListAdapter, (dialog, which) -> { builder.setAdapter(mAccountListAdapter, (dialog, which) -> {
final ReceiveExternalFilesActivity parent1 = (ReceiveExternalFilesActivity) getActivity(); final ReceiveExternalFilesActivity parentActivity = (ReceiveExternalFilesActivity) getActivity();
parent1.setAccount(parent1.mAccountManager.getAccountsByType( parentActivity.setAccount(parentActivity.mAccountManager.getAccountsByType(
MainApp.getAccountType(getActivity()))[which], false); MainApp.getAccountType(getActivity()))[which], false);
parent1.onAccountSet(parent1.mAccountWasRestored); parentActivity.onAccountSet(parentActivity.mAccountWasRestored);
dialog.dismiss(); dialog.dismiss();
}); });
builder.setCancelable(true); builder.setCancelable(true);

View File

@ -2,8 +2,11 @@
* Nextcloud Android client application * Nextcloud Android client application
* *
* @author Tobias Kaminsky * @author Tobias Kaminsky
* @author Chris Narkiewicz
*
* Copyright (C) 2018 Tobias Kaminsky * Copyright (C) 2018 Tobias Kaminsky
* Copyright (C) 2018 Nextcloud GmbH. * Copyright (C) 2018 Nextcloud GmbH.
* Copyright (C) 2019 Chris Narkiewicz <hello@ezaquarii.com>
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -44,6 +47,7 @@ import android.widget.Toast;
import com.bumptech.glide.Glide; import com.bumptech.glide.Glide;
import com.google.android.material.snackbar.Snackbar; import com.google.android.material.snackbar.Snackbar;
import com.nextcloud.client.account.CurrentAccountProvider;
import com.owncloud.android.R; import com.owncloud.android.R;
import com.owncloud.android.authentication.AccountUtils; import com.owncloud.android.authentication.AccountUtils;
import com.owncloud.android.datamodel.OCFile; import com.owncloud.android.datamodel.OCFile;
@ -62,6 +66,8 @@ import org.parceler.Parcels;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
import javax.inject.Inject;
import androidx.annotation.RequiresApi; import androidx.annotation.RequiresApi;
import butterknife.BindView; import butterknife.BindView;
import butterknife.ButterKnife; import butterknife.ButterKnife;
@ -94,6 +100,9 @@ public class RichDocumentsWebView extends ExternalSiteWebView {
@BindView(R.id.filename) @BindView(R.id.filename)
TextView fileName; TextView fileName;
@Inject
protected CurrentAccountProvider currentAccountProvider;
@SuppressLint("AddJavascriptInterface") // suppress warning as webview is only used >= Lollipop @SuppressLint("AddJavascriptInterface") // suppress warning as webview is only used >= Lollipop
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
@ -131,7 +140,7 @@ public class RichDocumentsWebView extends ExternalSiteWebView {
break; break;
} }
Glide.with(this).using(new CustomGlideStreamLoader()).load(template.getThumbnailLink()) Glide.with(this).using(new CustomGlideStreamLoader(currentAccountProvider)).load(template.getThumbnailLink())
.placeholder(placeholder) .placeholder(placeholder)
.error(placeholder) .error(placeholder)
.into(thumbnail); .into(thumbnail);

View File

@ -4,6 +4,7 @@
* @author Bartek Przybylski * @author Bartek Przybylski
* @author David A. Velasco * @author David A. Velasco
* @author Chris Narkiewicz * @author Chris Narkiewicz
*
* Copyright (C) 2011 Bartek Przybylski * Copyright (C) 2011 Bartek Przybylski
* Copyright (C) 2016 ownCloud Inc. * Copyright (C) 2016 ownCloud Inc.
* Copyright (C) 2016 Nextcloud * Copyright (C) 2016 Nextcloud
@ -126,8 +127,9 @@ public class SettingsActivity extends PreferenceActivity
private String pendingLock; private String pendingLock;
private Account account; private Account account;
private ArbitraryDataProvider arbitraryDataProvider; @Inject ArbitraryDataProvider arbitraryDataProvider;
@Inject AppPreferences preferences; @Inject AppPreferences preferences;
@Inject UserAccountManager accountManager;
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@Override @Override
@ -151,8 +153,7 @@ public class SettingsActivity extends PreferenceActivity
String appVersion = getAppVersion(); String appVersion = getAppVersion();
PreferenceScreen preferenceScreen = (PreferenceScreen) findPreference("preference_screen"); PreferenceScreen preferenceScreen = (PreferenceScreen) findPreference("preference_screen");
account = AccountUtils.getCurrentOwnCloudAccount(getApplicationContext()); account = accountManager.getCurrentAccount();
arbitraryDataProvider = new ArbitraryDataProvider(getContentResolver());
// retrieve user's base uri // retrieve user's base uri
setupBaseUri(); setupBaseUri();

View File

@ -133,7 +133,7 @@ public class SyncedFoldersActivity extends FileActivity implements SyncedFolderA
if (account != null && currentAccount != null && !account.equalsIgnoreCase(currentAccount.name)) { if (account != null && currentAccount != null && !account.equalsIgnoreCase(currentAccount.name)) {
AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), account); AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), account);
setAccount(AccountUtils.getCurrentOwnCloudAccount(this)); setAccount(getUserAccountManager().getCurrentAccount());
} }
path = getIntent().getStringExtra(MediaFoldersDetectionJob.KEY_MEDIA_FOLDER_PATH); path = getIntent().getStringExtra(MediaFoldersDetectionJob.KEY_MEDIA_FOLDER_PATH);
@ -205,7 +205,13 @@ public class SyncedFoldersActivity extends FileActivity implements SyncedFolderA
if (getResources().getBoolean(R.bool.bottom_toolbar_enabled)) { if (getResources().getBoolean(R.bool.bottom_toolbar_enabled)) {
bottomNavigationView.setVisibility(View.VISIBLE); bottomNavigationView.setVisibility(View.VISIBLE);
DisplayUtils.setupBottomBar(bottomNavigationView, getResources(), this, -1); DisplayUtils.setupBottomBar(
getUserAccountManager().getCurrentAccount(),
bottomNavigationView,
getResources(),
this,
-1
);
} }
load(gridWidth * 2, false); load(gridWidth * 2, false);
@ -228,7 +234,7 @@ public class SyncedFoldersActivity extends FileActivity implements SyncedFolderA
List<SyncedFolder> syncedFolderArrayList = mSyncedFolderProvider.getSyncedFolders(); List<SyncedFolder> syncedFolderArrayList = mSyncedFolderProvider.getSyncedFolders();
List<SyncedFolder> currentAccountSyncedFoldersList = new ArrayList<>(); List<SyncedFolder> currentAccountSyncedFoldersList = new ArrayList<>();
Account currentAccount = AccountUtils.getCurrentOwnCloudAccount(this); Account currentAccount = getUserAccountManager().getCurrentAccount();
for (SyncedFolder syncedFolder : syncedFolderArrayList) { for (SyncedFolder syncedFolder : syncedFolderArrayList) {
if (currentAccount != null && syncedFolder.getAccount().equals(currentAccount.name)) { if (currentAccount != null && syncedFolder.getAccount().equals(currentAccount.name)) {

View File

@ -81,8 +81,6 @@ public class UploadListActivity extends FileActivity {
private static final String TAG = UploadListActivity.class.getSimpleName(); private static final String TAG = UploadListActivity.class.getSimpleName();
private UploadsStorageManager uploadStorageManager;
private UploadMessagesReceiver uploadMessagesReceiver; private UploadMessagesReceiver uploadMessagesReceiver;
private UploadListAdapter uploadListAdapter; private UploadListAdapter uploadListAdapter;
@ -108,7 +106,12 @@ public class UploadListActivity extends FileActivity {
public String noResultsMessage; public String noResultsMessage;
private Unbinder unbinder; private Unbinder unbinder;
@Inject UserAccountManager userAccountManager;
@Inject
protected UserAccountManager userAccountManager;
@Inject
protected UploadsStorageManager uploadsStorageManager;
@Override @Override
public void showFiles(boolean onDeviceOnly) { public void showFiles(boolean onDeviceOnly) {
@ -122,8 +125,6 @@ public class UploadListActivity extends FileActivity {
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
uploadStorageManager = new UploadsStorageManager(getContentResolver(), getApplicationContext());
setContentView(R.layout.upload_list_layout); setContentView(R.layout.upload_list_layout);
unbinder = ButterKnife.bind(this); unbinder = ButterKnife.bind(this);
@ -150,7 +151,13 @@ public class UploadListActivity extends FileActivity {
if (getResources().getBoolean(R.bool.bottom_toolbar_enabled)) { if (getResources().getBoolean(R.bool.bottom_toolbar_enabled)) {
bottomNavigationView.setVisibility(View.VISIBLE); bottomNavigationView.setVisibility(View.VISIBLE);
DisplayUtils.setupBottomBar(bottomNavigationView, getResources(), this, -1); DisplayUtils.setupBottomBar(
getUserAccountManager().getCurrentAccount(),
bottomNavigationView,
getResources(),
this,
-1
);
} }
} }
@ -165,7 +172,7 @@ public class UploadListActivity extends FileActivity {
emptyContentHeadline.setText(noResultsHeadline); emptyContentHeadline.setText(noResultsHeadline);
emptyContentMessage.setText(noResultsMessage); emptyContentMessage.setText(noResultsMessage);
uploadListAdapter = new UploadListAdapter(this); uploadListAdapter = new UploadListAdapter(this, uploadsStorageManager);
final GridLayoutManager lm = new GridLayoutManager(this, 1); final GridLayoutManager lm = new GridLayoutManager(this, 1);
uploadListAdapter.setLayoutManager(lm); uploadListAdapter.setLayoutManager(lm);
@ -209,7 +216,7 @@ public class UploadListActivity extends FileActivity {
// retry failed uploads // retry failed uploads
FileUploader.UploadRequester requester = new FileUploader.UploadRequester(); FileUploader.UploadRequester requester = new FileUploader.UploadRequester();
new Thread(() -> requester.retryFailedUploads(this, null, null)).start(); new Thread(() -> requester.retryFailedUploads(this, null, uploadsStorageManager,null)).start();
// update UI // update UI
uploadListAdapter.loadUploadItemsFromDb(); uploadListAdapter.loadUploadItemsFromDb();
@ -266,7 +273,7 @@ public class UploadListActivity extends FileActivity {
} }
break; break;
case R.id.action_clear_failed_uploads: case R.id.action_clear_failed_uploads:
uploadStorageManager.clearFailedButNotDelayedUploads(); uploadsStorageManager.clearFailedButNotDelayedUploads();
uploadListAdapter.loadUploadItemsFromDb(); uploadListAdapter.loadUploadItemsFromDb();
break; break;
@ -281,7 +288,7 @@ public class UploadListActivity extends FileActivity {
protected void onActivityResult(int requestCode, int resultCode, Intent data) { protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data); super.onActivityResult(requestCode, resultCode, data);
if (requestCode == FileActivity.REQUEST_CODE__UPDATE_CREDENTIALS && resultCode == RESULT_OK) { if (requestCode == FileActivity.REQUEST_CODE__UPDATE_CREDENTIALS && resultCode == RESULT_OK) {
FilesSyncHelper.restartJobsIfNeeded(userAccountManager); FilesSyncHelper.restartJobsIfNeeded(uploadsStorageManager, userAccountManager);
} }
} }
@ -301,7 +308,7 @@ public class UploadListActivity extends FileActivity {
} else { } else {
// already updated -> just retry! // already updated -> just retry!
FilesSyncHelper.restartJobsIfNeeded(userAccountManager); FilesSyncHelper.restartJobsIfNeeded(uploadsStorageManager, userAccountManager);
} }
} else { } else {

View File

@ -120,7 +120,6 @@ public class UserInfoActivity extends FileActivity implements Injectable {
@BindString(R.string.user_information_retrieval_error) protected String sorryMessage; @BindString(R.string.user_information_retrieval_error) protected String sorryMessage;
@Inject AppPreferences preferences; @Inject AppPreferences preferences;
@Inject UserAccountManager accountManager;
private float mCurrentAccountAvatarRadiusDimension; private float mCurrentAccountAvatarRadiusDimension;
private Unbinder unbinder; private Unbinder unbinder;
@ -145,7 +144,7 @@ public class UserInfoActivity extends FileActivity implements Injectable {
setContentView(R.layout.user_info_layout); setContentView(R.layout.user_info_layout);
unbinder = ButterKnife.bind(this); unbinder = ButterKnife.bind(this);
setAccount(AccountUtils.getCurrentOwnCloudAccount(this)); setAccount(getUserAccountManager().getCurrentAccount());
onAccountSet(false); onAccountSet(false);
boolean useBackgroundImage = URLUtil.isValidUrl( boolean useBackgroundImage = URLUtil.isValidUrl(
@ -447,7 +446,7 @@ public class UserInfoActivity extends FileActivity implements Injectable {
@Subscribe(threadMode = ThreadMode.BACKGROUND) @Subscribe(threadMode = ThreadMode.BACKGROUND)
public void onMessageEvent(TokenPushEvent event) { public void onMessageEvent(TokenPushEvent event) {
PushUtils.pushRegistrationToServer(accountManager, preferences.getPushToken()); PushUtils.pushRegistrationToServer(getUserAccountManager(), preferences.getPushToken());
} }

View File

@ -33,7 +33,6 @@ import android.widget.TextView;
import com.nextcloud.client.account.UserAccountManager; import com.nextcloud.client.account.UserAccountManager;
import com.owncloud.android.R; import com.owncloud.android.R;
import com.owncloud.android.authentication.AccountUtils;
import com.owncloud.android.lib.common.OwnCloudAccount; import com.owncloud.android.lib.common.OwnCloudAccount;
import com.owncloud.android.lib.common.utils.Log_OC; import com.owncloud.android.lib.common.utils.Log_OC;
import com.owncloud.android.ui.activity.BaseActivity; import com.owncloud.android.ui.activity.BaseActivity;
@ -54,10 +53,12 @@ public class AccountListAdapter extends ArrayAdapter<AccountListItem> implements
private List<AccountListItem> mValues; private List<AccountListItem> mValues;
private AccountListAdapterListener mListener; private AccountListAdapterListener mListener;
private Drawable mTintedCheck; private Drawable mTintedCheck;
private UserAccountManager accountManager;
public AccountListAdapter(BaseActivity context, List<AccountListItem> values, Drawable tintedCheck) { public AccountListAdapter(BaseActivity context, UserAccountManager accountManager, List<AccountListItem> values, Drawable tintedCheck) {
super(context, -1, values); super(context, -1, values);
this.mContext = context; this.mContext = context;
this.accountManager = accountManager;
this.mValues = values; this.mValues = values;
if (context instanceof AccountListAdapterListener) { if (context instanceof AccountListAdapterListener) {
this.mListener = (AccountListAdapterListener) context; this.mListener = (AccountListAdapterListener) context;
@ -149,7 +150,7 @@ public class AccountListAdapter extends ArrayAdapter<AccountListItem> implements
} }
private void setCurrentlyActiveState(AccountViewHolderItem viewHolder, Account account) { private void setCurrentlyActiveState(AccountViewHolderItem viewHolder, Account account) {
Account currentAccount = AccountUtils.getCurrentOwnCloudAccount(getContext()); Account currentAccount = accountManager.getCurrentAccount();
if (currentAccount != null && currentAccount.name.equals(account.name)) { if (currentAccount != null && currentAccount.name.equals(account.name)) {
viewHolder.checkViewItem.setVisibility(View.VISIBLE); viewHolder.checkViewItem.setVisibility(View.VISIBLE);
} else { } else {

View File

@ -1,3 +1,26 @@
/*
* Nextcloud Android client application
*
* @author Chris Narkiewicz
* @author Tobias Kaminsky
*
* Copyright (C) 2019 Tobias Kaminsky
* Copyright (C) 2019 Chris Narkiewicz <hello@ezaquarii.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.owncloud.android.ui.adapter; package com.owncloud.android.ui.adapter;
import android.content.Context; import android.content.Context;
@ -8,6 +31,7 @@ import android.view.ViewGroup;
import android.widget.ImageView; import android.widget.ImageView;
import android.widget.TextView; import android.widget.TextView;
import com.nextcloud.client.account.CurrentAccountProvider;
import com.owncloud.android.R; import com.owncloud.android.R;
import com.owncloud.android.datamodel.FileDataStorageManager; import com.owncloud.android.datamodel.FileDataStorageManager;
import com.owncloud.android.lib.common.OwnCloudClient; import com.owncloud.android.lib.common.OwnCloudClient;
@ -32,10 +56,15 @@ public class ActivityAndVersionListAdapter extends ActivityListAdapter {
private static final int VERSION_TYPE = 102; private static final int VERSION_TYPE = 102;
private VersionListInterface.View versionListInterface; private VersionListInterface.View versionListInterface;
public ActivityAndVersionListAdapter(Context context, ActivityListInterface activityListInterface, public ActivityAndVersionListAdapter(
VersionListInterface.View versionListInterface, Context context,
FileDataStorageManager storageManager, OCCapability capability) { CurrentAccountProvider currentAccountProvider,
super(context, activityListInterface, storageManager, capability, true); ActivityListInterface activityListInterface,
VersionListInterface.View versionListInterface,
FileDataStorageManager storageManager,
OCCapability capability
) {
super(context, currentAccountProvider, activityListInterface, storageManager, capability, true);
this.versionListInterface = versionListInterface; this.versionListInterface = versionListInterface;
} }

View File

@ -2,7 +2,10 @@
* Nextcloud Android client application * Nextcloud Android client application
* *
* @author Alejandro Bautista * @author Alejandro Bautista
* @author Chris Narkiewicz
*
* Copyright (C) 2017 Alejandro Bautista * Copyright (C) 2017 Alejandro Bautista
* Copyright (C) 2019 Chris Narkiewicz <hello@ezaquarii.com>
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
@ -48,6 +51,7 @@ import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.model.StreamEncoder; import com.bumptech.glide.load.model.StreamEncoder;
import com.bumptech.glide.load.resource.file.FileToStreamDecoder; import com.bumptech.glide.load.resource.file.FileToStreamDecoder;
import com.caverock.androidsvg.SVG; import com.caverock.androidsvg.SVG;
import com.nextcloud.client.account.CurrentAccountProvider;
import com.owncloud.android.MainApp; import com.owncloud.android.MainApp;
import com.owncloud.android.R; import com.owncloud.android.R;
import com.owncloud.android.datamodel.FileDataStorageManager; import com.owncloud.android.datamodel.FileDataStorageManager;
@ -90,15 +94,23 @@ public class ActivityListAdapter extends RecyclerView.Adapter<RecyclerView.ViewH
protected OwnCloudClient client; protected OwnCloudClient client;
protected Context context; protected Context context;
private CurrentAccountProvider currentAccountProvider;
private FileDataStorageManager storageManager; private FileDataStorageManager storageManager;
private OCCapability capability; private OCCapability capability;
protected List<Object> values; protected List<Object> values;
private boolean isDetailView; private boolean isDetailView;
public ActivityListAdapter(Context context, ActivityListInterface activityListInterface, public ActivityListAdapter(
FileDataStorageManager storageManager, OCCapability capability, boolean isDetailView) { Context context,
CurrentAccountProvider currentAccountProvider,
ActivityListInterface activityListInterface,
FileDataStorageManager storageManager,
OCCapability capability,
boolean isDetailView
) {
this.values = new ArrayList<>(); this.values = new ArrayList<>();
this.context = context; this.context = context;
this.currentAccountProvider = currentAccountProvider;
this.activityListInterface = activityListInterface; this.activityListInterface = activityListInterface;
this.storageManager = storageManager; this.storageManager = storageManager;
this.capability = capability; this.capability = capability;
@ -237,7 +249,7 @@ public class ActivityListAdapter extends RecyclerView.Adapter<RecyclerView.ViewH
if (MimeTypeUtil.isImageOrVideo(previewObject.getMimeType())) { if (MimeTypeUtil.isImageOrVideo(previewObject.getMimeType())) {
int placeholder = R.drawable.file; int placeholder = R.drawable.file;
Glide.with(context).using(new CustomGlideStreamLoader()).load(previewObject.getSource()). Glide.with(context).using(new CustomGlideStreamLoader(currentAccountProvider)).load(previewObject.getSource()).
placeholder(placeholder).error(placeholder).into(imageView); placeholder(placeholder).error(placeholder).into(imageView);
} else { } else {
if (MimeTypeUtil.isFolder(previewObject.getMimeType())) { if (MimeTypeUtil.isFolder(previewObject.getMimeType())) {
@ -288,7 +300,7 @@ public class ActivityListAdapter extends RecyclerView.Adapter<RecyclerView.ViewH
String uri = client.getBaseUri() + "/index.php/apps/files/api/v1/thumbnail/" + px + "/" + px + String uri = client.getBaseUri() + "/index.php/apps/files/api/v1/thumbnail/" + px + "/" + px +
Uri.encode(file.getRemotePath(), "/"); Uri.encode(file.getRemotePath(), "/");
Glide.with(context).using(new CustomGlideStreamLoader()).load(uri).placeholder(placeholder) Glide.with(context).using(new CustomGlideStreamLoader(currentAccountProvider)).load(uri).placeholder(placeholder)
.error(placeholder).into(fileIcon); // using custom fetcher .error(placeholder).into(fileIcon); // using custom fetcher
} else { } else {

View File

@ -2,8 +2,11 @@
* Nextcloud Android client application * Nextcloud Android client application
* *
* @author Tobias Kaminsky * @author Tobias Kaminsky
* @author Chris Narkiewicz
*
* Copyright (C) 2018 Tobias Kaminsky * Copyright (C) 2018 Tobias Kaminsky
* Copyright (C) 2018 Nextcloud * Copyright (C) 2018 Nextcloud
* Copyright (C) 2019 Chris Narkiewicz <hello@ezaquarii.com>
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
@ -107,7 +110,7 @@ public class OCFileListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
private Set<OCFile> checkedFiles; private Set<OCFile> checkedFiles;
private FileDataStorageManager mStorageManager; private FileDataStorageManager mStorageManager;
private Account mAccount; private Account account;
private OCFileListFragmentInterface ocFileListFragmentInterface; private OCFileListFragmentInterface ocFileListFragmentInterface;
private FilesFilter mFilesFilter; private FilesFilter mFilesFilter;
@ -121,14 +124,20 @@ public class OCFileListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
private List<ThumbnailsCacheManager.ThumbnailGenerationTask> asyncTasks = new ArrayList<>(); private List<ThumbnailsCacheManager.ThumbnailGenerationTask> asyncTasks = new ArrayList<>();
private boolean onlyOnDevice; private boolean onlyOnDevice;
public OCFileListAdapter(Context context, AppPreferences preferences, ComponentsGetter transferServiceGetter, public OCFileListAdapter(
OCFileListFragmentInterface ocFileListFragmentInterface, boolean argHideItemOptions, Context context,
boolean gridView) { Account account,
AppPreferences preferences,
ComponentsGetter transferServiceGetter,
OCFileListFragmentInterface ocFileListFragmentInterface,
boolean argHideItemOptions,
boolean gridView
) {
this.ocFileListFragmentInterface = ocFileListFragmentInterface; this.ocFileListFragmentInterface = ocFileListFragmentInterface;
mContext = context; mContext = context;
this.preferences = preferences; this.preferences = preferences;
mAccount = AccountUtils.getCurrentOwnCloudAccount(mContext); this.account = account;
mHideItemOptions = argHideItemOptions; mHideItemOptions = argHideItemOptions;
this.gridView = gridView; this.gridView = gridView;
checkedFiles = new HashSet<>(); checkedFiles = new HashSet<>();
@ -331,7 +340,7 @@ public class OCFileListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
showFederatedShareAvatar(file, avatarRadius, resources, itemViewHolder); showFederatedShareAvatar(file, avatarRadius, resources, itemViewHolder);
} else { } else {
itemViewHolder.sharedAvatar.setTag(file.getOwnerId()); itemViewHolder.sharedAvatar.setTag(file.getOwnerId());
DisplayUtils.setAvatar(mAccount, file.getOwnerId(), this, avatarRadius, resources, DisplayUtils.setAvatar(account, file.getOwnerId(), this, avatarRadius, resources,
itemViewHolder.sharedAvatar, mContext); itemViewHolder.sharedAvatar, mContext);
} }
@ -369,17 +378,17 @@ public class OCFileListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
gridViewHolder.localFileIndicator.setVisibility(View.INVISIBLE); // default first gridViewHolder.localFileIndicator.setVisibility(View.INVISIBLE); // default first
if (operationsServiceBinder != null && operationsServiceBinder.isSynchronizing(mAccount, file)) { if (operationsServiceBinder != null && operationsServiceBinder.isSynchronizing(account, file)) {
//synchronizing //synchronizing
gridViewHolder.localFileIndicator.setImageResource(R.drawable.ic_synchronizing); gridViewHolder.localFileIndicator.setImageResource(R.drawable.ic_synchronizing);
gridViewHolder.localFileIndicator.setVisibility(View.VISIBLE); gridViewHolder.localFileIndicator.setVisibility(View.VISIBLE);
} else if (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, file)) { } else if (downloaderBinder != null && downloaderBinder.isDownloading(account, file)) {
// downloading // downloading
gridViewHolder.localFileIndicator.setImageResource(R.drawable.ic_synchronizing); gridViewHolder.localFileIndicator.setImageResource(R.drawable.ic_synchronizing);
gridViewHolder.localFileIndicator.setVisibility(View.VISIBLE); gridViewHolder.localFileIndicator.setVisibility(View.VISIBLE);
} else if (uploaderBinder != null && uploaderBinder.isUploading(mAccount, file)) { } else if (uploaderBinder != null && uploaderBinder.isUploading(account, file)) {
//uploading //uploading
gridViewHolder.localFileIndicator.setImageResource(R.drawable.ic_synchronizing); gridViewHolder.localFileIndicator.setImageResource(R.drawable.ic_synchronizing);
gridViewHolder.localFileIndicator.setVisibility(View.VISIBLE); gridViewHolder.localFileIndicator.setVisibility(View.VISIBLE);
@ -485,12 +494,12 @@ public class OCFileListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
try { try {
final ThumbnailsCacheManager.ThumbnailGenerationTask task = final ThumbnailsCacheManager.ThumbnailGenerationTask task =
new ThumbnailsCacheManager.ThumbnailGenerationTask(thumbnailView, mStorageManager, new ThumbnailsCacheManager.ThumbnailGenerationTask(thumbnailView, mStorageManager,
mAccount, asyncTasks); account, asyncTasks);
if (thumbnail == null) { if (thumbnail == null) {
thumbnail = BitmapUtils.drawableToBitmap( thumbnail = BitmapUtils.drawableToBitmap(
MimeTypeUtil.getFileTypeIcon(file.getMimeType(), file.getFileName(), MimeTypeUtil.getFileTypeIcon(file.getMimeType(), file.getFileName(),
mAccount, mContext)); account, mContext));
} }
final ThumbnailsCacheManager.AsyncThumbnailDrawable asyncDrawable = final ThumbnailsCacheManager.AsyncThumbnailDrawable asyncDrawable =
new ThumbnailsCacheManager.AsyncThumbnailDrawable(mContext.getResources(), new ThumbnailsCacheManager.AsyncThumbnailDrawable(mContext.getResources(),
@ -510,7 +519,7 @@ public class OCFileListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
} }
} else { } else {
thumbnailView.setImageDrawable(MimeTypeUtil.getFileTypeIcon(file.getMimeType(), file.getFileName(), thumbnailView.setImageDrawable(MimeTypeUtil.getFileTypeIcon(file.getMimeType(), file.getFileName(),
mAccount, mContext)); account, mContext));
} }
} }
} }
@ -589,7 +598,7 @@ public class OCFileListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
sharedIconView.setImageResource(R.drawable.ic_unshared); sharedIconView.setImageResource(R.drawable.ic_unshared);
sharedIconView.setContentDescription(mContext.getString(R.string.shared_icon_share)); sharedIconView.setContentDescription(mContext.getString(R.string.shared_icon_share));
} }
if (AccountUtils.accountOwnsFile(file, mAccount)) { if (AccountUtils.accountOwnsFile(file, account)) {
sharedIconView.setOnClickListener(view -> ocFileListFragmentInterface.onShareIconClick(file)); sharedIconView.setOnClickListener(view -> ocFileListFragmentInterface.onShareIconClick(file));
} else { } else {
sharedIconView.setOnClickListener(view -> ocFileListFragmentInterface.showShareDetailView(file)); sharedIconView.setOnClickListener(view -> ocFileListFragmentInterface.showShareDetailView(file));
@ -606,13 +615,17 @@ public class OCFileListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
* @param updatedStorageManager Optional updated storage manager; used to replace * @param updatedStorageManager Optional updated storage manager; used to replace
* @param limitToMimeType show only files of this mimeType * @param limitToMimeType show only files of this mimeType
*/ */
public void swapDirectory(OCFile directory, FileDataStorageManager updatedStorageManager, public void swapDirectory(
boolean onlyOnDevice, String limitToMimeType) { Account account,
OCFile directory,
FileDataStorageManager updatedStorageManager,
boolean onlyOnDevice, String limitToMimeType
) {
this.onlyOnDevice = onlyOnDevice; this.onlyOnDevice = onlyOnDevice;
if (updatedStorageManager != null && !updatedStorageManager.equals(mStorageManager)) { if (updatedStorageManager != null && !updatedStorageManager.equals(mStorageManager)) {
mStorageManager = updatedStorageManager; mStorageManager = updatedStorageManager;
mAccount = AccountUtils.getCurrentOwnCloudAccount(mContext); this.account = account;
} }
if (mStorageManager != null) { if (mStorageManager != null) {
mFiles = mStorageManager.getFolderContent(directory, onlyOnDevice); mFiles = mStorageManager.getFolderContent(directory, onlyOnDevice);
@ -639,7 +652,7 @@ public class OCFileListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
private void searchForLocalFileInDefaultPath(OCFile file) { private void searchForLocalFileInDefaultPath(OCFile file) {
if (file.getStoragePath() == null && !file.isFolder()) { if (file.getStoragePath() == null && !file.isFolder()) {
File f = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file)); File f = new File(FileStorageUtils.getDefaultSavePathFor(account.name, file));
if (f.exists()) { if (f.exists()) {
file.setStoragePath(f.getAbsolutePath()); file.setStoragePath(f.getAbsolutePath());
file.setLastSyncDateForData(f.lastModified()); file.setLastSyncDateForData(f.lastModified());
@ -690,7 +703,7 @@ public class OCFileListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
shares.add(ocShare); shares.add(ocShare);
// get ocFile from Server to have an up-to-date copy // get ocFile from Server to have an up-to-date copy
RemoteOperationResult result = new ReadFileRemoteOperation(ocShare.getPath()).execute(mAccount, RemoteOperationResult result = new ReadFileRemoteOperation(ocShare.getPath()).execute(account,
mContext); mContext);
if (result.isSuccess()) { if (result.isSuccess()) {
@ -750,8 +763,8 @@ public class OCFileListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
if (ocFile.isFolder()) { if (ocFile.isFolder()) {
long currentSyncTime = System.currentTimeMillis(); long currentSyncTime = System.currentTimeMillis();
RemoteOperation refreshFolderOperation = new RefreshFolderOperation(ocFile, currentSyncTime, false, RemoteOperation refreshFolderOperation = new RefreshFolderOperation(ocFile, currentSyncTime, false,
false, mStorageManager, mAccount, mContext); false, mStorageManager, account, mContext);
refreshFolderOperation.execute(mAccount, mContext); refreshFolderOperation.execute(account, mContext);
} }
if (!onlyImages || MimeTypeUtil.isImage(ocFile)) { if (!onlyImages || MimeTypeUtil.isImage(ocFile)) {

View File

@ -2,8 +2,11 @@
* Nextcloud Android client application * Nextcloud Android client application
* *
* @author Tobias Kaminsky * @author Tobias Kaminsky
* @author Chris Narkiewicz
*
* Copyright (C) 2018 Tobias Kaminsky * Copyright (C) 2018 Tobias Kaminsky
* Copyright (C) 2018 Nextcloud GmbH. * Copyright (C) 2018 Nextcloud GmbH.
* Copyright (C) 2019 Chris Narkiewicz <hello@ezaquarii.com>
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by * it under the terms of the GNU Affero General Public License as published by
@ -29,6 +32,7 @@ import android.widget.ImageView;
import android.widget.TextView; import android.widget.TextView;
import com.bumptech.glide.Glide; import com.bumptech.glide.Glide;
import com.nextcloud.client.account.CurrentAccountProvider;
import com.owncloud.android.R; import com.owncloud.android.R;
import com.owncloud.android.datamodel.Template; import com.owncloud.android.datamodel.Template;
import com.owncloud.android.ui.dialog.ChooseTemplateDialogFragment; import com.owncloud.android.ui.dialog.ChooseTemplateDialogFragment;
@ -51,11 +55,18 @@ public class TemplateAdapter extends RecyclerView.Adapter<TemplateAdapter.ViewHo
private ClickListener clickListener; private ClickListener clickListener;
private Context context; private Context context;
private ChooseTemplateDialogFragment.Type type; private ChooseTemplateDialogFragment.Type type;
private CurrentAccountProvider currentAccountProvider;
public TemplateAdapter(ChooseTemplateDialogFragment.Type type, ClickListener clickListener, Context context) { public TemplateAdapter(
ChooseTemplateDialogFragment.Type type,
ClickListener clickListener,
Context context,
CurrentAccountProvider currentAccountProvider
) {
this.clickListener = clickListener; this.clickListener = clickListener;
this.type = type; this.type = type;
this.context = context; this.context = context;
this.currentAccountProvider = currentAccountProvider;
} }
@NonNull @NonNull
@ -124,7 +135,7 @@ public class TemplateAdapter extends RecyclerView.Adapter<TemplateAdapter.ViewHo
break; break;
} }
Glide.with(context).using(new CustomGlideStreamLoader()).load(template.getThumbnailLink()) Glide.with(context).using(new CustomGlideStreamLoader(currentAccountProvider)).load(template.getThumbnailLink())
.placeholder(placeholder) .placeholder(placeholder)
.error(placeholder) .error(placeholder)
.into(thumbnail); .into(thumbnail);

View File

@ -69,11 +69,16 @@ public class TrashbinListAdapter extends RecyclerView.Adapter<RecyclerView.ViewH
private final List<ThumbnailsCacheManager.ThumbnailGenerationTask> asyncTasks = new ArrayList<>(); private final List<ThumbnailsCacheManager.ThumbnailGenerationTask> asyncTasks = new ArrayList<>();
public TrashbinListAdapter(TrashbinActivityInterface trashbinActivityInterface, public TrashbinListAdapter(
FileDataStorageManager storageManager, AppPreferences preferences, Context context) { TrashbinActivityInterface trashbinActivityInterface,
FileDataStorageManager storageManager,
AppPreferences preferences,
Context context,
Account account
) {
this.files = new ArrayList<>(); this.files = new ArrayList<>();
this.trashbinActivityInterface = trashbinActivityInterface; this.trashbinActivityInterface = trashbinActivityInterface;
this.account = AccountUtils.getCurrentOwnCloudAccount(context); this.account = account;
this.storageManager = storageManager; this.storageManager = storageManager;
this.preferences = preferences; this.preferences = preferences;
this.context = context; this.context = context;

View File

@ -2,8 +2,10 @@
* Nextcloud Android client application * Nextcloud Android client application
* *
* @author Tobias Kaminsky * @author Tobias Kaminsky
* @author Chris Narkiewicz
* Copyright (C) 2018 Tobias Kaminsky * Copyright (C) 2018 Tobias Kaminsky
* Copyright (C) 2018 Nextcloud * Copyright (C) 2018 Nextcloud
* Copyright (C) 2019 Chris Narkiewicz <hello@ezaquarii.com>
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
@ -122,7 +124,12 @@ public class UploadListAdapter extends SectionedRecyclerViewAdapter<SectionedVie
break; break;
case FAILED: case FAILED:
new Thread(() -> new FileUploader.UploadRequester() new Thread(() -> new FileUploader.UploadRequester()
.retryFailedUploads(parentActivity, null, null)).start(); .retryFailedUploads(
parentActivity,
null,
uploadsStorageManager,
null))
.start();
break; break;
default: default:
@ -139,11 +146,10 @@ public class UploadListAdapter extends SectionedRecyclerViewAdapter<SectionedVie
// not needed // not needed
} }
public UploadListAdapter(FileActivity fileActivity) { public UploadListAdapter(final FileActivity fileActivity, final UploadsStorageManager uploadsStorageManager) {
Log_OC.d(TAG, "UploadListAdapter"); Log_OC.d(TAG, "UploadListAdapter");
parentActivity = fileActivity; this.parentActivity = fileActivity;
uploadsStorageManager = new UploadsStorageManager(parentActivity.getContentResolver(), this.uploadsStorageManager = uploadsStorageManager;
parentActivity.getApplicationContext());
uploadGroups = new UploadGroup[3]; uploadGroups = new UploadGroup[3];
shouldShowHeadersForEmptySections(false); shouldShowHeadersForEmptySections(false);

View File

@ -2,8 +2,11 @@
* Nextcloud Android client application * Nextcloud Android client application
* *
* @author Tobias Kaminsky * @author Tobias Kaminsky
* @author Chris Narkiewicz
*
* Copyright (C) 2018 Tobias Kaminsky * Copyright (C) 2018 Tobias Kaminsky
* Copyright (C) 2018 Nextcloud GmbH. * Copyright (C) 2018 Nextcloud GmbH.
* Copyright (C) 2019 Chris Narkiewicz <hello@ezaquarii.com>
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -36,9 +39,10 @@ import android.view.Window;
import android.view.WindowManager.LayoutParams; import android.view.WindowManager.LayoutParams;
import android.widget.EditText; import android.widget.EditText;
import com.nextcloud.client.account.CurrentAccountProvider;
import com.nextcloud.client.di.Injectable;
import com.owncloud.android.MainApp; import com.owncloud.android.MainApp;
import com.owncloud.android.R; import com.owncloud.android.R;
import com.owncloud.android.authentication.AccountUtils;
import com.owncloud.android.datamodel.OCFile; import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.datamodel.Template; import com.owncloud.android.datamodel.Template;
import com.owncloud.android.files.CreateFileFromTemplateOperation; import com.owncloud.android.files.CreateFileFromTemplateOperation;
@ -60,6 +64,8 @@ import java.lang.ref.WeakReference;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import javax.inject.Inject;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment; import androidx.fragment.app.DialogFragment;
@ -72,7 +78,7 @@ import butterknife.ButterKnife;
* Dialog to show templates for new documents/spreadsheets/presentations. * Dialog to show templates for new documents/spreadsheets/presentations.
*/ */
public class ChooseTemplateDialogFragment extends DialogFragment implements DialogInterface.OnClickListener, public class ChooseTemplateDialogFragment extends DialogFragment implements DialogInterface.OnClickListener,
TemplateAdapter.ClickListener { TemplateAdapter.ClickListener, Injectable {
private static final String ARG_PARENT_FOLDER = "PARENT_FOLDER"; private static final String ARG_PARENT_FOLDER = "PARENT_FOLDER";
private static final String ARG_TYPE = "TYPE"; private static final String ARG_TYPE = "TYPE";
@ -82,6 +88,7 @@ public class ChooseTemplateDialogFragment extends DialogFragment implements Dial
private TemplateAdapter adapter; private TemplateAdapter adapter;
private OCFile parentFolder; private OCFile parentFolder;
private OwnCloudClient client; private OwnCloudClient client;
@Inject CurrentAccountProvider currentAccount;
public enum Type { public enum Type {
DOCUMENT, DOCUMENT,
@ -144,7 +151,7 @@ public class ChooseTemplateDialogFragment extends DialogFragment implements Dial
fileName.getBackground().setColorFilter(accentColor, PorterDuff.Mode.SRC_ATOP); fileName.getBackground().setColorFilter(accentColor, PorterDuff.Mode.SRC_ATOP);
try { try {
Account account = AccountUtils.getCurrentOwnCloudAccount(activity); Account account = currentAccount.getCurrentAccount();
OwnCloudAccount ocAccount = new OwnCloudAccount(account, activity); OwnCloudAccount ocAccount = new OwnCloudAccount(account, activity);
client = OwnCloudClientManagerFactory.getDefaultSingleton().getClientFor(ocAccount, getContext()); client = OwnCloudClientManagerFactory.getDefaultSingleton().getClientFor(ocAccount, getContext());
@ -155,7 +162,7 @@ public class ChooseTemplateDialogFragment extends DialogFragment implements Dial
listView.setHasFixedSize(true); listView.setHasFixedSize(true);
listView.setLayoutManager(new GridLayoutManager(activity, 2)); listView.setLayoutManager(new GridLayoutManager(activity, 2));
adapter = new TemplateAdapter(type, this, getContext()); adapter = new TemplateAdapter(type, this, getContext(), currentAccount);
listView.setAdapter(adapter); listView.setAdapter(adapter);
// Build the dialog // Build the dialog

View File

@ -2,9 +2,12 @@
* ownCloud Android client application * ownCloud Android client application
* *
* @author Mario Danic * @author Mario Danic
* @author Chris Narkiewicz
*
* Copyright (C) 2017 Mario Danic * Copyright (C) 2017 Mario Danic
* Copyright (C) 2012 Bartek Przybylski * Copyright (C) 2012 Bartek Przybylski
* Copyright (C) 2012-2016 ownCloud Inc. * Copyright (C) 2012-2016 ownCloud Inc.
* Copyright (C) 2019 Chris Narkiewicz <hello@ezaquarii.com>
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2, * it under the terms of the GNU General Public License version 2,
@ -52,6 +55,7 @@ import android.widget.TextView;
import com.google.android.material.bottomnavigation.BottomNavigationView; import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.nextcloud.client.account.UserAccountManager;
import com.nextcloud.client.di.Injectable; import com.nextcloud.client.di.Injectable;
import com.nextcloud.client.preferences.AppPreferences; import com.nextcloud.client.preferences.AppPreferences;
import com.owncloud.android.MainApp; import com.owncloud.android.MainApp;
@ -111,6 +115,7 @@ public class ExtendedListFragment extends Fragment implements
private int maxColumnSizeLandscape = 10; private int maxColumnSizeLandscape = 10;
@Inject AppPreferences preferences; @Inject AppPreferences preferences;
@Inject UserAccountManager accountManager;
private ScaleGestureDetector mScaleGestureDetector; private ScaleGestureDetector mScaleGestureDetector;
protected SwipeRefreshLayout mRefreshListLayout; protected SwipeRefreshLayout mRefreshListLayout;
protected LinearLayout mEmptyListContainer; protected LinearLayout mEmptyListContainer;
@ -222,8 +227,7 @@ public class ExtendedListFragment extends Fragment implements
setFabVisible(!hasFocus); setFabVisible(!hasFocus);
} }
boolean searchSupported = AccountUtils.hasSearchSupport(AccountUtils. boolean searchSupported = AccountUtils.hasSearchSupport(accountManager.getCurrentAccount());
getCurrentOwnCloudAccount(MainApp.getAppContext()));
if (getResources().getBoolean(R.bool.bottom_toolbar_enabled) && searchSupported) { if (getResources().getBoolean(R.bool.bottom_toolbar_enabled) && searchSupported) {
BottomNavigationView bottomNavigationView = getActivity(). BottomNavigationView bottomNavigationView = getActivity().
@ -313,8 +317,7 @@ public class ExtendedListFragment extends Fragment implements
handler.postDelayed(new Runnable() { handler.postDelayed(new Runnable() {
@Override @Override
public void run() { public void run() {
if (AccountUtils.hasSearchSupport(AccountUtils. if (AccountUtils.hasSearchSupport(accountManager.getCurrentAccount())) {
getCurrentOwnCloudAccount(MainApp.getAppContext()))) {
EventBus.getDefault().post(new SearchEvent(query, EventBus.getDefault().post(new SearchEvent(query,
SearchRemoteOperation.SearchType.FILE_SEARCH, SearchEvent.UnsetType.NO_UNSET)); SearchRemoteOperation.SearchType.FILE_SEARCH, SearchEvent.UnsetType.NO_UNSET));
} else { } else {
@ -400,8 +403,7 @@ public class ExtendedListFragment extends Fragment implements
mFabMain = v.findViewById(R.id.fab_main); mFabMain = v.findViewById(R.id.fab_main);
ThemeUtils.tintFloatingActionButton(mFabMain, R.drawable.ic_plus, getContext()); ThemeUtils.tintFloatingActionButton(mFabMain, R.drawable.ic_plus, getContext());
boolean searchSupported = AccountUtils.hasSearchSupport(AccountUtils. boolean searchSupported = AccountUtils.hasSearchSupport(accountManager.getCurrentAccount());
getCurrentOwnCloudAccount(MainApp.getAppContext()));
if (getResources().getBoolean(R.bool.bottom_toolbar_enabled) && searchSupported) { if (getResources().getBoolean(R.bool.bottom_toolbar_enabled) && searchSupported) {
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mFabMain.getLayoutParams(); RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mFabMain.getLayoutParams();

View File

@ -2,7 +2,10 @@
* Nextcloud Android client application * Nextcloud Android client application
* *
* @author Andy Scherzinger * @author Andy Scherzinger
* @author Chris Narkiewicz
*
* Copyright (C) 2018 Andy Scherzinger * Copyright (C) 2018 Andy Scherzinger
* Copyright (C) 2019 Chris Narkiewicz <hello@ezaquarii.com>
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
@ -39,6 +42,8 @@ import android.widget.TextView;
import com.google.android.material.snackbar.Snackbar; import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.textfield.TextInputEditText; import com.google.android.material.textfield.TextInputEditText;
import com.nextcloud.client.account.CurrentAccountProvider;
import com.nextcloud.client.di.Injectable;
import com.owncloud.android.MainApp; import com.owncloud.android.MainApp;
import com.owncloud.android.R; import com.owncloud.android.R;
import com.owncloud.android.authentication.AccountUtils; import com.owncloud.android.authentication.AccountUtils;
@ -73,6 +78,8 @@ import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import javax.inject.Inject;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment; import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity; import androidx.fragment.app.FragmentActivity;
@ -85,7 +92,11 @@ import butterknife.ButterKnife;
import butterknife.OnClick; import butterknife.OnClick;
import butterknife.Unbinder; import butterknife.Unbinder;
public class FileDetailActivitiesFragment extends Fragment implements ActivityListInterface, VersionListInterface.View { public class FileDetailActivitiesFragment extends Fragment implements
ActivityListInterface,
VersionListInterface.View,
Injectable {
private static final String TAG = FileDetailActivitiesFragment.class.getSimpleName(); private static final String TAG = FileDetailActivitiesFragment.class.getSimpleName();
private static final String ARG_FILE = "FILE"; private static final String ARG_FILE = "FILE";
@ -139,6 +150,9 @@ public class FileDetailActivitiesFragment extends Fragment implements ActivityLi
private FileOperationsHelper operationsHelper; private FileOperationsHelper operationsHelper;
private VersionListInterface.CommentCallback callback; private VersionListInterface.CommentCallback callback;
@Inject
protected CurrentAccountProvider accountManager;
public static FileDetailActivitiesFragment newInstance(OCFile file, Account account) { public static FileDetailActivitiesFragment newInstance(OCFile file, Account account) {
FileDetailActivitiesFragment fragment = new FileDetailActivitiesFragment(); FileDetailActivitiesFragment fragment = new FileDetailActivitiesFragment();
Bundle args = new Bundle(); Bundle args = new Bundle();
@ -251,7 +265,7 @@ public class FileDetailActivitiesFragment extends Fragment implements ActivityLi
PorterDuff.Mode.SRC_IN); PorterDuff.Mode.SRC_IN);
emptyContentIcon.setImageDrawable(getResources().getDrawable(R.drawable.ic_activity_light_grey)); emptyContentIcon.setImageDrawable(getResources().getDrawable(R.drawable.ic_activity_light_grey));
adapter = new ActivityAndVersionListAdapter(getContext(), this, this, storageManager, capability); adapter = new ActivityAndVersionListAdapter(getContext(), accountManager, this, this, storageManager, capability);
recyclerView.setAdapter(adapter); recyclerView.setAdapter(adapter);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext()); LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
@ -285,7 +299,7 @@ public class FileDetailActivitiesFragment extends Fragment implements ActivityLi
* @param pageUrl String * @param pageUrl String
*/ */
private void fetchAndSetData(String pageUrl) { private void fetchAndSetData(String pageUrl) {
final Account currentAccount = AccountUtils.getCurrentOwnCloudAccount(MainApp.getAppContext()); final Account currentAccount = accountManager.getCurrentAccount();
final Context context = MainApp.getAppContext(); final Context context = MainApp.getAppContext();
final FragmentActivity activity = getActivity(); final FragmentActivity activity = getActivity();

View File

@ -5,6 +5,7 @@
* @author masensio * @author masensio
* @author David A. Velasco * @author David A. Velasco
* @author Andy Scherzinger * @author Andy Scherzinger
* @author Chris Narkiewicz
* Copyright (C) 2011 Bartek Przybylski * Copyright (C) 2011 Bartek Przybylski
* Copyright (C) 2016 ownCloud Inc. * Copyright (C) 2016 ownCloud Inc.
* Copyright (C) 2018 Andy Scherzinger * Copyright (C) 2018 Andy Scherzinger
@ -49,6 +50,7 @@ import android.widget.RelativeLayout;
import com.google.android.material.bottomnavigation.BottomNavigationView; import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.snackbar.Snackbar; import com.google.android.material.snackbar.Snackbar;
import com.nextcloud.client.account.UserAccountManager;
import com.nextcloud.client.di.Injectable; import com.nextcloud.client.di.Injectable;
import com.nextcloud.client.preferences.AppPreferences; import com.nextcloud.client.preferences.AppPreferences;
import com.owncloud.android.MainApp; import com.owncloud.android.MainApp;
@ -167,6 +169,7 @@ public class OCFileListFragment extends ExtendedListFragment implements
private static final int SINGLE_SELECTION = 1; private static final int SINGLE_SELECTION = 1;
@Inject AppPreferences preferences; @Inject AppPreferences preferences;
@Inject UserAccountManager accountManager;
private FileFragment.ContainerActivity mContainerActivity; private FileFragment.ContainerActivity mContainerActivity;
private OCFile mFile; private OCFile mFile;
@ -279,7 +282,12 @@ public class OCFileListFragment extends ExtendedListFragment implements
if (getResources().getBoolean(R.bool.bottom_toolbar_enabled)) { if (getResources().getBoolean(R.bool.bottom_toolbar_enabled)) {
bottomNavigationView.setVisibility(View.VISIBLE); bottomNavigationView.setVisibility(View.VISIBLE);
DisplayUtils.setupBottomBar(bottomNavigationView, getResources(), getActivity(), R.id.nav_bar_files); DisplayUtils.setupBottomBar(
accountManager.getCurrentAccount(),
bottomNavigationView, getResources(),
getActivity(),
R.id.nav_bar_files
);
} }
if (!getResources().getBoolean(R.bool.bottom_toolbar_enabled) || savedInstanceState != null) { if (!getResources().getBoolean(R.bool.bottom_toolbar_enabled) || savedInstanceState != null) {
@ -345,8 +353,15 @@ public class OCFileListFragment extends ExtendedListFragment implements
mLimitToMimeType = args != null ? args.getString(ARG_MIMETYPE, "") : ""; mLimitToMimeType = args != null ? args.getString(ARG_MIMETYPE, "") : "";
boolean hideItemOptions = args != null && args.getBoolean(ARG_HIDE_ITEM_OPTIONS, false); boolean hideItemOptions = args != null && args.getBoolean(ARG_HIDE_ITEM_OPTIONS, false);
mAdapter = new OCFileListAdapter(getActivity(), preferences, mContainerActivity, this, hideItemOptions, mAdapter = new OCFileListAdapter(
isGridViewPreferred(mFile)); getActivity(),
accountManager.getCurrentAccount(),
preferences,
mContainerActivity,
this,
hideItemOptions,
isGridViewPreferred(mFile)
);
setRecyclerViewAdapter(mAdapter); setRecyclerViewAdapter(mAdapter);
mHideFab = args != null && args.getBoolean(ARG_HIDE_FAB, false); mHideFab = args != null && args.getBoolean(ARG_HIDE_FAB, false);
@ -927,7 +942,7 @@ public class OCFileListFragment extends ExtendedListFragment implements
mContainerActivity.getFileOperationsHelper().openFile(file); mContainerActivity.getFileOperationsHelper().openFile(file);
} }
} else { } else {
Account account = AccountUtils.getCurrentOwnCloudAccount(getContext()); Account account = accountManager.getCurrentAccount();
OCCapability capability = mContainerActivity.getStorageManager().getCapability(account.name); OCCapability capability = mContainerActivity.getStorageManager().getCapability(account.name);
if (PreviewMediaFragment.canBePreviewed(file) && AccountUtils.getServerVersion(account) if (PreviewMediaFragment.canBePreviewed(file) && AccountUtils.getServerVersion(account)
@ -1160,7 +1175,13 @@ public class OCFileListFragment extends ExtendedListFragment implements
}); });
} }
mAdapter.swapDirectory(directory, storageManager, onlyOnDevice, mLimitToMimeType); mAdapter.swapDirectory(
accountManager.getCurrentAccount(),
directory,
storageManager,
onlyOnDevice,
mLimitToMimeType
);
if (mFile == null || !mFile.equals(directory)) { if (mFile == null || !mFile.equals(directory)) {
getRecyclerView().scrollToPosition(0); getRecyclerView().scrollToPosition(0);
} }
@ -1402,7 +1423,7 @@ public class OCFileListFragment extends ExtendedListFragment implements
@Subscribe(threadMode = ThreadMode.BACKGROUND) @Subscribe(threadMode = ThreadMode.BACKGROUND)
public void onMessageEvent(FavoriteEvent event) { public void onMessageEvent(FavoriteEvent event) {
Account currentAccount = AccountUtils.getCurrentOwnCloudAccount(MainApp.getAppContext()); Account currentAccount = accountManager.getCurrentAccount();
OwnCloudAccount ocAccount; OwnCloudAccount ocAccount;
AccountManager mAccountMgr = AccountManager.get(getActivity()); AccountManager mAccountMgr = AccountManager.get(getActivity());
@ -1482,7 +1503,7 @@ public class OCFileListFragment extends ExtendedListFragment implements
new Handler(Looper.getMainLooper()).post(switchViewsRunnable); new Handler(Looper.getMainLooper()).post(switchViewsRunnable);
} }
final Account currentAccount = AccountUtils.getCurrentOwnCloudAccount(MainApp.getAppContext()); final Account currentAccount = accountManager.getCurrentAccount();
final RemoteOperation remoteOperation; final RemoteOperation remoteOperation;
if (currentSearchType != SearchType.SHARED_FILTER) { if (currentSearchType != SearchType.SHARED_FILTER) {
@ -1553,7 +1574,7 @@ public class OCFileListFragment extends ExtendedListFragment implements
@Subscribe(threadMode = ThreadMode.BACKGROUND) @Subscribe(threadMode = ThreadMode.BACKGROUND)
public void onMessageEvent(EncryptionEvent event) { public void onMessageEvent(EncryptionEvent event) {
Account currentAccount = AccountUtils.getCurrentOwnCloudAccount(MainApp.getAppContext()); Account currentAccount = accountManager.getCurrentAccount();
OwnCloudAccount ocAccount; OwnCloudAccount ocAccount;
try { try {

View File

@ -5,8 +5,11 @@
* @author David A. Velasco * @author David A. Velasco
* @author Juan Carlos González Cabrero * @author Juan Carlos González Cabrero
* @author Andy Scherzinger * @author Andy Scherzinger
* @author Chris Narkiewicz
*
* Copyright (C) 2015 ownCloud Inc. * Copyright (C) 2015 ownCloud Inc.
* Copyright (C) 2018 Andy Scherzinger * Copyright (C) 2018 Andy Scherzinger
* Copyright (C) 2019 Chris Narkiewicz <hello@ezaquarii.com>
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2, * it under the terms of the GNU General Public License version 2,
@ -42,9 +45,9 @@ import android.webkit.MimeTypeMap;
import com.evernote.android.job.JobRequest; import com.evernote.android.job.JobRequest;
import com.evernote.android.job.util.Device; import com.evernote.android.job.util.Device;
import com.nextcloud.client.account.CurrentAccountProvider;
import com.owncloud.android.MainApp; import com.owncloud.android.MainApp;
import com.owncloud.android.R; import com.owncloud.android.R;
import com.owncloud.android.authentication.AccountUtils;
import com.owncloud.android.datamodel.FileDataStorageManager; import com.owncloud.android.datamodel.FileDataStorageManager;
import com.owncloud.android.datamodel.OCFile; import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.files.StreamMediaFileOperation; import com.owncloud.android.files.StreamMediaFileOperation;
@ -110,11 +113,14 @@ public class FileOperationsHelper {
private static final String FILE_EXTENSION_DESKTOP = "desktop"; private static final String FILE_EXTENSION_DESKTOP = "desktop";
private static final String FILE_EXTENSION_WEBLOC = "webloc"; private static final String FILE_EXTENSION_WEBLOC = "webloc";
private FileActivity mFileActivity; private FileActivity mFileActivity;
private CurrentAccountProvider currentAccount;
/// Identifier of operation in progress which result shouldn't be lost /// Identifier of operation in progress which result shouldn't be lost
private long mWaitingForOpId = Long.MAX_VALUE; private long mWaitingForOpId = Long.MAX_VALUE;
public FileOperationsHelper(FileActivity fileActivity) { public FileOperationsHelper(FileActivity fileActivity, CurrentAccountProvider currentAccount) {
mFileActivity = fileActivity; mFileActivity = fileActivity;
this.currentAccount = currentAccount;
} }
@Nullable @Nullable
@ -280,7 +286,7 @@ public class FileOperationsHelper {
new Thread(new Runnable() { new Thread(new Runnable() {
@Override @Override
public void run() { public void run() {
Account account = AccountUtils.getCurrentOwnCloudAccount(mFileActivity); Account account = currentAccount.getCurrentAccount();
FileDataStorageManager storageManager = FileDataStorageManager storageManager =
new FileDataStorageManager(account, mFileActivity.getContentResolver()); new FileDataStorageManager(account, mFileActivity.getContentResolver());
// a fresh object is needed; many things could have occurred to the file // a fresh object is needed; many things could have occurred to the file
@ -391,9 +397,8 @@ public class FileOperationsHelper {
public void streamMediaFile(OCFile file) { public void streamMediaFile(OCFile file) {
mFileActivity.showLoadingDialog(mFileActivity.getString(R.string.wait_a_moment)); mFileActivity.showLoadingDialog(mFileActivity.getString(R.string.wait_a_moment));
final Account account = currentAccount.getCurrentAccount();
new Thread(() -> { new Thread(() -> {
Account account = AccountUtils.getCurrentOwnCloudAccount(mFileActivity);
StreamMediaFileOperation sfo = new StreamMediaFileOperation(file.getLocalId()); StreamMediaFileOperation sfo = new StreamMediaFileOperation(file.getLocalId());
RemoteOperationResult result = sfo.execute(account, mFileActivity); RemoteOperationResult result = sfo.execute(account, mFileActivity);

View File

@ -2,7 +2,10 @@
* ownCloud Android client application * ownCloud Android client application
* *
* @author David A. Velasco * @author David A. Velasco
* @author Chris Narkiewicz
*
* Copyright (C) 2016 ownCloud Inc. * Copyright (C) 2016 ownCloud Inc.
* Copyright (C) 2019 Chris Narkiewicz <hello@ezaquarii.com>
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2, * it under the terms of the GNU General Public License version 2,
@ -19,6 +22,7 @@
*/ */
package com.owncloud.android.ui.preview; package com.owncloud.android.ui.preview;
import android.accounts.Account;
import android.annotation.SuppressLint; import android.annotation.SuppressLint;
import android.content.BroadcastReceiver; import android.content.BroadcastReceiver;
import android.content.ComponentName; import android.content.ComponentName;
@ -361,11 +365,11 @@ public class PreviewImageActivity extends FileActivity implements
@SuppressFBWarnings("DLS") @SuppressFBWarnings("DLS")
@Override @Override
public void showDetails(OCFile file) { public void showDetails(OCFile file) {
final Account currentAccount = getUserAccountManager().getCurrentAccount();
final Intent showDetailsIntent = new Intent(this, FileDisplayActivity.class); final Intent showDetailsIntent = new Intent(this, FileDisplayActivity.class);
showDetailsIntent.setAction(FileDisplayActivity.ACTION_DETAILS); showDetailsIntent.setAction(FileDisplayActivity.ACTION_DETAILS);
showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, file); showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, file);
showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, currentAccount);
AccountUtils.getCurrentOwnCloudAccount(this));
showDetailsIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); showDetailsIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(showDetailsIntent); startActivity(showDetailsIntent);
finish(); finish();

View File

@ -2,8 +2,11 @@
* Nextcloud Android client application * Nextcloud Android client application
* *
* @author Tobias Kaminsky * @author Tobias Kaminsky
* @author Chris Narkiewicz
*
* Copyright (C) 2018 Tobias Kaminsky * Copyright (C) 2018 Tobias Kaminsky
* Copyright (C) 2018 Nextcloud GmbH. * Copyright (C) 2018 Nextcloud GmbH.
* Copyright (C) 2019 Chris Narkiewicz <hello@ezaquarii.com>
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -26,7 +29,6 @@ import android.content.Context;
import android.os.AsyncTask; import android.os.AsyncTask;
import com.owncloud.android.R; import com.owncloud.android.R;
import com.owncloud.android.authentication.AccountUtils;
import com.owncloud.android.lib.common.OwnCloudAccount; import com.owncloud.android.lib.common.OwnCloudAccount;
import com.owncloud.android.lib.common.OwnCloudClient; import com.owncloud.android.lib.common.OwnCloudClient;
import com.owncloud.android.lib.common.OwnCloudClientManagerFactory; import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
@ -49,19 +51,19 @@ public class RemoteTrashbinRepository implements TrashbinRepository {
private String userId; private String userId;
private OwnCloudClient client; private OwnCloudClient client;
RemoteTrashbinRepository(Context context) { RemoteTrashbinRepository(final Context context, final Account account) {
AccountManager accountManager = AccountManager.get(context); AccountManager platformAccountManager = AccountManager.get(context);
Account account = AccountUtils.getCurrentOwnCloudAccount(context);
try { try {
OwnCloudAccount ocAccount = new OwnCloudAccount(account, context); OwnCloudAccount nextcloudAccount = new OwnCloudAccount(account, context);
client = OwnCloudClientManagerFactory.getDefaultSingleton().getClientFor(ocAccount, context); client = OwnCloudClientManagerFactory.getDefaultSingleton().getClientFor(nextcloudAccount, context);
} catch (Exception e) { } catch (Exception e) {
Log_OC.e(TAG, e.getMessage()); Log_OC.e(TAG, e.getMessage());
} }
userId = accountManager.getUserData(account, userId = platformAccountManager.getUserData(
com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_USER_ID); account,
com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_USER_ID
);
} }
public void removeTrashbinFile(TrashbinFile file, OperationCallback callback) { public void removeTrashbinFile(TrashbinFile file, OperationCallback callback) {

View File

@ -2,8 +2,11 @@
* Nextcloud Android client application * Nextcloud Android client application
* *
* @author Tobias Kaminsky * @author Tobias Kaminsky
* @author Chris Narkiewicz
*
* Copyright (C) 2018 Tobias Kaminsky * Copyright (C) 2018 Tobias Kaminsky
* Copyright (C) 2018 Nextcloud GmbH. * Copyright (C) 2018 Nextcloud GmbH.
* Copyright (C) 2019 Chris Narkiewicz <hello@ezaquarii.com>
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -20,6 +23,7 @@
*/ */
package com.owncloud.android.ui.trashbin; package com.owncloud.android.ui.trashbin;
import android.accounts.Account;
import android.content.Intent; import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
import android.view.Menu; import android.view.Menu;
@ -98,7 +102,9 @@ public class TrashbinActivity extends FileActivity implements
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
trashbinPresenter = new TrashbinPresenter(new RemoteTrashbinRepository(this), this); final Account currentAccount = getUserAccountManager().getCurrentAccount();
final RemoteTrashbinRepository trashRepository = new RemoteTrashbinRepository(this, currentAccount);
trashbinPresenter = new TrashbinPresenter(trashRepository, this);
setContentView(R.layout.trashbin_activity); setContentView(R.layout.trashbin_activity);
unbinder = ButterKnife.bind(this); unbinder = ButterKnife.bind(this);
@ -135,7 +141,9 @@ public class TrashbinActivity extends FileActivity implements
this, this,
getStorageManager(), getStorageManager(),
preferences, preferences,
this); this,
getUserAccountManager().getCurrentAccount()
);
recyclerView.setAdapter(trashbinListAdapter); recyclerView.setAdapter(trashbinListAdapter);
recyclerView.setHasFixedSize(true); recyclerView.setHasFixedSize(true);
recyclerView.setHasFooter(true); recyclerView.setHasFooter(true);

View File

@ -557,12 +557,16 @@ public final class DisplayUtils {
} }
} }
public static void setupBottomBar(BottomNavigationView view, Resources resources, final Activity activity, public static void setupBottomBar(
int checkedMenuItem) { Account account,
BottomNavigationView view,
Resources resources,
final Activity activity,
int checkedMenuItem
) {
Menu menu = view.getMenu(); Menu menu = view.getMenu();
Account account = AccountUtils.getCurrentOwnCloudAccount(MainApp.getAppContext());
boolean searchSupported = AccountUtils.hasSearchSupport(account); boolean searchSupported = AccountUtils.hasSearchSupport(account);
if (!searchSupported) { if (!searchSupported) {

View File

@ -3,6 +3,7 @@
* *
* @author Mario Danic * @author Mario Danic
* @author Chris Narkiewicz * @author Chris Narkiewicz
*
* Copyright (C) 2017 Mario Danic * Copyright (C) 2017 Mario Danic
* Copyright (C) 2017 Nextcloud * Copyright (C) 2017 Nextcloud
* Copyright (C) 2019 Chris Narkiewicz <hello@ezaquarii.com> * Copyright (C) 2019 Chris Narkiewicz <hello@ezaquarii.com>
@ -214,14 +215,13 @@ public final class FilesSyncHelper {
} }
} }
public static void restartJobsIfNeeded(UserAccountManager accountManager) { public static void restartJobsIfNeeded(UploadsStorageManager uploadsStorageManager, UserAccountManager accountManager) {
final Context context = MainApp.getAppContext(); final Context context = MainApp.getAppContext();
FileUploader.UploadRequester uploadRequester = new FileUploader.UploadRequester(); FileUploader.UploadRequester uploadRequester = new FileUploader.UploadRequester();
boolean accountExists; boolean accountExists;
UploadsStorageManager uploadsStorageManager = new UploadsStorageManager(context.getContentResolver(), context);
OCUpload[] failedUploads = uploadsStorageManager.getFailedUploads(); OCUpload[] failedUploads = uploadsStorageManager.getFailedUploads();
for (OCUpload failedUpload : failedUploads) { for (OCUpload failedUpload : failedUploads) {
@ -243,7 +243,7 @@ public final class FilesSyncHelper {
new Thread(() -> { new Thread(() -> {
if (!Device.getNetworkType(context).equals(JobRequest.NetworkType.ANY) && if (!Device.getNetworkType(context).equals(JobRequest.NetworkType.ANY) &&
!ConnectivityUtils.isInternetWalled(context)) { !ConnectivityUtils.isInternetWalled(context)) {
uploadRequester.retryFailedUploads(context, null, null); uploadRequester.retryFailedUploads(context, null, uploadsStorageManager, null);
} }
}).start(); }).start();
} }

View File

@ -31,6 +31,7 @@ import com.evernote.android.job.JobRequest;
import com.evernote.android.job.util.Device; import com.evernote.android.job.util.Device;
import com.nextcloud.client.account.UserAccountManager; import com.nextcloud.client.account.UserAccountManager;
import com.owncloud.android.MainApp; import com.owncloud.android.MainApp;
import com.owncloud.android.datamodel.UploadsStorageManager;
/** /**
* Helper for setting up network and power receivers * Helper for setting up network and power receivers
@ -41,7 +42,10 @@ public final class ReceiversHelper {
// utility class -> private constructor // utility class -> private constructor
} }
public static void registerNetworkChangeReceiver(final UserAccountManager accountManager) { public static void registerNetworkChangeReceiver(
final UploadsStorageManager uploadsStorageManager,
final UserAccountManager accountManager
) {
Context context = MainApp.getAppContext(); Context context = MainApp.getAppContext();
IntentFilter intentFilter = new IntentFilter(); IntentFilter intentFilter = new IntentFilter();
@ -52,7 +56,7 @@ public final class ReceiversHelper {
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
if (!Device.getNetworkType(context).equals(JobRequest.NetworkType.ANY)) { if (!Device.getNetworkType(context).equals(JobRequest.NetworkType.ANY)) {
FilesSyncHelper.restartJobsIfNeeded(accountManager); FilesSyncHelper.restartJobsIfNeeded(uploadsStorageManager, accountManager);
} }
} }
}; };
@ -60,7 +64,10 @@ public final class ReceiversHelper {
context.registerReceiver(broadcastReceiver, intentFilter); context.registerReceiver(broadcastReceiver, intentFilter);
} }
public static void registerPowerChangeReceiver(final UserAccountManager accountManager) { public static void registerPowerChangeReceiver(
final UploadsStorageManager uploadsStorageManager,
final UserAccountManager accountManager
) {
Context context = MainApp.getAppContext(); Context context = MainApp.getAppContext();
IntentFilter intentFilter = new IntentFilter(); IntentFilter intentFilter = new IntentFilter();
@ -71,7 +78,7 @@ public final class ReceiversHelper {
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_POWER_CONNECTED.equals(intent.getAction())) { if (Intent.ACTION_POWER_CONNECTED.equals(intent.getAction())) {
FilesSyncHelper.restartJobsIfNeeded(accountManager); FilesSyncHelper.restartJobsIfNeeded(uploadsStorageManager, accountManager);
} }
} }
}; };
@ -79,7 +86,10 @@ public final class ReceiversHelper {
context.registerReceiver(broadcastReceiver, intentFilter); context.registerReceiver(broadcastReceiver, intentFilter);
} }
public static void registerPowerSaveReceiver(final UserAccountManager accountManager) { public static void registerPowerSaveReceiver(
final UploadsStorageManager uploadsStorageManager,
final UserAccountManager accountManager
) {
Context context = MainApp.getAppContext(); Context context = MainApp.getAppContext();
IntentFilter intentFilter = new IntentFilter(); IntentFilter intentFilter = new IntentFilter();
@ -89,7 +99,7 @@ public final class ReceiversHelper {
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
if (!PowerUtils.isPowerSaveMode(context)) { if (!PowerUtils.isPowerSaveMode(context)) {
FilesSyncHelper.restartJobsIfNeeded(accountManager); FilesSyncHelper.restartJobsIfNeeded(uploadsStorageManager, accountManager);
} }
} }
}; };

View File

@ -2,7 +2,10 @@
* Nextcloud Android client application * Nextcloud Android client application
* *
* @author Alejandro Bautista * @author Alejandro Bautista
* @author Chris Narkiewicz
*
* Copyright (C) 2017 Alejandro Bautista * Copyright (C) 2017 Alejandro Bautista
* Copyright (C) 2019 Chris Narkiewicz <hello@ezaquarii.com>
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
@ -21,16 +24,23 @@ package com.owncloud.android.utils.glide;
import com.bumptech.glide.load.data.DataFetcher; import com.bumptech.glide.load.data.DataFetcher;
import com.bumptech.glide.load.model.stream.StreamModelLoader; import com.bumptech.glide.load.model.stream.StreamModelLoader;
import com.nextcloud.client.account.CurrentAccountProvider;
import java.io.InputStream; import java.io.InputStream;
/** /**
* Custom Model for OwnCloudClient * Custom Model for OwnCloudClient
*/ */
public class CustomGlideStreamLoader implements StreamModelLoader<String> { public class CustomGlideStreamLoader implements StreamModelLoader<String> {
private final CurrentAccountProvider currentAccount;
public CustomGlideStreamLoader(CurrentAccountProvider currentAccount) {
this.currentAccount = currentAccount;
}
@Override @Override
public DataFetcher<InputStream> getResourceFetcher(String url, int width, int height) { public DataFetcher<InputStream> getResourceFetcher(String url, int width, int height) {
return new HttpStreamFetcher(url); return new HttpStreamFetcher(currentAccount, url);
} }
} }

View File

@ -2,7 +2,10 @@
* Nextcloud Android client application * Nextcloud Android client application
* *
* @author Alejandro Bautista * @author Alejandro Bautista
* @author Chris Narkiewicz
*
* Copyright (C) 2017 Alejandro Bautista * Copyright (C) 2017 Alejandro Bautista
* Copyright (C) 2019 Chris Narkiewicz <hello@ezaquarii.com>
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
@ -23,6 +26,7 @@ import android.accounts.Account;
import com.bumptech.glide.Priority; import com.bumptech.glide.Priority;
import com.bumptech.glide.load.data.DataFetcher; import com.bumptech.glide.load.data.DataFetcher;
import com.nextcloud.client.account.CurrentAccountProvider;
import com.owncloud.android.MainApp; import com.owncloud.android.MainApp;
import com.owncloud.android.authentication.AccountUtils; import com.owncloud.android.authentication.AccountUtils;
import com.owncloud.android.lib.common.OwnCloudAccount; import com.owncloud.android.lib.common.OwnCloudAccount;
@ -39,29 +43,28 @@ import java.io.InputStream;
/** /**
* Fetcher with OwnCloudClient * Fetcher with OwnCloudClient
*/ */
public class HttpStreamFetcher implements DataFetcher<InputStream> { public class HttpStreamFetcher implements DataFetcher<InputStream> {
private static final String TAG = HttpStreamFetcher.class.getName(); private static final String TAG = HttpStreamFetcher.class.getName();
private final String mURL; private final String url;
private final CurrentAccountProvider currentAccount;
public HttpStreamFetcher(String url) {
this.mURL = url;
HttpStreamFetcher(final CurrentAccountProvider currentAccount, final String url) {
this.currentAccount = currentAccount;
this.url = url;
} }
@Override @Override
public InputStream loadData(Priority priority) throws Exception { public InputStream loadData(Priority priority) throws Exception {
Account account = currentAccount.getCurrentAccount();
Account mAccount = AccountUtils.getCurrentOwnCloudAccount(MainApp.getAppContext()); OwnCloudAccount ocAccount = new OwnCloudAccount(account, MainApp.getAppContext());
OwnCloudAccount ocAccount = new OwnCloudAccount(mAccount, MainApp.getAppContext());
OwnCloudClient mClient = OwnCloudClientManagerFactory.getDefaultSingleton(). OwnCloudClient mClient = OwnCloudClientManagerFactory.getDefaultSingleton().
getClientFor(ocAccount, MainApp.getAppContext()); getClientFor(ocAccount, MainApp.getAppContext());
if (mClient != null) { if (mClient != null) {
GetMethod get; GetMethod get;
try { try {
get = new GetMethod(mURL); get = new GetMethod(url);
get.setRequestHeader("Cookie", "nc_sameSiteCookielax=true;nc_sameSiteCookiestrict=true"); get.setRequestHeader("Cookie", "nc_sameSiteCookielax=true;nc_sameSiteCookiestrict=true");
get.setRequestHeader(RemoteOperation.OCS_API_HEADER, RemoteOperation.OCS_API_HEADER_VALUE); get.setRequestHeader(RemoteOperation.OCS_API_HEADER, RemoteOperation.OCS_API_HEADER_VALUE);
int status = mClient.executeMethod(get); int status = mClient.executeMethod(get);
@ -84,7 +87,7 @@ public class HttpStreamFetcher implements DataFetcher<InputStream> {
@Override @Override
public String getId() { public String getId() {
return mURL; return url;
} }
@Override @Override