ManageAccountsActivity.java 19 KB

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