ManageAccountsActivity.java 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. /*
  2. * ownCloud Android client application
  3. *
  4. * @author Andy Scherzinger
  5. * @author Chris Narkiewicz
  6. * Copyright (C) 2016 ownCloud Inc.
  7. * Copyright (C) 2019 Chris Narkiewicz <hello@ezaquarii.com>
  8. * <p/>
  9. * This program is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License version 2,
  11. * as published by the Free Software Foundation.
  12. * <p/>
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. * <p/>
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. */
  21. package com.owncloud.android.ui.activity;
  22. import android.accounts.Account;
  23. import android.accounts.AccountManager;
  24. import android.accounts.AccountManagerCallback;
  25. import android.accounts.AccountManagerFuture;
  26. import android.accounts.OperationCanceledException;
  27. import android.content.ComponentName;
  28. import android.content.Context;
  29. import android.content.Intent;
  30. import android.content.ServiceConnection;
  31. import android.graphics.drawable.Drawable;
  32. import android.os.Bundle;
  33. import android.os.Handler;
  34. import android.os.IBinder;
  35. import android.view.MenuItem;
  36. import com.evernote.android.job.JobRequest;
  37. import com.evernote.android.job.util.support.PersistableBundleCompat;
  38. import com.nextcloud.client.account.UserAccountManager;
  39. import com.nextcloud.client.onboarding.FirstRunActivity;
  40. import com.owncloud.android.MainApp;
  41. import com.owncloud.android.R;
  42. import com.owncloud.android.datamodel.ArbitraryDataProvider;
  43. import com.owncloud.android.datamodel.FileDataStorageManager;
  44. import com.owncloud.android.files.services.FileDownloader;
  45. import com.owncloud.android.files.services.FileUploader;
  46. import com.owncloud.android.jobs.AccountRemovalJob;
  47. import com.owncloud.android.lib.common.OwnCloudAccount;
  48. import com.owncloud.android.lib.common.utils.Log_OC;
  49. import com.owncloud.android.services.OperationsService;
  50. import com.owncloud.android.ui.adapter.AccountListAdapter;
  51. import com.owncloud.android.ui.adapter.AccountListItem;
  52. import com.owncloud.android.ui.events.AccountRemovedEvent;
  53. import com.owncloud.android.ui.helpers.FileOperationsHelper;
  54. import com.owncloud.android.utils.DisplayUtils;
  55. import com.owncloud.android.utils.ThemeUtils;
  56. import org.greenrobot.eventbus.Subscribe;
  57. import org.greenrobot.eventbus.ThreadMode;
  58. import org.parceler.Parcels;
  59. import java.util.ArrayList;
  60. import java.util.Arrays;
  61. import java.util.List;
  62. import java.util.Set;
  63. import javax.inject.Inject;
  64. import androidx.core.content.ContextCompat;
  65. import androidx.core.graphics.drawable.DrawableCompat;
  66. import androidx.recyclerview.widget.LinearLayoutManager;
  67. import androidx.recyclerview.widget.RecyclerView;
  68. import static com.owncloud.android.ui.adapter.AccountListAdapter.KEY_DISPLAY_NAME;
  69. import static com.owncloud.android.ui.adapter.AccountListAdapter.KEY_USER_INFO_REQUEST_CODE;
  70. /**
  71. * An Activity that allows the user to manage accounts.
  72. */
  73. public class ManageAccountsActivity extends FileActivity implements AccountListAdapter.AccountListAdapterListener,
  74. AccountManagerCallback<Boolean>,
  75. ComponentsGetter,
  76. AccountListAdapter.ClickListener {
  77. private static final String TAG = ManageAccountsActivity.class.getSimpleName();
  78. public static final String KEY_ACCOUNT_LIST_CHANGED = "ACCOUNT_LIST_CHANGED";
  79. public static final String KEY_CURRENT_ACCOUNT_CHANGED = "CURRENT_ACCOUNT_CHANGED";
  80. public static final String PENDING_FOR_REMOVAL = UserAccountManager.PENDING_FOR_REMOVAL;
  81. private static final int KEY_DELETE_CODE = 101;
  82. private static final int SINGLE_ACCOUNT = 1;
  83. private static final int MIN_MULTI_ACCOUNT_SIZE = 2;
  84. private RecyclerView recyclerView;
  85. private final Handler handler = new Handler();
  86. private String accountName;
  87. private AccountListAdapter accountListAdapter;
  88. private ServiceConnection downloadServiceConnection;
  89. private ServiceConnection uploadServiceConnection;
  90. private Set<String> originalAccounts;
  91. private String originalCurrentAccount;
  92. private Drawable tintedCheck;
  93. private ArbitraryDataProvider arbitraryDataProvider;
  94. private boolean multipleAccountsSupported;
  95. @Inject UserAccountManager accountManager;
  96. @Override
  97. protected void onCreate(Bundle savedInstanceState) {
  98. super.onCreate(savedInstanceState);
  99. tintedCheck = DrawableCompat.wrap(ContextCompat.getDrawable(this, R.drawable.account_circle_white));
  100. int tint = ThemeUtils.elementColor(this);
  101. DrawableCompat.setTint(tintedCheck, tint);
  102. setContentView(R.layout.accounts_layout);
  103. recyclerView = findViewById(R.id.account_list);
  104. setupToolbar();
  105. updateActionBarTitleAndHomeButtonByString(getResources().getString(R.string.prefs_manage_accounts));
  106. Account[] accountList = AccountManager.get(this).getAccountsByType(MainApp.getAccountType(this));
  107. originalAccounts = DisplayUtils.toAccountNameSet(Arrays.asList(accountList));
  108. Account currentAccount = getUserAccountManager().getCurrentAccount();
  109. if (currentAccount != null) {
  110. originalCurrentAccount = currentAccount.name;
  111. }
  112. setAccount(currentAccount);
  113. onAccountSet();
  114. arbitraryDataProvider = new ArbitraryDataProvider(getContentResolver());
  115. multipleAccountsSupported = getResources().getBoolean(R.bool.multiaccount_support);
  116. accountListAdapter = new AccountListAdapter(this,
  117. accountManager,
  118. getAccountListItems(),
  119. tintedCheck,
  120. this,
  121. multipleAccountsSupported);
  122. recyclerView.setAdapter(accountListAdapter);
  123. recyclerView.setLayoutManager(new LinearLayoutManager(this));
  124. initializeComponentGetters();
  125. }
  126. @Override
  127. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  128. super.onActivityResult(requestCode, resultCode, data);
  129. if (resultCode == KEY_DELETE_CODE && data != null) {
  130. Bundle bundle = data.getExtras();
  131. if (bundle != null && bundle.containsKey(UserInfoActivity.KEY_ACCOUNT)) {
  132. Account account = Parcels.unwrap(bundle.getParcelable(UserInfoActivity.KEY_ACCOUNT));
  133. accountName = account.name;
  134. performAccountRemoval(account);
  135. }
  136. }
  137. }
  138. @Override
  139. public void onBackPressed() {
  140. Intent resultIntent = new Intent();
  141. resultIntent.putExtra(KEY_ACCOUNT_LIST_CHANGED, hasAccountListChanged());
  142. resultIntent.putExtra(KEY_CURRENT_ACCOUNT_CHANGED, hasCurrentAccountChanged());
  143. setResult(RESULT_OK, resultIntent);
  144. super.onBackPressed();
  145. }
  146. /**
  147. * checks the set of actual accounts against the set of original accounts when the activity has been started.
  148. *
  149. * @return true if account list has changed, false if not
  150. */
  151. private boolean hasAccountListChanged() {
  152. Account[] accountList = AccountManager.get(this).getAccountsByType(MainApp.getAccountType(this));
  153. ArrayList<Account> newList = new ArrayList<>();
  154. for (Account account : accountList) {
  155. boolean pendingForRemoval = arbitraryDataProvider.getBooleanValue(account, PENDING_FOR_REMOVAL);
  156. if (!pendingForRemoval) {
  157. newList.add(account);
  158. }
  159. }
  160. Set<String> actualAccounts = DisplayUtils.toAccountNameSet(newList);
  161. return !originalAccounts.equals(actualAccounts);
  162. }
  163. /**
  164. * checks actual current account against current accounts when the activity has been started.
  165. *
  166. * @return true if account list has changed, false if not
  167. */
  168. private boolean hasCurrentAccountChanged() {
  169. Account account = getUserAccountManager().getCurrentAccount();
  170. if (account == null) {
  171. return true;
  172. } else {
  173. return !account.name.equals(originalCurrentAccount);
  174. }
  175. }
  176. /**
  177. * Initialize ComponentsGetters.
  178. */
  179. private void initializeComponentGetters() {
  180. downloadServiceConnection = newTransferenceServiceConnection();
  181. if (downloadServiceConnection != null) {
  182. bindService(new Intent(this, FileDownloader.class), downloadServiceConnection,
  183. Context.BIND_AUTO_CREATE);
  184. }
  185. uploadServiceConnection = newTransferenceServiceConnection();
  186. if (uploadServiceConnection != null) {
  187. bindService(new Intent(this, FileUploader.class), uploadServiceConnection,
  188. Context.BIND_AUTO_CREATE);
  189. }
  190. }
  191. /**
  192. * creates the account list items list including the add-account action in case multiaccount_support is enabled.
  193. *
  194. * @return list of account list items
  195. */
  196. private List<AccountListItem> getAccountListItems() {
  197. Account[] accountList = AccountManager.get(this).getAccountsByType(MainApp.getAccountType(this));
  198. List<AccountListItem> adapterAccountList = new ArrayList<>(accountList.length);
  199. for (Account account : accountList) {
  200. boolean pendingForRemoval = arbitraryDataProvider.getBooleanValue(account, PENDING_FOR_REMOVAL);
  201. adapterAccountList.add(new AccountListItem(account, !pendingForRemoval));
  202. }
  203. // Add Create Account item at the end of account list if multi-account is enabled
  204. if (getResources().getBoolean(R.bool.multiaccount_support)) {
  205. adapterAccountList.add(new AccountListItem());
  206. }
  207. return adapterAccountList;
  208. }
  209. @Override
  210. public boolean onOptionsItemSelected(MenuItem item) {
  211. boolean retval = true;
  212. switch (item.getItemId()) {
  213. case android.R.id.home:
  214. onBackPressed();
  215. break;
  216. default:
  217. retval = super.onOptionsItemSelected(item);
  218. break;
  219. }
  220. return retval;
  221. }
  222. @Override
  223. public void showFirstRunActivity() {
  224. Intent firstRunIntent = new Intent(getApplicationContext(), FirstRunActivity.class);
  225. firstRunIntent.putExtra(FirstRunActivity.EXTRA_ALLOW_CLOSE, true);
  226. startActivity(firstRunIntent);
  227. }
  228. @Override
  229. public void createAccount() {
  230. AccountManager am = AccountManager.get(getApplicationContext());
  231. am.addAccount(MainApp.getAccountType(this),
  232. null,
  233. null,
  234. null,
  235. this,
  236. future -> {
  237. if (future != null) {
  238. try {
  239. Bundle result = future.getResult();
  240. String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
  241. accountManager.setCurrentOwnCloudAccount(name);
  242. accountListAdapter = new AccountListAdapter(
  243. this,
  244. accountManager,
  245. getAccountListItems(),
  246. tintedCheck,
  247. this,
  248. multipleAccountsSupported
  249. );
  250. recyclerView.setAdapter(accountListAdapter);
  251. runOnUiThread(() -> accountListAdapter.notifyDataSetChanged());
  252. } catch (OperationCanceledException e) {
  253. Log_OC.d(TAG, "Account creation canceled");
  254. } catch (Exception e) {
  255. Log_OC.e(TAG, "Account creation finished in exception: ", e);
  256. }
  257. }
  258. }, handler);
  259. }
  260. @Subscribe(threadMode = ThreadMode.MAIN)
  261. public void onAccountRemovedEvent(AccountRemovedEvent event) {
  262. List<AccountListItem> accountListItemArray = getAccountListItems();
  263. accountListAdapter.clear();
  264. accountListAdapter.addAll(accountListItemArray);
  265. accountListAdapter.notifyDataSetChanged();
  266. }
  267. @Override
  268. public void run(AccountManagerFuture<Boolean> future) {
  269. if (future.isDone()) {
  270. // after remove account
  271. Account account = new Account(accountName, MainApp.getAccountType(this));
  272. if (!accountManager.exists(account)) {
  273. // Cancel transfers of the removed account
  274. if (mUploaderBinder != null) {
  275. mUploaderBinder.cancel(account);
  276. }
  277. if (mDownloaderBinder != null) {
  278. mDownloaderBinder.cancel(account);
  279. }
  280. }
  281. if (getUserAccountManager().getCurrentAccount() == null) {
  282. String accountName = "";
  283. Account[] accounts = AccountManager.get(this).getAccountsByType(MainApp.getAccountType(this));
  284. if (accounts.length != 0) {
  285. accountName = accounts[0].name;
  286. }
  287. accountManager.setCurrentOwnCloudAccount(accountName);
  288. }
  289. List<AccountListItem> accountListItemArray = getAccountListItems();
  290. if (accountListItemArray.size() > SINGLE_ACCOUNT) {
  291. accountListAdapter = new AccountListAdapter(this,
  292. accountManager,
  293. accountListItemArray,
  294. tintedCheck,
  295. this,
  296. multipleAccountsSupported
  297. );
  298. recyclerView.setAdapter(accountListAdapter);
  299. } else {
  300. onBackPressed();
  301. }
  302. }
  303. }
  304. @Override
  305. protected void onDestroy() {
  306. if (downloadServiceConnection != null) {
  307. unbindService(downloadServiceConnection);
  308. downloadServiceConnection = null;
  309. }
  310. if (uploadServiceConnection != null) {
  311. unbindService(uploadServiceConnection);
  312. uploadServiceConnection = null;
  313. }
  314. super.onDestroy();
  315. }
  316. public Handler getHandler() { return handler; }
  317. @Override
  318. public FileUploader.FileUploaderBinder getFileUploaderBinder() {
  319. return mUploaderBinder;
  320. }
  321. @Override
  322. public OperationsService.OperationsServiceBinder getOperationsServiceBinder() {
  323. return null;
  324. }
  325. @Override
  326. public FileDataStorageManager getStorageManager() {
  327. return super.getStorageManager();
  328. }
  329. @Override
  330. public FileOperationsHelper getFileOperationsHelper() {
  331. return null;
  332. }
  333. protected ServiceConnection newTransferenceServiceConnection() {
  334. return new ManageAccountsServiceConnection();
  335. }
  336. private void performAccountRemoval(Account account) {
  337. // disable account in recycler view
  338. for (int i = 0; i < accountListAdapter.getItemCount(); i++) {
  339. AccountListItem item = accountListAdapter.getItem(i);
  340. if (item != null && item.getAccount().equals(account)) {
  341. item.setEnabled(false);
  342. break;
  343. }
  344. accountListAdapter.notifyDataSetChanged();
  345. }
  346. // store pending account removal
  347. ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(getContentResolver());
  348. arbitraryDataProvider.storeOrUpdateKeyValue(account.name, PENDING_FOR_REMOVAL, String.valueOf(true));
  349. // Cancel transfers
  350. if (mUploaderBinder != null) {
  351. mUploaderBinder.cancel(account);
  352. }
  353. if (mDownloaderBinder != null) {
  354. mDownloaderBinder.cancel(account);
  355. }
  356. // schedule job
  357. PersistableBundleCompat bundle = new PersistableBundleCompat();
  358. bundle.putString(AccountRemovalJob.ACCOUNT, account.name);
  359. new JobRequest.Builder(AccountRemovalJob.TAG)
  360. .startNow()
  361. .setExtras(bundle)
  362. .setUpdateCurrent(false)
  363. .build()
  364. .schedule();
  365. // immediately select a new account
  366. Account[] accounts = AccountManager.get(this).getAccountsByType(MainApp.getAccountType(this));
  367. String newAccountName = "";
  368. for (Account acc: accounts) {
  369. if (!account.name.equalsIgnoreCase(acc.name)) {
  370. newAccountName = acc.name;
  371. break;
  372. }
  373. }
  374. if (newAccountName.isEmpty()) {
  375. Log_OC.d(TAG, "new account set to null");
  376. accountManager.resetOwnCloudAccount();
  377. } else {
  378. Log_OC.d(TAG, "new account set to: " + newAccountName);
  379. accountManager.setCurrentOwnCloudAccount(newAccountName);
  380. }
  381. // only one to be (deleted) account remaining
  382. if (accounts.length < MIN_MULTI_ACCOUNT_SIZE) {
  383. Intent resultIntent = new Intent();
  384. resultIntent.putExtra(KEY_ACCOUNT_LIST_CHANGED, true);
  385. resultIntent.putExtra(KEY_CURRENT_ACCOUNT_CHANGED, true);
  386. setResult(RESULT_OK, resultIntent);
  387. super.onBackPressed();
  388. }
  389. }
  390. @Override
  391. public void onClick(Account account) {
  392. final Intent intent = new Intent(this, UserInfoActivity.class);
  393. intent.putExtra(UserInfoActivity.KEY_ACCOUNT, Parcels.wrap(account));
  394. try {
  395. OwnCloudAccount oca = new OwnCloudAccount(account, MainApp.getAppContext());
  396. intent.putExtra(KEY_DISPLAY_NAME, oca.getDisplayName());
  397. } catch (com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException e) {
  398. Log_OC.d(TAG, "Failed to find NC account");
  399. }
  400. startActivityForResult(intent, KEY_USER_INFO_REQUEST_CODE);
  401. }
  402. /**
  403. * Defines callbacks for service binding, passed to bindService()
  404. */
  405. private class ManageAccountsServiceConnection implements ServiceConnection {
  406. @Override
  407. public void onServiceConnected(ComponentName component, IBinder service) {
  408. if (component.equals(new ComponentName(ManageAccountsActivity.this, FileDownloader.class))) {
  409. mDownloaderBinder = (FileDownloader.FileDownloaderBinder) service;
  410. } else if (component.equals(new ComponentName(ManageAccountsActivity.this, FileUploader.class))) {
  411. Log_OC.d(TAG, "Upload service connected");
  412. mUploaderBinder = (FileUploader.FileUploaderBinder) service;
  413. }
  414. }
  415. @Override
  416. public void onServiceDisconnected(ComponentName component) {
  417. if (component.equals(new ComponentName(ManageAccountsActivity.this, FileDownloader.class))) {
  418. Log_OC.d(TAG, "Download service suddenly disconnected");
  419. mDownloaderBinder = null;
  420. } else if (component.equals(new ComponentName(ManageAccountsActivity.this, FileUploader.class))) {
  421. Log_OC.d(TAG, "Upload service suddenly disconnected");
  422. mUploaderBinder = null;
  423. }
  424. }
  425. }
  426. }