ManageAccountsActivity.java 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  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.AnalyticsUtils;
  57. import com.owncloud.android.utils.DisplayUtils;
  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.Arrays;
  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, mUploadServiceConnection = null;
  82. Set<String> mOriginalAccounts;
  83. String mOriginalCurrentAccount;
  84. private Drawable mTintedCheck;
  85. private static final String SCREEN_NAME = "Logs";
  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.ic_account_circle_white_18dp));
  91. int tint = ThemeUtils.primaryColor(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());
  98. mOriginalAccounts = DisplayUtils.toAccountNameSet(Arrays.asList(accountList));
  99. mOriginalCurrentAccount = AccountUtils.getCurrentOwnCloudAccount(this).name;
  100. setAccount(AccountUtils.getCurrentOwnCloudAccount(this));
  101. onAccountSet(false);
  102. arbitraryDataProvider = new ArbitraryDataProvider(getContentResolver());
  103. mAccountListAdapter = new AccountListAdapter(this, getAccountListItems(), mTintedCheck);
  104. mListView.setAdapter(mAccountListAdapter);
  105. final Intent intent = new Intent(this, UserInfoActivity.class);
  106. mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
  107. @Override
  108. public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
  109. AccountListItem item = mAccountListAdapter.getItem(position);
  110. if (item != null && item.isEnabled()) {
  111. Account account = item.getAccount();
  112. intent.putExtra(UserInfoActivity.KEY_ACCOUNT, Parcels.wrap(account));
  113. try {
  114. OwnCloudAccount oca = new OwnCloudAccount(account, MainApp.getAppContext());
  115. intent.putExtra(KEY_DISPLAY_NAME, oca.getDisplayName());
  116. } catch (com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException e) {
  117. Log_OC.d(TAG, "Failed to find NC account");
  118. }
  119. startActivityForResult(intent, KEY_USER_INFO_REQUEST_CODE);
  120. }
  121. }
  122. });
  123. initializeComponentGetters();
  124. }
  125. @Override
  126. protected void onResume() {
  127. super.onResume();
  128. AnalyticsUtils.setCurrentScreenName(this, SCREEN_NAME, TAG);
  129. }
  130. @Override
  131. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  132. super.onActivityResult(requestCode, resultCode, data);
  133. switch (resultCode) {
  134. case KEY_DELETE_CODE:
  135. if (data != null) {
  136. Bundle bundle = data.getExtras();
  137. if (bundle.containsKey(UserInfoActivity.KEY_ACCOUNT)) {
  138. Account account = Parcels.unwrap(bundle.getParcelable(UserInfoActivity.KEY_ACCOUNT));
  139. mAccountName = account.name;
  140. performAccountRemoval(account);
  141. }
  142. }
  143. break;
  144. default:
  145. break;
  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. Account[] accountList = AccountManager.get(this).getAccountsByType(MainApp.getAccountType());
  163. ArrayList<Account> newList = new ArrayList<>();
  164. for (Account account : accountList) {
  165. boolean pendingForRemoval = arbitraryDataProvider.getBooleanValue(account, PENDING_FOR_REMOVAL);
  166. if (!pendingForRemoval) {
  167. newList.add(account);
  168. }
  169. }
  170. Set<String> actualAccounts = DisplayUtils.toAccountNameSet(newList);
  171. return !mOriginalAccounts.equals(actualAccounts);
  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. Account account = AccountUtils.getCurrentOwnCloudAccount(this);
  180. if (account == null) {
  181. return true;
  182. } else {
  183. return !mOriginalCurrentAccount.equals(account.name);
  184. }
  185. }
  186. /**
  187. * Initialize ComponentsGetters.
  188. */
  189. private void initializeComponentGetters() {
  190. mDownloadServiceConnection = newTransferenceServiceConnection();
  191. if (mDownloadServiceConnection != null) {
  192. bindService(new Intent(this, FileDownloader.class), mDownloadServiceConnection,
  193. Context.BIND_AUTO_CREATE);
  194. }
  195. mUploadServiceConnection = newTransferenceServiceConnection();
  196. if (mUploadServiceConnection != null) {
  197. bindService(new Intent(this, FileUploader.class), mUploadServiceConnection,
  198. Context.BIND_AUTO_CREATE);
  199. }
  200. }
  201. /**
  202. * creates the account list items list including the add-account action in case multiaccount_support is enabled.
  203. *
  204. * @return list of account list items
  205. */
  206. private ArrayList<AccountListItem> getAccountListItems() {
  207. Account[] accountList = AccountManager.get(this).getAccountsByType(MainApp.getAccountType());
  208. ArrayList<AccountListItem> adapterAccountList = new ArrayList<>(accountList.length);
  209. for (Account account : accountList) {
  210. boolean pendingForRemoval = arbitraryDataProvider.getBooleanValue(account, PENDING_FOR_REMOVAL);
  211. adapterAccountList.add(new AccountListItem(account, !pendingForRemoval));
  212. }
  213. // Add Create Account item at the end of account list if multi-account is enabled
  214. if (getResources().getBoolean(R.bool.multiaccount_support)) {
  215. adapterAccountList.add(new AccountListItem());
  216. }
  217. return adapterAccountList;
  218. }
  219. @Override
  220. public boolean onOptionsItemSelected(MenuItem item) {
  221. boolean retval = true;
  222. switch (item.getItemId()) {
  223. case android.R.id.home:
  224. onBackPressed();
  225. break;
  226. default:
  227. retval = super.onOptionsItemSelected(item);
  228. break;
  229. }
  230. return retval;
  231. }
  232. @Override
  233. public void createAccount() {
  234. AccountManager am = AccountManager.get(getApplicationContext());
  235. am.addAccount(MainApp.getAccountType(),
  236. null,
  237. null,
  238. null,
  239. this,
  240. new AccountManagerCallback<Bundle>() {
  241. @Override
  242. public void run(AccountManagerFuture<Bundle> future) {
  243. if (future != null) {
  244. try {
  245. Bundle result = future.getResult();
  246. String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
  247. AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), name);
  248. mAccountListAdapter = new AccountListAdapter(
  249. ManageAccountsActivity.this,
  250. getAccountListItems(),
  251. mTintedCheck
  252. );
  253. mListView.setAdapter(mAccountListAdapter);
  254. runOnUiThread(new Runnable() {
  255. @Override
  256. public void run() {
  257. mAccountListAdapter.notifyDataSetChanged();
  258. }
  259. });
  260. } catch (OperationCanceledException e) {
  261. Log_OC.d(TAG, "Account creation canceled");
  262. } catch (Exception e) {
  263. Log_OC.e(TAG, "Account creation finished in exception: ", e);
  264. }
  265. }
  266. }
  267. }, mHandler);
  268. }
  269. @Subscribe(threadMode = ThreadMode.MAIN)
  270. public void onAccountRemovedEvent(AccountRemovedEvent event) {
  271. ArrayList<AccountListItem> accountListItemArray = getAccountListItems();
  272. mAccountListAdapter.clear();
  273. mAccountListAdapter.addAll(accountListItemArray);
  274. mAccountListAdapter.notifyDataSetChanged();
  275. }
  276. @Override
  277. public void run(AccountManagerFuture<Boolean> future) {
  278. if (future.isDone()) {
  279. // after remove account
  280. Account account = new Account(mAccountName, MainApp.getAccountType());
  281. if (!AccountUtils.exists(account, MainApp.getAppContext())) {
  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. if (AccountUtils.getCurrentOwnCloudAccount(this) == null) {
  291. String accountName = "";
  292. Account[] accounts = AccountManager.get(this).getAccountsByType(MainApp.getAccountType());
  293. if (accounts.length != 0) {
  294. accountName = accounts[0].name;
  295. }
  296. AccountUtils.setCurrentOwnCloudAccount(this, accountName);
  297. }
  298. ArrayList<AccountListItem> accountListItemArray = getAccountListItems();
  299. if (accountListItemArray.size() > 1) {
  300. mAccountListAdapter = new AccountListAdapter(this, accountListItemArray, mTintedCheck);
  301. mListView.setAdapter(mAccountListAdapter);
  302. } else {
  303. onBackPressed();
  304. }
  305. }
  306. }
  307. @Override
  308. protected void onDestroy() {
  309. if (mDownloadServiceConnection != null) {
  310. unbindService(mDownloadServiceConnection);
  311. mDownloadServiceConnection = null;
  312. }
  313. if (mUploadServiceConnection != null) {
  314. unbindService(mUploadServiceConnection);
  315. mUploadServiceConnection = null;
  316. }
  317. super.onDestroy();
  318. }
  319. public Handler getHandler() { return mHandler; }
  320. @Override
  321. public FileUploader.FileUploaderBinder getFileUploaderBinder() {
  322. return mUploaderBinder;
  323. }
  324. @Override
  325. public OperationsService.OperationsServiceBinder getOperationsServiceBinder() {
  326. return null;
  327. }
  328. @Override
  329. public FileDataStorageManager getStorageManager() {
  330. return super.getStorageManager();
  331. }
  332. @Override
  333. public FileOperationsHelper getFileOperationsHelper() {
  334. return null;
  335. }
  336. protected ServiceConnection newTransferenceServiceConnection() {
  337. return new ManageAccountsServiceConnection();
  338. }
  339. private void performAccountRemoval(Account account) {
  340. // disable account in list view
  341. for (int i = 0; i < mAccountListAdapter.getCount(); i++) {
  342. AccountListItem item = mAccountListAdapter.getItem(i);
  343. if (item != null && item.getAccount().equals(account)) {
  344. item.setEnabled(false);
  345. break;
  346. }
  347. mAccountListAdapter.notifyDataSetChanged();
  348. }
  349. // store pending account removal
  350. ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(getContentResolver());
  351. arbitraryDataProvider.storeOrUpdateKeyValue(account.name, PENDING_FOR_REMOVAL, String.valueOf(true));
  352. // Cancel transfers
  353. if (mUploaderBinder != null) {
  354. mUploaderBinder.cancel(account);
  355. }
  356. if (mDownloaderBinder != null) {
  357. mDownloaderBinder.cancel(account);
  358. }
  359. // schedule job
  360. PersistableBundleCompat bundle = new PersistableBundleCompat();
  361. bundle.putString(AccountRemovalJob.ACCOUNT, account.name);
  362. new JobRequest.Builder(AccountRemovalJob.TAG)
  363. .startNow()
  364. .setExtras(bundle)
  365. .setUpdateCurrent(false)
  366. .build()
  367. .schedule();
  368. // immediately select a new account
  369. Account[] accounts = AccountManager.get(this).getAccountsByType(MainApp.getAccountType());
  370. String newAccountName = "";
  371. for (Account acc: accounts) {
  372. if (!account.name.equalsIgnoreCase(acc.name)) {
  373. newAccountName = acc.name;
  374. break;
  375. }
  376. }
  377. if (newAccountName.isEmpty()) {
  378. Log_OC.d(TAG, "new account set to null");
  379. AccountUtils.resetOwnCloudAccount(this);
  380. } else {
  381. Log_OC.d(TAG, "new account set to: " + newAccountName);
  382. AccountUtils.setCurrentOwnCloudAccount(this, newAccountName);
  383. }
  384. // only one to be (deleted) account remaining
  385. if (accounts.length < 2) {
  386. Intent resultIntent = new Intent();
  387. resultIntent.putExtra(KEY_ACCOUNT_LIST_CHANGED, true);
  388. resultIntent.putExtra(KEY_CURRENT_ACCOUNT_CHANGED, true);
  389. setResult(RESULT_OK, resultIntent);
  390. super.onBackPressed();
  391. }
  392. }
  393. /**
  394. * Defines callbacks for service binding, passed to bindService()
  395. */
  396. private class ManageAccountsServiceConnection implements ServiceConnection {
  397. @Override
  398. public void onServiceConnected(ComponentName component, IBinder service) {
  399. if (component.equals(new ComponentName(ManageAccountsActivity.this, FileDownloader.class))) {
  400. mDownloaderBinder = (FileDownloader.FileDownloaderBinder) service;
  401. } else if (component.equals(new ComponentName(ManageAccountsActivity.this, FileUploader.class))) {
  402. Log_OC.d(TAG, "Upload service connected");
  403. mUploaderBinder = (FileUploader.FileUploaderBinder) service;
  404. }
  405. }
  406. @Override
  407. public void onServiceDisconnected(ComponentName component) {
  408. if (component.equals(new ComponentName(ManageAccountsActivity.this, FileDownloader.class))) {
  409. Log_OC.d(TAG, "Download service suddenly disconnected");
  410. mDownloaderBinder = null;
  411. } else if (component.equals(new ComponentName(ManageAccountsActivity.this, FileUploader.class))) {
  412. Log_OC.d(TAG, "Upload service suddenly disconnected");
  413. mUploaderBinder = null;
  414. }
  415. }
  416. }
  417. }