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
.lib
.common
.utils
.Log_OC
;
56 import com
.owncloud
.android
.operations
.CreateShareOperation
;
57 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
58 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
60 import com
.owncloud
.android
.services
.OperationsService
;
61 import com
.owncloud
.android
.services
.OperationsService
.OperationsServiceBinder
;
62 import com
.owncloud
.android
.ui
.dialog
.LoadingDialog
;
63 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
67 * Activity with common behaviour for activities handling {@link OCFile}s in ownCloud {@link Account}s .
69 * @author David A. Velasco
71 public class FileActivity
extends SherlockFragmentActivity
72 implements OnRemoteOperationListener
, ComponentsGetter
{
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_WAITING_TO_PREVIEW
= "com.owncloud.android.ui.activity.WAITING_TO_PREVIEW";
77 public static final String EXTRA_FROM_NOTIFICATION
= "com.owncloud.android.ui.activity.FROM_NOTIFICATION";
79 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";;
84 protected static final long DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
= 200;
87 /** OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located. */
88 private Account mAccount
;
90 /** Main {@link OCFile} handled by the activity.*/
93 /** Flag to signal that the activity will is finishing to enforce the creation of an ownCloud {@link Account} */
94 private boolean mRedirectingToSetupAccount
= false
;
96 /** Flag to signal when the value of mAccount was set */
97 private boolean mAccountWasSet
;
99 /** Flag to signal when the value of mAccount was restored from a saved state */
100 private boolean mAccountWasRestored
;
102 /** Flag to signal if the activity is launched by a notification */
103 private boolean mFromNotification
;
105 /** Messages handler associated to the main thread and the life cycle of the activity */
106 private Handler mHandler
;
108 /** Access point to the cached database for the current ownCloud {@link Account} */
109 private FileDataStorageManager mStorageManager
= null
;
111 private FileOperationsHelper mFileOperationsHelper
;
113 private ServiceConnection mOperationsServiceConnection
= null
;
115 private OperationsServiceBinder mOperationsServiceBinder
= null
;
117 protected FileDownloaderBinder mDownloaderBinder
= null
;
118 protected FileUploaderBinder mUploaderBinder
= null
;
119 private ServiceConnection mDownloadServiceConnection
, mUploadServiceConnection
= null
;
123 * Loads the ownCloud {@link Account} and main {@link OCFile} to be handled by the instance of
124 * the {@link FileActivity}.
126 * Grants that a valid ownCloud {@link Account} is associated to the instance, or that the user
127 * is requested to create a new one.
130 protected void onCreate(Bundle savedInstanceState
) {
131 super.onCreate(savedInstanceState
);
132 mHandler
= new Handler();
133 mFileOperationsHelper
= new FileOperationsHelper(this);
135 if(savedInstanceState
!= null
) {
136 account
= savedInstanceState
.getParcelable(FileActivity
.EXTRA_ACCOUNT
);
137 mFile
= savedInstanceState
.getParcelable(FileActivity
.EXTRA_FILE
);
138 mFromNotification
= savedInstanceState
.getBoolean(FileActivity
.EXTRA_FROM_NOTIFICATION
);
139 mFileOperationsHelper
.setOpIdWaitingFor(
140 savedInstanceState
.getLong(KEY_WAITING_FOR_OP_ID
, Long
.MAX_VALUE
)
143 account
= getIntent().getParcelableExtra(FileActivity
.EXTRA_ACCOUNT
);
144 mFile
= getIntent().getParcelableExtra(FileActivity
.EXTRA_FILE
);
145 mFromNotification
= getIntent().getBooleanExtra(FileActivity
.EXTRA_FROM_NOTIFICATION
, false
);
148 setAccount(account
, savedInstanceState
!= null
);
150 mOperationsServiceConnection
= new OperationsServiceConnection();
151 bindService(new Intent(this, OperationsService
.class), mOperationsServiceConnection
, Context
.BIND_AUTO_CREATE
);
153 mDownloadServiceConnection
= newTransferenceServiceConnection();
154 if (mDownloadServiceConnection
!= null
) {
155 bindService(new Intent(this, FileDownloader
.class), mDownloadServiceConnection
, Context
.BIND_AUTO_CREATE
);
157 mUploadServiceConnection
= newTransferenceServiceConnection();
158 if (mUploadServiceConnection
!= null
) {
159 bindService(new Intent(this, FileUploader
.class), mUploadServiceConnection
, Context
.BIND_AUTO_CREATE
);
166 * Since ownCloud {@link Account}s can be managed from the system setting menu,
167 * the existence of the {@link Account} associated to the instance must be checked
168 * every time it is restarted.
171 protected void onRestart() {
173 boolean validAccount
= (mAccount
!= null
&& AccountUtils
.setCurrentOwnCloudAccount(getApplicationContext(), mAccount
.name
));
175 swapToDefaultAccount();
181 protected void onStart() {
184 if (mAccountWasSet
) {
185 onAccountSet(mAccountWasRestored
);
190 protected void onResume() {
193 if (mOperationsServiceBinder
!= null
) {
194 doOnResumeAndBound();
200 protected void onPause() {
202 if (mOperationsServiceBinder
!= null
) {
203 mOperationsServiceBinder
.removeOperationListener(this);
211 protected void onDestroy() {
212 if (mOperationsServiceConnection
!= null
) {
213 unbindService(mOperationsServiceConnection
);
214 mOperationsServiceBinder
= null
;
216 if (mDownloadServiceConnection
!= null
) {
217 unbindService(mDownloadServiceConnection
);
218 mDownloadServiceConnection
= null
;
220 if (mUploadServiceConnection
!= null
) {
221 unbindService(mUploadServiceConnection
);
222 mUploadServiceConnection
= null
;
229 * Sets and validates the ownCloud {@link Account} associated to the Activity.
231 * If not valid, tries to swap it for other valid and existing ownCloud {@link Account}.
233 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
235 * @param account New {@link Account} to set.
236 * @param savedAccount When 'true', account was retrieved from a saved instance state.
238 private void setAccount(Account account
, boolean savedAccount
) {
239 Account oldAccount
= mAccount
;
240 boolean validAccount
= (account
!= null
&& AccountUtils
.setCurrentOwnCloudAccount(getApplicationContext(), account
.name
));
243 mAccountWasSet
= true
;
244 mAccountWasRestored
= (savedAccount
|| mAccount
.equals(oldAccount
));
247 swapToDefaultAccount();
253 * Tries to swap the current ownCloud {@link Account} for other valid and existing.
255 * If no valid ownCloud {@link Account} exists, the the user is requested
256 * to create a new ownCloud {@link Account}.
258 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
260 * @return 'True' if the checked {@link Account} was valid.
262 private void swapToDefaultAccount() {
263 // default to the most recently used account
264 Account newAccount
= AccountUtils
.getCurrentOwnCloudAccount(getApplicationContext());
265 if (newAccount
== null
) {
266 /// no account available: force account creation
267 createFirstAccount();
268 mRedirectingToSetupAccount
= true
;
269 mAccountWasSet
= false
;
270 mAccountWasRestored
= false
;
273 mAccountWasSet
= true
;
274 mAccountWasRestored
= (newAccount
.equals(mAccount
));
275 mAccount
= newAccount
;
281 * Launches the account creation activity. To use when no ownCloud account is available
283 private void createFirstAccount() {
284 AccountManager am
= AccountManager
.get(getApplicationContext());
285 am
.addAccount(MainApp
.getAccountType(),
290 new AccountCreationCallback(),
299 protected void onSaveInstanceState(Bundle outState
) {
300 super.onSaveInstanceState(outState
);
301 outState
.putParcelable(FileActivity
.EXTRA_FILE
, mFile
);
302 outState
.putParcelable(FileActivity
.EXTRA_ACCOUNT
, mAccount
);
303 outState
.putBoolean(FileActivity
.EXTRA_FROM_NOTIFICATION
, mFromNotification
);
304 outState
.putLong(KEY_WAITING_FOR_OP_ID
, mFileOperationsHelper
.getOpIdWaitingFor());
309 * Getter for the main {@link OCFile} handled by the activity.
311 * @return Main {@link OCFile} handled by the activity.
313 public OCFile
getFile() {
319 * Setter for the main {@link OCFile} handled by the activity.
321 * @param file Main {@link OCFile} to be handled by the activity.
323 public void setFile(OCFile file
) {
329 * Getter for the ownCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
331 * @return OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
333 public Account
getAccount() {
338 * @return Value of mFromNotification: True if the Activity is launched by a notification
340 public boolean fromNotification() {
341 return mFromNotification
;
345 * @return 'True' when the Activity is finishing to enforce the setup of a new account.
347 protected boolean isRedirectingToSetupAccount() {
348 return mRedirectingToSetupAccount
;
352 public OperationsServiceBinder
getOperationsServiceBinder() {
353 return mOperationsServiceBinder
;
356 protected ServiceConnection
newTransferenceServiceConnection() {
362 * Helper class handling a callback from the {@link AccountManager} after the creation of
363 * a new ownCloud {@link Account} finished, successfully or not.
365 * At this moment, only called after the creation of the first account.
367 * @author David A. Velasco
369 public class AccountCreationCallback
implements AccountManagerCallback
<Bundle
> {
372 public void run(AccountManagerFuture
<Bundle
> future
) {
373 FileActivity
.this.mRedirectingToSetupAccount
= false
;
374 boolean accountWasSet
= false
;
375 if (future
!= null
) {
378 result
= future
.getResult();
379 String name
= result
.getString(AccountManager
.KEY_ACCOUNT_NAME
);
380 String type
= result
.getString(AccountManager
.KEY_ACCOUNT_TYPE
);
381 if (AccountUtils
.setCurrentOwnCloudAccount(getApplicationContext(), name
)) {
382 setAccount(new Account(name
, type
), false
);
383 accountWasSet
= true
;
385 } catch (OperationCanceledException e
) {
386 Log_OC
.d(TAG
, "Account creation canceled");
388 } catch (Exception e
) {
389 Log_OC
.e(TAG
, "Account creation finished in exception: ", e
);
393 Log_OC
.e(TAG
, "Account creation callback with null bundle");
395 if (!accountWasSet
) {
396 moveTaskToBack(true
);
404 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
406 * Child classes must grant that state depending on the {@link Account} is updated.
408 protected void onAccountSet(boolean stateWasRecovered
) {
409 if (getAccount() != null
) {
410 mStorageManager
= new FileDataStorageManager(getAccount(), getContentResolver());
413 Log_OC
.wtf(TAG
, "onAccountChanged was called with NULL account associated!");
418 public FileDataStorageManager
getStorageManager() {
419 return mStorageManager
;
423 public OnRemoteOperationListener
getRemoteOperationListener() {
428 public Handler
getHandler() {
432 public FileOperationsHelper
getFileOperationsHelper() {
433 return mFileOperationsHelper
;
438 * @param operation Removal operation performed.
439 * @param result Result of the removal.
442 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
443 Log_OC
.d(TAG
, "Received result of operation in FileActivity - common behaviour for all the FileActivities ");
445 mFileOperationsHelper
.setOpIdWaitingFor(Long
.MAX_VALUE
);
447 if (!result
.isSuccess() && (
448 result
.getCode() == ResultCode
.UNAUTHORIZED
||
449 result
.isIdPRedirection() ||
450 (result
.isException() && result
.getException() instanceof AuthenticatorException
)
453 requestCredentialsUpdate();
455 if (result
.getCode() == ResultCode
.UNAUTHORIZED
) {
456 dismissLoadingDialog();
457 Toast t
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
462 } else if (operation
instanceof CreateShareOperation
) {
463 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
465 } else if (operation
instanceof UnshareLinkOperation
) {
466 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
468 } else if (operation
instanceof SynchronizeFolderOperation
) {
469 onSynchronizeFolderOperationFinish((SynchronizeFolderOperation
)operation
, result
);
474 protected void requestCredentialsUpdate() {
475 Intent updateAccountCredentials
= new Intent(this, AuthenticatorActivity
.class);
476 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACCOUNT
, getAccount());
477 updateAccountCredentials
.putExtra(
478 AuthenticatorActivity
.EXTRA_ACTION
,
479 AuthenticatorActivity
.ACTION_UPDATE_EXPIRED_TOKEN
);
480 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
481 startActivity(updateAccountCredentials
);
485 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
486 dismissLoadingDialog();
487 if (result
.isSuccess()) {
490 Intent sendIntent
= operation
.getSendIntent();
491 startActivity(sendIntent
);
494 Toast t
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
501 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
502 dismissLoadingDialog();
504 if (result
.isSuccess()){
508 Toast t
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
514 private void onSynchronizeFolderOperationFinish(SynchronizeFolderOperation operation
, RemoteOperationResult result
) {
515 if (!result
.isSuccess() && result
.getCode() != ResultCode
.CANCELLED
){
516 Toast t
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
522 protected void updateFileFromDB(){
523 OCFile file
= getFile();
525 file
= getStorageManager().getFileByPath(file
.getRemotePath());
531 * Show loading dialog
533 public void showLoadingDialog() {
535 LoadingDialog loading
= new LoadingDialog(getResources().getString(R
.string
.wait_a_moment
));
536 FragmentManager fm
= getSupportFragmentManager();
537 FragmentTransaction ft
= fm
.beginTransaction();
538 loading
.show(ft
, DIALOG_WAIT_TAG
);
544 * Dismiss loading dialog
546 public void dismissLoadingDialog(){
547 Fragment frag
= getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG
);
549 LoadingDialog loading
= (LoadingDialog
) frag
;
555 private void doOnResumeAndBound() {
556 mOperationsServiceBinder
.addOperationListener(FileActivity
.this, mHandler
);
557 long waitingForOpId
= mFileOperationsHelper
.getOpIdWaitingFor();
558 if (waitingForOpId
<= Integer
.MAX_VALUE
) {
559 boolean wait
= mOperationsServiceBinder
.dispatchResultIfFinished((int)waitingForOpId
, this);
561 dismissLoadingDialog();
568 * Implements callback methods for service binding. Passed as a parameter to {
570 private class OperationsServiceConnection
implements ServiceConnection
{
573 public void onServiceConnected(ComponentName component
, IBinder service
) {
574 if (component
.equals(new ComponentName(FileActivity
.this, OperationsService
.class))) {
575 Log_OC
.d(TAG
, "Operations service connected");
576 mOperationsServiceBinder
= (OperationsServiceBinder
) service
;
577 /*if (!mOperationsServiceBinder.isPerformingBlockingOperation()) {
578 dismissLoadingDialog();
580 doOnResumeAndBound();
589 public void onServiceDisconnected(ComponentName component
) {
590 if (component
.equals(new ComponentName(FileActivity
.this, OperationsService
.class))) {
591 Log_OC
.d(TAG
, "Operations service disconnected");
592 mOperationsServiceBinder
= null
;
593 // TODO whatever could be waiting for the service is unbound
600 public FileDownloaderBinder
getFileDownloaderBinder() {
601 return mDownloaderBinder
;
606 public FileUploaderBinder
getFileUploaderBinder() {
607 return mUploaderBinder
;