ManageAccountsActivity.java 20 KB

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