ManageAccountsActivity.java 19 KB

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