FileActivity.java 22 KB

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