FileActivity.java 21 KB

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