FileActivity.java 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  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.AccountUtils;
  39. import com.owncloud.android.authentication.AuthenticatorActivity;
  40. import com.owncloud.android.datamodel.OCFile;
  41. import com.owncloud.android.files.services.FileDownloader;
  42. import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
  43. import com.owncloud.android.files.services.FileUploader;
  44. import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
  45. import com.owncloud.android.lib.common.OwnCloudAccount;
  46. import com.owncloud.android.lib.common.OwnCloudClient;
  47. import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
  48. import com.owncloud.android.lib.common.OwnCloudCredentials;
  49. import com.owncloud.android.lib.common.network.CertificateCombinedException;
  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.lib.common.utils.Log_OC;
  55. import com.owncloud.android.operations.CreateShareWithShareeOperation;
  56. import com.owncloud.android.operations.GetSharesForFileOperation;
  57. import com.owncloud.android.operations.SynchronizeFileOperation;
  58. import com.owncloud.android.operations.SynchronizeFolderOperation;
  59. import com.owncloud.android.operations.UnshareOperation;
  60. import com.owncloud.android.operations.UpdateSharePermissionsOperation;
  61. import com.owncloud.android.operations.UpdateShareViaLinkOperation;
  62. import com.owncloud.android.services.OperationsService;
  63. import com.owncloud.android.services.OperationsService.OperationsServiceBinder;
  64. import com.owncloud.android.ui.dialog.ConfirmationDialogFragment;
  65. import com.owncloud.android.ui.dialog.LoadingDialog;
  66. import com.owncloud.android.ui.dialog.SslUntrustedCertDialog;
  67. import com.owncloud.android.ui.helpers.FileOperationsHelper;
  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. Thread t = new Thread(new Runnable() {
  135. @Override
  136. public void run() {
  137. // best place, before any access to AccountManager or database
  138. AccountUtils.updateAccountVersion(getApplicationContext());
  139. }
  140. });
  141. t.start();
  142. setAccount(account, savedInstanceState != null);
  143. mOperationsServiceConnection = new OperationsServiceConnection();
  144. bindService(new Intent(this, OperationsService.class), mOperationsServiceConnection,
  145. Context.BIND_AUTO_CREATE);
  146. mDownloadServiceConnection = newTransferenceServiceConnection();
  147. if (mDownloadServiceConnection != null) {
  148. bindService(new Intent(this, FileDownloader.class), mDownloadServiceConnection,
  149. Context.BIND_AUTO_CREATE);
  150. }
  151. mUploadServiceConnection = newTransferenceServiceConnection();
  152. if (mUploadServiceConnection != null) {
  153. bindService(new Intent(this, FileUploader.class), mUploadServiceConnection,
  154. Context.BIND_AUTO_CREATE);
  155. }
  156. }
  157. @Override
  158. protected void onStart() {
  159. super.onStart();
  160. fetchExternalLinks(false);
  161. }
  162. @Override
  163. protected void onResume() {
  164. super.onResume();
  165. mResumed = true;
  166. if (mOperationsServiceBinder != null) {
  167. doOnResumeAndBound();
  168. }
  169. }
  170. @Override
  171. protected void onPause() {
  172. if (mOperationsServiceBinder != null) {
  173. mOperationsServiceBinder.removeOperationListener(this);
  174. }
  175. mResumed = false;
  176. super.onPause();
  177. }
  178. @Override
  179. protected void onDestroy() {
  180. if (mOperationsServiceConnection != null) {
  181. unbindService(mOperationsServiceConnection);
  182. mOperationsServiceBinder = null;
  183. }
  184. if (mDownloadServiceConnection != null) {
  185. unbindService(mDownloadServiceConnection);
  186. mDownloadServiceConnection = null;
  187. }
  188. if (mUploadServiceConnection != null) {
  189. unbindService(mUploadServiceConnection);
  190. mUploadServiceConnection = null;
  191. }
  192. super.onDestroy();
  193. }
  194. /**
  195. * {@inheritDoc}
  196. */
  197. @Override
  198. protected void onSaveInstanceState(Bundle outState) {
  199. super.onSaveInstanceState(outState);
  200. outState.putParcelable(FileActivity.EXTRA_FILE, mFile);
  201. outState.putBoolean(FileActivity.EXTRA_FROM_NOTIFICATION, mFromNotification);
  202. outState.putLong(KEY_WAITING_FOR_OP_ID, mFileOperationsHelper.getOpIdWaitingFor());
  203. if(getSupportActionBar() != null && getSupportActionBar().getTitle() != null) {
  204. // Null check in case the actionbar is used in ActionBar.NAVIGATION_MODE_LIST
  205. // since it doesn't have a title then
  206. outState.putString(KEY_ACTION_BAR_TITLE, getSupportActionBar().getTitle().toString());
  207. }
  208. }
  209. /**
  210. * Getter for the main {@link OCFile} handled by the activity.
  211. *
  212. * @return Main {@link OCFile} handled by the activity.
  213. */
  214. public OCFile getFile() {
  215. return mFile;
  216. }
  217. /**
  218. * Setter for the main {@link OCFile} handled by the activity.
  219. *
  220. * @param file Main {@link OCFile} to be handled by the activity.
  221. */
  222. public void setFile(OCFile file) {
  223. mFile = file;
  224. }
  225. /**
  226. * @return Value of mFromNotification: True if the Activity is launched by a notification
  227. */
  228. public boolean fromNotification() {
  229. return mFromNotification;
  230. }
  231. public OperationsServiceBinder getOperationsServiceBinder() {
  232. return mOperationsServiceBinder;
  233. }
  234. protected ServiceConnection newTransferenceServiceConnection() {
  235. return null;
  236. }
  237. public OnRemoteOperationListener getRemoteOperationListener() {
  238. return this;
  239. }
  240. public Handler getHandler() {
  241. return mHandler;
  242. }
  243. public FileOperationsHelper getFileOperationsHelper() {
  244. return mFileOperationsHelper;
  245. }
  246. /**
  247. *
  248. * @param operation Operation performed.
  249. * @param result Result of the removal.
  250. */
  251. @Override
  252. public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
  253. Log_OC.d(TAG, "Received result of operation in FileActivity - common behaviour for all the "
  254. + "FileActivities ");
  255. mFileOperationsHelper.setOpIdWaitingFor(Long.MAX_VALUE);
  256. dismissLoadingDialog();
  257. if (!result.isSuccess() && (
  258. result.getCode() == ResultCode.UNAUTHORIZED ||
  259. (result.isException() && result.getException() instanceof AuthenticatorException)
  260. )) {
  261. requestCredentialsUpdate(this);
  262. if (result.getCode() == ResultCode.UNAUTHORIZED) {
  263. Toast t = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result,
  264. operation, getResources()),
  265. Toast.LENGTH_LONG);
  266. t.show();
  267. }
  268. } else if (!result.isSuccess() && ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED.equals(result.getCode())) {
  269. showUntrustedCertDialog(result);
  270. } else if (operation == null ||
  271. operation instanceof CreateShareWithShareeOperation ||
  272. operation instanceof UnshareOperation ||
  273. operation instanceof SynchronizeFolderOperation ||
  274. operation instanceof UpdateShareViaLinkOperation ||
  275. operation instanceof UpdateSharePermissionsOperation
  276. ) {
  277. if (result.isSuccess()) {
  278. updateFileFromDB();
  279. } else if (result.getCode() != ResultCode.CANCELLED) {
  280. Toast t = Toast.makeText(this,
  281. ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  282. Toast.LENGTH_LONG);
  283. t.show();
  284. }
  285. } else if (operation instanceof SynchronizeFileOperation) {
  286. onSynchronizeFileOperationFinish((SynchronizeFileOperation) operation, result);
  287. } else if (operation instanceof GetSharesForFileOperation) {
  288. if (result.isSuccess() || result.getCode() == ResultCode.SHARE_NOT_FOUND) {
  289. updateFileFromDB();
  290. } else {
  291. Toast t = Toast.makeText(this,
  292. ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  293. Toast.LENGTH_LONG);
  294. t.show();
  295. }
  296. }
  297. }
  298. /**
  299. * Invalidates the credentials stored for the current OC account and requests new credentials to the user,
  300. * navigating to {@link AuthenticatorActivity}
  301. *
  302. * Equivalent to call requestCredentialsUpdate(context, null);
  303. *
  304. * @param context Android Context needed to access the {@link AccountManager}. Received as a parameter
  305. * to make the method accessible to {@link android.content.BroadcastReceiver}s.
  306. */
  307. protected void requestCredentialsUpdate(Context context) {
  308. requestCredentialsUpdate(context, null);
  309. }
  310. /**
  311. * Invalidates the credentials stored for the given OC account and requests new credentials to the user,
  312. * navigating to {@link AuthenticatorActivity}
  313. *
  314. * @param context Android Context needed to access the {@link AccountManager}. Received as a parameter
  315. * to make the method accessible to {@link android.content.BroadcastReceiver}s.
  316. * @param account Stored OC account to request credentials update for. If null, current account will
  317. * be used.
  318. */
  319. protected void requestCredentialsUpdate(Context context, Account account) {
  320. try {
  321. /// step 1 - invalidate credentials of current account
  322. if (account == null) {
  323. account = getAccount();
  324. }
  325. OwnCloudClient client;
  326. OwnCloudAccount ocAccount = new OwnCloudAccount(account, context);
  327. client = (OwnCloudClientManagerFactory.getDefaultSingleton().
  328. removeClientFor(ocAccount));
  329. if (client != null) {
  330. OwnCloudCredentials cred = client.getCredentials();
  331. if (cred != null) {
  332. AccountManager am = AccountManager.get(context);
  333. if (cred.authTokenExpires()) {
  334. am.invalidateAuthToken(
  335. account.type,
  336. cred.getAuthToken()
  337. );
  338. } else {
  339. am.clearPassword(account);
  340. }
  341. }
  342. }
  343. /// step 2 - request credentials to user
  344. Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
  345. updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, account);
  346. updateAccountCredentials.putExtra(
  347. AuthenticatorActivity.EXTRA_ACTION,
  348. AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
  349. updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
  350. startActivityForResult(updateAccountCredentials, REQUEST_CODE__UPDATE_CREDENTIALS);
  351. } catch (com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException e) {
  352. Toast.makeText(context, R.string.auth_account_does_not_exist, Toast.LENGTH_SHORT).show();
  353. }
  354. }
  355. /**
  356. * Show untrusted cert dialog
  357. */
  358. public void showUntrustedCertDialog(RemoteOperationResult result) {
  359. // Show a dialog with the certificate info
  360. FragmentManager fm = getSupportFragmentManager();
  361. SslUntrustedCertDialog dialog = (SslUntrustedCertDialog) fm.findFragmentByTag(DIALOG_UNTRUSTED_CERT);
  362. if(dialog == null) {
  363. dialog = SslUntrustedCertDialog.newInstanceForFullSslError(
  364. (CertificateCombinedException) result.getException());
  365. FragmentTransaction ft = fm.beginTransaction();
  366. dialog.show(ft, DIALOG_UNTRUSTED_CERT);
  367. }
  368. }
  369. private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation,
  370. RemoteOperationResult result) {
  371. OCFile syncedFile = operation.getLocalFile();
  372. if (!result.isSuccess()) {
  373. if (result.getCode() == ResultCode.SYNC_CONFLICT) {
  374. Intent i = new Intent(this, ConflictsResolveActivity.class);
  375. i.putExtra(ConflictsResolveActivity.EXTRA_FILE, syncedFile);
  376. i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, getAccount());
  377. startActivity(i);
  378. }
  379. } else {
  380. if (!operation.transferWasRequested()) {
  381. Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result,
  382. operation, getResources()), Toast.LENGTH_LONG);
  383. msg.show();
  384. }
  385. supportInvalidateOptionsMenu();
  386. }
  387. }
  388. protected void updateFileFromDB(){
  389. OCFile file = getFile();
  390. if (file != null) {
  391. file = getStorageManager().getFileByPath(file.getRemotePath());
  392. setFile(file);
  393. }
  394. }
  395. /**
  396. * Show loading dialog
  397. */
  398. public void showLoadingDialog(String message) {
  399. // grant that only one waiting dialog is shown
  400. dismissLoadingDialog();
  401. // Construct dialog
  402. Fragment frag = getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG);
  403. if (frag == null) {
  404. Log_OC.d(TAG, "show loading dialog");
  405. LoadingDialog loading = LoadingDialog.newInstance(message);
  406. FragmentManager fm = getSupportFragmentManager();
  407. FragmentTransaction ft = fm.beginTransaction();
  408. loading.show(ft, DIALOG_WAIT_TAG);
  409. fm.executePendingTransactions();
  410. }
  411. }
  412. /**
  413. * Dismiss loading dialog
  414. */
  415. public void dismissLoadingDialog() {
  416. Fragment frag = getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG);
  417. if (frag != null) {
  418. Log_OC.d(TAG, "dismiss loading dialog");
  419. LoadingDialog loading = (LoadingDialog) frag;
  420. loading.dismissAllowingStateLoss();
  421. }
  422. }
  423. private void doOnResumeAndBound() {
  424. mOperationsServiceBinder.addOperationListener(FileActivity.this, mHandler);
  425. long waitingForOpId = mFileOperationsHelper.getOpIdWaitingFor();
  426. if (waitingForOpId <= Integer.MAX_VALUE) {
  427. boolean wait = mOperationsServiceBinder.dispatchResultIfFinished((int)waitingForOpId,
  428. this);
  429. if (!wait ) {
  430. dismissLoadingDialog();
  431. }
  432. }
  433. }
  434. /**
  435. * Implements callback methods for service binding. Passed as a parameter to {
  436. */
  437. private class OperationsServiceConnection implements ServiceConnection {
  438. @Override
  439. public void onServiceConnected(ComponentName component, IBinder service) {
  440. if (component.equals(new ComponentName(FileActivity.this, OperationsService.class))) {
  441. Log_OC.d(TAG, "Operations service connected");
  442. mOperationsServiceBinder = (OperationsServiceBinder) service;
  443. /*if (!mOperationsServiceBinder.isPerformingBlockingOperation()) {
  444. dismissLoadingDialog();
  445. }*/
  446. if (mResumed) {
  447. doOnResumeAndBound();
  448. }
  449. } else {
  450. return;
  451. }
  452. }
  453. @Override
  454. public void onServiceDisconnected(ComponentName component) {
  455. if (component.equals(new ComponentName(FileActivity.this, OperationsService.class))) {
  456. Log_OC.d(TAG, "Operations service disconnected");
  457. mOperationsServiceBinder = null;
  458. // TODO whatever could be waiting for the service is unbound
  459. }
  460. }
  461. }
  462. @Override
  463. public FileDownloaderBinder getFileDownloaderBinder() {
  464. return mDownloaderBinder;
  465. }
  466. @Override
  467. public FileUploaderBinder getFileUploaderBinder() {
  468. return mUploaderBinder;
  469. }
  470. @Override
  471. public void restart(){
  472. Intent i = new Intent(this, FileDisplayActivity.class);
  473. i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  474. startActivity(i);
  475. fetchExternalLinks(false);
  476. }
  477. protected OCFile getCurrentDir() {
  478. OCFile file = getFile();
  479. if (file != null) {
  480. if (file.isFolder()) {
  481. return file;
  482. } else if (getStorageManager() != null) {
  483. String parentPath = file.getParentRemotePath();
  484. return getStorageManager().getFileByPath(parentPath);
  485. }
  486. }
  487. return null;
  488. }
  489. /* OnSslUntrustedCertListener methods */
  490. @Override
  491. public void onSavedCertificate() {
  492. // Nothing to do in this context
  493. }
  494. @Override
  495. public void onFailedSavingCertificate() {
  496. ConfirmationDialogFragment dialog = ConfirmationDialogFragment.newInstance(
  497. R.string.ssl_validator_not_saved, new String[]{}, 0, R.string.common_ok, -1, -1
  498. );
  499. dialog.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED);
  500. }
  501. @Override
  502. public void onCancelCertificate() {
  503. // nothing to do
  504. }
  505. }