1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2015 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
.OnAccountsUpdateListener
;
27 import android
.accounts
.OperationCanceledException
;
28 import android
.content
.ComponentName
;
29 import android
.content
.Context
;
30 import android
.content
.Intent
;
31 import android
.content
.ServiceConnection
;
32 import android
.os
.Bundle
;
33 import android
.os
.Handler
;
34 import android
.os
.IBinder
;
35 import android
.support
.v4
.app
.Fragment
;
36 import android
.support
.v4
.app
.FragmentManager
;
37 import android
.support
.v4
.app
.FragmentTransaction
;
38 import android
.widget
.Toast
;
40 import com
.actionbarsherlock
.app
.SherlockFragmentActivity
;
41 import com
.owncloud
.android
.MainApp
;
42 import com
.owncloud
.android
.R
;
43 import com
.owncloud
.android
.authentication
.AccountUtils
;
44 import com
.owncloud
.android
.authentication
.AuthenticatorActivity
;
45 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
46 import com
.owncloud
.android
.datamodel
.OCFile
;
47 import com
.owncloud
.android
.files
.FileOperationsHelper
;
48 import com
.owncloud
.android
.files
.services
.FileDownloader
;
49 import com
.owncloud
.android
.files
.services
.FileUploader
;
50 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
51 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
52 import com
.owncloud
.android
.lib
.common
.operations
.OnRemoteOperationListener
;
53 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
54 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
55 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
56 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
57 import com
.owncloud
.android
.operations
.CreateShareOperation
;
58 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
59 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
61 import com
.owncloud
.android
.services
.OperationsService
;
62 import com
.owncloud
.android
.services
.OperationsService
.OperationsServiceBinder
;
63 import com
.owncloud
.android
.ui
.dialog
.LoadingDialog
;
64 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
68 * Activity with common behaviour for activities handling {@link OCFile}s in ownCloud {@link Account}s .
70 * @author David A. Velasco
72 public class FileActivity
extends SherlockFragmentActivity
73 implements OnRemoteOperationListener
, ComponentsGetter
, OnAccountsUpdateListener
{
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";
85 protected static final long DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
= 200;
88 /** OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located. */
89 private Account mAccount
;
91 /** Main {@link OCFile} handled by the activity.*/
94 /** Flag to signal that the activity will is finishing to enforce the creation of an ownCloud {@link Account} */
95 private boolean mRedirectingToSetupAccount
= false
;
97 /** Flag to signal when the value of mAccount was set */
98 private boolean mAccountWasSet
;
100 /** Flag to signal when the value of mAccount was restored from a saved state */
101 private boolean mAccountWasRestored
;
103 /** Flag to signal if the activity is launched by a notification */
104 private boolean mFromNotification
;
106 /** Messages handler associated to the main thread and the life cycle of the activity */
107 private Handler mHandler
;
109 /** Access point to the cached database for the current ownCloud {@link Account} */
110 private FileDataStorageManager mStorageManager
= null
;
112 private FileOperationsHelper mFileOperationsHelper
;
114 private ServiceConnection mOperationsServiceConnection
= null
;
116 private OperationsServiceBinder mOperationsServiceBinder
= null
;
118 protected FileDownloaderBinder mDownloaderBinder
= null
;
119 protected FileUploaderBinder mUploaderBinder
= null
;
120 private ServiceConnection mDownloadServiceConnection
, mUploadServiceConnection
= null
;
124 * Loads the ownCloud {@link Account} and main {@link OCFile} to be handled by the instance of
125 * the {@link FileActivity}.
127 * Grants that a valid ownCloud {@link Account} is associated to the instance, or that the user
128 * is requested to create a new one.
131 protected void onCreate(Bundle savedInstanceState
) {
132 super.onCreate(savedInstanceState
);
133 mHandler
= new Handler();
134 mFileOperationsHelper
= new FileOperationsHelper(this);
136 if(savedInstanceState
!= null
) {
137 account
= savedInstanceState
.getParcelable(FileActivity
.EXTRA_ACCOUNT
);
138 mFile
= savedInstanceState
.getParcelable(FileActivity
.EXTRA_FILE
);
139 mFromNotification
= savedInstanceState
.getBoolean(FileActivity
.EXTRA_FROM_NOTIFICATION
);
140 mFileOperationsHelper
.setOpIdWaitingFor(
141 savedInstanceState
.getLong(KEY_WAITING_FOR_OP_ID
, Long
.MAX_VALUE
)
144 account
= getIntent().getParcelableExtra(FileActivity
.EXTRA_ACCOUNT
);
145 mFile
= getIntent().getParcelableExtra(FileActivity
.EXTRA_FILE
);
146 mFromNotification
= getIntent().getBooleanExtra(FileActivity
.EXTRA_FROM_NOTIFICATION
, false
);
149 setAccount(account
, savedInstanceState
!= null
);
151 mOperationsServiceConnection
= new OperationsServiceConnection();
152 bindService(new Intent(this, OperationsService
.class), mOperationsServiceConnection
, Context
.BIND_AUTO_CREATE
);
154 mDownloadServiceConnection
= newTransferenceServiceConnection();
155 if (mDownloadServiceConnection
!= null
) {
156 bindService(new Intent(this, FileDownloader
.class), mDownloadServiceConnection
, Context
.BIND_AUTO_CREATE
);
158 mUploadServiceConnection
= newTransferenceServiceConnection();
159 if (mUploadServiceConnection
!= null
) {
160 bindService(new Intent(this, FileUploader
.class), mUploadServiceConnection
, Context
.BIND_AUTO_CREATE
);
163 // add AccountsUpdatedListener
164 AccountManager am
= AccountManager
.get(getApplicationContext());
165 am
.addOnAccountsUpdatedListener(this, null
, false
);
171 * Since ownCloud {@link Account}s can be managed from the system setting menu,
172 * the existence of the {@link Account} associated to the instance must be checked
173 * every time it is restarted.
176 protected void onRestart() {
178 boolean validAccount
= (mAccount
!= null
&& AccountUtils
.setCurrentOwnCloudAccount(getApplicationContext(), mAccount
.name
));
180 swapToDefaultAccount();
186 protected void onStart() {
189 if (mAccountWasSet
) {
190 onAccountSet(mAccountWasRestored
);
195 protected void onResume() {
198 if (mOperationsServiceBinder
!= null
) {
199 doOnResumeAndBound();
205 protected void onPause() {
207 if (mOperationsServiceBinder
!= null
) {
208 mOperationsServiceBinder
.removeOperationListener(this);
216 protected void onDestroy() {
217 if (mOperationsServiceConnection
!= null
) {
218 unbindService(mOperationsServiceConnection
);
219 mOperationsServiceBinder
= null
;
221 if (mDownloadServiceConnection
!= null
) {
222 unbindService(mDownloadServiceConnection
);
223 mDownloadServiceConnection
= null
;
225 if (mUploadServiceConnection
!= null
) {
226 unbindService(mUploadServiceConnection
);
227 mUploadServiceConnection
= null
;
230 // remove AccountsUpdatedListener
231 AccountManager am
= AccountManager
.get(getApplicationContext());
232 am
.removeOnAccountsUpdatedListener(this);
239 * Sets and validates the ownCloud {@link Account} associated to the Activity.
241 * If not valid, tries to swap it for other valid and existing ownCloud {@link Account}.
243 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
245 * @param account New {@link Account} to set.
246 * @param savedAccount When 'true', account was retrieved from a saved instance state.
248 private void setAccount(Account account
, boolean savedAccount
) {
249 Account oldAccount
= mAccount
;
250 boolean validAccount
= (account
!= null
&& AccountUtils
.setCurrentOwnCloudAccount(getApplicationContext(), account
.name
));
253 mAccountWasSet
= true
;
254 mAccountWasRestored
= (savedAccount
|| mAccount
.equals(oldAccount
));
257 swapToDefaultAccount();
263 * Tries to swap the current ownCloud {@link Account} for other valid and existing.
265 * If no valid ownCloud {@link Account} exists, the the user is requested
266 * to create a new ownCloud {@link Account}.
268 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
270 private void swapToDefaultAccount() {
271 // default to the most recently used account
272 Account newAccount
= AccountUtils
.getCurrentOwnCloudAccount(getApplicationContext());
273 if (newAccount
== null
) {
274 /// no account available: force account creation
275 createFirstAccount();
276 mRedirectingToSetupAccount
= true
;
277 mAccountWasSet
= false
;
278 mAccountWasRestored
= false
;
281 mAccountWasSet
= true
;
282 mAccountWasRestored
= (newAccount
.equals(mAccount
));
283 mAccount
= newAccount
;
289 * Launches the account creation activity. To use when no ownCloud account is available
291 private void createFirstAccount() {
292 AccountManager am
= AccountManager
.get(getApplicationContext());
293 am
.addAccount(MainApp
.getAccountType(),
298 new AccountCreationCallback(),
300 am
.addOnAccountsUpdatedListener(this, null
, true
);
308 protected void onSaveInstanceState(Bundle outState
) {
309 super.onSaveInstanceState(outState
);
310 outState
.putParcelable(FileActivity
.EXTRA_FILE
, mFile
);
311 outState
.putParcelable(FileActivity
.EXTRA_ACCOUNT
, mAccount
);
312 outState
.putBoolean(FileActivity
.EXTRA_FROM_NOTIFICATION
, mFromNotification
);
313 outState
.putLong(KEY_WAITING_FOR_OP_ID
, mFileOperationsHelper
.getOpIdWaitingFor());
318 * Getter for the main {@link OCFile} handled by the activity.
320 * @return Main {@link OCFile} handled by the activity.
322 public OCFile
getFile() {
328 * Setter for the main {@link OCFile} handled by the activity.
330 * @param file Main {@link OCFile} to be handled by the activity.
332 public void setFile(OCFile file
) {
338 * Getter for the ownCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
340 * @return OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
342 public Account
getAccount() {
347 * @return Value of mFromNotification: True if the Activity is launched by a notification
349 public boolean fromNotification() {
350 return mFromNotification
;
354 * @return 'True' when the Activity is finishing to enforce the setup of a new account.
356 protected boolean isRedirectingToSetupAccount() {
357 return mRedirectingToSetupAccount
;
361 public OperationsServiceBinder
getOperationsServiceBinder() {
362 return mOperationsServiceBinder
;
365 protected ServiceConnection
newTransferenceServiceConnection() {
370 public void onAccountsUpdated(Account
[] accounts
) {
371 // detect a change in the list of accounts
372 Log_OC
.d(TAG
, "onAccountsUpdated");
373 mDownloaderBinder
.reviewDownloads();
374 mUploaderBinder
.reviewUploads();
379 * Helper class handling a callback from the {@link AccountManager} after the creation of
380 * a new ownCloud {@link Account} finished, successfully or not.
382 * At this moment, only called after the creation of the first account.
384 * @author David A. Velasco
386 public class AccountCreationCallback
implements AccountManagerCallback
<Bundle
> {
389 public void run(AccountManagerFuture
<Bundle
> future
) {
390 FileActivity
.this.mRedirectingToSetupAccount
= false
;
391 boolean accountWasSet
= false
;
392 if (future
!= null
) {
395 result
= future
.getResult();
396 String name
= result
.getString(AccountManager
.KEY_ACCOUNT_NAME
);
397 String type
= result
.getString(AccountManager
.KEY_ACCOUNT_TYPE
);
398 if (AccountUtils
.setCurrentOwnCloudAccount(getApplicationContext(), name
)) {
399 setAccount(new Account(name
, type
), false
);
400 accountWasSet
= true
;
402 } catch (OperationCanceledException e
) {
403 Log_OC
.d(TAG
, "Account creation canceled");
405 } catch (Exception e
) {
406 Log_OC
.e(TAG
, "Account creation finished in exception: ", e
);
410 Log_OC
.e(TAG
, "Account creation callback with null bundle");
412 if (!accountWasSet
) {
413 moveTaskToBack(true
);
421 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
423 * Child classes must grant that state depending on the {@link Account} is updated.
425 protected void onAccountSet(boolean stateWasRecovered
) {
426 if (getAccount() != null
) {
427 mStorageManager
= new FileDataStorageManager(getAccount(), getContentResolver());
430 Log_OC
.wtf(TAG
, "onAccountChanged was called with NULL account associated!");
435 public FileDataStorageManager
getStorageManager() {
436 return mStorageManager
;
440 public OnRemoteOperationListener
getRemoteOperationListener() {
445 public Handler
getHandler() {
449 public FileOperationsHelper
getFileOperationsHelper() {
450 return mFileOperationsHelper
;
455 * @param operation Removal operation performed.
456 * @param result Result of the removal.
459 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
460 Log_OC
.d(TAG
, "Received result of operation in FileActivity - common behaviour for all the FileActivities ");
462 mFileOperationsHelper
.setOpIdWaitingFor(Long
.MAX_VALUE
);
464 if (!result
.isSuccess() && (
465 result
.getCode() == ResultCode
.UNAUTHORIZED
||
466 result
.isIdPRedirection() ||
467 (result
.isException() && result
.getException() instanceof AuthenticatorException
)
470 requestCredentialsUpdate();
472 if (result
.getCode() == ResultCode
.UNAUTHORIZED
) {
473 dismissLoadingDialog();
474 Toast t
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
479 } else if (operation
instanceof CreateShareOperation
) {
480 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
482 } else if (operation
instanceof UnshareLinkOperation
) {
483 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
485 } else if (operation
instanceof SynchronizeFolderOperation
) {
486 onSynchronizeFolderOperationFinish((SynchronizeFolderOperation
)operation
, result
);
491 protected void requestCredentialsUpdate() {
492 Intent updateAccountCredentials
= new Intent(this, AuthenticatorActivity
.class);
493 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACCOUNT
, getAccount());
494 updateAccountCredentials
.putExtra(
495 AuthenticatorActivity
.EXTRA_ACTION
,
496 AuthenticatorActivity
.ACTION_UPDATE_EXPIRED_TOKEN
);
497 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
498 startActivity(updateAccountCredentials
);
502 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
503 dismissLoadingDialog();
504 if (result
.isSuccess()) {
507 Intent sendIntent
= operation
.getSendIntent();
508 startActivity(sendIntent
);
511 Toast t
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
518 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
519 dismissLoadingDialog();
521 if (result
.isSuccess()){
525 Toast t
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
531 private void onSynchronizeFolderOperationFinish(SynchronizeFolderOperation operation
, RemoteOperationResult result
) {
532 if (!result
.isSuccess() && result
.getCode() != ResultCode
.CANCELLED
){
533 Toast t
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
539 protected void updateFileFromDB(){
540 OCFile file
= getFile();
542 file
= getStorageManager().getFileByPath(file
.getRemotePath());
548 * Show loading dialog
550 public void showLoadingDialog() {
552 LoadingDialog loading
= new LoadingDialog(getResources().getString(R
.string
.wait_a_moment
));
553 FragmentManager fm
= getSupportFragmentManager();
554 FragmentTransaction ft
= fm
.beginTransaction();
555 loading
.show(ft
, DIALOG_WAIT_TAG
);
561 * Dismiss loading dialog
563 public void dismissLoadingDialog(){
564 Fragment frag
= getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG
);
566 LoadingDialog loading
= (LoadingDialog
) frag
;
572 private void doOnResumeAndBound() {
573 mOperationsServiceBinder
.addOperationListener(FileActivity
.this, mHandler
);
574 long waitingForOpId
= mFileOperationsHelper
.getOpIdWaitingFor();
575 if (waitingForOpId
<= Integer
.MAX_VALUE
) {
576 boolean wait
= mOperationsServiceBinder
.dispatchResultIfFinished((int)waitingForOpId
, this);
578 dismissLoadingDialog();
585 * Implements callback methods for service binding. Passed as a parameter to {
587 private class OperationsServiceConnection
implements ServiceConnection
{
590 public void onServiceConnected(ComponentName component
, IBinder service
) {
591 if (component
.equals(new ComponentName(FileActivity
.this, OperationsService
.class))) {
592 Log_OC
.d(TAG
, "Operations service connected");
593 mOperationsServiceBinder
= (OperationsServiceBinder
) service
;
594 /*if (!mOperationsServiceBinder.isPerformingBlockingOperation()) {
595 dismissLoadingDialog();
597 doOnResumeAndBound();
606 public void onServiceDisconnected(ComponentName component
) {
607 if (component
.equals(new ComponentName(FileActivity
.this, OperationsService
.class))) {
608 Log_OC
.d(TAG
, "Operations service disconnected");
609 mOperationsServiceBinder
= null
;
610 // TODO whatever could be waiting for the service is unbound
617 public FileDownloaderBinder
getFileDownloaderBinder() {
618 return mDownloaderBinder
;
623 public FileUploaderBinder
getFileUploaderBinder() {
624 return mUploaderBinder
;