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
.LoadingDialog
;
65 import com
.owncloud
.android
.ui
.dialog
.SharePasswordDialogFragment
;
66 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
70 * Activity with common behaviour for activities handling {@link OCFile}s in ownCloud {@link Account}s .
72 public class FileActivity
extends SherlockFragmentActivity
73 implements OnRemoteOperationListener
, ComponentsGetter
{
75 public static final String EXTRA_FILE
= "com.owncloud.android.ui.activity.FILE";
76 public static final String EXTRA_ACCOUNT
= "com.owncloud.android.ui.activity.ACCOUNT";
77 public static final String EXTRA_WAITING_TO_PREVIEW
= "com.owncloud.android.ui.activity.WAITING_TO_PREVIEW";
78 public static final String EXTRA_FROM_NOTIFICATION
= "com.owncloud.android.ui.activity.FROM_NOTIFICATION";
80 public static final String TAG
= FileActivity
.class.getSimpleName();
82 private static final String DIALOG_WAIT_TAG
= "DIALOG_WAIT";
83 private static final String KEY_WAITING_FOR_OP_ID
= "WAITING_FOR_OP_ID";
84 private static final String DIALOG_SHARE_PASSWORD
= "DIALOG_SHARE_PASSWORD";
85 private static final String KEY_TRY_SHARE_AGAIN
= "TRY_SHARE_AGAIN";
87 protected static final long DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
= 200;
90 /** OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located. */
91 private Account mAccount
;
93 /** Main {@link OCFile} handled by the activity.*/
96 /** Flag to signal that the activity will is finishing to enforce the creation of an ownCloud {@link Account} */
97 private boolean mRedirectingToSetupAccount
= false
;
99 /** Flag to signal when the value of mAccount was set */
100 protected boolean mAccountWasSet
;
102 /** Flag to signal when the value of mAccount was restored from a saved state */
103 protected boolean mAccountWasRestored
;
105 /** Flag to signal if the activity is launched by a notification */
106 private boolean mFromNotification
;
108 /** Messages handler associated to the main thread and the life cycle of the activity */
109 private Handler mHandler
;
111 /** Access point to the cached database for the current ownCloud {@link Account} */
112 private FileDataStorageManager mStorageManager
= null
;
114 private FileOperationsHelper mFileOperationsHelper
;
116 private ServiceConnection mOperationsServiceConnection
= null
;
118 private OperationsServiceBinder mOperationsServiceBinder
= null
;
120 protected FileDownloaderBinder mDownloaderBinder
= null
;
121 protected FileUploaderBinder mUploaderBinder
= null
;
122 private ServiceConnection mDownloadServiceConnection
, mUploadServiceConnection
= null
;
124 private boolean mTryShareAgain
= false
;
128 * Loads the ownCloud {@link Account} and main {@link OCFile} to be handled by the instance of
129 * the {@link FileActivity}.
131 * Grants that a valid ownCloud {@link Account} is associated to the instance, or that the user
132 * is requested to create a new one.
135 protected void onCreate(Bundle savedInstanceState
) {
136 super.onCreate(savedInstanceState
);
137 mHandler
= new Handler();
138 mFileOperationsHelper
= new FileOperationsHelper(this);
140 if(savedInstanceState
!= null
) {
141 account
= savedInstanceState
.getParcelable(FileActivity
.EXTRA_ACCOUNT
);
142 mFile
= savedInstanceState
.getParcelable(FileActivity
.EXTRA_FILE
);
143 mFromNotification
= savedInstanceState
.getBoolean(FileActivity
.EXTRA_FROM_NOTIFICATION
);
144 mFileOperationsHelper
.setOpIdWaitingFor(
145 savedInstanceState
.getLong(KEY_WAITING_FOR_OP_ID
, Long
.MAX_VALUE
)
147 mTryShareAgain
= savedInstanceState
.getBoolean(KEY_TRY_SHARE_AGAIN
);
149 account
= getIntent().getParcelableExtra(FileActivity
.EXTRA_ACCOUNT
);
150 mFile
= getIntent().getParcelableExtra(FileActivity
.EXTRA_FILE
);
151 mFromNotification
= getIntent().getBooleanExtra(FileActivity
.EXTRA_FROM_NOTIFICATION
, false
);
154 setAccount(account
, savedInstanceState
!= null
);
156 mOperationsServiceConnection
= new OperationsServiceConnection();
157 bindService(new Intent(this, OperationsService
.class), mOperationsServiceConnection
, Context
.BIND_AUTO_CREATE
);
159 mDownloadServiceConnection
= newTransferenceServiceConnection();
160 if (mDownloadServiceConnection
!= null
) {
161 bindService(new Intent(this, FileDownloader
.class), mDownloadServiceConnection
, Context
.BIND_AUTO_CREATE
);
163 mUploadServiceConnection
= newTransferenceServiceConnection();
164 if (mUploadServiceConnection
!= null
) {
165 bindService(new Intent(this, FileUploader
.class), mUploadServiceConnection
, Context
.BIND_AUTO_CREATE
);
172 * Since ownCloud {@link Account}s can be managed from the system setting menu,
173 * the existence of the {@link Account} associated to the instance must be checked
174 * every time it is restarted.
177 protected void onRestart() {
178 Log_OC
.v(TAG
, "onRestart() start");
180 boolean validAccount
=
181 (mAccount
!= null
&& AccountUtils
.setCurrentOwnCloudAccount(getApplicationContext(), mAccount
.name
));
183 swapToDefaultAccount();
185 Log_OC
.v(TAG
, "onRestart() end");
190 protected void onStart() {
191 Log_OC
.v(TAG
, "onStart() start");
194 if (mAccountWasSet
) {
195 onAccountSet(mAccountWasRestored
);
197 Log_OC
.v(TAG
, "onStart() end");
201 protected void onResume() {
202 Log_OC
.v(TAG
, "onResume() start");
205 if (mOperationsServiceBinder
!= null
) {
206 doOnResumeAndBound();
208 Log_OC
.v(TAG
, "onResume() end");
212 protected void onPause() {
213 Log_OC
.v(TAG
, "onPause() start");
215 if (mOperationsServiceBinder
!= null
) {
216 mOperationsServiceBinder
.removeOperationListener(this);
220 Log_OC
.v(TAG
, "onPause() end");
225 protected void onDestroy() {
226 if (mOperationsServiceConnection
!= null
) {
227 unbindService(mOperationsServiceConnection
);
228 mOperationsServiceBinder
= null
;
230 if (mDownloadServiceConnection
!= null
) {
231 unbindService(mDownloadServiceConnection
);
232 mDownloadServiceConnection
= null
;
234 if (mUploadServiceConnection
!= null
) {
235 unbindService(mUploadServiceConnection
);
236 mUploadServiceConnection
= null
;
244 * Sets and validates the ownCloud {@link Account} associated to the Activity.
246 * If not valid, tries to swap it for other valid and existing ownCloud {@link Account}.
248 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
250 * @param account New {@link Account} to set.
251 * @param savedAccount When 'true', account was retrieved from a saved instance state.
253 protected void setAccount(Account account
, boolean savedAccount
) {
254 Account oldAccount
= mAccount
;
255 boolean validAccount
=
256 (account
!= null
&& AccountUtils
.setCurrentOwnCloudAccount(getApplicationContext(), account
.name
));
259 mAccountWasSet
= true
;
260 mAccountWasRestored
= (savedAccount
|| mAccount
.equals(oldAccount
));
263 swapToDefaultAccount();
269 * Tries to swap the current ownCloud {@link Account} for other valid and existing.
271 * If no valid ownCloud {@link Account} exists, the the user is requested
272 * to create a new ownCloud {@link Account}.
274 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
276 private void swapToDefaultAccount() {
277 // default to the most recently used account
278 Account newAccount
= AccountUtils
.getCurrentOwnCloudAccount(getApplicationContext());
279 if (newAccount
== null
) {
280 /// no account available: force account creation
281 createFirstAccount();
282 mRedirectingToSetupAccount
= true
;
283 mAccountWasSet
= false
;
284 mAccountWasRestored
= false
;
287 mAccountWasSet
= true
;
288 mAccountWasRestored
= (newAccount
.equals(mAccount
));
289 mAccount
= newAccount
;
295 * Launches the account creation activity. To use when no ownCloud account is available
297 private void createFirstAccount() {
298 AccountManager am
= AccountManager
.get(getApplicationContext());
299 am
.addAccount(MainApp
.getAccountType(),
304 new AccountCreationCallback(),
313 protected void onSaveInstanceState(Bundle outState
) {
314 super.onSaveInstanceState(outState
);
315 outState
.putParcelable(FileActivity
.EXTRA_FILE
, mFile
);
316 outState
.putParcelable(FileActivity
.EXTRA_ACCOUNT
, mAccount
);
317 outState
.putBoolean(FileActivity
.EXTRA_FROM_NOTIFICATION
, mFromNotification
);
318 outState
.putLong(KEY_WAITING_FOR_OP_ID
, mFileOperationsHelper
.getOpIdWaitingFor());
319 outState
.putBoolean(KEY_TRY_SHARE_AGAIN
, mTryShareAgain
);
324 * Getter for the main {@link OCFile} handled by the activity.
326 * @return Main {@link OCFile} handled by the activity.
328 public OCFile
getFile() {
334 * Setter for the main {@link OCFile} handled by the activity.
336 * @param file Main {@link OCFile} to be handled by the activity.
338 public void setFile(OCFile file
) {
344 * Getter for the ownCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
346 * @return OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
348 public Account
getAccount() {
352 protected void setAccount(Account account
) {
357 * @return Value of mFromNotification: True if the Activity is launched by a notification
359 public boolean fromNotification() {
360 return mFromNotification
;
364 * @return 'True' when the Activity is finishing to enforce the setup of a new account.
366 protected boolean isRedirectingToSetupAccount() {
367 return mRedirectingToSetupAccount
;
370 public boolean isTryShareAgain(){
371 return mTryShareAgain
;
374 public void setTryShareAgain(boolean tryShareAgain
) {
375 mTryShareAgain
= tryShareAgain
;
378 public OperationsServiceBinder
getOperationsServiceBinder() {
379 return mOperationsServiceBinder
;
382 protected ServiceConnection
newTransferenceServiceConnection() {
387 * Helper class handling a callback from the {@link AccountManager} after the creation of
388 * a new ownCloud {@link Account} finished, successfully or not.
390 * At this moment, only called after the creation of the first account.
392 public class AccountCreationCallback
implements AccountManagerCallback
<Bundle
> {
395 public void run(AccountManagerFuture
<Bundle
> future
) {
396 FileActivity
.this.mRedirectingToSetupAccount
= false
;
397 boolean accountWasSet
= false
;
398 if (future
!= null
) {
401 result
= future
.getResult();
402 String name
= result
.getString(AccountManager
.KEY_ACCOUNT_NAME
);
403 String type
= result
.getString(AccountManager
.KEY_ACCOUNT_TYPE
);
404 if (AccountUtils
.setCurrentOwnCloudAccount(getApplicationContext(), name
)) {
405 setAccount(new Account(name
, type
), false
);
406 accountWasSet
= true
;
408 } catch (OperationCanceledException e
) {
409 Log_OC
.d(TAG
, "Account creation canceled");
411 } catch (Exception e
) {
412 Log_OC
.e(TAG
, "Account creation finished in exception: ", e
);
416 Log_OC
.e(TAG
, "Account creation callback with null bundle");
418 if (!accountWasSet
) {
419 moveTaskToBack(true
);
427 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
429 * Child classes must grant that state depending on the {@link Account} is updated.
431 protected void onAccountSet(boolean stateWasRecovered
) {
432 if (getAccount() != null
) {
433 mStorageManager
= new FileDataStorageManager(getAccount(), getContentResolver());
436 Log_OC
.wtf(TAG
, "onAccountChanged was called with NULL account associated!");
441 public FileDataStorageManager
getStorageManager() {
442 return mStorageManager
;
446 public OnRemoteOperationListener
getRemoteOperationListener() {
451 public Handler
getHandler() {
455 public FileOperationsHelper
getFileOperationsHelper() {
456 return mFileOperationsHelper
;
461 * @param operation Removal operation performed.
462 * @param result Result of the removal.
465 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
466 Log_OC
.d(TAG
, "Received result of operation in FileActivity - common behaviour for all the FileActivities ");
468 mFileOperationsHelper
.setOpIdWaitingFor(Long
.MAX_VALUE
);
470 if (!result
.isSuccess() && (
471 result
.getCode() == ResultCode
.UNAUTHORIZED
||
472 result
.isIdPRedirection() ||
473 (result
.isException() && result
.getException() instanceof AuthenticatorException
)
476 requestCredentialsUpdate();
478 if (result
.getCode() == ResultCode
.UNAUTHORIZED
) {
479 dismissLoadingDialog();
480 Toast t
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
,
481 operation
, getResources()),
485 mTryShareAgain
= false
;
487 } else if (operation
instanceof CreateShareOperation
) {
488 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
490 } else if (operation
instanceof UnshareLinkOperation
) {
491 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
493 } else if (operation
instanceof SynchronizeFolderOperation
) {
494 onSynchronizeFolderOperationFinish((SynchronizeFolderOperation
)operation
, result
);
499 protected void requestCredentialsUpdate() {
500 Intent updateAccountCredentials
= new Intent(this, AuthenticatorActivity
.class);
501 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACCOUNT
, getAccount());
502 updateAccountCredentials
.putExtra(
503 AuthenticatorActivity
.EXTRA_ACTION
,
504 AuthenticatorActivity
.ACTION_UPDATE_EXPIRED_TOKEN
);
505 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
506 startActivity(updateAccountCredentials
);
510 private void onCreateShareOperationFinish(CreateShareOperation operation
,
511 RemoteOperationResult result
) {
512 dismissLoadingDialog();
513 if (result
.isSuccess()) {
514 mTryShareAgain
= false
;
517 Intent sendIntent
= operation
.getSendIntent();
518 startActivity(sendIntent
);
520 // Detect Failure (403) --> needs Password
521 if (result
.getCode() == ResultCode
.SHARE_FORBIDDEN
) {
522 if (!isTryShareAgain()) {
523 SharePasswordDialogFragment dialog
=
524 SharePasswordDialogFragment
.newInstance(new OCFile(operation
.getPath()),
525 operation
.getSendIntent());
526 dialog
.show(getSupportFragmentManager(), DIALOG_SHARE_PASSWORD
);
528 Toast t
= Toast
.makeText(this,
529 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
532 mTryShareAgain
= false
;
535 Toast t
= Toast
.makeText(this,
536 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
544 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
545 dismissLoadingDialog();
547 if (result
.isSuccess()){
551 Toast t
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
557 private void onSynchronizeFolderOperationFinish(
558 SynchronizeFolderOperation operation
, RemoteOperationResult result
560 if (!result
.isSuccess() && result
.getCode() != ResultCode
.CANCELLED
){
561 Toast t
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
567 protected void updateFileFromDB(){
568 OCFile file
= getFile();
570 file
= getStorageManager().getFileByPath(file
.getRemotePath());
576 * Show loading dialog
578 public void showLoadingDialog() {
580 LoadingDialog loading
= new LoadingDialog(getResources().getString(R
.string
.wait_a_moment
));
581 FragmentManager fm
= getSupportFragmentManager();
582 FragmentTransaction ft
= fm
.beginTransaction();
583 loading
.show(ft
, DIALOG_WAIT_TAG
);
589 * Dismiss loading dialog
591 public void dismissLoadingDialog(){
592 Fragment frag
= getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG
);
594 LoadingDialog loading
= (LoadingDialog
) frag
;
600 private void doOnResumeAndBound() {
601 mOperationsServiceBinder
.addOperationListener(FileActivity
.this, mHandler
);
602 long waitingForOpId
= mFileOperationsHelper
.getOpIdWaitingFor();
603 if (waitingForOpId
<= Integer
.MAX_VALUE
) {
604 boolean wait
= mOperationsServiceBinder
.dispatchResultIfFinished((int)waitingForOpId
, this);
606 dismissLoadingDialog();
613 * Implements callback methods for service binding. Passed as a parameter to {
615 private class OperationsServiceConnection
implements ServiceConnection
{
618 public void onServiceConnected(ComponentName component
, IBinder service
) {
619 if (component
.equals(new ComponentName(FileActivity
.this, OperationsService
.class))) {
620 Log_OC
.d(TAG
, "Operations service connected");
621 mOperationsServiceBinder
= (OperationsServiceBinder
) service
;
622 /*if (!mOperationsServiceBinder.isPerformingBlockingOperation()) {
623 dismissLoadingDialog();
625 doOnResumeAndBound();
634 public void onServiceDisconnected(ComponentName component
) {
635 if (component
.equals(new ComponentName(FileActivity
.this, OperationsService
.class))) {
636 Log_OC
.d(TAG
, "Operations service disconnected");
637 mOperationsServiceBinder
= null
;
638 // TODO whatever could be waiting for the service is unbound
645 public FileDownloaderBinder
getFileDownloaderBinder() {
646 return mDownloaderBinder
;
651 public FileUploaderBinder
getFileUploaderBinder() {
652 return mUploaderBinder
;