FileActivity.java 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  1. /* ownCloud Android client application
  2. * Copyright (C) 2011 Bartek Przybylski
  3. * Copyright (C) 2012-2014 ownCloud Inc.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License version 2,
  7. * as published by the Free Software Foundation.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. *
  17. */
  18. package com.owncloud.android.ui.activity;
  19. import android.accounts.Account;
  20. import android.accounts.AccountManager;
  21. import android.accounts.AccountManagerCallback;
  22. import android.accounts.AccountManagerFuture;
  23. import android.accounts.AuthenticatorException;
  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.os.Bundle;
  30. import android.os.Handler;
  31. import android.os.IBinder;
  32. import android.support.v4.app.Fragment;
  33. import android.support.v4.app.FragmentManager;
  34. import android.support.v4.app.FragmentTransaction;
  35. import android.widget.Toast;
  36. import com.actionbarsherlock.app.SherlockFragmentActivity;
  37. import com.owncloud.android.MainApp;
  38. import com.owncloud.android.R;
  39. import com.owncloud.android.authentication.AccountUtils;
  40. import com.owncloud.android.authentication.AuthenticatorActivity;
  41. import com.owncloud.android.datamodel.FileDataStorageManager;
  42. import com.owncloud.android.datamodel.OCFile;
  43. import com.owncloud.android.files.FileOperationsHelper;
  44. import com.owncloud.android.files.services.FileDownloader;
  45. import com.owncloud.android.files.services.FileUploader;
  46. import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
  47. import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
  48. import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;
  49. import com.owncloud.android.lib.common.operations.RemoteOperation;
  50. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  51. import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
  52. import com.owncloud.android.lib.common.utils.Log_OC;
  53. import com.owncloud.android.operations.CreateShareOperation;
  54. import com.owncloud.android.operations.SynchronizeFolderOperation;
  55. import com.owncloud.android.operations.UnshareLinkOperation;
  56. import com.owncloud.android.services.OperationsService;
  57. import com.owncloud.android.services.OperationsService.OperationsServiceBinder;
  58. import com.owncloud.android.ui.dialog.LoadingDialog;
  59. import com.owncloud.android.utils.ErrorMessageAdapter;
  60. /**
  61. * Activity with common behaviour for activities handling {@link OCFile}s in ownCloud {@link Account}s .
  62. *
  63. * @author David A. Velasco
  64. */
  65. public class FileActivity extends SherlockFragmentActivity
  66. implements OnRemoteOperationListener, ComponentsGetter {
  67. public static final String EXTRA_FILE = "com.owncloud.android.ui.activity.FILE";
  68. public static final String EXTRA_ACCOUNT = "com.owncloud.android.ui.activity.ACCOUNT";
  69. public static final String EXTRA_WAITING_TO_PREVIEW = "com.owncloud.android.ui.activity.WAITING_TO_PREVIEW";
  70. public static final String EXTRA_FROM_NOTIFICATION= "com.owncloud.android.ui.activity.FROM_NOTIFICATION";
  71. public static final String TAG = FileActivity.class.getSimpleName();
  72. private static final String DIALOG_WAIT_TAG = "DIALOG_WAIT";
  73. private static final String KEY_WAITING_FOR_OP_ID = "WAITING_FOR_OP_ID";;
  74. protected static final long DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS = 200;
  75. /** OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located. */
  76. private Account mAccount;
  77. /** Main {@link OCFile} handled by the activity.*/
  78. private OCFile mFile;
  79. /** Flag to signal that the activity will is finishing to enforce the creation of an ownCloud {@link Account} */
  80. private boolean mRedirectingToSetupAccount = false;
  81. /** Flag to signal when the value of mAccount was set */
  82. private boolean mAccountWasSet;
  83. /** Flag to signal when the value of mAccount was restored from a saved state */
  84. private boolean mAccountWasRestored;
  85. /** Flag to signal if the activity is launched by a notification */
  86. private boolean mFromNotification;
  87. /** Messages handler associated to the main thread and the life cycle of the activity */
  88. private Handler mHandler;
  89. /** Access point to the cached database for the current ownCloud {@link Account} */
  90. private FileDataStorageManager mStorageManager = null;
  91. private FileOperationsHelper mFileOperationsHelper;
  92. private ServiceConnection mOperationsServiceConnection = null;
  93. private OperationsServiceBinder mOperationsServiceBinder = null;
  94. protected FileDownloaderBinder mDownloaderBinder = null;
  95. protected FileUploaderBinder mUploaderBinder = null;
  96. private ServiceConnection mDownloadServiceConnection, mUploadServiceConnection = null;
  97. /**
  98. * Loads the ownCloud {@link Account} and main {@link OCFile} to be handled by the instance of
  99. * the {@link FileActivity}.
  100. *
  101. * Grants that a valid ownCloud {@link Account} is associated to the instance, or that the user
  102. * is requested to create a new one.
  103. */
  104. @Override
  105. protected void onCreate(Bundle savedInstanceState) {
  106. super.onCreate(savedInstanceState);
  107. mHandler = new Handler();
  108. mFileOperationsHelper = new FileOperationsHelper(this);
  109. Account account;
  110. if(savedInstanceState != null) {
  111. account = savedInstanceState.getParcelable(FileActivity.EXTRA_ACCOUNT);
  112. mFile = savedInstanceState.getParcelable(FileActivity.EXTRA_FILE);
  113. mFromNotification = savedInstanceState.getBoolean(FileActivity.EXTRA_FROM_NOTIFICATION);
  114. mFileOperationsHelper.setOpIdWaitingFor(
  115. savedInstanceState.getLong(KEY_WAITING_FOR_OP_ID, Long.MAX_VALUE)
  116. );
  117. } else {
  118. account = getIntent().getParcelableExtra(FileActivity.EXTRA_ACCOUNT);
  119. mFile = getIntent().getParcelableExtra(FileActivity.EXTRA_FILE);
  120. mFromNotification = getIntent().getBooleanExtra(FileActivity.EXTRA_FROM_NOTIFICATION, false);
  121. }
  122. setAccount(account, savedInstanceState != null);
  123. mOperationsServiceConnection = new OperationsServiceConnection();
  124. bindService(new Intent(this, OperationsService.class), mOperationsServiceConnection, Context.BIND_AUTO_CREATE);
  125. mDownloadServiceConnection = newTransferenceServiceConnection();
  126. if (mDownloadServiceConnection != null) {
  127. bindService(new Intent(this, FileDownloader.class), mDownloadServiceConnection, Context.BIND_AUTO_CREATE);
  128. }
  129. mUploadServiceConnection = newTransferenceServiceConnection();
  130. if (mUploadServiceConnection != null) {
  131. bindService(new Intent(this, FileUploader.class), mUploadServiceConnection, Context.BIND_AUTO_CREATE);
  132. }
  133. }
  134. /**
  135. * Since ownCloud {@link Account}s can be managed from the system setting menu,
  136. * the existence of the {@link Account} associated to the instance must be checked
  137. * every time it is restarted.
  138. */
  139. @Override
  140. protected void onRestart() {
  141. super.onRestart();
  142. boolean validAccount = (mAccount != null && AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), mAccount.name));
  143. if (!validAccount) {
  144. swapToDefaultAccount();
  145. }
  146. }
  147. @Override
  148. protected void onStart() {
  149. super.onStart();
  150. if (mAccountWasSet) {
  151. onAccountSet(mAccountWasRestored);
  152. }
  153. }
  154. @Override
  155. protected void onResume() {
  156. super.onResume();
  157. if (mOperationsServiceBinder != null) {
  158. doOnResumeAndBound();
  159. }
  160. }
  161. @Override
  162. protected void onPause() {
  163. if (mOperationsServiceBinder != null) {
  164. mOperationsServiceBinder.removeOperationListener(this);
  165. }
  166. super.onPause();
  167. }
  168. @Override
  169. protected void onDestroy() {
  170. if (mOperationsServiceConnection != null) {
  171. unbindService(mOperationsServiceConnection);
  172. mOperationsServiceBinder = null;
  173. }
  174. if (mDownloadServiceConnection != null) {
  175. unbindService(mDownloadServiceConnection);
  176. mDownloadServiceConnection = null;
  177. }
  178. if (mUploadServiceConnection != null) {
  179. unbindService(mUploadServiceConnection);
  180. mUploadServiceConnection = null;
  181. }
  182. super.onDestroy();
  183. }
  184. /**
  185. * Sets and validates the ownCloud {@link Account} associated to the Activity.
  186. *
  187. * If not valid, tries to swap it for other valid and existing ownCloud {@link Account}.
  188. *
  189. * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
  190. *
  191. * @param account New {@link Account} to set.
  192. * @param savedAccount When 'true', account was retrieved from a saved instance state.
  193. */
  194. private void setAccount(Account account, boolean savedAccount) {
  195. Account oldAccount = mAccount;
  196. boolean validAccount = (account != null && AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), account.name));
  197. if (validAccount) {
  198. mAccount = account;
  199. mAccountWasSet = true;
  200. mAccountWasRestored = (savedAccount || mAccount.equals(oldAccount));
  201. } else {
  202. swapToDefaultAccount();
  203. }
  204. }
  205. /**
  206. * Tries to swap the current ownCloud {@link Account} for other valid and existing.
  207. *
  208. * If no valid ownCloud {@link Account} exists, the the user is requested
  209. * to create a new ownCloud {@link Account}.
  210. *
  211. * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
  212. *
  213. * @return 'True' if the checked {@link Account} was valid.
  214. */
  215. private void swapToDefaultAccount() {
  216. // default to the most recently used account
  217. Account newAccount = AccountUtils.getCurrentOwnCloudAccount(getApplicationContext());
  218. if (newAccount == null) {
  219. /// no account available: force account creation
  220. createFirstAccount();
  221. mRedirectingToSetupAccount = true;
  222. mAccountWasSet = false;
  223. mAccountWasRestored = false;
  224. } else {
  225. mAccountWasSet = true;
  226. mAccountWasRestored = (newAccount.equals(mAccount));
  227. mAccount = newAccount;
  228. }
  229. }
  230. /**
  231. * Launches the account creation activity. To use when no ownCloud account is available
  232. */
  233. private void createFirstAccount() {
  234. AccountManager am = AccountManager.get(getApplicationContext());
  235. am.addAccount(MainApp.getAccountType(),
  236. null,
  237. null,
  238. null,
  239. this,
  240. new AccountCreationCallback(),
  241. null);
  242. }
  243. /**
  244. * {@inheritDoc}
  245. */
  246. @Override
  247. protected void onSaveInstanceState(Bundle outState) {
  248. super.onSaveInstanceState(outState);
  249. outState.putParcelable(FileActivity.EXTRA_FILE, mFile);
  250. outState.putParcelable(FileActivity.EXTRA_ACCOUNT, mAccount);
  251. outState.putBoolean(FileActivity.EXTRA_FROM_NOTIFICATION, mFromNotification);
  252. outState.putLong(KEY_WAITING_FOR_OP_ID, mFileOperationsHelper.getOpIdWaitingFor());
  253. }
  254. /**
  255. * Getter for the main {@link OCFile} handled by the activity.
  256. *
  257. * @return Main {@link OCFile} handled by the activity.
  258. */
  259. public OCFile getFile() {
  260. return mFile;
  261. }
  262. /**
  263. * Setter for the main {@link OCFile} handled by the activity.
  264. *
  265. * @param file Main {@link OCFile} to be handled by the activity.
  266. */
  267. public void setFile(OCFile file) {
  268. mFile = file;
  269. }
  270. /**
  271. * Getter for the ownCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
  272. *
  273. * @return OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
  274. */
  275. public Account getAccount() {
  276. return mAccount;
  277. }
  278. /**
  279. * @return Value of mFromNotification: True if the Activity is launched by a notification
  280. */
  281. public boolean fromNotification() {
  282. return mFromNotification;
  283. }
  284. /**
  285. * @return 'True' when the Activity is finishing to enforce the setup of a new account.
  286. */
  287. protected boolean isRedirectingToSetupAccount() {
  288. return mRedirectingToSetupAccount;
  289. }
  290. public OperationsServiceBinder getOperationsServiceBinder() {
  291. return mOperationsServiceBinder;
  292. }
  293. protected ServiceConnection newTransferenceServiceConnection() {
  294. return null;
  295. }
  296. /**
  297. * Helper class handling a callback from the {@link AccountManager} after the creation of
  298. * a new ownCloud {@link Account} finished, successfully or not.
  299. *
  300. * At this moment, only called after the creation of the first account.
  301. *
  302. * @author David A. Velasco
  303. */
  304. public class AccountCreationCallback implements AccountManagerCallback<Bundle> {
  305. @Override
  306. public void run(AccountManagerFuture<Bundle> future) {
  307. FileActivity.this.mRedirectingToSetupAccount = false;
  308. boolean accountWasSet = false;
  309. if (future != null) {
  310. try {
  311. Bundle result;
  312. result = future.getResult();
  313. String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
  314. String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
  315. if (AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), name)) {
  316. setAccount(new Account(name, type), false);
  317. accountWasSet = true;
  318. }
  319. } catch (OperationCanceledException e) {
  320. Log_OC.d(TAG, "Account creation canceled");
  321. } catch (Exception e) {
  322. Log_OC.e(TAG, "Account creation finished in exception: ", e);
  323. }
  324. } else {
  325. Log_OC.e(TAG, "Account creation callback with null bundle");
  326. }
  327. if (!accountWasSet) {
  328. moveTaskToBack(true);
  329. }
  330. }
  331. }
  332. /**
  333. * Called when the ownCloud {@link Account} associated to the Activity was just updated.
  334. *
  335. * Child classes must grant that state depending on the {@link Account} is updated.
  336. */
  337. protected void onAccountSet(boolean stateWasRecovered) {
  338. if (getAccount() != null) {
  339. mStorageManager = new FileDataStorageManager(getAccount(), getContentResolver());
  340. } else {
  341. Log_OC.wtf(TAG, "onAccountChanged was called with NULL account associated!");
  342. }
  343. }
  344. public FileDataStorageManager getStorageManager() {
  345. return mStorageManager;
  346. }
  347. public OnRemoteOperationListener getRemoteOperationListener() {
  348. return this;
  349. }
  350. public Handler getHandler() {
  351. return mHandler;
  352. }
  353. public FileOperationsHelper getFileOperationsHelper() {
  354. return mFileOperationsHelper;
  355. }
  356. /**
  357. *
  358. * @param operation Removal operation performed.
  359. * @param result Result of the removal.
  360. */
  361. @Override
  362. public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
  363. Log_OC.d(TAG, "Received result of operation in FileActivity - common behaviour for all the FileActivities ");
  364. mFileOperationsHelper.setOpIdWaitingFor(Long.MAX_VALUE);
  365. if (!result.isSuccess() && (
  366. result.getCode() == ResultCode.UNAUTHORIZED ||
  367. result.isIdPRedirection() ||
  368. (result.isException() && result.getException() instanceof AuthenticatorException)
  369. )) {
  370. requestCredentialsUpdate();
  371. if (result.getCode() == ResultCode.UNAUTHORIZED) {
  372. dismissLoadingDialog();
  373. Toast t = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  374. Toast.LENGTH_LONG);
  375. t.show();
  376. }
  377. } else if (operation instanceof CreateShareOperation) {
  378. onCreateShareOperationFinish((CreateShareOperation) operation, result);
  379. } else if (operation instanceof UnshareLinkOperation) {
  380. onUnshareLinkOperationFinish((UnshareLinkOperation)operation, result);
  381. } else if (operation instanceof SynchronizeFolderOperation) {
  382. onSynchronizeFolderOperationFinish((SynchronizeFolderOperation)operation, result);
  383. }
  384. }
  385. protected void requestCredentialsUpdate() {
  386. Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
  387. updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, getAccount());
  388. updateAccountCredentials.putExtra(
  389. AuthenticatorActivity.EXTRA_ACTION,
  390. AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
  391. updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
  392. startActivity(updateAccountCredentials);
  393. }
  394. private void onCreateShareOperationFinish(CreateShareOperation operation, RemoteOperationResult result) {
  395. dismissLoadingDialog();
  396. if (result.isSuccess()) {
  397. updateFileFromDB();
  398. Intent sendIntent = operation.getSendIntent();
  399. startActivity(sendIntent);
  400. } else {
  401. Toast t = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  402. Toast.LENGTH_LONG);
  403. t.show();
  404. }
  405. }
  406. private void onUnshareLinkOperationFinish(UnshareLinkOperation operation, RemoteOperationResult result) {
  407. dismissLoadingDialog();
  408. if (result.isSuccess()){
  409. updateFileFromDB();
  410. } else {
  411. Toast t = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  412. Toast.LENGTH_LONG);
  413. t.show();
  414. }
  415. }
  416. private void onSynchronizeFolderOperationFinish(SynchronizeFolderOperation operation, RemoteOperationResult result) {
  417. if (!result.isSuccess()){
  418. Toast t = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  419. Toast.LENGTH_LONG);
  420. t.show();
  421. }
  422. }
  423. protected void updateFileFromDB(){
  424. OCFile file = getFile();
  425. if (file != null) {
  426. file = getStorageManager().getFileByPath(file.getRemotePath());
  427. setFile(file);
  428. }
  429. }
  430. /**
  431. * Show loading dialog
  432. */
  433. public void showLoadingDialog() {
  434. // Construct dialog
  435. LoadingDialog loading = new LoadingDialog(getResources().getString(R.string.wait_a_moment));
  436. FragmentManager fm = getSupportFragmentManager();
  437. FragmentTransaction ft = fm.beginTransaction();
  438. loading.show(ft, DIALOG_WAIT_TAG);
  439. }
  440. /**
  441. * Dismiss loading dialog
  442. */
  443. public void dismissLoadingDialog(){
  444. Fragment frag = getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG);
  445. if (frag != null) {
  446. LoadingDialog loading = (LoadingDialog) frag;
  447. loading.dismiss();
  448. }
  449. }
  450. private void doOnResumeAndBound() {
  451. mOperationsServiceBinder.addOperationListener(FileActivity.this, mHandler);
  452. long waitingForOpId = mFileOperationsHelper.getOpIdWaitingFor();
  453. if (waitingForOpId <= Integer.MAX_VALUE) {
  454. boolean wait = mOperationsServiceBinder.dispatchResultIfFinished((int)waitingForOpId, this);
  455. if (!wait ) {
  456. dismissLoadingDialog();
  457. }
  458. }
  459. }
  460. /**
  461. * Implements callback methods for service binding. Passed as a parameter to {
  462. */
  463. private class OperationsServiceConnection implements ServiceConnection {
  464. @Override
  465. public void onServiceConnected(ComponentName component, IBinder service) {
  466. if (component.equals(new ComponentName(FileActivity.this, OperationsService.class))) {
  467. Log_OC.d(TAG, "Operations service connected");
  468. mOperationsServiceBinder = (OperationsServiceBinder) service;
  469. /*if (!mOperationsServiceBinder.isPerformingBlockingOperation()) {
  470. dismissLoadingDialog();
  471. }*/
  472. doOnResumeAndBound();
  473. } else {
  474. return;
  475. }
  476. }
  477. @Override
  478. public void onServiceDisconnected(ComponentName component) {
  479. if (component.equals(new ComponentName(FileActivity.this, OperationsService.class))) {
  480. Log_OC.d(TAG, "Operations service disconnected");
  481. mOperationsServiceBinder = null;
  482. // TODO whatever could be waiting for the service is unbound
  483. }
  484. }
  485. }
  486. @Override
  487. public FileDownloaderBinder getFileDownloaderBinder() {
  488. return mDownloaderBinder;
  489. }
  490. @Override
  491. public FileUploaderBinder getFileUploaderBinder() {
  492. return mUploaderBinder;
  493. };
  494. }