ManageAccountsActivity.java 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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.User;
  39. import com.nextcloud.client.account.UserAccountManager;
  40. import com.nextcloud.client.onboarding.FirstRunActivity;
  41. import com.owncloud.android.MainApp;
  42. import com.owncloud.android.R;
  43. import com.owncloud.android.datamodel.ArbitraryDataProvider;
  44. import com.owncloud.android.datamodel.FileDataStorageManager;
  45. import com.owncloud.android.files.services.FileDownloader;
  46. import com.owncloud.android.files.services.FileUploader;
  47. import com.owncloud.android.jobs.AccountRemovalJob;
  48. import com.owncloud.android.lib.common.OwnCloudAccount;
  49. import com.owncloud.android.lib.common.utils.Log_OC;
  50. import com.owncloud.android.services.OperationsService;
  51. import com.owncloud.android.ui.adapter.AccountListAdapter;
  52. import com.owncloud.android.ui.adapter.AccountListItem;
  53. import com.owncloud.android.ui.events.AccountRemovedEvent;
  54. import com.owncloud.android.ui.helpers.FileOperationsHelper;
  55. import com.owncloud.android.utils.DisplayUtils;
  56. import com.owncloud.android.utils.ThemeUtils;
  57. import org.greenrobot.eventbus.Subscribe;
  58. import org.greenrobot.eventbus.ThreadMode;
  59. import org.parceler.Parcels;
  60. import java.util.ArrayList;
  61. import java.util.Arrays;
  62. import java.util.List;
  63. import java.util.Set;
  64. import javax.inject.Inject;
  65. import androidx.core.content.ContextCompat;
  66. import androidx.core.graphics.drawable.DrawableCompat;
  67. import androidx.recyclerview.widget.LinearLayoutManager;
  68. import androidx.recyclerview.widget.RecyclerView;
  69. import static com.owncloud.android.ui.adapter.AccountListAdapter.KEY_DISPLAY_NAME;
  70. import static com.owncloud.android.ui.adapter.AccountListAdapter.KEY_USER_INFO_REQUEST_CODE;
  71. /**
  72. * An Activity that allows the user to manage accounts.
  73. */
  74. public class ManageAccountsActivity extends FileActivity implements AccountListAdapter.AccountListAdapterListener,
  75. AccountManagerCallback<Boolean>,
  76. ComponentsGetter,
  77. AccountListAdapter.ClickListener {
  78. private static final String TAG = ManageAccountsActivity.class.getSimpleName();
  79. public static final String KEY_ACCOUNT_LIST_CHANGED = "ACCOUNT_LIST_CHANGED";
  80. public static final String KEY_CURRENT_ACCOUNT_CHANGED = "CURRENT_ACCOUNT_CHANGED";
  81. public static final String PENDING_FOR_REMOVAL = UserAccountManager.PENDING_FOR_REMOVAL;
  82. private static final int KEY_DELETE_CODE = 101;
  83. private static final int SINGLE_ACCOUNT = 1;
  84. private static final int MIN_MULTI_ACCOUNT_SIZE = 2;
  85. private RecyclerView recyclerView;
  86. private final Handler handler = new Handler();
  87. private String accountName;
  88. private AccountListAdapter accountListAdapter;
  89. private ServiceConnection downloadServiceConnection;
  90. private ServiceConnection uploadServiceConnection;
  91. private Set<String> originalAccounts;
  92. private String originalCurrentAccount;
  93. private Drawable tintedCheck;
  94. private ArbitraryDataProvider arbitraryDataProvider;
  95. private boolean multipleAccountsSupported;
  96. @Inject UserAccountManager accountManager;
  97. @Override
  98. protected void onCreate(Bundle savedInstanceState) {
  99. super.onCreate(savedInstanceState);
  100. tintedCheck = DrawableCompat.wrap(ContextCompat.getDrawable(this, R.drawable.account_circle_white));
  101. int tint = ThemeUtils.elementColor(this);
  102. DrawableCompat.setTint(tintedCheck, tint);
  103. setContentView(R.layout.accounts_layout);
  104. recyclerView = findViewById(R.id.account_list);
  105. setupToolbar();
  106. updateActionBarTitleAndHomeButtonByString(getResources().getString(R.string.prefs_manage_accounts));
  107. Account[] accountList = AccountManager.get(this).getAccountsByType(MainApp.getAccountType(this));
  108. originalAccounts = DisplayUtils.toAccountNameSet(Arrays.asList(accountList));
  109. Account currentAccount = getAccount();
  110. if (currentAccount != null) {
  111. originalCurrentAccount = currentAccount.name;
  112. }
  113. arbitraryDataProvider = new ArbitraryDataProvider(getContentResolver());
  114. multipleAccountsSupported = getResources().getBoolean(R.bool.multiaccount_support);
  115. accountListAdapter = new AccountListAdapter(this,
  116. accountManager,
  117. getAccountListItems(),
  118. tintedCheck,
  119. this,
  120. multipleAccountsSupported);
  121. recyclerView.setAdapter(accountListAdapter);
  122. recyclerView.setLayoutManager(new LinearLayoutManager(this));
  123. initializeComponentGetters();
  124. }
  125. @Override
  126. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  127. super.onActivityResult(requestCode, resultCode, data);
  128. if (resultCode == KEY_DELETE_CODE && data != null) {
  129. Bundle bundle = data.getExtras();
  130. if (bundle != null && bundle.containsKey(UserInfoActivity.KEY_ACCOUNT)) {
  131. Account account = Parcels.unwrap(bundle.getParcelable(UserInfoActivity.KEY_ACCOUNT));
  132. accountName = account.name;
  133. performAccountRemoval(account);
  134. }
  135. }
  136. }
  137. @Override
  138. public void onBackPressed() {
  139. Intent resultIntent = new Intent();
  140. resultIntent.putExtra(KEY_ACCOUNT_LIST_CHANGED, hasAccountListChanged());
  141. resultIntent.putExtra(KEY_CURRENT_ACCOUNT_CHANGED, hasCurrentAccountChanged());
  142. setResult(RESULT_OK, resultIntent);
  143. super.onBackPressed();
  144. }
  145. /**
  146. * checks the set of actual accounts against the set of original accounts when the activity has been started.
  147. *
  148. * @return true if account list has changed, false if not
  149. */
  150. private boolean hasAccountListChanged() {
  151. Account[] accountList = AccountManager.get(this).getAccountsByType(MainApp.getAccountType(this));
  152. ArrayList<Account> newList = new ArrayList<>();
  153. for (Account account : accountList) {
  154. boolean pendingForRemoval = arbitraryDataProvider.getBooleanValue(account, PENDING_FOR_REMOVAL);
  155. if (!pendingForRemoval) {
  156. newList.add(account);
  157. }
  158. }
  159. Set<String> actualAccounts = DisplayUtils.toAccountNameSet(newList);
  160. return !originalAccounts.equals(actualAccounts);
  161. }
  162. /**
  163. * checks actual current account against current accounts when the activity has been started.
  164. *
  165. * @return true if account list has changed, false if not
  166. */
  167. private boolean hasCurrentAccountChanged() {
  168. User account = getUserAccountManager().getUser();
  169. if (account.isAnonymous()) {
  170. return true;
  171. } else {
  172. return !account.getAccountName().equals(originalCurrentAccount);
  173. }
  174. }
  175. /**
  176. * Initialize ComponentsGetters.
  177. */
  178. private void initializeComponentGetters() {
  179. downloadServiceConnection = newTransferenceServiceConnection();
  180. if (downloadServiceConnection != null) {
  181. bindService(new Intent(this, FileDownloader.class), downloadServiceConnection,
  182. Context.BIND_AUTO_CREATE);
  183. }
  184. uploadServiceConnection = newTransferenceServiceConnection();
  185. if (uploadServiceConnection != null) {
  186. bindService(new Intent(this, FileUploader.class), uploadServiceConnection,
  187. Context.BIND_AUTO_CREATE);
  188. }
  189. }
  190. /**
  191. * creates the account list items list including the add-account action in case multiaccount_support is enabled.
  192. *
  193. * @return list of account list items
  194. */
  195. private List<AccountListItem> getAccountListItems() {
  196. Account[] accountList = AccountManager.get(this).getAccountsByType(MainApp.getAccountType(this));
  197. List<AccountListItem> adapterAccountList = new ArrayList<>(accountList.length);
  198. for (Account account : accountList) {
  199. boolean pendingForRemoval = arbitraryDataProvider.getBooleanValue(account, PENDING_FOR_REMOVAL);
  200. adapterAccountList.add(new AccountListItem(account, !pendingForRemoval));
  201. }
  202. // Add Create Account item at the end of account list if multi-account is enabled
  203. if (getResources().getBoolean(R.bool.multiaccount_support)) {
  204. adapterAccountList.add(new AccountListItem());
  205. }
  206. return adapterAccountList;
  207. }
  208. @Override
  209. public boolean onOptionsItemSelected(MenuItem item) {
  210. boolean retval = true;
  211. switch (item.getItemId()) {
  212. case android.R.id.home:
  213. onBackPressed();
  214. break;
  215. default:
  216. retval = super.onOptionsItemSelected(item);
  217. break;
  218. }
  219. return retval;
  220. }
  221. @Override
  222. public void showFirstRunActivity() {
  223. Intent firstRunIntent = new Intent(getApplicationContext(), FirstRunActivity.class);
  224. firstRunIntent.putExtra(FirstRunActivity.EXTRA_ALLOW_CLOSE, true);
  225. startActivity(firstRunIntent);
  226. }
  227. @Override
  228. public void createAccount() {
  229. AccountManager am = AccountManager.get(getApplicationContext());
  230. am.addAccount(MainApp.getAccountType(this),
  231. null,
  232. null,
  233. null,
  234. this,
  235. future -> {
  236. if (future != null) {
  237. try {
  238. Bundle result = future.getResult();
  239. String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
  240. accountManager.setCurrentOwnCloudAccount(name);
  241. accountListAdapter = new AccountListAdapter(
  242. this,
  243. accountManager,
  244. getAccountListItems(),
  245. tintedCheck,
  246. this,
  247. multipleAccountsSupported
  248. );
  249. recyclerView.setAdapter(accountListAdapter);
  250. runOnUiThread(() -> accountListAdapter.notifyDataSetChanged());
  251. } catch (OperationCanceledException e) {
  252. Log_OC.d(TAG, "Account creation canceled");
  253. } catch (Exception e) {
  254. Log_OC.e(TAG, "Account creation finished in exception: ", e);
  255. }
  256. }
  257. }, handler);
  258. }
  259. @Subscribe(threadMode = ThreadMode.MAIN)
  260. public void onAccountRemovedEvent(AccountRemovedEvent event) {
  261. List<AccountListItem> accountListItemArray = getAccountListItems();
  262. accountListAdapter.clear();
  263. accountListAdapter.addAll(accountListItemArray);
  264. accountListAdapter.notifyDataSetChanged();
  265. }
  266. @Override
  267. public void run(AccountManagerFuture<Boolean> future) {
  268. if (future.isDone()) {
  269. // after remove account
  270. Account account = new Account(accountName, MainApp.getAccountType(this));
  271. if (!accountManager.exists(account)) {
  272. // Cancel transfers of the removed account
  273. if (mUploaderBinder != null) {
  274. mUploaderBinder.cancel(account);
  275. }
  276. if (mDownloaderBinder != null) {
  277. mDownloaderBinder.cancel(account);
  278. }
  279. }
  280. User user = getUserAccountManager().getUser();
  281. if (user.isAnonymous()) {
  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. }