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 org
.apache
.commons
.httpclient
.Credentials
;
23 import android
.accounts
.Account
;
24 import android
.accounts
.AccountManager
;
25 import android
.accounts
.AccountManagerCallback
;
26 import android
.accounts
.AccountManagerFuture
;
27 import android
.accounts
.AuthenticatorException
;
28 import android
.accounts
.OperationCanceledException
;
29 import android
.app
.PendingIntent
;
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
.network
.BearerCredentials
;
55 import com
.owncloud
.android
.lib
.common
.operations
.OnRemoteOperationListener
;
56 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
57 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
58 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
59 import com
.owncloud
.android
.operations
.CreateShareOperation
;
60 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
.utils
.Log_OC
;
69 * Activity with common behaviour for activities handling {@link OCFile}s in ownCloud {@link Account}s .
71 * @author David A. Velasco
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";;
87 /** OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located. */
88 private Account mAccount
;
90 /** Main {@link OCFile} handled by the activity.*/
93 /** Flag to signal that the activity will is finishing to enforce the creation of an ownCloud {@link Account} */
94 private boolean mRedirectingToSetupAccount
= false
;
96 /** Flag to signal when the value of mAccount was set */
97 private boolean mAccountWasSet
;
99 /** Flag to signal when the value of mAccount was restored from a saved state */
100 private boolean mAccountWasRestored
;
102 /** Flag to signal if the activity is launched by a notification */
103 private boolean mFromNotification
;
105 /** Messages handler associated to the main thread and the life cycle of the activity */
106 private Handler mHandler
;
108 /** Access point to the cached database for the current ownCloud {@link Account} */
109 private FileDataStorageManager mStorageManager
= null
;
111 private FileOperationsHelper mFileOperationsHelper
;
113 private ServiceConnection mOperationsServiceConnection
= null
;
115 private OperationsServiceBinder mOperationsServiceBinder
= null
;
117 protected FileDownloaderBinder mDownloaderBinder
= null
;
118 protected FileUploaderBinder mUploaderBinder
= null
;
119 private ServiceConnection mDownloadServiceConnection
, mUploadServiceConnection
= null
;
123 * Loads the ownCloud {@link Account} and main {@link OCFile} to be handled by the instance of
124 * the {@link FileActivity}.
126 * Grants that a valid ownCloud {@link Account} is associated to the instance, or that the user
127 * is requested to create a new one.
130 protected void onCreate(Bundle savedInstanceState
) {
131 super.onCreate(savedInstanceState
);
132 mHandler
= new Handler();
133 mFileOperationsHelper
= new FileOperationsHelper(this);
135 if(savedInstanceState
!= null
) {
136 account
= savedInstanceState
.getParcelable(FileActivity
.EXTRA_ACCOUNT
);
137 mFile
= savedInstanceState
.getParcelable(FileActivity
.EXTRA_FILE
);
138 mFromNotification
= savedInstanceState
.getBoolean(FileActivity
.EXTRA_FROM_NOTIFICATION
);
139 mFileOperationsHelper
.setOpIdWaitingFor(
140 savedInstanceState
.getLong(KEY_WAITING_FOR_OP_ID
, Long
.MAX_VALUE
)
143 account
= getIntent().getParcelableExtra(FileActivity
.EXTRA_ACCOUNT
);
144 mFile
= getIntent().getParcelableExtra(FileActivity
.EXTRA_FILE
);
145 mFromNotification
= getIntent().getBooleanExtra(FileActivity
.EXTRA_FROM_NOTIFICATION
, false
);
148 setAccount(account
, savedInstanceState
!= null
);
150 mOperationsServiceConnection
= new OperationsServiceConnection();
151 bindService(new Intent(this, OperationsService
.class), mOperationsServiceConnection
, Context
.BIND_AUTO_CREATE
);
153 mDownloadServiceConnection
= newTransferenceServiceConnection();
154 if (mDownloadServiceConnection
!= null
) {
155 bindService(new Intent(this, FileDownloader
.class), mDownloadServiceConnection
, Context
.BIND_AUTO_CREATE
);
157 mUploadServiceConnection
= newTransferenceServiceConnection();
158 if (mUploadServiceConnection
!= null
) {
159 bindService(new Intent(this, FileUploader
.class), mUploadServiceConnection
, Context
.BIND_AUTO_CREATE
);
166 * Since ownCloud {@link Account}s can be managed from the system setting menu,
167 * the existence of the {@link Account} associated to the instance must be checked
168 * every time it is restarted.
171 protected void onRestart() {
173 boolean validAccount
= (mAccount
!= null
&& AccountUtils
.setCurrentOwnCloudAccount(getApplicationContext(), mAccount
.name
));
175 swapToDefaultAccount();
181 protected void onStart() {
184 if (mAccountWasSet
) {
185 onAccountSet(mAccountWasRestored
);
187 if (mOperationsServiceBinder
!= null
) {
188 mOperationsServiceBinder
.addOperationListener(FileActivity
.this, mHandler
);
193 protected void onResume() {
196 if (mOperationsServiceBinder
!= null
) {
197 doOnResumeAndBound();
203 protected void onPause() {
204 if (mOperationsServiceBinder
!= null
) {
205 mOperationsServiceBinder
.removeOperationListener(this);
212 protected void onStop() {
214 if (mOperationsServiceBinder
!= null
) {
215 mOperationsServiceBinder
.removeOperationListener(this);
223 protected void onDestroy() {
225 if (mOperationsServiceConnection
!= null
) {
226 unbindService(mOperationsServiceConnection
);
227 mOperationsServiceBinder
= null
;
229 if (mDownloadServiceConnection
!= null
) {
230 unbindService(mDownloadServiceConnection
);
231 mDownloadServiceConnection
= null
;
233 if (mUploadServiceConnection
!= null
) {
234 unbindService(mUploadServiceConnection
);
235 mUploadServiceConnection
= null
;
241 * Sets and validates the ownCloud {@link Account} associated to the Activity.
243 * If not valid, tries to swap it for other valid and existing ownCloud {@link Account}.
245 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
247 * @param account New {@link Account} to set.
248 * @param savedAccount When 'true', account was retrieved from a saved instance state.
250 private void setAccount(Account account
, boolean savedAccount
) {
251 Account oldAccount
= mAccount
;
252 boolean validAccount
= (account
!= null
&& AccountUtils
.setCurrentOwnCloudAccount(getApplicationContext(), account
.name
));
255 mAccountWasSet
= true
;
256 mAccountWasRestored
= (savedAccount
|| mAccount
.equals(oldAccount
));
259 swapToDefaultAccount();
265 * Tries to swap the current ownCloud {@link Account} for other valid and existing.
267 * If no valid ownCloud {@link Account} exists, the the user is requested
268 * to create a new ownCloud {@link Account}.
270 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
272 * @return 'True' if the checked {@link Account} was valid.
274 private void swapToDefaultAccount() {
275 // default to the most recently used account
276 Account newAccount
= AccountUtils
.getCurrentOwnCloudAccount(getApplicationContext());
277 if (newAccount
== null
) {
278 /// no account available: force account creation
279 createFirstAccount();
280 mRedirectingToSetupAccount
= true
;
281 mAccountWasSet
= false
;
282 mAccountWasRestored
= false
;
285 mAccountWasSet
= true
;
286 mAccountWasRestored
= (newAccount
.equals(mAccount
));
287 mAccount
= newAccount
;
293 * Launches the account creation activity. To use when no ownCloud account is available
295 private void createFirstAccount() {
296 AccountManager am
= AccountManager
.get(getApplicationContext());
297 am
.addAccount(MainApp
.getAccountType(),
302 new AccountCreationCallback(),
311 protected void onSaveInstanceState(Bundle outState
) {
312 super.onSaveInstanceState(outState
);
313 outState
.putParcelable(FileActivity
.EXTRA_FILE
, mFile
);
314 outState
.putParcelable(FileActivity
.EXTRA_ACCOUNT
, mAccount
);
315 outState
.putBoolean(FileActivity
.EXTRA_FROM_NOTIFICATION
, mFromNotification
);
316 outState
.putLong(KEY_WAITING_FOR_OP_ID
, mFileOperationsHelper
.getOpIdWaitingFor());
321 * Getter for the main {@link OCFile} handled by the activity.
323 * @return Main {@link OCFile} handled by the activity.
325 public OCFile
getFile() {
331 * Setter for the main {@link OCFile} handled by the activity.
333 * @param file Main {@link OCFile} to be handled by the activity.
335 public void setFile(OCFile file
) {
341 * Getter for the ownCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
343 * @return OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
345 public Account
getAccount() {
350 * @return Value of mFromNotification: True if the Activity is launched by a notification
352 public boolean fromNotification() {
353 return mFromNotification
;
357 * @return 'True' when the Activity is finishing to enforce the setup of a new account.
359 protected boolean isRedirectingToSetupAccount() {
360 return mRedirectingToSetupAccount
;
364 public OperationsServiceBinder
getOperationsServiceBinder() {
365 return mOperationsServiceBinder
;
368 protected ServiceConnection
newTransferenceServiceConnection() {
374 * Helper class handling a callback from the {@link AccountManager} after the creation of
375 * a new ownCloud {@link Account} finished, successfully or not.
377 * At this moment, only called after the creation of the first account.
379 * @author David A. Velasco
381 public class AccountCreationCallback
implements AccountManagerCallback
<Bundle
> {
384 public void run(AccountManagerFuture
<Bundle
> future
) {
385 FileActivity
.this.mRedirectingToSetupAccount
= false
;
386 boolean accountWasSet
= false
;
387 if (future
!= null
) {
390 result
= future
.getResult();
391 String name
= result
.getString(AccountManager
.KEY_ACCOUNT_NAME
);
392 String type
= result
.getString(AccountManager
.KEY_ACCOUNT_TYPE
);
393 if (AccountUtils
.setCurrentOwnCloudAccount(getApplicationContext(), name
)) {
394 setAccount(new Account(name
, type
), false
);
395 accountWasSet
= true
;
397 } catch (OperationCanceledException e
) {
398 Log_OC
.d(TAG
, "Account creation canceled");
400 } catch (Exception e
) {
401 Log_OC
.e(TAG
, "Account creation finished in exception: ", e
);
405 Log_OC
.e(TAG
, "Account creation callback with null bundle");
407 if (!accountWasSet
) {
408 moveTaskToBack(true
);
416 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
418 * Child classes must grant that state depending on the {@link Account} is updated.
420 protected void onAccountSet(boolean stateWasRecovered
) {
421 if (getAccount() != null
) {
422 mStorageManager
= new FileDataStorageManager(getAccount(), getContentResolver());
425 Log_OC
.wtf(TAG
, "onAccountChanged was called with NULL account associated!");
430 public FileDataStorageManager
getStorageManager() {
431 return mStorageManager
;
435 public OnRemoteOperationListener
getRemoteOperationListener() {
440 public Handler
getHandler() {
444 public FileOperationsHelper
getFileOperationsHelper() {
445 return mFileOperationsHelper
;
450 * @param operation Removal operation performed.
451 * @param result Result of the removal.
454 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
455 Log_OC
.d(TAG
, "Received result of operation in FileActivity - common behaviour for all the FileActivities ");
457 mFileOperationsHelper
.setOpIdWaitingFor(Long
.MAX_VALUE
);
459 if (!result
.isSuccess() && (
460 result
.getCode() == ResultCode
.UNAUTHORIZED
||
461 result
.isIdPRedirection() ||
462 (result
.isException() && result
.getException() instanceof AuthenticatorException
)
465 requestCredentialsUpdate();
467 } else if (operation
instanceof CreateShareOperation
) {
468 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
470 } else if (operation
instanceof UnshareLinkOperation
) {
471 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
476 private void requestCredentialsUpdate() {
477 Intent updateAccountCredentials
= new Intent(this, AuthenticatorActivity
.class);
478 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACCOUNT
, getAccount());
479 updateAccountCredentials
.putExtra(
480 AuthenticatorActivity
.EXTRA_ACTION
,
481 AuthenticatorActivity
.ACTION_UPDATE_EXPIRED_TOKEN
);
482 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
483 startActivity(updateAccountCredentials
);
487 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
488 dismissLoadingDialog();
489 if (result
.isSuccess()) {
492 Intent sendIntent
= operation
.getSendIntent();
493 startActivity(sendIntent
);
495 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) { // Error --> SHARE_NOT_FOUND
496 Toast t
= Toast
.makeText(this, getString(R
.string
.share_link_file_no_exist
), Toast
.LENGTH_LONG
);
498 } else { // Generic error
499 // Show a Message, operation finished without success
500 Toast t
= Toast
.makeText(this, getString(R
.string
.share_link_file_error
), Toast
.LENGTH_LONG
);
506 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
507 dismissLoadingDialog();
509 if (result
.isSuccess()){
512 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) { // Error --> SHARE_NOT_FOUND
513 Toast t
= Toast
.makeText(this, getString(R
.string
.unshare_link_file_no_exist
), Toast
.LENGTH_LONG
);
515 } else { // Generic error
516 // Show a Message, operation finished without success
517 Toast t
= Toast
.makeText(this, getString(R
.string
.unshare_link_file_error
), Toast
.LENGTH_LONG
);
524 private void updateFileFromDB(){
525 OCFile file
= getStorageManager().getFileByPath(getFile().getRemotePath());
532 * Show loading dialog
534 public void showLoadingDialog() {
536 LoadingDialog loading
= new LoadingDialog(getResources().getString(R
.string
.wait_a_moment
));
537 FragmentManager fm
= getSupportFragmentManager();
538 FragmentTransaction ft
= fm
.beginTransaction();
539 loading
.show(ft
, DIALOG_WAIT_TAG
);
545 * Dismiss loading dialog
547 public void dismissLoadingDialog(){
548 Fragment frag
= getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG
);
550 LoadingDialog loading
= (LoadingDialog
) frag
;
556 private void doOnResumeAndBound() {
557 mOperationsServiceBinder
.addOperationListener(FileActivity
.this, mHandler
);
558 long waitingForOpId
= mFileOperationsHelper
.getOpIdWaitingFor();
559 if (waitingForOpId
<= Integer
.MAX_VALUE
) {
560 mOperationsServiceBinder
.dispatchResultIfFinished((int)waitingForOpId
, this);
566 * Implements callback methods for service binding. Passed as a parameter to {
568 private class OperationsServiceConnection
implements ServiceConnection
{
571 public void onServiceConnected(ComponentName component
, IBinder service
) {
572 if (component
.equals(new ComponentName(FileActivity
.this, OperationsService
.class))) {
573 Log_OC
.d(TAG
, "Operations service connected");
574 mOperationsServiceBinder
= (OperationsServiceBinder
) service
;
575 /*if (!mOperationsServiceBinder.isPerformingBlockingOperation()) {
576 dismissLoadingDialog();
578 doOnResumeAndBound();
587 public void onServiceDisconnected(ComponentName component
) {
588 if (component
.equals(new ComponentName(FileActivity
.this, OperationsService
.class))) {
589 Log_OC
.d(TAG
, "Operations service disconnected");
590 mOperationsServiceBinder
= null
;
591 // TODO whatever could be waiting for the service is unbound
598 public FileDownloaderBinder
getFileDownloaderBinder() {
599 return mDownloaderBinder
;
604 public FileUploaderBinder
getFileUploaderBinder() {
605 return mUploaderBinder
;