2 * ownCloud Android client application
4 * @author David A. Velasco
5 * Copyright (C) 2011 Bartek Przybylski
6 * Copyright (C) 2015 ownCloud Inc.
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.
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.
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/>.
22 package com
.owncloud
.android
.ui
.activity
;
24 import android
.accounts
.Account
;
25 import android
.accounts
.AccountManager
;
26 import android
.accounts
.AccountManagerCallback
;
27 import android
.accounts
.AccountManagerFuture
;
28 import android
.accounts
.AuthenticatorException
;
29 import android
.accounts
.OperationCanceledException
;
30 import android
.content
.ComponentName
;
31 import android
.content
.Context
;
32 import android
.content
.Intent
;
33 import android
.content
.ServiceConnection
;
34 import android
.os
.Bundle
;
35 import android
.os
.Handler
;
36 import android
.os
.IBinder
;
37 import android
.support
.v4
.app
.Fragment
;
38 import android
.support
.v4
.app
.FragmentManager
;
39 import android
.support
.v4
.app
.FragmentTransaction
;
40 import android
.widget
.Toast
;
42 import com
.actionbarsherlock
.app
.SherlockFragmentActivity
;
43 import com
.owncloud
.android
.MainApp
;
44 import com
.owncloud
.android
.R
;
45 import com
.owncloud
.android
.authentication
.AccountUtils
;
46 import com
.owncloud
.android
.authentication
.AuthenticatorActivity
;
47 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
48 import com
.owncloud
.android
.datamodel
.OCFile
;
49 import com
.owncloud
.android
.files
.FileOperationsHelper
;
50 import com
.owncloud
.android
.files
.services
.FileDownloader
;
51 import com
.owncloud
.android
.files
.services
.FileUploader
;
52 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
53 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
54 import com
.owncloud
.android
.lib
.common
.operations
.OnRemoteOperationListener
;
55 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
56 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
57 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
58 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
59 import com
.owncloud
.android
.operations
.CreateShareOperation
;
60 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
61 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
62 import com
.owncloud
.android
.services
.OperationsService
;
63 import com
.owncloud
.android
.services
.OperationsService
.OperationsServiceBinder
;
64 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
65 import com
.owncloud
.android
.ui
.dialog
.LoadingDialog
;
66 import com
.owncloud
.android
.ui
.dialog
.SharePasswordDialogFragment
;
67 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
71 * Activity with common behaviour for activities handling {@link OCFile}s in ownCloud {@link Account}s .
73 public class FileActivity
extends SherlockFragmentActivity
74 implements OnRemoteOperationListener
, ComponentsGetter
{
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_WAITING_TO_PREVIEW
= "com.owncloud.android.ui.activity.WAITING_TO_PREVIEW";
79 public static final String EXTRA_FROM_NOTIFICATION
= "com.owncloud.android.ui.activity.FROM_NOTIFICATION";
81 public static final String TAG
= FileActivity
.class.getSimpleName();
83 private static final String DIALOG_WAIT_TAG
= "DIALOG_WAIT";
84 private static final String KEY_WAITING_FOR_OP_ID
= "WAITING_FOR_OP_ID";
85 private static final String DIALOG_SHARE_PASSWORD
= "DIALOG_SHARE_PASSWORD";
86 private static final String KEY_TRY_SHARE_AGAIN
= "TRY_SHARE_AGAIN";
88 protected static final long DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
= 200;
91 /** OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located. */
92 private Account mAccount
;
94 /** Main {@link OCFile} handled by the activity.*/
97 /** Flag to signal that the activity will is finishing to enforce the creation of an ownCloud {@link Account} */
98 private boolean mRedirectingToSetupAccount
= false
;
100 /** Flag to signal when the value of mAccount was set */
101 protected boolean mAccountWasSet
;
103 /** Flag to signal when the value of mAccount was restored from a saved state */
104 protected boolean mAccountWasRestored
;
106 /** Flag to signal if the activity is launched by a notification */
107 private boolean mFromNotification
;
109 /** Messages handler associated to the main thread and the life cycle of the activity */
110 private Handler mHandler
;
112 /** Access point to the cached database for the current ownCloud {@link Account} */
113 private FileDataStorageManager mStorageManager
= null
;
115 private FileOperationsHelper mFileOperationsHelper
;
117 private ServiceConnection mOperationsServiceConnection
= null
;
119 private OperationsServiceBinder mOperationsServiceBinder
= null
;
121 protected FileDownloaderBinder mDownloaderBinder
= null
;
122 protected FileUploaderBinder mUploaderBinder
= null
;
123 private ServiceConnection mDownloadServiceConnection
, mUploadServiceConnection
= null
;
125 private boolean mTryShareAgain
= false
;
129 * Loads the ownCloud {@link Account} and main {@link OCFile} to be handled by the instance of
130 * the {@link FileActivity}.
132 * Grants that a valid ownCloud {@link Account} is associated to the instance, or that the user
133 * is requested to create a new one.
136 protected void onCreate(Bundle savedInstanceState
) {
137 super.onCreate(savedInstanceState
);
138 mHandler
= new Handler();
139 mFileOperationsHelper
= new FileOperationsHelper(this);
141 if(savedInstanceState
!= null
) {
142 account
= savedInstanceState
.getParcelable(FileActivity
.EXTRA_ACCOUNT
);
143 mFile
= savedInstanceState
.getParcelable(FileActivity
.EXTRA_FILE
);
144 mFromNotification
= savedInstanceState
.getBoolean(FileActivity
.EXTRA_FROM_NOTIFICATION
);
145 mFileOperationsHelper
.setOpIdWaitingFor(
146 savedInstanceState
.getLong(KEY_WAITING_FOR_OP_ID
, Long
.MAX_VALUE
)
148 mTryShareAgain
= savedInstanceState
.getBoolean(KEY_TRY_SHARE_AGAIN
);
150 account
= getIntent().getParcelableExtra(FileActivity
.EXTRA_ACCOUNT
);
151 mFile
= getIntent().getParcelableExtra(FileActivity
.EXTRA_FILE
);
152 mFromNotification
= getIntent().getBooleanExtra(FileActivity
.EXTRA_FROM_NOTIFICATION
, false
);
155 setAccount(account
, savedInstanceState
!= null
);
157 mOperationsServiceConnection
= new OperationsServiceConnection();
158 bindService(new Intent(this, OperationsService
.class), mOperationsServiceConnection
, Context
.BIND_AUTO_CREATE
);
160 mDownloadServiceConnection
= newTransferenceServiceConnection();
161 if (mDownloadServiceConnection
!= null
) {
162 bindService(new Intent(this, FileDownloader
.class), mDownloadServiceConnection
, Context
.BIND_AUTO_CREATE
);
164 mUploadServiceConnection
= newTransferenceServiceConnection();
165 if (mUploadServiceConnection
!= null
) {
166 bindService(new Intent(this, FileUploader
.class), mUploadServiceConnection
, Context
.BIND_AUTO_CREATE
);
173 * Since ownCloud {@link Account}s can be managed from the system setting menu,
174 * the existence of the {@link Account} associated to the instance must be checked
175 * every time it is restarted.
178 protected void onRestart() {
180 boolean validAccount
= (mAccount
!= null
&& AccountUtils
.setCurrentOwnCloudAccount(getApplicationContext(), mAccount
.name
));
182 swapToDefaultAccount();
188 protected void onStart() {
191 if (mAccountWasSet
) {
192 onAccountSet(mAccountWasRestored
);
197 protected void onResume() {
200 if (mOperationsServiceBinder
!= null
) {
201 doOnResumeAndBound();
207 protected void onPause() {
209 if (mOperationsServiceBinder
!= null
) {
210 mOperationsServiceBinder
.removeOperationListener(this);
218 protected void onDestroy() {
219 if (mOperationsServiceConnection
!= null
) {
220 unbindService(mOperationsServiceConnection
);
221 mOperationsServiceBinder
= null
;
223 if (mDownloadServiceConnection
!= null
) {
224 unbindService(mDownloadServiceConnection
);
225 mDownloadServiceConnection
= null
;
227 if (mUploadServiceConnection
!= null
) {
228 unbindService(mUploadServiceConnection
);
229 mUploadServiceConnection
= null
;
237 * Sets and validates the ownCloud {@link Account} associated to the Activity.
239 * If not valid, tries to swap it for other valid and existing ownCloud {@link Account}.
241 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
243 * @param account New {@link Account} to set.
244 * @param savedAccount When 'true', account was retrieved from a saved instance state.
246 protected void setAccount(Account account
, boolean savedAccount
) {
247 Account oldAccount
= mAccount
;
248 boolean validAccount
= (account
!= null
&& AccountUtils
.setCurrentOwnCloudAccount(getApplicationContext(), account
.name
));
251 mAccountWasSet
= true
;
252 mAccountWasRestored
= (savedAccount
|| mAccount
.equals(oldAccount
));
255 swapToDefaultAccount();
261 * Tries to swap the current ownCloud {@link Account} for other valid and existing.
263 * If no valid ownCloud {@link Account} exists, the the user is requested
264 * to create a new ownCloud {@link Account}.
266 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
268 private void swapToDefaultAccount() {
269 // default to the most recently used account
270 Account newAccount
= AccountUtils
.getCurrentOwnCloudAccount(getApplicationContext());
271 if (newAccount
== null
) {
272 /// no account available: force account creation
273 createFirstAccount();
274 mRedirectingToSetupAccount
= true
;
275 mAccountWasSet
= false
;
276 mAccountWasRestored
= false
;
279 mAccountWasSet
= true
;
280 mAccountWasRestored
= (newAccount
.equals(mAccount
));
281 mAccount
= newAccount
;
287 * Launches the account creation activity. To use when no ownCloud account is available
289 private void createFirstAccount() {
290 AccountManager am
= AccountManager
.get(getApplicationContext());
291 am
.addAccount(MainApp
.getAccountType(),
296 new AccountCreationCallback(),
305 protected void onSaveInstanceState(Bundle outState
) {
306 super.onSaveInstanceState(outState
);
307 outState
.putParcelable(FileActivity
.EXTRA_FILE
, mFile
);
308 outState
.putParcelable(FileActivity
.EXTRA_ACCOUNT
, mAccount
);
309 outState
.putBoolean(FileActivity
.EXTRA_FROM_NOTIFICATION
, mFromNotification
);
310 outState
.putLong(KEY_WAITING_FOR_OP_ID
, mFileOperationsHelper
.getOpIdWaitingFor());
311 outState
.putBoolean(KEY_TRY_SHARE_AGAIN
, mTryShareAgain
);
316 * Getter for the main {@link OCFile} handled by the activity.
318 * @return Main {@link OCFile} handled by the activity.
320 public OCFile
getFile() {
326 * Setter for the main {@link OCFile} handled by the activity.
328 * @param file Main {@link OCFile} to be handled by the activity.
330 public void setFile(OCFile file
) {
336 * Getter for the ownCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
338 * @return OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
340 public Account
getAccount() {
344 protected void setAccount(Account account
) {
349 * @return Value of mFromNotification: True if the Activity is launched by a notification
351 public boolean fromNotification() {
352 return mFromNotification
;
356 * @return 'True' when the Activity is finishing to enforce the setup of a new account.
358 protected boolean isRedirectingToSetupAccount() {
359 return mRedirectingToSetupAccount
;
362 public boolean isTryShareAgain(){
363 return mTryShareAgain
;
366 public void setTryShareAgain(boolean tryShareAgain
) {
367 mTryShareAgain
= tryShareAgain
;
370 public OperationsServiceBinder
getOperationsServiceBinder() {
371 return mOperationsServiceBinder
;
374 protected ServiceConnection
newTransferenceServiceConnection() {
379 * Helper class handling a callback from the {@link AccountManager} after the creation of
380 * a new ownCloud {@link Account} finished, successfully or not.
382 * At this moment, only called after the creation of the first account.
384 public class AccountCreationCallback
implements AccountManagerCallback
<Bundle
> {
387 public void run(AccountManagerFuture
<Bundle
> future
) {
388 FileActivity
.this.mRedirectingToSetupAccount
= false
;
389 boolean accountWasSet
= false
;
390 if (future
!= null
) {
393 result
= future
.getResult();
394 String name
= result
.getString(AccountManager
.KEY_ACCOUNT_NAME
);
395 String type
= result
.getString(AccountManager
.KEY_ACCOUNT_TYPE
);
396 if (AccountUtils
.setCurrentOwnCloudAccount(getApplicationContext(), name
)) {
397 setAccount(new Account(name
, type
), false
);
398 accountWasSet
= true
;
400 } catch (OperationCanceledException e
) {
401 Log_OC
.d(TAG
, "Account creation canceled");
403 } catch (Exception e
) {
404 Log_OC
.e(TAG
, "Account creation finished in exception: ", e
);
408 Log_OC
.e(TAG
, "Account creation callback with null bundle");
410 if (!accountWasSet
) {
411 moveTaskToBack(true
);
419 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
421 * Child classes must grant that state depending on the {@link Account} is updated.
423 protected void onAccountSet(boolean stateWasRecovered
) {
424 if (getAccount() != null
) {
425 mStorageManager
= new FileDataStorageManager(getAccount(), getContentResolver());
428 Log_OC
.wtf(TAG
, "onAccountChanged was called with NULL account associated!");
433 public FileDataStorageManager
getStorageManager() {
434 return mStorageManager
;
438 public OnRemoteOperationListener
getRemoteOperationListener() {
443 public Handler
getHandler() {
447 public FileOperationsHelper
getFileOperationsHelper() {
448 return mFileOperationsHelper
;
453 * @param operation Removal operation performed.
454 * @param result Result of the removal.
457 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
458 Log_OC
.d(TAG
, "Received result of operation in FileActivity - common behaviour for all the FileActivities ");
460 mFileOperationsHelper
.setOpIdWaitingFor(Long
.MAX_VALUE
);
462 if (!result
.isSuccess() && (
463 result
.getCode() == ResultCode
.UNAUTHORIZED
||
464 result
.isIdPRedirection() ||
465 (result
.isException() && result
.getException() instanceof AuthenticatorException
)
468 requestCredentialsUpdate();
470 if (result
.getCode() == ResultCode
.UNAUTHORIZED
) {
471 dismissLoadingDialog();
472 Toast t
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
,
473 operation
, getResources()),
477 mTryShareAgain
= false
;
479 } else if (operation
instanceof CreateShareOperation
) {
480 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
482 } else if (operation
instanceof UnshareLinkOperation
) {
483 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
485 } else if (operation
instanceof SynchronizeFolderOperation
) {
486 onSynchronizeFolderOperationFinish((SynchronizeFolderOperation
)operation
, result
);
491 protected void requestCredentialsUpdate() {
492 Intent updateAccountCredentials
= new Intent(this, AuthenticatorActivity
.class);
493 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACCOUNT
, getAccount());
494 updateAccountCredentials
.putExtra(
495 AuthenticatorActivity
.EXTRA_ACTION
,
496 AuthenticatorActivity
.ACTION_UPDATE_EXPIRED_TOKEN
);
497 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
498 startActivity(updateAccountCredentials
);
502 private void onCreateShareOperationFinish(CreateShareOperation operation
,
503 RemoteOperationResult result
) {
504 dismissLoadingDialog();
505 if (result
.isSuccess()) {
506 mTryShareAgain
= false
;
509 Intent sendIntent
= operation
.getSendIntent();
510 startActivity(sendIntent
);
512 // Detect Failure (403) --> needs Password
513 if (result
.getCode() == ResultCode
.SHARE_FORBIDDEN
) {
514 if (!isTryShareAgain()) {
515 SharePasswordDialogFragment dialog
=
516 SharePasswordDialogFragment
.newInstance(new OCFile(operation
.getPath()),
517 operation
.getSendIntent());
518 dialog
.show(getSupportFragmentManager(), DIALOG_SHARE_PASSWORD
);
520 Toast t
= Toast
.makeText(this,
521 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
524 mTryShareAgain
= false
;
527 Toast t
= Toast
.makeText(this,
528 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
536 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
537 dismissLoadingDialog();
539 if (result
.isSuccess()){
543 Toast t
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
549 private void onSynchronizeFolderOperationFinish(SynchronizeFolderOperation operation
, RemoteOperationResult result
) {
550 if (!result
.isSuccess() && result
.getCode() != ResultCode
.CANCELLED
){
551 Toast t
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
557 protected void updateFileFromDB(){
558 OCFile file
= getFile();
560 file
= getStorageManager().getFileByPath(file
.getRemotePath());
566 * Show loading dialog
568 public void showLoadingDialog() {
570 LoadingDialog loading
= new LoadingDialog(getResources().getString(R
.string
.wait_a_moment
));
571 FragmentManager fm
= getSupportFragmentManager();
572 FragmentTransaction ft
= fm
.beginTransaction();
573 loading
.show(ft
, DIALOG_WAIT_TAG
);
579 * Dismiss loading dialog
581 public void dismissLoadingDialog(){
582 Fragment frag
= getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG
);
584 LoadingDialog loading
= (LoadingDialog
) frag
;
590 private void doOnResumeAndBound() {
591 mOperationsServiceBinder
.addOperationListener(FileActivity
.this, mHandler
);
592 long waitingForOpId
= mFileOperationsHelper
.getOpIdWaitingFor();
593 if (waitingForOpId
<= Integer
.MAX_VALUE
) {
594 boolean wait
= mOperationsServiceBinder
.dispatchResultIfFinished((int)waitingForOpId
, this);
596 dismissLoadingDialog();
603 * Implements callback methods for service binding. Passed as a parameter to {
605 private class OperationsServiceConnection
implements ServiceConnection
{
608 public void onServiceConnected(ComponentName component
, IBinder service
) {
609 if (component
.equals(new ComponentName(FileActivity
.this, OperationsService
.class))) {
610 Log_OC
.d(TAG
, "Operations service connected");
611 mOperationsServiceBinder
= (OperationsServiceBinder
) service
;
612 /*if (!mOperationsServiceBinder.isPerformingBlockingOperation()) {
613 dismissLoadingDialog();
615 doOnResumeAndBound();
624 public void onServiceDisconnected(ComponentName component
) {
625 if (component
.equals(new ComponentName(FileActivity
.this, OperationsService
.class))) {
626 Log_OC
.d(TAG
, "Operations service disconnected");
627 mOperationsServiceBinder
= null
;
628 // TODO whatever could be waiting for the service is unbound
635 public FileDownloaderBinder
getFileDownloaderBinder() {
636 return mDownloaderBinder
;
641 public FileUploaderBinder
getFileUploaderBinder() {
642 return mUploaderBinder
;