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";
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 private boolean mAccountWasSet
;
102 /** Flag to signal when the value of mAccount was restored from a saved state */
103 private 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
;
126 * Loads the ownCloud {@link Account} and main {@link OCFile} to be handled by the instance of
127 * the {@link FileActivity}.
129 * Grants that a valid ownCloud {@link Account} is associated to the instance, or that the user
130 * is requested to create a new one.
133 protected void onCreate(Bundle savedInstanceState
) {
134 super.onCreate(savedInstanceState
);
135 mHandler
= new Handler();
136 mFileOperationsHelper
= new FileOperationsHelper(this);
138 if(savedInstanceState
!= null
) {
139 account
= savedInstanceState
.getParcelable(FileActivity
.EXTRA_ACCOUNT
);
140 mFile
= savedInstanceState
.getParcelable(FileActivity
.EXTRA_FILE
);
141 mFromNotification
= savedInstanceState
.getBoolean(FileActivity
.EXTRA_FROM_NOTIFICATION
);
142 mFileOperationsHelper
.setOpIdWaitingFor(
143 savedInstanceState
.getLong(KEY_WAITING_FOR_OP_ID
, Long
.MAX_VALUE
)
146 account
= getIntent().getParcelableExtra(FileActivity
.EXTRA_ACCOUNT
);
147 mFile
= getIntent().getParcelableExtra(FileActivity
.EXTRA_FILE
);
148 mFromNotification
= getIntent().getBooleanExtra(FileActivity
.EXTRA_FROM_NOTIFICATION
, false
);
151 setAccount(account
, savedInstanceState
!= null
);
153 mOperationsServiceConnection
= new OperationsServiceConnection();
154 bindService(new Intent(this, OperationsService
.class), mOperationsServiceConnection
, Context
.BIND_AUTO_CREATE
);
156 mDownloadServiceConnection
= newTransferenceServiceConnection();
157 if (mDownloadServiceConnection
!= null
) {
158 bindService(new Intent(this, FileDownloader
.class), mDownloadServiceConnection
, Context
.BIND_AUTO_CREATE
);
160 mUploadServiceConnection
= newTransferenceServiceConnection();
161 if (mUploadServiceConnection
!= null
) {
162 bindService(new Intent(this, FileUploader
.class), mUploadServiceConnection
, Context
.BIND_AUTO_CREATE
);
169 * Since ownCloud {@link Account}s can be managed from the system setting menu,
170 * the existence of the {@link Account} associated to the instance must be checked
171 * every time it is restarted.
174 protected void onRestart() {
176 boolean validAccount
= (mAccount
!= null
&& AccountUtils
.setCurrentOwnCloudAccount(getApplicationContext(), mAccount
.name
));
178 swapToDefaultAccount();
184 protected void onStart() {
187 if (mAccountWasSet
) {
188 onAccountSet(mAccountWasRestored
);
193 protected void onResume() {
196 if (mOperationsServiceBinder
!= null
) {
197 doOnResumeAndBound();
203 protected void onPause() {
205 if (mOperationsServiceBinder
!= null
) {
206 mOperationsServiceBinder
.removeOperationListener(this);
214 protected void onDestroy() {
215 if (mOperationsServiceConnection
!= null
) {
216 unbindService(mOperationsServiceConnection
);
217 mOperationsServiceBinder
= null
;
219 if (mDownloadServiceConnection
!= null
) {
220 unbindService(mDownloadServiceConnection
);
221 mDownloadServiceConnection
= null
;
223 if (mUploadServiceConnection
!= null
) {
224 unbindService(mUploadServiceConnection
);
225 mUploadServiceConnection
= null
;
233 * Sets and validates the ownCloud {@link Account} associated to the Activity.
235 * If not valid, tries to swap it for other valid and existing ownCloud {@link Account}.
237 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
239 * @param account New {@link Account} to set.
240 * @param savedAccount When 'true', account was retrieved from a saved instance state.
242 private void setAccount(Account account
, boolean savedAccount
) {
243 Account oldAccount
= mAccount
;
244 boolean validAccount
= (account
!= null
&& AccountUtils
.setCurrentOwnCloudAccount(getApplicationContext(), account
.name
));
247 mAccountWasSet
= true
;
248 mAccountWasRestored
= (savedAccount
|| mAccount
.equals(oldAccount
));
251 swapToDefaultAccount();
257 * Tries to swap the current ownCloud {@link Account} for other valid and existing.
259 * If no valid ownCloud {@link Account} exists, the the user is requested
260 * to create a new ownCloud {@link Account}.
262 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
264 private void swapToDefaultAccount() {
265 // default to the most recently used account
266 Account newAccount
= AccountUtils
.getCurrentOwnCloudAccount(getApplicationContext());
267 if (newAccount
== null
) {
268 /// no account available: force account creation
269 createFirstAccount();
270 mRedirectingToSetupAccount
= true
;
271 mAccountWasSet
= false
;
272 mAccountWasRestored
= false
;
275 mAccountWasSet
= true
;
276 mAccountWasRestored
= (newAccount
.equals(mAccount
));
277 mAccount
= newAccount
;
283 * Launches the account creation activity. To use when no ownCloud account is available
285 private void createFirstAccount() {
286 AccountManager am
= AccountManager
.get(getApplicationContext());
287 am
.addAccount(MainApp
.getAccountType(),
292 new AccountCreationCallback(),
301 protected void onSaveInstanceState(Bundle outState
) {
302 super.onSaveInstanceState(outState
);
303 outState
.putParcelable(FileActivity
.EXTRA_FILE
, mFile
);
304 outState
.putParcelable(FileActivity
.EXTRA_ACCOUNT
, mAccount
);
305 outState
.putBoolean(FileActivity
.EXTRA_FROM_NOTIFICATION
, mFromNotification
);
306 outState
.putLong(KEY_WAITING_FOR_OP_ID
, mFileOperationsHelper
.getOpIdWaitingFor());
311 * Getter for the main {@link OCFile} handled by the activity.
313 * @return Main {@link OCFile} handled by the activity.
315 public OCFile
getFile() {
321 * Setter for the main {@link OCFile} handled by the activity.
323 * @param file Main {@link OCFile} to be handled by the activity.
325 public void setFile(OCFile file
) {
331 * Getter for the ownCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
333 * @return OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
335 public Account
getAccount() {
340 * @return Value of mFromNotification: True if the Activity is launched by a notification
342 public boolean fromNotification() {
343 return mFromNotification
;
347 * @return 'True' when the Activity is finishing to enforce the setup of a new account.
349 protected boolean isRedirectingToSetupAccount() {
350 return mRedirectingToSetupAccount
;
354 public OperationsServiceBinder
getOperationsServiceBinder() {
355 return mOperationsServiceBinder
;
358 protected ServiceConnection
newTransferenceServiceConnection() {
363 * Helper class handling a callback from the {@link AccountManager} after the creation of
364 * a new ownCloud {@link Account} finished, successfully or not.
366 * At this moment, only called after the creation of the first account.
368 public class AccountCreationCallback
implements AccountManagerCallback
<Bundle
> {
371 public void run(AccountManagerFuture
<Bundle
> future
) {
372 FileActivity
.this.mRedirectingToSetupAccount
= false
;
373 boolean accountWasSet
= false
;
374 if (future
!= null
) {
377 result
= future
.getResult();
378 String name
= result
.getString(AccountManager
.KEY_ACCOUNT_NAME
);
379 String type
= result
.getString(AccountManager
.KEY_ACCOUNT_TYPE
);
380 if (AccountUtils
.setCurrentOwnCloudAccount(getApplicationContext(), name
)) {
381 setAccount(new Account(name
, type
), false
);
382 accountWasSet
= true
;
384 } catch (OperationCanceledException e
) {
385 Log_OC
.d(TAG
, "Account creation canceled");
387 } catch (Exception e
) {
388 Log_OC
.e(TAG
, "Account creation finished in exception: ", e
);
392 Log_OC
.e(TAG
, "Account creation callback with null bundle");
394 if (!accountWasSet
) {
395 moveTaskToBack(true
);
403 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
405 * Child classes must grant that state depending on the {@link Account} is updated.
407 protected void onAccountSet(boolean stateWasRecovered
) {
408 if (getAccount() != null
) {
409 mStorageManager
= new FileDataStorageManager(getAccount(), getContentResolver());
412 Log_OC
.wtf(TAG
, "onAccountChanged was called with NULL account associated!");
417 public FileDataStorageManager
getStorageManager() {
418 return mStorageManager
;
422 public OnRemoteOperationListener
getRemoteOperationListener() {
427 public Handler
getHandler() {
431 public FileOperationsHelper
getFileOperationsHelper() {
432 return mFileOperationsHelper
;
437 * @param operation Removal operation performed.
438 * @param result Result of the removal.
441 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
442 Log_OC
.d(TAG
, "Received result of operation in FileActivity - common behaviour for all the FileActivities ");
444 mFileOperationsHelper
.setOpIdWaitingFor(Long
.MAX_VALUE
);
446 if (!result
.isSuccess() && (
447 result
.getCode() == ResultCode
.UNAUTHORIZED
||
448 result
.isIdPRedirection() ||
449 (result
.isException() && result
.getException() instanceof AuthenticatorException
)
452 requestCredentialsUpdate();
454 if (result
.getCode() == ResultCode
.UNAUTHORIZED
) {
455 dismissLoadingDialog();
456 Toast t
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
461 } else if (operation
instanceof CreateShareOperation
) {
462 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
464 } else if (operation
instanceof UnshareLinkOperation
) {
465 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
467 } else if (operation
instanceof SynchronizeFolderOperation
) {
468 onSynchronizeFolderOperationFinish((SynchronizeFolderOperation
)operation
, result
);
473 protected void requestCredentialsUpdate() {
474 Intent updateAccountCredentials
= new Intent(this, AuthenticatorActivity
.class);
475 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACCOUNT
, getAccount());
476 updateAccountCredentials
.putExtra(
477 AuthenticatorActivity
.EXTRA_ACTION
,
478 AuthenticatorActivity
.ACTION_UPDATE_EXPIRED_TOKEN
);
479 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
480 startActivity(updateAccountCredentials
);
484 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
485 dismissLoadingDialog();
486 if (result
.isSuccess()) {
489 Intent sendIntent
= operation
.getSendIntent();
490 startActivity(sendIntent
);
493 // TODO Detect Failure (403) --> needs Password
494 if (result
.getCode() == ResultCode
.SHARE_FORBIDDEN
) {
495 SharePasswordDialogFragment dialog
=
496 SharePasswordDialogFragment
.newInstance(getFile());
497 dialog
.show(getSupportFragmentManager(), DIALOG_SHARE_PASSWORD
);
499 Toast t
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
507 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
508 dismissLoadingDialog();
510 if (result
.isSuccess()){
514 Toast t
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
520 private void onSynchronizeFolderOperationFinish(SynchronizeFolderOperation operation
, RemoteOperationResult result
) {
521 if (!result
.isSuccess() && result
.getCode() != ResultCode
.CANCELLED
){
522 Toast t
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
528 protected void updateFileFromDB(){
529 OCFile file
= getFile();
531 file
= getStorageManager().getFileByPath(file
.getRemotePath());
537 * Show loading dialog
539 public void showLoadingDialog() {
541 LoadingDialog loading
= new LoadingDialog(getResources().getString(R
.string
.wait_a_moment
));
542 FragmentManager fm
= getSupportFragmentManager();
543 FragmentTransaction ft
= fm
.beginTransaction();
544 loading
.show(ft
, DIALOG_WAIT_TAG
);
550 * Dismiss loading dialog
552 public void dismissLoadingDialog(){
553 Fragment frag
= getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG
);
555 LoadingDialog loading
= (LoadingDialog
) frag
;
561 private void doOnResumeAndBound() {
562 mOperationsServiceBinder
.addOperationListener(FileActivity
.this, mHandler
);
563 long waitingForOpId
= mFileOperationsHelper
.getOpIdWaitingFor();
564 if (waitingForOpId
<= Integer
.MAX_VALUE
) {
565 boolean wait
= mOperationsServiceBinder
.dispatchResultIfFinished((int)waitingForOpId
, this);
567 dismissLoadingDialog();
574 * Implements callback methods for service binding. Passed as a parameter to {
576 private class OperationsServiceConnection
implements ServiceConnection
{
579 public void onServiceConnected(ComponentName component
, IBinder service
) {
580 if (component
.equals(new ComponentName(FileActivity
.this, OperationsService
.class))) {
581 Log_OC
.d(TAG
, "Operations service connected");
582 mOperationsServiceBinder
= (OperationsServiceBinder
) service
;
583 /*if (!mOperationsServiceBinder.isPerformingBlockingOperation()) {
584 dismissLoadingDialog();
586 doOnResumeAndBound();
595 public void onServiceDisconnected(ComponentName component
) {
596 if (component
.equals(new ComponentName(FileActivity
.this, OperationsService
.class))) {
597 Log_OC
.d(TAG
, "Operations service disconnected");
598 mOperationsServiceBinder
= null
;
599 // TODO whatever could be waiting for the service is unbound
606 public FileDownloaderBinder
getFileDownloaderBinder() {
607 return mDownloaderBinder
;
612 public FileUploaderBinder
getFileUploaderBinder() {
613 return mUploaderBinder
;