ManageAccountsActivity.java 19 KB

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