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() {
200 Log_OC
.v(TAG
, "onStart() start");
203 if (mAccountWasSet
) {
204 onAccountSet(mAccountWasRestored
);
206 Log_OC
.v(TAG
, "onStart() end");
210 protected void onResume() {
211 Log_OC
.v(TAG
, "onResume() start");
214 if (mOperationsServiceBinder
!= null
) {
215 doOnResumeAndBound();
217 Log_OC
.v(TAG
, "onResume() end");
221 protected void onPause() {
222 Log_OC
.v(TAG
, "onPause() start");
224 if (mOperationsServiceBinder
!= null
) {
225 mOperationsServiceBinder
.removeOperationListener(this);
229 Log_OC
.v(TAG
, "onPause() end");
234 protected void onDestroy() {
235 Log_OC
.v(TAG
, "onDestroy() start");
236 if (mOperationsServiceConnection
!= null
) {
237 unbindService(mOperationsServiceConnection
);
238 mOperationsServiceBinder
= null
;
240 if (mDownloadServiceConnection
!= null
) {
241 unbindService(mDownloadServiceConnection
);
242 mDownloadServiceConnection
= null
;
244 if (mUploadServiceConnection
!= null
) {
245 unbindService(mUploadServiceConnection
);
246 mUploadServiceConnection
= null
;
250 Log_OC
.v(TAG
, "onDestroy() end");
255 * Sets and validates the ownCloud {@link Account} associated to the Activity.
257 * If not valid, tries to swap it for other valid and existing ownCloud {@link Account}.
259 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
261 * @param account New {@link Account} to set.
262 * @param savedAccount When 'true', account was retrieved from a saved instance state.
264 protected void setAccount(Account account
, boolean savedAccount
) {
265 Account oldAccount
= mAccount
;
266 boolean validAccount
=
267 (account
!= null
&& AccountUtils
.setCurrentOwnCloudAccount(getApplicationContext(), account
.name
));
270 mAccountWasSet
= true
;
271 mAccountWasRestored
= (savedAccount
|| mAccount
.equals(oldAccount
));
274 swapToDefaultAccount();
280 * Tries to swap the current ownCloud {@link Account} for other valid and existing.
282 * If no valid ownCloud {@link Account} exists, the the user is requested
283 * to create a new ownCloud {@link Account}.
285 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
287 private void swapToDefaultAccount() {
288 // default to the most recently used account
289 Account newAccount
= AccountUtils
.getCurrentOwnCloudAccount(getApplicationContext());
290 if (newAccount
== null
) {
291 /// no account available: force account creation
292 createFirstAccount();
293 mRedirectingToSetupAccount
= true
;
294 mAccountWasSet
= false
;
295 mAccountWasRestored
= false
;
298 mAccountWasSet
= true
;
299 mAccountWasRestored
= (newAccount
.equals(mAccount
));
300 mAccount
= newAccount
;
306 * Launches the account creation activity. To use when no ownCloud account is available
308 private void createFirstAccount() {
309 AccountManager am
= AccountManager
.get(getApplicationContext());
310 am
.addAccount(MainApp
.getAccountType(),
315 new AccountCreationCallback(),
324 protected void onSaveInstanceState(Bundle outState
) {
325 super.onSaveInstanceState(outState
);
326 outState
.putParcelable(FileActivity
.EXTRA_FILE
, mFile
);
327 outState
.putBoolean(FileActivity
.EXTRA_FROM_NOTIFICATION
, mFromNotification
);
328 outState
.putLong(KEY_WAITING_FOR_OP_ID
, mFileOperationsHelper
.getOpIdWaitingFor());
329 outState
.putBoolean(KEY_TRY_SHARE_AGAIN
, mTryShareAgain
);
334 * Getter for the main {@link OCFile} handled by the activity.
336 * @return Main {@link OCFile} handled by the activity.
338 public OCFile
getFile() {
344 * Setter for the main {@link OCFile} handled by the activity.
346 * @param file Main {@link OCFile} to be handled by the activity.
348 public void setFile(OCFile file
) {
354 * Getter for the ownCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
356 * @return OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
358 public Account
getAccount() {
362 protected void setAccount(Account account
) {
367 * @return Value of mFromNotification: True if the Activity is launched by a notification
369 public boolean fromNotification() {
370 return mFromNotification
;
374 * @return 'True' when the Activity is finishing to enforce the setup of a new account.
376 protected boolean isRedirectingToSetupAccount() {
377 return mRedirectingToSetupAccount
;
380 public boolean isTryShareAgain(){
381 return mTryShareAgain
;
384 public void setTryShareAgain(boolean tryShareAgain
) {
385 mTryShareAgain
= tryShareAgain
;
388 public OperationsServiceBinder
getOperationsServiceBinder() {
389 return mOperationsServiceBinder
;
392 protected ServiceConnection
newTransferenceServiceConnection() {
397 * Helper class handling a callback from the {@link AccountManager} after the creation of
398 * a new ownCloud {@link Account} finished, successfully or not.
400 * At this moment, only called after the creation of the first account.
402 public class AccountCreationCallback
implements AccountManagerCallback
<Bundle
> {
405 public void run(AccountManagerFuture
<Bundle
> future
) {
406 FileActivity
.this.mRedirectingToSetupAccount
= false
;
407 boolean accountWasSet
= false
;
408 if (future
!= null
) {
411 result
= future
.getResult();
412 String name
= result
.getString(AccountManager
.KEY_ACCOUNT_NAME
);
413 String type
= result
.getString(AccountManager
.KEY_ACCOUNT_TYPE
);
414 if (AccountUtils
.setCurrentOwnCloudAccount(getApplicationContext(), name
)) {
415 setAccount(new Account(name
, type
), false
);
416 accountWasSet
= true
;
418 } catch (OperationCanceledException e
) {
419 Log_OC
.d(TAG
, "Account creation canceled");
421 } catch (Exception e
) {
422 Log_OC
.e(TAG
, "Account creation finished in exception: ", e
);
426 Log_OC
.e(TAG
, "Account creation callback with null bundle");
428 if (!accountWasSet
) {
429 moveTaskToBack(true
);
437 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
439 * Child classes must grant that state depending on the {@link Account} is updated.
441 protected void onAccountSet(boolean stateWasRecovered
) {
442 if (getAccount() != null
) {
443 mStorageManager
= new FileDataStorageManager(getAccount(), getContentResolver());
446 Log_OC
.wtf(TAG
, "onAccountChanged was called with NULL account associated!");
451 public FileDataStorageManager
getStorageManager() {
452 return mStorageManager
;
456 public OnRemoteOperationListener
getRemoteOperationListener() {
461 public Handler
getHandler() {
465 public FileOperationsHelper
getFileOperationsHelper() {
466 return mFileOperationsHelper
;
471 * @param operation Removal operation performed.
472 * @param result Result of the removal.
475 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
476 Log_OC
.d(TAG
, "Received result of operation in FileActivity - common behaviour for all the FileActivities ");
478 mFileOperationsHelper
.setOpIdWaitingFor(Long
.MAX_VALUE
);
480 if (!result
.isSuccess() && (
481 result
.getCode() == ResultCode
.UNAUTHORIZED
||
482 result
.isIdPRedirection() ||
483 (result
.isException() && result
.getException() instanceof AuthenticatorException
)
486 requestCredentialsUpdate();
488 if (result
.getCode() == ResultCode
.UNAUTHORIZED
) {
489 dismissLoadingDialog();
490 Toast t
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
,
491 operation
, getResources()),
495 mTryShareAgain
= false
;
497 } else if (operation
instanceof CreateShareOperation
) {
498 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
500 } else if (operation
instanceof UnshareLinkOperation
) {
501 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
503 } else if (operation
instanceof SynchronizeFolderOperation
) {
504 onSynchronizeFolderOperationFinish((SynchronizeFolderOperation
)operation
, result
);
509 protected void requestCredentialsUpdate() {
510 Intent updateAccountCredentials
= new Intent(this, AuthenticatorActivity
.class);
511 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACCOUNT
, getAccount());
512 updateAccountCredentials
.putExtra(
513 AuthenticatorActivity
.EXTRA_ACTION
,
514 AuthenticatorActivity
.ACTION_UPDATE_EXPIRED_TOKEN
);
515 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
516 startActivity(updateAccountCredentials
);
520 private void onCreateShareOperationFinish(CreateShareOperation operation
,
521 RemoteOperationResult result
) {
522 dismissLoadingDialog();
523 if (result
.isSuccess()) {
524 mTryShareAgain
= false
;
527 Intent sendIntent
= operation
.getSendIntent();
528 startActivity(sendIntent
);
530 // Detect Failure (403) --> needs Password
531 if (result
.getCode() == ResultCode
.SHARE_FORBIDDEN
) {
532 if (!isTryShareAgain()) {
533 SharePasswordDialogFragment dialog
=
534 SharePasswordDialogFragment
.newInstance(new OCFile(operation
.getPath()),
535 operation
.getSendIntent());
536 dialog
.show(getSupportFragmentManager(), DIALOG_SHARE_PASSWORD
);
538 Toast t
= Toast
.makeText(this,
539 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
542 mTryShareAgain
= false
;
545 Toast t
= Toast
.makeText(this,
546 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
554 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
555 dismissLoadingDialog();
557 if (result
.isSuccess()){
561 Toast t
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
567 private void onSynchronizeFolderOperationFinish(
568 SynchronizeFolderOperation operation
, RemoteOperationResult result
570 if (!result
.isSuccess() && result
.getCode() != ResultCode
.CANCELLED
){
571 Toast t
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
577 protected void updateFileFromDB(){
578 OCFile file
= getFile();
580 file
= getStorageManager().getFileByPath(file
.getRemotePath());
586 * Show loading dialog
588 public void showLoadingDialog() {
590 LoadingDialog loading
= new LoadingDialog(getResources().getString(R
.string
.wait_a_moment
));
591 FragmentManager fm
= getSupportFragmentManager();
592 FragmentTransaction ft
= fm
.beginTransaction();
593 loading
.show(ft
, DIALOG_WAIT_TAG
);
599 * Dismiss loading dialog
601 public void dismissLoadingDialog(){
602 Fragment frag
= getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG
);
604 LoadingDialog loading
= (LoadingDialog
) frag
;
610 private void doOnResumeAndBound() {
611 mOperationsServiceBinder
.addOperationListener(FileActivity
.this, mHandler
);
612 long waitingForOpId
= mFileOperationsHelper
.getOpIdWaitingFor();
613 if (waitingForOpId
<= Integer
.MAX_VALUE
) {
614 boolean wait
= mOperationsServiceBinder
.dispatchResultIfFinished((int)waitingForOpId
, this);
616 dismissLoadingDialog();
623 * Implements callback methods for service binding. Passed as a parameter to {
625 private class OperationsServiceConnection
implements ServiceConnection
{
628 public void onServiceConnected(ComponentName component
, IBinder service
) {
629 if (component
.equals(new ComponentName(FileActivity
.this, OperationsService
.class))) {
630 Log_OC
.d(TAG
, "Operations service connected");
631 mOperationsServiceBinder
= (OperationsServiceBinder
) service
;
632 /*if (!mOperationsServiceBinder.isPerformingBlockingOperation()) {
633 dismissLoadingDialog();
635 doOnResumeAndBound();
644 public void onServiceDisconnected(ComponentName component
) {
645 if (component
.equals(new ComponentName(FileActivity
.this, OperationsService
.class))) {
646 Log_OC
.d(TAG
, "Operations service disconnected");
647 mOperationsServiceBinder
= null
;
648 // TODO whatever could be waiting for the service is unbound
655 public FileDownloaderBinder
getFileDownloaderBinder() {
656 return mDownloaderBinder
;
661 public FileUploaderBinder
getFileUploaderBinder() {
662 return mUploaderBinder
;