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);
139 Account account
= null
;
140 if(savedInstanceState
!= null
) {
141 mFile
= savedInstanceState
.getParcelable(FileActivity
.EXTRA_FILE
);
142 mFromNotification
= savedInstanceState
.getBoolean(FileActivity
.EXTRA_FROM_NOTIFICATION
);
143 mFileOperationsHelper
.setOpIdWaitingFor(
144 savedInstanceState
.getLong(KEY_WAITING_FOR_OP_ID
, Long
.MAX_VALUE
)
146 mTryShareAgain
= savedInstanceState
.getBoolean(KEY_TRY_SHARE_AGAIN
);
148 account
= getIntent().getParcelableExtra(FileActivity
.EXTRA_ACCOUNT
);
149 mFile
= getIntent().getParcelableExtra(FileActivity
.EXTRA_FILE
);
150 mFromNotification
= getIntent().getBooleanExtra(FileActivity
.EXTRA_FROM_NOTIFICATION
, false
);
153 AccountUtils
.updateAccountVersion(this); // best place, before any access to AccountManager or database
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
);
172 protected void onNewIntent (Intent intent
) {
173 Log_OC
.v(TAG
, "onNewIntent() start");
174 Account current
= AccountUtils
.getCurrentOwnCloudAccount(this);
175 if (current
!= null
&& mAccount
!= null
&& !mAccount
.name
.equals(current
.name
)) {
178 Log_OC
.v(TAG
, "onNewIntent() stop");
182 * Since ownCloud {@link Account}s can be managed from the system setting menu,
183 * the existence of the {@link Account} associated to the instance must be checked
184 * every time it is restarted.
187 protected void onRestart() {
188 Log_OC
.v(TAG
, "onRestart() start");
190 boolean validAccount
= (mAccount
!= null
&& AccountUtils
.exists(mAccount
, this));
192 swapToDefaultAccount();
194 Log_OC
.v(TAG
, "onRestart() end");
199 protected void onStart() {
202 if (mAccountWasSet
) {
203 onAccountSet(mAccountWasRestored
);
208 protected void onResume() {
211 if (mOperationsServiceBinder
!= null
) {
212 doOnResumeAndBound();
217 protected void onPause() {
218 if (mOperationsServiceBinder
!= null
) {
219 mOperationsServiceBinder
.removeOperationListener(this);
227 protected void onDestroy() {
228 if (mOperationsServiceConnection
!= null
) {
229 unbindService(mOperationsServiceConnection
);
230 mOperationsServiceBinder
= null
;
232 if (mDownloadServiceConnection
!= null
) {
233 unbindService(mDownloadServiceConnection
);
234 mDownloadServiceConnection
= null
;
236 if (mUploadServiceConnection
!= null
) {
237 unbindService(mUploadServiceConnection
);
238 mUploadServiceConnection
= null
;
246 * Sets and validates the ownCloud {@link Account} associated to the Activity.
248 * If not valid, tries to swap it for other valid and existing ownCloud {@link Account}.
250 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
252 * @param account New {@link Account} to set.
253 * @param savedAccount When 'true', account was retrieved from a saved instance state.
255 protected void setAccount(Account account
, boolean savedAccount
) {
256 Account oldAccount
= mAccount
;
257 boolean validAccount
=
258 (account
!= null
&& AccountUtils
.setCurrentOwnCloudAccount(getApplicationContext(), account
.name
));
261 mAccountWasSet
= true
;
262 mAccountWasRestored
= (savedAccount
|| mAccount
.equals(oldAccount
));
265 swapToDefaultAccount();
271 * Tries to swap the current ownCloud {@link Account} for other valid and existing.
273 * If no valid ownCloud {@link Account} exists, the the user is requested
274 * to create a new ownCloud {@link Account}.
276 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
278 private void swapToDefaultAccount() {
279 // default to the most recently used account
280 Account newAccount
= AccountUtils
.getCurrentOwnCloudAccount(getApplicationContext());
281 if (newAccount
== null
) {
282 /// no account available: force account creation
283 createFirstAccount();
284 mRedirectingToSetupAccount
= true
;
285 mAccountWasSet
= false
;
286 mAccountWasRestored
= false
;
289 mAccountWasSet
= true
;
290 mAccountWasRestored
= (newAccount
.equals(mAccount
));
291 mAccount
= newAccount
;
297 * Launches the account creation activity. To use when no ownCloud account is available
299 private void createFirstAccount() {
300 AccountManager am
= AccountManager
.get(getApplicationContext());
301 am
.addAccount(MainApp
.getAccountType(),
306 new AccountCreationCallback(),
315 protected void onSaveInstanceState(Bundle outState
) {
316 super.onSaveInstanceState(outState
);
317 outState
.putParcelable(FileActivity
.EXTRA_FILE
, mFile
);
318 outState
.putBoolean(FileActivity
.EXTRA_FROM_NOTIFICATION
, mFromNotification
);
319 outState
.putLong(KEY_WAITING_FOR_OP_ID
, mFileOperationsHelper
.getOpIdWaitingFor());
320 outState
.putBoolean(KEY_TRY_SHARE_AGAIN
, mTryShareAgain
);
325 * Getter for the main {@link OCFile} handled by the activity.
327 * @return Main {@link OCFile} handled by the activity.
329 public OCFile
getFile() {
335 * Setter for the main {@link OCFile} handled by the activity.
337 * @param file Main {@link OCFile} to be handled by the activity.
339 public void setFile(OCFile file
) {
345 * Getter for the ownCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
347 * @return OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
349 public Account
getAccount() {
353 protected void setAccount(Account account
) {
358 * @return Value of mFromNotification: True if the Activity is launched by a notification
360 public boolean fromNotification() {
361 return mFromNotification
;
365 * @return 'True' when the Activity is finishing to enforce the setup of a new account.
367 protected boolean isRedirectingToSetupAccount() {
368 return mRedirectingToSetupAccount
;
371 public boolean isTryShareAgain(){
372 return mTryShareAgain
;
375 public void setTryShareAgain(boolean tryShareAgain
) {
376 mTryShareAgain
= tryShareAgain
;
379 public OperationsServiceBinder
getOperationsServiceBinder() {
380 return mOperationsServiceBinder
;
383 protected ServiceConnection
newTransferenceServiceConnection() {
388 * Helper class handling a callback from the {@link AccountManager} after the creation of
389 * a new ownCloud {@link Account} finished, successfully or not.
391 * At this moment, only called after the creation of the first account.
393 public class AccountCreationCallback
implements AccountManagerCallback
<Bundle
> {
396 public void run(AccountManagerFuture
<Bundle
> future
) {
397 FileActivity
.this.mRedirectingToSetupAccount
= false
;
398 boolean accountWasSet
= false
;
399 if (future
!= null
) {
402 result
= future
.getResult();
403 String name
= result
.getString(AccountManager
.KEY_ACCOUNT_NAME
);
404 String type
= result
.getString(AccountManager
.KEY_ACCOUNT_TYPE
);
405 if (AccountUtils
.setCurrentOwnCloudAccount(getApplicationContext(), name
)) {
406 setAccount(new Account(name
, type
), false
);
407 accountWasSet
= true
;
409 } catch (OperationCanceledException e
) {
410 Log_OC
.d(TAG
, "Account creation canceled");
412 } catch (Exception e
) {
413 Log_OC
.e(TAG
, "Account creation finished in exception: ", e
);
417 Log_OC
.e(TAG
, "Account creation callback with null bundle");
419 if (!accountWasSet
) {
420 moveTaskToBack(true
);
428 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
430 * Child classes must grant that state depending on the {@link Account} is updated.
432 protected void onAccountSet(boolean stateWasRecovered
) {
433 if (getAccount() != null
) {
434 mStorageManager
= new FileDataStorageManager(getAccount(), getContentResolver());
437 Log_OC
.wtf(TAG
, "onAccountChanged was called with NULL account associated!");
442 public FileDataStorageManager
getStorageManager() {
443 return mStorageManager
;
447 public OnRemoteOperationListener
getRemoteOperationListener() {
452 public Handler
getHandler() {
456 public FileOperationsHelper
getFileOperationsHelper() {
457 return mFileOperationsHelper
;
462 * @param operation Removal operation performed.
463 * @param result Result of the removal.
466 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
467 Log_OC
.d(TAG
, "Received result of operation in FileActivity - common behaviour for all the FileActivities ");
469 mFileOperationsHelper
.setOpIdWaitingFor(Long
.MAX_VALUE
);
471 if (!result
.isSuccess() && (
472 result
.getCode() == ResultCode
.UNAUTHORIZED
||
473 result
.isIdPRedirection() ||
474 (result
.isException() && result
.getException() instanceof AuthenticatorException
)
477 requestCredentialsUpdate();
479 if (result
.getCode() == ResultCode
.UNAUTHORIZED
) {
480 dismissLoadingDialog();
481 Toast t
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
,
482 operation
, getResources()),
486 mTryShareAgain
= false
;
488 } else if (operation
instanceof CreateShareOperation
) {
489 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
491 } else if (operation
instanceof UnshareLinkOperation
) {
492 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
494 } else if (operation
instanceof SynchronizeFolderOperation
) {
495 onSynchronizeFolderOperationFinish((SynchronizeFolderOperation
)operation
, result
);
500 protected void requestCredentialsUpdate() {
501 Intent updateAccountCredentials
= new Intent(this, AuthenticatorActivity
.class);
502 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACCOUNT
, getAccount());
503 updateAccountCredentials
.putExtra(
504 AuthenticatorActivity
.EXTRA_ACTION
,
505 AuthenticatorActivity
.ACTION_UPDATE_EXPIRED_TOKEN
);
506 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
507 startActivity(updateAccountCredentials
);
511 private void onCreateShareOperationFinish(CreateShareOperation operation
,
512 RemoteOperationResult result
) {
513 dismissLoadingDialog();
514 if (result
.isSuccess()) {
515 mTryShareAgain
= false
;
518 Intent sendIntent
= operation
.getSendIntent();
519 startActivity(sendIntent
);
521 // Detect Failure (403) --> needs Password
522 if (result
.getCode() == ResultCode
.SHARE_FORBIDDEN
) {
523 if (!isTryShareAgain()) {
524 SharePasswordDialogFragment dialog
=
525 SharePasswordDialogFragment
.newInstance(new OCFile(operation
.getPath()),
526 operation
.getSendIntent());
527 dialog
.show(getSupportFragmentManager(), DIALOG_SHARE_PASSWORD
);
529 Toast t
= Toast
.makeText(this,
530 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
533 mTryShareAgain
= false
;
536 Toast t
= Toast
.makeText(this,
537 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
545 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
546 dismissLoadingDialog();
548 if (result
.isSuccess()){
552 Toast t
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
558 private void onSynchronizeFolderOperationFinish(
559 SynchronizeFolderOperation operation
, RemoteOperationResult result
561 if (!result
.isSuccess() && result
.getCode() != ResultCode
.CANCELLED
){
562 Toast t
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
568 protected void updateFileFromDB(){
569 OCFile file
= getFile();
571 file
= getStorageManager().getFileByPath(file
.getRemotePath());
577 * Show loading dialog
579 public void showLoadingDialog() {
581 LoadingDialog loading
= new LoadingDialog(getResources().getString(R
.string
.wait_a_moment
));
582 FragmentManager fm
= getSupportFragmentManager();
583 FragmentTransaction ft
= fm
.beginTransaction();
584 loading
.show(ft
, DIALOG_WAIT_TAG
);
590 * Dismiss loading dialog
592 public void dismissLoadingDialog(){
593 Fragment frag
= getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG
);
595 LoadingDialog loading
= (LoadingDialog
) frag
;
601 private void doOnResumeAndBound() {
602 mOperationsServiceBinder
.addOperationListener(FileActivity
.this, mHandler
);
603 long waitingForOpId
= mFileOperationsHelper
.getOpIdWaitingFor();
604 if (waitingForOpId
<= Integer
.MAX_VALUE
) {
605 boolean wait
= mOperationsServiceBinder
.dispatchResultIfFinished((int)waitingForOpId
, this);
607 dismissLoadingDialog();
614 * Implements callback methods for service binding. Passed as a parameter to {
616 private class OperationsServiceConnection
implements ServiceConnection
{
619 public void onServiceConnected(ComponentName component
, IBinder service
) {
620 if (component
.equals(new ComponentName(FileActivity
.this, OperationsService
.class))) {
621 Log_OC
.d(TAG
, "Operations service connected");
622 mOperationsServiceBinder
= (OperationsServiceBinder
) service
;
623 /*if (!mOperationsServiceBinder.isPerformingBlockingOperation()) {
624 dismissLoadingDialog();
626 doOnResumeAndBound();
635 public void onServiceDisconnected(ComponentName component
) {
636 if (component
.equals(new ComponentName(FileActivity
.this, OperationsService
.class))) {
637 Log_OC
.d(TAG
, "Operations service disconnected");
638 mOperationsServiceBinder
= null
;
639 // TODO whatever could be waiting for the service is unbound
646 public FileDownloaderBinder
getFileDownloaderBinder() {
647 return mDownloaderBinder
;
652 public FileUploaderBinder
getFileUploaderBinder() {
653 return mUploaderBinder
;