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
.operations
.CreateShareOperation
;
56 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
58 import com
.owncloud
.android
.services
.OperationsService
;
59 import com
.owncloud
.android
.services
.OperationsService
.OperationsServiceBinder
;
60 import com
.owncloud
.android
.ui
.dialog
.LoadingDialog
;
61 import com
.owncloud
.android
.utils
.Log_OC
;
65 * Activity with common behaviour for activities handling {@link OCFile}s in ownCloud {@link Account}s .
67 * @author David A. Velasco
69 public class FileActivity
extends SherlockFragmentActivity
70 implements OnRemoteOperationListener
, ComponentsGetter
{
72 public static final String EXTRA_FILE
= "com.owncloud.android.ui.activity.FILE";
73 public static final String EXTRA_ACCOUNT
= "com.owncloud.android.ui.activity.ACCOUNT";
74 public static final String EXTRA_WAITING_TO_PREVIEW
= "com.owncloud.android.ui.activity.WAITING_TO_PREVIEW";
75 public static final String EXTRA_FROM_NOTIFICATION
= "com.owncloud.android.ui.activity.FROM_NOTIFICATION";
77 public static final String TAG
= FileActivity
.class.getSimpleName();
79 private static final String DIALOG_WAIT_TAG
= "DIALOG_WAIT";
80 private static final String KEY_WAITING_FOR_OP_ID
= "WAITING_FOR_OP_ID";;
83 /** OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located. */
84 private Account mAccount
;
86 /** Main {@link OCFile} handled by the activity.*/
89 /** Flag to signal that the activity will is finishing to enforce the creation of an ownCloud {@link Account} */
90 private boolean mRedirectingToSetupAccount
= false
;
92 /** Flag to signal when the value of mAccount was set */
93 private boolean mAccountWasSet
;
95 /** Flag to signal when the value of mAccount was restored from a saved state */
96 private boolean mAccountWasRestored
;
98 /** Flag to signal if the activity is launched by a notification */
99 private boolean mFromNotification
;
101 /** Messages handler associated to the main thread and the life cycle of the activity */
102 private Handler mHandler
;
104 /** Access point to the cached database for the current ownCloud {@link Account} */
105 private FileDataStorageManager mStorageManager
= null
;
107 private FileOperationsHelper mFileOperationsHelper
;
109 private ServiceConnection mOperationsServiceConnection
= null
;
111 private OperationsServiceBinder mOperationsServiceBinder
= null
;
113 protected FileDownloaderBinder mDownloaderBinder
= null
;
114 protected FileUploaderBinder mUploaderBinder
= null
;
115 private ServiceConnection mDownloadServiceConnection
, mUploadServiceConnection
= null
;
119 * Loads the ownCloud {@link Account} and main {@link OCFile} to be handled by the instance of
120 * the {@link FileActivity}.
122 * Grants that a valid ownCloud {@link Account} is associated to the instance, or that the user
123 * is requested to create a new one.
126 protected void onCreate(Bundle savedInstanceState
) {
127 super.onCreate(savedInstanceState
);
128 mHandler
= new Handler();
129 mFileOperationsHelper
= new FileOperationsHelper(this);
131 if(savedInstanceState
!= null
) {
132 account
= savedInstanceState
.getParcelable(FileActivity
.EXTRA_ACCOUNT
);
133 mFile
= savedInstanceState
.getParcelable(FileActivity
.EXTRA_FILE
);
134 mFromNotification
= savedInstanceState
.getBoolean(FileActivity
.EXTRA_FROM_NOTIFICATION
);
135 mFileOperationsHelper
.setOpIdWaitingFor(
136 savedInstanceState
.getLong(KEY_WAITING_FOR_OP_ID
, Long
.MAX_VALUE
)
139 account
= getIntent().getParcelableExtra(FileActivity
.EXTRA_ACCOUNT
);
140 mFile
= getIntent().getParcelableExtra(FileActivity
.EXTRA_FILE
);
141 mFromNotification
= getIntent().getBooleanExtra(FileActivity
.EXTRA_FROM_NOTIFICATION
, false
);
144 setAccount(account
, savedInstanceState
!= null
);
146 mOperationsServiceConnection
= new OperationsServiceConnection();
147 bindService(new Intent(this, OperationsService
.class), mOperationsServiceConnection
, Context
.BIND_AUTO_CREATE
);
149 mDownloadServiceConnection
= newTransferenceServiceConnection();
150 if (mDownloadServiceConnection
!= null
) {
151 bindService(new Intent(this, FileDownloader
.class), mDownloadServiceConnection
, Context
.BIND_AUTO_CREATE
);
153 mUploadServiceConnection
= newTransferenceServiceConnection();
154 if (mUploadServiceConnection
!= null
) {
155 bindService(new Intent(this, FileUploader
.class), mUploadServiceConnection
, Context
.BIND_AUTO_CREATE
);
162 * Since ownCloud {@link Account}s can be managed from the system setting menu,
163 * the existence of the {@link Account} associated to the instance must be checked
164 * every time it is restarted.
167 protected void onRestart() {
169 boolean validAccount
= (mAccount
!= null
&& AccountUtils
.setCurrentOwnCloudAccount(getApplicationContext(), mAccount
.name
));
171 swapToDefaultAccount();
177 protected void onStart() {
180 if (mAccountWasSet
) {
181 onAccountSet(mAccountWasRestored
);
183 if (mOperationsServiceBinder
!= null
) {
184 mOperationsServiceBinder
.addOperationListener(FileActivity
.this, mHandler
);
189 protected void onResume() {
192 if (mOperationsServiceBinder
!= null
) {
193 doOnResumeAndBound();
199 protected void onPause() {
200 if (mOperationsServiceBinder
!= null
) {
201 mOperationsServiceBinder
.removeOperationListener(this);
208 protected void onStop() {
210 if (mOperationsServiceBinder
!= null
) {
211 mOperationsServiceBinder
.removeOperationListener(this);
219 protected void onDestroy() {
221 if (mOperationsServiceConnection
!= null
) {
222 unbindService(mOperationsServiceConnection
);
223 mOperationsServiceBinder
= null
;
225 if (mDownloadServiceConnection
!= null
) {
226 unbindService(mDownloadServiceConnection
);
227 mDownloadServiceConnection
= null
;
229 if (mUploadServiceConnection
!= null
) {
230 unbindService(mUploadServiceConnection
);
231 mUploadServiceConnection
= null
;
237 * Sets and validates the ownCloud {@link Account} associated to the Activity.
239 * If not valid, tries to swap it for other valid and existing ownCloud {@link Account}.
241 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
243 * @param account New {@link Account} to set.
244 * @param savedAccount When 'true', account was retrieved from a saved instance state.
246 private void setAccount(Account account
, boolean savedAccount
) {
247 Account oldAccount
= mAccount
;
248 boolean validAccount
= (account
!= null
&& AccountUtils
.setCurrentOwnCloudAccount(getApplicationContext(), account
.name
));
251 mAccountWasSet
= true
;
252 mAccountWasRestored
= (savedAccount
|| mAccount
.equals(oldAccount
));
255 swapToDefaultAccount();
261 * Tries to swap the current ownCloud {@link Account} for other valid and existing.
263 * If no valid ownCloud {@link Account} exists, the the user is requested
264 * to create a new ownCloud {@link Account}.
266 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
268 * @return 'True' if the checked {@link Account} was valid.
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(),
307 protected void onSaveInstanceState(Bundle outState
) {
308 super.onSaveInstanceState(outState
);
309 outState
.putParcelable(FileActivity
.EXTRA_FILE
, mFile
);
310 outState
.putParcelable(FileActivity
.EXTRA_ACCOUNT
, mAccount
);
311 outState
.putBoolean(FileActivity
.EXTRA_FROM_NOTIFICATION
, mFromNotification
);
312 outState
.putLong(KEY_WAITING_FOR_OP_ID
, mFileOperationsHelper
.getOpIdWaitingFor());
317 * Getter for the main {@link OCFile} handled by the activity.
319 * @return Main {@link OCFile} handled by the activity.
321 public OCFile
getFile() {
327 * Setter for the main {@link OCFile} handled by the activity.
329 * @param file Main {@link OCFile} to be handled by the activity.
331 public void setFile(OCFile file
) {
337 * Getter for the ownCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
339 * @return OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
341 public Account
getAccount() {
346 * @return Value of mFromNotification: True if the Activity is launched by a notification
348 public boolean fromNotification() {
349 return mFromNotification
;
353 * @return 'True' when the Activity is finishing to enforce the setup of a new account.
355 protected boolean isRedirectingToSetupAccount() {
356 return mRedirectingToSetupAccount
;
360 public OperationsServiceBinder
getOperationsServiceBinder() {
361 return mOperationsServiceBinder
;
364 protected ServiceConnection
newTransferenceServiceConnection() {
370 * Helper class handling a callback from the {@link AccountManager} after the creation of
371 * a new ownCloud {@link Account} finished, successfully or not.
373 * At this moment, only called after the creation of the first account.
375 * @author David A. Velasco
377 public class AccountCreationCallback
implements AccountManagerCallback
<Bundle
> {
380 public void run(AccountManagerFuture
<Bundle
> future
) {
381 FileActivity
.this.mRedirectingToSetupAccount
= false
;
382 boolean accountWasSet
= false
;
383 if (future
!= null
) {
386 result
= future
.getResult();
387 String name
= result
.getString(AccountManager
.KEY_ACCOUNT_NAME
);
388 String type
= result
.getString(AccountManager
.KEY_ACCOUNT_TYPE
);
389 if (AccountUtils
.setCurrentOwnCloudAccount(getApplicationContext(), name
)) {
390 setAccount(new Account(name
, type
), false
);
391 accountWasSet
= true
;
393 } catch (OperationCanceledException e
) {
394 Log_OC
.d(TAG
, "Account creation canceled");
396 } catch (Exception e
) {
397 Log_OC
.e(TAG
, "Account creation finished in exception: ", e
);
401 Log_OC
.e(TAG
, "Account creation callback with null bundle");
403 if (!accountWasSet
) {
404 moveTaskToBack(true
);
412 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
414 * Child classes must grant that state depending on the {@link Account} is updated.
416 protected void onAccountSet(boolean stateWasRecovered
) {
417 if (getAccount() != null
) {
418 mStorageManager
= new FileDataStorageManager(getAccount(), getContentResolver());
421 Log_OC
.wtf(TAG
, "onAccountChanged was called with NULL account associated!");
426 public FileDataStorageManager
getStorageManager() {
427 return mStorageManager
;
431 public OnRemoteOperationListener
getRemoteOperationListener() {
436 public Handler
getHandler() {
440 public FileOperationsHelper
getFileOperationsHelper() {
441 return mFileOperationsHelper
;
446 * @param operation Removal operation performed.
447 * @param result Result of the removal.
450 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
451 Log_OC
.d(TAG
, "Received result of operation in FileActivity - common behaviour for all the FileActivities ");
453 mFileOperationsHelper
.setOpIdWaitingFor(Long
.MAX_VALUE
);
455 if (!result
.isSuccess() && (
456 result
.getCode() == ResultCode
.UNAUTHORIZED
||
457 result
.isIdPRedirection() ||
458 (result
.isException() && result
.getException() instanceof AuthenticatorException
)
461 requestCredentialsUpdate();
463 } else if (operation
instanceof CreateShareOperation
) {
464 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
466 } else if (operation
instanceof UnshareLinkOperation
) {
467 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
472 private void requestCredentialsUpdate() {
473 Intent updateAccountCredentials
= new Intent(this, AuthenticatorActivity
.class);
474 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACCOUNT
, getAccount());
475 updateAccountCredentials
.putExtra(
476 AuthenticatorActivity
.EXTRA_ACTION
,
477 AuthenticatorActivity
.ACTION_UPDATE_EXPIRED_TOKEN
);
478 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
479 startActivity(updateAccountCredentials
);
483 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
484 dismissLoadingDialog();
485 if (result
.isSuccess()) {
488 Intent sendIntent
= operation
.getSendIntent();
489 startActivity(sendIntent
);
491 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) { // Error --> SHARE_NOT_FOUND
492 Toast t
= Toast
.makeText(this, getString(R
.string
.share_link_file_no_exist
), Toast
.LENGTH_LONG
);
494 } else { // Generic error
495 // Show a Message, operation finished without success
496 Toast t
= Toast
.makeText(this, getString(R
.string
.share_link_file_error
), Toast
.LENGTH_LONG
);
502 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
503 dismissLoadingDialog();
505 if (result
.isSuccess()){
508 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) { // Error --> SHARE_NOT_FOUND
509 Toast t
= Toast
.makeText(this, getString(R
.string
.unshare_link_file_no_exist
), Toast
.LENGTH_LONG
);
511 } else { // Generic error
512 // Show a Message, operation finished without success
513 Toast t
= Toast
.makeText(this, getString(R
.string
.unshare_link_file_error
), Toast
.LENGTH_LONG
);
520 private void updateFileFromDB(){
521 OCFile file
= getStorageManager().getFileByPath(getFile().getRemotePath());
528 * Show loading dialog
530 public void showLoadingDialog() {
532 LoadingDialog loading
= new LoadingDialog(getResources().getString(R
.string
.wait_a_moment
));
533 FragmentManager fm
= getSupportFragmentManager();
534 FragmentTransaction ft
= fm
.beginTransaction();
535 loading
.show(ft
, DIALOG_WAIT_TAG
);
541 * Dismiss loading dialog
543 public void dismissLoadingDialog(){
544 Fragment frag
= getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG
);
546 LoadingDialog loading
= (LoadingDialog
) frag
;
552 private void doOnResumeAndBound() {
553 mOperationsServiceBinder
.addOperationListener(FileActivity
.this, mHandler
);
554 long waitingForOpId
= mFileOperationsHelper
.getOpIdWaitingFor();
555 if (waitingForOpId
<= Integer
.MAX_VALUE
) {
556 mOperationsServiceBinder
.dispatchResultIfFinished((int)waitingForOpId
, this);
562 * Implements callback methods for service binding. Passed as a parameter to {
564 private class OperationsServiceConnection
implements ServiceConnection
{
567 public void onServiceConnected(ComponentName component
, IBinder service
) {
568 if (component
.equals(new ComponentName(FileActivity
.this, OperationsService
.class))) {
569 Log_OC
.d(TAG
, "Operations service connected");
570 mOperationsServiceBinder
= (OperationsServiceBinder
) service
;
571 /*if (!mOperationsServiceBinder.isPerformingBlockingOperation()) {
572 dismissLoadingDialog();
574 doOnResumeAndBound();
583 public void onServiceDisconnected(ComponentName component
) {
584 if (component
.equals(new ComponentName(FileActivity
.this, OperationsService
.class))) {
585 Log_OC
.d(TAG
, "Operations service disconnected");
586 mOperationsServiceBinder
= null
;
587 // TODO whatever could be waiting for the service is unbound
594 public FileDownloaderBinder
getFileDownloaderBinder() {
595 return mDownloaderBinder
;
600 public FileUploaderBinder
getFileUploaderBinder() {
601 return mUploaderBinder
;