FileActivity.java 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  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 java.io.IOException;
  20. import android.accounts.Account;
  21. import android.accounts.AccountManager;
  22. import android.accounts.AccountManagerCallback;
  23. import android.accounts.AccountManagerFuture;
  24. import android.accounts.AuthenticatorException;
  25. import android.accounts.OperationCanceledException;
  26. import android.content.ComponentName;
  27. import android.content.Context;
  28. import android.content.Intent;
  29. import android.content.ServiceConnection;
  30. import android.os.Bundle;
  31. import android.os.Handler;
  32. import android.os.IBinder;
  33. import android.support.v4.app.Fragment;
  34. import android.support.v4.app.FragmentManager;
  35. import android.support.v4.app.FragmentTransaction;
  36. import android.widget.Toast;
  37. import com.actionbarsherlock.app.SherlockFragmentActivity;
  38. import com.owncloud.android.MainApp;
  39. import com.owncloud.android.R;
  40. import com.owncloud.android.authentication.AccountUtils;
  41. import com.owncloud.android.authentication.AuthenticatorActivity;
  42. import com.owncloud.android.datamodel.FileDataStorageManager;
  43. import com.owncloud.android.datamodel.OCFile;
  44. import com.owncloud.android.files.FileOperationsHelper;
  45. import com.owncloud.android.files.services.FileDownloader;
  46. import com.owncloud.android.files.services.FileUploader;
  47. import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
  48. import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
  49. import com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException;
  50. import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;
  51. import com.owncloud.android.lib.common.operations.RemoteOperation;
  52. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  53. import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
  54. import com.owncloud.android.operations.CreateShareOperation;
  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. import com.owncloud.android.utils.Log_OC;
  61. /**
  62. * Activity with common behaviour for activities handling {@link OCFile}s in ownCloud {@link Account}s .
  63. *
  64. * @author David A. Velasco
  65. */
  66. public class FileActivity extends SherlockFragmentActivity
  67. implements OnRemoteOperationListener, ComponentsGetter {
  68. public static final String EXTRA_FILE = "com.owncloud.android.ui.activity.FILE";
  69. public static final String EXTRA_ACCOUNT = "com.owncloud.android.ui.activity.ACCOUNT";
  70. public static final String EXTRA_WAITING_TO_PREVIEW = "com.owncloud.android.ui.activity.WAITING_TO_PREVIEW";
  71. public static final String EXTRA_FROM_NOTIFICATION= "com.owncloud.android.ui.activity.FROM_NOTIFICATION";
  72. public static final String TAG = FileActivity.class.getSimpleName();
  73. private static final String DIALOG_WAIT_TAG = "DIALOG_WAIT";
  74. private static final String KEY_WAITING_FOR_OP_ID = "WAITING_FOR_OP_ID";;
  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. // Save cookies here
  164. Log_OC.wtf(TAG, "Saving Cookies" );
  165. if (mAccount != null) {
  166. try {
  167. ((MainApp)getApplicationContext()).getOwnCloudClientManager().
  168. saveClient(mAccount, this);
  169. // TODO get rid of the exceptions
  170. } catch (AccountNotFoundException e) {
  171. e.printStackTrace();
  172. } catch (AuthenticatorException e) {
  173. e.printStackTrace();
  174. } catch (OperationCanceledException e) {
  175. e.printStackTrace();
  176. } catch (IOException e) {
  177. e.printStackTrace();
  178. }
  179. }
  180. if (mOperationsServiceBinder != null) {
  181. mOperationsServiceBinder.removeOperationListener(this);
  182. }
  183. super.onPause();
  184. }
  185. @Override
  186. protected void onDestroy() {
  187. if (mOperationsServiceConnection != null) {
  188. unbindService(mOperationsServiceConnection);
  189. mOperationsServiceBinder = null;
  190. }
  191. if (mDownloadServiceConnection != null) {
  192. unbindService(mDownloadServiceConnection);
  193. mDownloadServiceConnection = null;
  194. }
  195. if (mUploadServiceConnection != null) {
  196. unbindService(mUploadServiceConnection);
  197. mUploadServiceConnection = null;
  198. }
  199. super.onDestroy();
  200. }
  201. /**
  202. * Sets and validates the ownCloud {@link Account} associated to the Activity.
  203. *
  204. * If not valid, tries to swap it for other valid and existing ownCloud {@link Account}.
  205. *
  206. * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
  207. *
  208. * @param account New {@link Account} to set.
  209. * @param savedAccount When 'true', account was retrieved from a saved instance state.
  210. */
  211. private void setAccount(Account account, boolean savedAccount) {
  212. Account oldAccount = mAccount;
  213. boolean validAccount = (account != null && AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), account.name));
  214. if (validAccount) {
  215. mAccount = account;
  216. mAccountWasSet = true;
  217. mAccountWasRestored = (savedAccount || mAccount.equals(oldAccount));
  218. } else {
  219. swapToDefaultAccount();
  220. }
  221. }
  222. /**
  223. * Tries to swap the current ownCloud {@link Account} for other valid and existing.
  224. *
  225. * If no valid ownCloud {@link Account} exists, the the user is requested
  226. * to create a new ownCloud {@link Account}.
  227. *
  228. * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
  229. *
  230. * @return 'True' if the checked {@link Account} was valid.
  231. */
  232. private void swapToDefaultAccount() {
  233. // default to the most recently used account
  234. Account newAccount = AccountUtils.getCurrentOwnCloudAccount(getApplicationContext());
  235. if (newAccount == null) {
  236. /// no account available: force account creation
  237. createFirstAccount();
  238. mRedirectingToSetupAccount = true;
  239. mAccountWasSet = false;
  240. mAccountWasRestored = false;
  241. } else {
  242. mAccountWasSet = true;
  243. mAccountWasRestored = (newAccount.equals(mAccount));
  244. mAccount = newAccount;
  245. }
  246. }
  247. /**
  248. * Launches the account creation activity. To use when no ownCloud account is available
  249. */
  250. private void createFirstAccount() {
  251. AccountManager am = AccountManager.get(getApplicationContext());
  252. am.addAccount(MainApp.getAccountType(),
  253. null,
  254. null,
  255. null,
  256. this,
  257. new AccountCreationCallback(),
  258. null);
  259. }
  260. /**
  261. * {@inheritDoc}
  262. */
  263. @Override
  264. protected void onSaveInstanceState(Bundle outState) {
  265. super.onSaveInstanceState(outState);
  266. outState.putParcelable(FileActivity.EXTRA_FILE, mFile);
  267. outState.putParcelable(FileActivity.EXTRA_ACCOUNT, mAccount);
  268. outState.putBoolean(FileActivity.EXTRA_FROM_NOTIFICATION, mFromNotification);
  269. outState.putLong(KEY_WAITING_FOR_OP_ID, mFileOperationsHelper.getOpIdWaitingFor());
  270. }
  271. /**
  272. * Getter for the main {@link OCFile} handled by the activity.
  273. *
  274. * @return Main {@link OCFile} handled by the activity.
  275. */
  276. public OCFile getFile() {
  277. return mFile;
  278. }
  279. /**
  280. * Setter for the main {@link OCFile} handled by the activity.
  281. *
  282. * @param file Main {@link OCFile} to be handled by the activity.
  283. */
  284. public void setFile(OCFile file) {
  285. mFile = file;
  286. }
  287. /**
  288. * Getter for the ownCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
  289. *
  290. * @return OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
  291. */
  292. public Account getAccount() {
  293. return mAccount;
  294. }
  295. /**
  296. * @return Value of mFromNotification: True if the Activity is launched by a notification
  297. */
  298. public boolean fromNotification() {
  299. return mFromNotification;
  300. }
  301. /**
  302. * @return 'True' when the Activity is finishing to enforce the setup of a new account.
  303. */
  304. protected boolean isRedirectingToSetupAccount() {
  305. return mRedirectingToSetupAccount;
  306. }
  307. public OperationsServiceBinder getOperationsServiceBinder() {
  308. return mOperationsServiceBinder;
  309. }
  310. protected ServiceConnection newTransferenceServiceConnection() {
  311. return null;
  312. }
  313. /**
  314. * Helper class handling a callback from the {@link AccountManager} after the creation of
  315. * a new ownCloud {@link Account} finished, successfully or not.
  316. *
  317. * At this moment, only called after the creation of the first account.
  318. *
  319. * @author David A. Velasco
  320. */
  321. public class AccountCreationCallback implements AccountManagerCallback<Bundle> {
  322. @Override
  323. public void run(AccountManagerFuture<Bundle> future) {
  324. FileActivity.this.mRedirectingToSetupAccount = false;
  325. boolean accountWasSet = false;
  326. if (future != null) {
  327. try {
  328. Bundle result;
  329. result = future.getResult();
  330. String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
  331. String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
  332. if (AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), name)) {
  333. setAccount(new Account(name, type), false);
  334. accountWasSet = true;
  335. }
  336. } catch (OperationCanceledException e) {
  337. Log_OC.d(TAG, "Account creation canceled");
  338. } catch (Exception e) {
  339. Log_OC.e(TAG, "Account creation finished in exception: ", e);
  340. }
  341. } else {
  342. Log_OC.e(TAG, "Account creation callback with null bundle");
  343. }
  344. if (!accountWasSet) {
  345. moveTaskToBack(true);
  346. }
  347. }
  348. }
  349. /**
  350. * Called when the ownCloud {@link Account} associated to the Activity was just updated.
  351. *
  352. * Child classes must grant that state depending on the {@link Account} is updated.
  353. */
  354. protected void onAccountSet(boolean stateWasRecovered) {
  355. if (getAccount() != null) {
  356. mStorageManager = new FileDataStorageManager(getAccount(), getContentResolver());
  357. } else {
  358. Log_OC.wtf(TAG, "onAccountChanged was called with NULL account associated!");
  359. }
  360. }
  361. public FileDataStorageManager getStorageManager() {
  362. return mStorageManager;
  363. }
  364. public OnRemoteOperationListener getRemoteOperationListener() {
  365. return this;
  366. }
  367. public Handler getHandler() {
  368. return mHandler;
  369. }
  370. public FileOperationsHelper getFileOperationsHelper() {
  371. return mFileOperationsHelper;
  372. }
  373. /**
  374. *
  375. * @param operation Removal operation performed.
  376. * @param result Result of the removal.
  377. */
  378. @Override
  379. public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
  380. Log_OC.d(TAG, "Received result of operation in FileActivity - common behaviour for all the FileActivities ");
  381. mFileOperationsHelper.setOpIdWaitingFor(Long.MAX_VALUE);
  382. if (!result.isSuccess() && (
  383. result.getCode() == ResultCode.UNAUTHORIZED ||
  384. result.isIdPRedirection() ||
  385. (result.isException() && result.getException() instanceof AuthenticatorException)
  386. )) {
  387. requestCredentialsUpdate();
  388. if (result.getCode() == ResultCode.UNAUTHORIZED) {
  389. dismissLoadingDialog();
  390. Toast t = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  391. Toast.LENGTH_LONG);
  392. t.show();
  393. }
  394. } else if (operation instanceof CreateShareOperation) {
  395. onCreateShareOperationFinish((CreateShareOperation) operation, result);
  396. } else if (operation instanceof UnshareLinkOperation) {
  397. onUnshareLinkOperationFinish((UnshareLinkOperation)operation, result);
  398. }
  399. }
  400. protected void requestCredentialsUpdate() {
  401. Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
  402. updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, getAccount());
  403. updateAccountCredentials.putExtra(
  404. AuthenticatorActivity.EXTRA_ACTION,
  405. AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
  406. updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
  407. startActivity(updateAccountCredentials);
  408. }
  409. private void onCreateShareOperationFinish(CreateShareOperation operation, RemoteOperationResult result) {
  410. dismissLoadingDialog();
  411. if (result.isSuccess()) {
  412. updateFileFromDB();
  413. Intent sendIntent = operation.getSendIntent();
  414. startActivity(sendIntent);
  415. } else {
  416. Toast t = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  417. Toast.LENGTH_LONG);
  418. t.show();
  419. }
  420. }
  421. private void onUnshareLinkOperationFinish(UnshareLinkOperation operation, RemoteOperationResult result) {
  422. dismissLoadingDialog();
  423. if (result.isSuccess()){
  424. updateFileFromDB();
  425. } else {
  426. Toast t = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  427. Toast.LENGTH_LONG);
  428. t.show();
  429. }
  430. }
  431. private void updateFileFromDB(){
  432. OCFile file = getStorageManager().getFileByPath(getFile().getRemotePath());
  433. if (file != null) {
  434. setFile(file);
  435. }
  436. }
  437. /**
  438. * Show loading dialog
  439. */
  440. public void showLoadingDialog() {
  441. // Construct dialog
  442. LoadingDialog loading = new LoadingDialog(getResources().getString(R.string.wait_a_moment));
  443. FragmentManager fm = getSupportFragmentManager();
  444. FragmentTransaction ft = fm.beginTransaction();
  445. loading.show(ft, DIALOG_WAIT_TAG);
  446. }
  447. /**
  448. * Dismiss loading dialog
  449. */
  450. public void dismissLoadingDialog(){
  451. Fragment frag = getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG);
  452. if (frag != null) {
  453. LoadingDialog loading = (LoadingDialog) frag;
  454. loading.dismiss();
  455. }
  456. }
  457. private void doOnResumeAndBound() {
  458. mOperationsServiceBinder.addOperationListener(FileActivity.this, mHandler);
  459. long waitingForOpId = mFileOperationsHelper.getOpIdWaitingFor();
  460. if (waitingForOpId <= Integer.MAX_VALUE) {
  461. boolean wait = mOperationsServiceBinder.dispatchResultIfFinished((int)waitingForOpId, this);
  462. if (!wait ) {
  463. dismissLoadingDialog();
  464. }
  465. }
  466. }
  467. /**
  468. * Implements callback methods for service binding. Passed as a parameter to {
  469. */
  470. private class OperationsServiceConnection implements ServiceConnection {
  471. @Override
  472. public void onServiceConnected(ComponentName component, IBinder service) {
  473. if (component.equals(new ComponentName(FileActivity.this, OperationsService.class))) {
  474. Log_OC.d(TAG, "Operations service connected");
  475. mOperationsServiceBinder = (OperationsServiceBinder) service;
  476. /*if (!mOperationsServiceBinder.isPerformingBlockingOperation()) {
  477. dismissLoadingDialog();
  478. }*/
  479. doOnResumeAndBound();
  480. } else {
  481. return;
  482. }
  483. }
  484. @Override
  485. public void onServiceDisconnected(ComponentName component) {
  486. if (component.equals(new ComponentName(FileActivity.this, OperationsService.class))) {
  487. Log_OC.d(TAG, "Operations service disconnected");
  488. mOperationsServiceBinder = null;
  489. // TODO whatever could be waiting for the service is unbound
  490. }
  491. }
  492. }
  493. @Override
  494. public FileDownloaderBinder getFileDownloaderBinder() {
  495. return mDownloaderBinder;
  496. }
  497. @Override
  498. public FileUploaderBinder getFileUploaderBinder() {
  499. return mUploaderBinder;
  500. };
  501. }