FileActivity.java 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. /**
  2. * ownCloud Android client application
  3. *
  4. * @author David A. Velasco
  5. * Copyright (C) 2011 Bartek Przybylski
  6. * Copyright (C) 2016 ownCloud Inc.
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License version 2,
  10. * as published by the Free Software Foundation.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. *
  20. */
  21. package com.owncloud.android.ui.activity;
  22. import android.accounts.Account;
  23. import android.accounts.AccountManager;
  24. import android.accounts.AuthenticatorException;
  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.owncloud.android.MainApp;
  37. import com.owncloud.android.R;
  38. import com.owncloud.android.authentication.AuthenticatorActivity;
  39. import com.owncloud.android.datamodel.OCFile;
  40. import com.owncloud.android.files.services.FileDownloader;
  41. import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
  42. import com.owncloud.android.files.services.FileUploader;
  43. import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
  44. import com.owncloud.android.lib.common.OwnCloudAccount;
  45. import com.owncloud.android.lib.common.OwnCloudClient;
  46. import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
  47. import com.owncloud.android.lib.common.OwnCloudCredentials;
  48. import com.owncloud.android.lib.common.network.CertificateCombinedException;
  49. import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;
  50. import com.owncloud.android.lib.common.operations.RemoteOperation;
  51. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  52. import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
  53. import com.owncloud.android.lib.common.utils.Log_OC;
  54. import com.owncloud.android.operations.CreateShareWithShareeOperation;
  55. import com.owncloud.android.operations.GetSharesForFileOperation;
  56. import com.owncloud.android.operations.SynchronizeFileOperation;
  57. import com.owncloud.android.operations.SynchronizeFolderOperation;
  58. import com.owncloud.android.operations.UnshareOperation;
  59. import com.owncloud.android.operations.UpdateSharePermissionsOperation;
  60. import com.owncloud.android.operations.UpdateShareViaLinkOperation;
  61. import com.owncloud.android.services.OperationsService;
  62. import com.owncloud.android.services.OperationsService.OperationsServiceBinder;
  63. import com.owncloud.android.ui.dialog.ConfirmationDialogFragment;
  64. import com.owncloud.android.ui.dialog.LoadingDialog;
  65. import com.owncloud.android.ui.dialog.SslUntrustedCertDialog;
  66. import com.owncloud.android.ui.helpers.FileOperationsHelper;
  67. import com.owncloud.android.utils.DisplayUtils;
  68. import com.owncloud.android.utils.ErrorMessageAdapter;
  69. /**
  70. * Activity with common behaviour for activities handling {@link OCFile}s in ownCloud {@link Account}s .
  71. */
  72. public abstract class FileActivity extends DrawerActivity
  73. implements OnRemoteOperationListener, ComponentsGetter, SslUntrustedCertDialog.OnSslUntrustedCertListener {
  74. public static final String EXTRA_FILE = "com.owncloud.android.ui.activity.FILE";
  75. public static final String EXTRA_ACCOUNT = "com.owncloud.android.ui.activity.ACCOUNT";
  76. public static final String EXTRA_FROM_NOTIFICATION =
  77. "com.owncloud.android.ui.activity.FROM_NOTIFICATION";
  78. public static final String TAG = FileActivity.class.getSimpleName();
  79. private static final String DIALOG_WAIT_TAG = "DIALOG_WAIT";
  80. private static final String KEY_WAITING_FOR_OP_ID = "WAITING_FOR_OP_ID";
  81. private static final String KEY_ACTION_BAR_TITLE = "ACTION_BAR_TITLE";
  82. public static final int REQUEST_CODE__UPDATE_CREDENTIALS = 0;
  83. public static final int REQUEST_CODE__LAST_SHARED = REQUEST_CODE__UPDATE_CREDENTIALS;
  84. protected static final long DELAY_TO_REQUEST_OPERATIONS_LATER = 200;
  85. /* Dialog tags */
  86. private static final String DIALOG_UNTRUSTED_CERT = "DIALOG_UNTRUSTED_CERT";
  87. private static final String DIALOG_CERT_NOT_SAVED = "DIALOG_CERT_NOT_SAVED";
  88. /** Main {@link OCFile} handled by the activity.*/
  89. private OCFile mFile;
  90. /** Flag to signal if the activity is launched by a notification */
  91. private boolean mFromNotification;
  92. /** Messages handler associated to the main thread and the life cycle of the activity */
  93. private Handler mHandler;
  94. private FileOperationsHelper mFileOperationsHelper;
  95. private ServiceConnection mOperationsServiceConnection = null;
  96. private OperationsServiceBinder mOperationsServiceBinder = null;
  97. private boolean mResumed = false;
  98. protected FileDownloaderBinder mDownloaderBinder = null;
  99. protected FileUploaderBinder mUploaderBinder = null;
  100. private ServiceConnection mDownloadServiceConnection, mUploadServiceConnection = null;
  101. @Override
  102. public void showFiles(boolean onDeviceOnly) {
  103. // must be specialized in subclasses
  104. MainApp.showOnlyFilesOnDevice(onDeviceOnly);
  105. }
  106. /**
  107. * Loads the ownCloud {@link Account} and main {@link OCFile} to be handled by the instance of
  108. * the {@link FileActivity}.
  109. *
  110. * Grants that a valid ownCloud {@link Account} is associated to the instance, or that the user
  111. * is requested to create a new one.
  112. */
  113. @Override
  114. protected void onCreate(Bundle savedInstanceState) {
  115. super.onCreate(savedInstanceState);
  116. mHandler = new Handler();
  117. mFileOperationsHelper = new FileOperationsHelper(this);
  118. Account account = null;
  119. if(savedInstanceState != null) {
  120. mFile = savedInstanceState.getParcelable(FileActivity.EXTRA_FILE);
  121. mFromNotification = savedInstanceState.getBoolean(FileActivity.EXTRA_FROM_NOTIFICATION);
  122. mFileOperationsHelper.setOpIdWaitingFor(
  123. savedInstanceState.getLong(KEY_WAITING_FOR_OP_ID, Long.MAX_VALUE)
  124. );
  125. if (getSupportActionBar() != null) {
  126. getSupportActionBar().setTitle(savedInstanceState.getString(KEY_ACTION_BAR_TITLE));
  127. }
  128. } else {
  129. account = getIntent().getParcelableExtra(FileActivity.EXTRA_ACCOUNT);
  130. mFile = getIntent().getParcelableExtra(FileActivity.EXTRA_FILE);
  131. mFromNotification = getIntent().getBooleanExtra(FileActivity.EXTRA_FROM_NOTIFICATION,
  132. false);
  133. }
  134. setAccount(account, savedInstanceState != null);
  135. mOperationsServiceConnection = new OperationsServiceConnection();
  136. bindService(new Intent(this, OperationsService.class), mOperationsServiceConnection,
  137. Context.BIND_AUTO_CREATE);
  138. mDownloadServiceConnection = newTransferenceServiceConnection();
  139. if (mDownloadServiceConnection != null) {
  140. bindService(new Intent(this, FileDownloader.class), mDownloadServiceConnection,
  141. Context.BIND_AUTO_CREATE);
  142. }
  143. mUploadServiceConnection = newTransferenceServiceConnection();
  144. if (mUploadServiceConnection != null) {
  145. bindService(new Intent(this, FileUploader.class), mUploadServiceConnection,
  146. Context.BIND_AUTO_CREATE);
  147. }
  148. }
  149. @Override
  150. protected void onStart() {
  151. super.onStart();
  152. fetchExternalLinks(false);
  153. }
  154. @Override
  155. protected void onResume() {
  156. super.onResume();
  157. mResumed = true;
  158. if (mOperationsServiceBinder != null) {
  159. doOnResumeAndBound();
  160. }
  161. }
  162. @Override
  163. protected void onPause() {
  164. if (mOperationsServiceBinder != null) {
  165. mOperationsServiceBinder.removeOperationListener(this);
  166. }
  167. mResumed = false;
  168. super.onPause();
  169. }
  170. @Override
  171. protected void onDestroy() {
  172. if (mOperationsServiceConnection != null) {
  173. unbindService(mOperationsServiceConnection);
  174. mOperationsServiceBinder = null;
  175. }
  176. if (mDownloadServiceConnection != null) {
  177. unbindService(mDownloadServiceConnection);
  178. mDownloadServiceConnection = null;
  179. }
  180. if (mUploadServiceConnection != null) {
  181. unbindService(mUploadServiceConnection);
  182. mUploadServiceConnection = null;
  183. }
  184. super.onDestroy();
  185. }
  186. /**
  187. * {@inheritDoc}
  188. */
  189. @Override
  190. protected void onSaveInstanceState(Bundle outState) {
  191. super.onSaveInstanceState(outState);
  192. outState.putParcelable(FileActivity.EXTRA_FILE, mFile);
  193. outState.putBoolean(FileActivity.EXTRA_FROM_NOTIFICATION, mFromNotification);
  194. outState.putLong(KEY_WAITING_FOR_OP_ID, mFileOperationsHelper.getOpIdWaitingFor());
  195. if(getSupportActionBar() != null && getSupportActionBar().getTitle() != null) {
  196. // Null check in case the actionbar is used in ActionBar.NAVIGATION_MODE_LIST
  197. // since it doesn't have a title then
  198. outState.putString(KEY_ACTION_BAR_TITLE, getSupportActionBar().getTitle().toString());
  199. }
  200. }
  201. /**
  202. * Getter for the main {@link OCFile} handled by the activity.
  203. *
  204. * @return Main {@link OCFile} handled by the activity.
  205. */
  206. public OCFile getFile() {
  207. return mFile;
  208. }
  209. /**
  210. * Setter for the main {@link OCFile} handled by the activity.
  211. *
  212. * @param file Main {@link OCFile} to be handled by the activity.
  213. */
  214. public void setFile(OCFile file) {
  215. mFile = file;
  216. }
  217. /**
  218. * @return Value of mFromNotification: True if the Activity is launched by a notification
  219. */
  220. public boolean fromNotification() {
  221. return mFromNotification;
  222. }
  223. public OperationsServiceBinder getOperationsServiceBinder() {
  224. return mOperationsServiceBinder;
  225. }
  226. protected ServiceConnection newTransferenceServiceConnection() {
  227. return null;
  228. }
  229. public OnRemoteOperationListener getRemoteOperationListener() {
  230. return this;
  231. }
  232. public Handler getHandler() {
  233. return mHandler;
  234. }
  235. public FileOperationsHelper getFileOperationsHelper() {
  236. return mFileOperationsHelper;
  237. }
  238. /**
  239. *
  240. * @param operation Operation performed.
  241. * @param result Result of the removal.
  242. */
  243. @Override
  244. public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
  245. Log_OC.d(TAG, "Received result of operation in FileActivity - common behaviour for all the "
  246. + "FileActivities ");
  247. mFileOperationsHelper.setOpIdWaitingFor(Long.MAX_VALUE);
  248. dismissLoadingDialog();
  249. if (!result.isSuccess() && (
  250. result.getCode() == ResultCode.UNAUTHORIZED ||
  251. (result.isException() && result.getException() instanceof AuthenticatorException)
  252. )) {
  253. requestCredentialsUpdate(this);
  254. if (result.getCode() == ResultCode.UNAUTHORIZED) {
  255. DisplayUtils.showSnackMessage(
  256. this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources())
  257. );
  258. }
  259. } else if (!result.isSuccess() && ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED.equals(result.getCode())) {
  260. showUntrustedCertDialog(result);
  261. } else if (operation == null ||
  262. operation instanceof CreateShareWithShareeOperation ||
  263. operation instanceof UnshareOperation ||
  264. operation instanceof SynchronizeFolderOperation ||
  265. operation instanceof UpdateShareViaLinkOperation ||
  266. operation instanceof UpdateSharePermissionsOperation
  267. ) {
  268. if (result.isSuccess()) {
  269. updateFileFromDB();
  270. } else if (result.getCode() != ResultCode.CANCELLED) {
  271. DisplayUtils.showSnackMessage(
  272. this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources())
  273. );
  274. }
  275. } else if (operation instanceof SynchronizeFileOperation) {
  276. onSynchronizeFileOperationFinish((SynchronizeFileOperation) operation, result);
  277. } else if (operation instanceof GetSharesForFileOperation) {
  278. if (result.isSuccess() || result.getCode() == ResultCode.SHARE_NOT_FOUND) {
  279. updateFileFromDB();
  280. } else {
  281. DisplayUtils.showSnackMessage(
  282. this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources())
  283. );
  284. }
  285. }
  286. }
  287. /**
  288. * Invalidates the credentials stored for the current OC account and requests new credentials to the user,
  289. * navigating to {@link AuthenticatorActivity}
  290. *
  291. * Equivalent to call requestCredentialsUpdate(context, null);
  292. *
  293. * @param context Android Context needed to access the {@link AccountManager}. Received as a parameter
  294. * to make the method accessible to {@link android.content.BroadcastReceiver}s.
  295. */
  296. protected void requestCredentialsUpdate(Context context) {
  297. requestCredentialsUpdate(context, null);
  298. }
  299. /**
  300. * Invalidates the credentials stored for the given OC account and requests new credentials to the user,
  301. * navigating to {@link AuthenticatorActivity}
  302. *
  303. * @param context Android Context needed to access the {@link AccountManager}. Received as a parameter
  304. * to make the method accessible to {@link android.content.BroadcastReceiver}s.
  305. * @param account Stored OC account to request credentials update for. If null, current account will
  306. * be used.
  307. */
  308. protected void requestCredentialsUpdate(Context context, Account account) {
  309. try {
  310. /// step 1 - invalidate credentials of current account
  311. if (account == null) {
  312. account = getAccount();
  313. }
  314. OwnCloudClient client;
  315. OwnCloudAccount ocAccount = new OwnCloudAccount(account, context);
  316. client = (OwnCloudClientManagerFactory.getDefaultSingleton().removeClientFor(ocAccount));
  317. if (client != null) {
  318. OwnCloudCredentials cred = client.getCredentials();
  319. if (cred != null) {
  320. AccountManager am = AccountManager.get(context);
  321. if (cred.authTokenExpires()) {
  322. am.invalidateAuthToken(
  323. account.type,
  324. cred.getAuthToken()
  325. );
  326. } else {
  327. am.clearPassword(account);
  328. }
  329. }
  330. }
  331. /// step 2 - request credentials to user
  332. Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
  333. updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, account);
  334. updateAccountCredentials.putExtra(
  335. AuthenticatorActivity.EXTRA_ACTION,
  336. AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
  337. updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
  338. startActivityForResult(updateAccountCredentials, REQUEST_CODE__UPDATE_CREDENTIALS);
  339. } catch (com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException e) {
  340. DisplayUtils.showSnackMessage(this, R.string.auth_account_does_not_exist);
  341. }
  342. }
  343. /**
  344. * Show untrusted cert dialog
  345. */
  346. public void showUntrustedCertDialog(RemoteOperationResult result) {
  347. // Show a dialog with the certificate info
  348. FragmentManager fm = getSupportFragmentManager();
  349. SslUntrustedCertDialog dialog = (SslUntrustedCertDialog) fm.findFragmentByTag(DIALOG_UNTRUSTED_CERT);
  350. if(dialog == null) {
  351. dialog = SslUntrustedCertDialog.newInstanceForFullSslError(
  352. (CertificateCombinedException) result.getException());
  353. FragmentTransaction ft = fm.beginTransaction();
  354. dialog.show(ft, DIALOG_UNTRUSTED_CERT);
  355. }
  356. }
  357. private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation,
  358. RemoteOperationResult result) {
  359. OCFile syncedFile = operation.getLocalFile();
  360. if (!result.isSuccess()) {
  361. if (result.getCode() == ResultCode.SYNC_CONFLICT) {
  362. Intent i = new Intent(this, ConflictsResolveActivity.class);
  363. i.putExtra(ConflictsResolveActivity.EXTRA_FILE, syncedFile);
  364. i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, getAccount());
  365. startActivity(i);
  366. }
  367. } else {
  368. if (!operation.transferWasRequested()) {
  369. Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result,
  370. operation, getResources()), Toast.LENGTH_LONG);
  371. msg.show();
  372. }
  373. supportInvalidateOptionsMenu();
  374. }
  375. }
  376. protected void updateFileFromDB(){
  377. OCFile file = getFile();
  378. if (file != null) {
  379. file = getStorageManager().getFileByPath(file.getRemotePath());
  380. setFile(file);
  381. }
  382. }
  383. /**
  384. * Show loading dialog
  385. */
  386. public void showLoadingDialog(String message) {
  387. // grant that only one waiting dialog is shown
  388. dismissLoadingDialog();
  389. // Construct dialog
  390. Fragment frag = getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG);
  391. if (frag == null) {
  392. Log_OC.d(TAG, "show loading dialog");
  393. LoadingDialog loading = LoadingDialog.newInstance(message);
  394. FragmentManager fm = getSupportFragmentManager();
  395. FragmentTransaction ft = fm.beginTransaction();
  396. loading.show(ft, DIALOG_WAIT_TAG);
  397. fm.executePendingTransactions();
  398. }
  399. }
  400. /**
  401. * Dismiss loading dialog
  402. */
  403. public void dismissLoadingDialog() {
  404. Fragment frag = getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG);
  405. if (frag != null) {
  406. Log_OC.d(TAG, "dismiss loading dialog");
  407. LoadingDialog loading = (LoadingDialog) frag;
  408. loading.dismissAllowingStateLoss();
  409. }
  410. }
  411. private void doOnResumeAndBound() {
  412. mOperationsServiceBinder.addOperationListener(FileActivity.this, mHandler);
  413. long waitingForOpId = mFileOperationsHelper.getOpIdWaitingFor();
  414. if (waitingForOpId <= Integer.MAX_VALUE) {
  415. boolean wait = mOperationsServiceBinder.dispatchResultIfFinished((int)waitingForOpId,
  416. this);
  417. if (!wait ) {
  418. dismissLoadingDialog();
  419. }
  420. }
  421. }
  422. /**
  423. * Implements callback methods for service binding. Passed as a parameter to {
  424. */
  425. private class OperationsServiceConnection implements ServiceConnection {
  426. @Override
  427. public void onServiceConnected(ComponentName component, IBinder service) {
  428. if (component.equals(new ComponentName(FileActivity.this, OperationsService.class))) {
  429. Log_OC.d(TAG, "Operations service connected");
  430. mOperationsServiceBinder = (OperationsServiceBinder) service;
  431. /*if (!mOperationsServiceBinder.isPerformingBlockingOperation()) {
  432. dismissLoadingDialog();
  433. }*/
  434. if (mResumed) {
  435. doOnResumeAndBound();
  436. }
  437. } else {
  438. return;
  439. }
  440. }
  441. @Override
  442. public void onServiceDisconnected(ComponentName component) {
  443. if (component.equals(new ComponentName(FileActivity.this, OperationsService.class))) {
  444. Log_OC.d(TAG, "Operations service disconnected");
  445. mOperationsServiceBinder = null;
  446. // TODO whatever could be waiting for the service is unbound
  447. }
  448. }
  449. }
  450. @Override
  451. public FileDownloaderBinder getFileDownloaderBinder() {
  452. return mDownloaderBinder;
  453. }
  454. @Override
  455. public FileUploaderBinder getFileUploaderBinder() {
  456. return mUploaderBinder;
  457. }
  458. @Override
  459. public void restart(){
  460. Intent i = new Intent(this, FileDisplayActivity.class);
  461. i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  462. startActivity(i);
  463. fetchExternalLinks(false);
  464. }
  465. protected OCFile getCurrentDir() {
  466. OCFile file = getFile();
  467. if (file != null) {
  468. if (file.isFolder()) {
  469. return file;
  470. } else if (getStorageManager() != null) {
  471. String parentPath = file.getParentRemotePath();
  472. return getStorageManager().getFileByPath(parentPath);
  473. }
  474. }
  475. return null;
  476. }
  477. /* OnSslUntrustedCertListener methods */
  478. @Override
  479. public void onSavedCertificate() {
  480. // Nothing to do in this context
  481. }
  482. @Override
  483. public void onFailedSavingCertificate() {
  484. ConfirmationDialogFragment dialog = ConfirmationDialogFragment.newInstance(
  485. R.string.ssl_validator_not_saved, new String[]{}, 0, R.string.common_ok, -1, -1
  486. );
  487. dialog.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED);
  488. }
  489. @Override
  490. public void onCancelCertificate() {
  491. // nothing to do
  492. }
  493. }