1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2014 ownCloud Inc.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 package com
.owncloud
.android
.ui
.activity
;
21 import android
.accounts
.Account
;
22 import android
.accounts
.AccountManager
;
23 import android
.accounts
.AccountManagerCallback
;
24 import android
.accounts
.AccountManagerFuture
;
25 import android
.accounts
.AuthenticatorException
;
26 import android
.accounts
.OperationCanceledException
;
27 import android
.content
.ComponentName
;
28 import android
.content
.Context
;
29 import android
.content
.Intent
;
30 import android
.content
.ServiceConnection
;
31 import android
.os
.Bundle
;
32 import android
.os
.Handler
;
33 import android
.os
.IBinder
;
34 import android
.support
.v4
.app
.Fragment
;
35 import android
.support
.v4
.app
.FragmentManager
;
36 import android
.support
.v4
.app
.FragmentTransaction
;
37 import android
.widget
.Toast
;
39 import com
.actionbarsherlock
.app
.SherlockFragmentActivity
;
40 import com
.owncloud
.android
.MainApp
;
41 import com
.owncloud
.android
.R
;
42 import com
.owncloud
.android
.authentication
.AccountUtils
;
43 import com
.owncloud
.android
.authentication
.AuthenticatorActivity
;
44 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
45 import com
.owncloud
.android
.datamodel
.OCFile
;
46 import com
.owncloud
.android
.files
.FileOperationsHelper
;
47 import com
.owncloud
.android
.files
.services
.FileDownloader
;
48 import com
.owncloud
.android
.files
.services
.FileUploader
;
49 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
50 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
51 import com
.owncloud
.android
.lib
.common
.operations
.OnRemoteOperationListener
;
52 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
53 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
54 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
55 import com
.owncloud
.android
.operations
.CreateShareOperation
;
56 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
58 import com
.owncloud
.android
.services
.OperationsService
;
59 import com
.owncloud
.android
.services
.OperationsService
.OperationsServiceBinder
;
60 import com
.owncloud
.android
.ui
.dialog
.LoadingDialog
;
61 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
62 import com
.owncloud
.android
.utils
.Log_OC
;
66 * Activity with common behaviour for activities handling {@link OCFile}s in ownCloud {@link Account}s .
68 * @author David A. Velasco
70 public class FileActivity
extends SherlockFragmentActivity
71 implements OnRemoteOperationListener
, ComponentsGetter
{
73 public static final String EXTRA_FILE
= "com.owncloud.android.ui.activity.FILE";
74 public static final String EXTRA_ACCOUNT
= "com.owncloud.android.ui.activity.ACCOUNT";
75 public static final String EXTRA_WAITING_TO_PREVIEW
= "com.owncloud.android.ui.activity.WAITING_TO_PREVIEW";
76 public static final String EXTRA_FROM_NOTIFICATION
= "com.owncloud.android.ui.activity.FROM_NOTIFICATION";
78 public static final String TAG
= FileActivity
.class.getSimpleName();
80 private static final String DIALOG_WAIT_TAG
= "DIALOG_WAIT";
81 private static final String KEY_WAITING_FOR_OP_ID
= "WAITING_FOR_OP_ID";;
84 /** OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located. */
85 private Account mAccount
;
87 /** Main {@link OCFile} handled by the activity.*/
90 /** Flag to signal that the activity will is finishing to enforce the creation of an ownCloud {@link Account} */
91 private boolean mRedirectingToSetupAccount
= false
;
93 /** Flag to signal when the value of mAccount was set */
94 private boolean mAccountWasSet
;
96 /** Flag to signal when the value of mAccount was restored from a saved state */
97 private boolean mAccountWasRestored
;
99 /** Flag to signal if the activity is launched by a notification */
100 private boolean mFromNotification
;
102 /** Messages handler associated to the main thread and the life cycle of the activity */
103 private Handler mHandler
;
105 /** Access point to the cached database for the current ownCloud {@link Account} */
106 private FileDataStorageManager mStorageManager
= null
;
108 private FileOperationsHelper mFileOperationsHelper
;
110 private ServiceConnection mOperationsServiceConnection
= null
;
112 private OperationsServiceBinder mOperationsServiceBinder
= null
;
114 protected FileDownloaderBinder mDownloaderBinder
= null
;
115 protected FileUploaderBinder mUploaderBinder
= null
;
116 private ServiceConnection mDownloadServiceConnection
, mUploadServiceConnection
= null
;
120 * Loads the ownCloud {@link Account} and main {@link OCFile} to be handled by the instance of
121 * the {@link FileActivity}.
123 * Grants that a valid ownCloud {@link Account} is associated to the instance, or that the user
124 * is requested to create a new one.
127 protected void onCreate(Bundle savedInstanceState
) {
128 super.onCreate(savedInstanceState
);
129 mHandler
= new Handler();
130 mFileOperationsHelper
= new FileOperationsHelper(this);
132 if(savedInstanceState
!= null
) {
133 account
= savedInstanceState
.getParcelable(FileActivity
.EXTRA_ACCOUNT
);
134 mFile
= savedInstanceState
.getParcelable(FileActivity
.EXTRA_FILE
);
135 mFromNotification
= savedInstanceState
.getBoolean(FileActivity
.EXTRA_FROM_NOTIFICATION
);
136 mFileOperationsHelper
.setOpIdWaitingFor(
137 savedInstanceState
.getLong(KEY_WAITING_FOR_OP_ID
, Long
.MAX_VALUE
)
140 account
= getIntent().getParcelableExtra(FileActivity
.EXTRA_ACCOUNT
);
141 mFile
= getIntent().getParcelableExtra(FileActivity
.EXTRA_FILE
);
142 mFromNotification
= getIntent().getBooleanExtra(FileActivity
.EXTRA_FROM_NOTIFICATION
, false
);
145 setAccount(account
, savedInstanceState
!= null
);
147 mOperationsServiceConnection
= new OperationsServiceConnection();
148 bindService(new Intent(this, OperationsService
.class), mOperationsServiceConnection
, Context
.BIND_AUTO_CREATE
);
150 mDownloadServiceConnection
= newTransferenceServiceConnection();
151 if (mDownloadServiceConnection
!= null
) {
152 bindService(new Intent(this, FileDownloader
.class), mDownloadServiceConnection
, Context
.BIND_AUTO_CREATE
);
154 mUploadServiceConnection
= newTransferenceServiceConnection();
155 if (mUploadServiceConnection
!= null
) {
156 bindService(new Intent(this, FileUploader
.class), mUploadServiceConnection
, Context
.BIND_AUTO_CREATE
);
163 * Since ownCloud {@link Account}s can be managed from the system setting menu,
164 * the existence of the {@link Account} associated to the instance must be checked
165 * every time it is restarted.
168 protected void onRestart() {
170 boolean validAccount
= (mAccount
!= null
&& AccountUtils
.setCurrentOwnCloudAccount(getApplicationContext(), mAccount
.name
));
172 swapToDefaultAccount();
178 protected void onStart() {
181 if (mAccountWasSet
) {
182 onAccountSet(mAccountWasRestored
);
187 protected void onResume() {
190 if (mOperationsServiceBinder
!= null
) {
191 doOnResumeAndBound();
197 protected void onPause() {
199 if (mOperationsServiceBinder
!= null
) {
200 mOperationsServiceBinder
.removeOperationListener(this);
208 protected void onDestroy() {
209 if (mOperationsServiceConnection
!= null
) {
210 unbindService(mOperationsServiceConnection
);
211 mOperationsServiceBinder
= null
;
213 if (mDownloadServiceConnection
!= null
) {
214 unbindService(mDownloadServiceConnection
);
215 mDownloadServiceConnection
= null
;
217 if (mUploadServiceConnection
!= null
) {
218 unbindService(mUploadServiceConnection
);
219 mUploadServiceConnection
= null
;
226 * Sets and validates the ownCloud {@link Account} associated to the Activity.
228 * If not valid, tries to swap it for other valid and existing ownCloud {@link Account}.
230 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
232 * @param account New {@link Account} to set.
233 * @param savedAccount When 'true', account was retrieved from a saved instance state.
235 private void setAccount(Account account
, boolean savedAccount
) {
236 Account oldAccount
= mAccount
;
237 boolean validAccount
= (account
!= null
&& AccountUtils
.setCurrentOwnCloudAccount(getApplicationContext(), account
.name
));
240 mAccountWasSet
= true
;
241 mAccountWasRestored
= (savedAccount
|| mAccount
.equals(oldAccount
));
244 swapToDefaultAccount();
250 * Tries to swap the current ownCloud {@link Account} for other valid and existing.
252 * If no valid ownCloud {@link Account} exists, the the user is requested
253 * to create a new ownCloud {@link Account}.
255 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
257 * @return 'True' if the checked {@link Account} was valid.
259 private void swapToDefaultAccount() {
260 // default to the most recently used account
261 Account newAccount
= AccountUtils
.getCurrentOwnCloudAccount(getApplicationContext());
262 if (newAccount
== null
) {
263 /// no account available: force account creation
264 createFirstAccount();
265 mRedirectingToSetupAccount
= true
;
266 mAccountWasSet
= false
;
267 mAccountWasRestored
= false
;
270 mAccountWasSet
= true
;
271 mAccountWasRestored
= (newAccount
.equals(mAccount
));
272 mAccount
= newAccount
;
278 * Launches the account creation activity. To use when no ownCloud account is available
280 private void createFirstAccount() {
281 AccountManager am
= AccountManager
.get(getApplicationContext());
282 am
.addAccount(MainApp
.getAccountType(),
287 new AccountCreationCallback(),
296 protected void onSaveInstanceState(Bundle outState
) {
297 super.onSaveInstanceState(outState
);
298 outState
.putParcelable(FileActivity
.EXTRA_FILE
, mFile
);
299 outState
.putParcelable(FileActivity
.EXTRA_ACCOUNT
, mAccount
);
300 outState
.putBoolean(FileActivity
.EXTRA_FROM_NOTIFICATION
, mFromNotification
);
301 outState
.putLong(KEY_WAITING_FOR_OP_ID
, mFileOperationsHelper
.getOpIdWaitingFor());
306 * Getter for the main {@link OCFile} handled by the activity.
308 * @return Main {@link OCFile} handled by the activity.
310 public OCFile
getFile() {
316 * Setter for the main {@link OCFile} handled by the activity.
318 * @param file Main {@link OCFile} to be handled by the activity.
320 public void setFile(OCFile file
) {
326 * Getter for the ownCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
328 * @return OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
330 public Account
getAccount() {
335 * @return Value of mFromNotification: True if the Activity is launched by a notification
337 public boolean fromNotification() {
338 return mFromNotification
;
342 * @return 'True' when the Activity is finishing to enforce the setup of a new account.
344 protected boolean isRedirectingToSetupAccount() {
345 return mRedirectingToSetupAccount
;
349 public OperationsServiceBinder
getOperationsServiceBinder() {
350 return mOperationsServiceBinder
;
353 protected ServiceConnection
newTransferenceServiceConnection() {
359 * Helper class handling a callback from the {@link AccountManager} after the creation of
360 * a new ownCloud {@link Account} finished, successfully or not.
362 * At this moment, only called after the creation of the first account.
364 * @author David A. Velasco
366 public class AccountCreationCallback
implements AccountManagerCallback
<Bundle
> {
369 public void run(AccountManagerFuture
<Bundle
> future
) {
370 FileActivity
.this.mRedirectingToSetupAccount
= false
;
371 boolean accountWasSet
= false
;
372 if (future
!= null
) {
375 result
= future
.getResult();
376 String name
= result
.getString(AccountManager
.KEY_ACCOUNT_NAME
);
377 String type
= result
.getString(AccountManager
.KEY_ACCOUNT_TYPE
);
378 if (AccountUtils
.setCurrentOwnCloudAccount(getApplicationContext(), name
)) {
379 setAccount(new Account(name
, type
), false
);
380 accountWasSet
= true
;
382 } catch (OperationCanceledException e
) {
383 Log_OC
.d(TAG
, "Account creation canceled");
385 } catch (Exception e
) {
386 Log_OC
.e(TAG
, "Account creation finished in exception: ", e
);
390 Log_OC
.e(TAG
, "Account creation callback with null bundle");
392 if (!accountWasSet
) {
393 moveTaskToBack(true
);
401 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
403 * Child classes must grant that state depending on the {@link Account} is updated.
405 protected void onAccountSet(boolean stateWasRecovered
) {
406 if (getAccount() != null
) {
407 mStorageManager
= new FileDataStorageManager(getAccount(), getContentResolver());
410 Log_OC
.wtf(TAG
, "onAccountChanged was called with NULL account associated!");
415 public FileDataStorageManager
getStorageManager() {
416 return mStorageManager
;
420 public OnRemoteOperationListener
getRemoteOperationListener() {
425 public Handler
getHandler() {
429 public FileOperationsHelper
getFileOperationsHelper() {
430 return mFileOperationsHelper
;
435 * @param operation Removal operation performed.
436 * @param result Result of the removal.
439 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
440 Log_OC
.d(TAG
, "Received result of operation in FileActivity - common behaviour for all the FileActivities ");
442 mFileOperationsHelper
.setOpIdWaitingFor(Long
.MAX_VALUE
);
444 if (!result
.isSuccess() && (
445 result
.getCode() == ResultCode
.UNAUTHORIZED
||
446 result
.isIdPRedirection() ||
447 (result
.isException() && result
.getException() instanceof AuthenticatorException
)
450 requestCredentialsUpdate();
452 if (result
.getCode() == ResultCode
.UNAUTHORIZED
) {
453 dismissLoadingDialog();
454 Toast t
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
459 } else if (operation
instanceof CreateShareOperation
) {
460 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
462 } else if (operation
instanceof UnshareLinkOperation
) {
463 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
468 protected void requestCredentialsUpdate() {
469 Intent updateAccountCredentials
= new Intent(this, AuthenticatorActivity
.class);
470 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACCOUNT
, getAccount());
471 updateAccountCredentials
.putExtra(
472 AuthenticatorActivity
.EXTRA_ACTION
,
473 AuthenticatorActivity
.ACTION_UPDATE_EXPIRED_TOKEN
);
474 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
475 startActivity(updateAccountCredentials
);
479 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
480 dismissLoadingDialog();
481 if (result
.isSuccess()) {
484 Intent sendIntent
= operation
.getSendIntent();
485 startActivity(sendIntent
);
488 Toast t
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
495 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
496 dismissLoadingDialog();
498 if (result
.isSuccess()){
502 Toast t
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
509 protected void updateFileFromDB(){
510 OCFile file
= getFile();
512 file
= getStorageManager().getFileByPath(file
.getRemotePath());
518 * Show loading dialog
520 public void showLoadingDialog() {
522 LoadingDialog loading
= new LoadingDialog(getResources().getString(R
.string
.wait_a_moment
));
523 FragmentManager fm
= getSupportFragmentManager();
524 FragmentTransaction ft
= fm
.beginTransaction();
525 loading
.show(ft
, DIALOG_WAIT_TAG
);
531 * Dismiss loading dialog
533 public void dismissLoadingDialog(){
534 Fragment frag
= getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG
);
536 LoadingDialog loading
= (LoadingDialog
) frag
;
542 private void doOnResumeAndBound() {
543 mOperationsServiceBinder
.addOperationListener(FileActivity
.this, mHandler
);
544 long waitingForOpId
= mFileOperationsHelper
.getOpIdWaitingFor();
545 if (waitingForOpId
<= Integer
.MAX_VALUE
) {
546 boolean wait
= mOperationsServiceBinder
.dispatchResultIfFinished((int)waitingForOpId
, this);
548 dismissLoadingDialog();
555 * Implements callback methods for service binding. Passed as a parameter to {
557 private class OperationsServiceConnection
implements ServiceConnection
{
560 public void onServiceConnected(ComponentName component
, IBinder service
) {
561 if (component
.equals(new ComponentName(FileActivity
.this, OperationsService
.class))) {
562 Log_OC
.d(TAG
, "Operations service connected");
563 mOperationsServiceBinder
= (OperationsServiceBinder
) service
;
564 /*if (!mOperationsServiceBinder.isPerformingBlockingOperation()) {
565 dismissLoadingDialog();
567 doOnResumeAndBound();
576 public void onServiceDisconnected(ComponentName component
) {
577 if (component
.equals(new ComponentName(FileActivity
.this, OperationsService
.class))) {
578 Log_OC
.d(TAG
, "Operations service disconnected");
579 mOperationsServiceBinder
= null
;
580 // TODO whatever could be waiting for the service is unbound
587 public FileDownloaderBinder
getFileDownloaderBinder() {
588 return mDownloaderBinder
;
593 public FileUploaderBinder
getFileUploaderBinder() {
594 return mUploaderBinder
;