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
.ErrorMessageAdapter
;
62 import com
.owncloud
.android
.utils
.Log_OC
;
66 * Activity with common behaviour for activities handling {@link OCFile}s in ownCloud {@link Account}s .
68 * @author David A. Velasco
70 public class FileActivity
extends SherlockFragmentActivity
71 implements OnRemoteOperationListener
, ComponentsGetter
{
73 public static final String EXTRA_FILE
= "com.owncloud.android.ui.activity.FILE";
74 public static final String EXTRA_ACCOUNT
= "com.owncloud.android.ui.activity.ACCOUNT";
75 public static final String EXTRA_WAITING_TO_PREVIEW
= "com.owncloud.android.ui.activity.WAITING_TO_PREVIEW";
76 public static final String EXTRA_FROM_NOTIFICATION
= "com.owncloud.android.ui.activity.FROM_NOTIFICATION";
78 public static final String TAG
= FileActivity
.class.getSimpleName();
80 private static final String DIALOG_WAIT_TAG
= "DIALOG_WAIT";
81 private static final String KEY_WAITING_FOR_OP_ID
= "WAITING_FOR_OP_ID";;
84 /** OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located. */
85 private Account mAccount
;
87 /** Main {@link OCFile} handled by the activity.*/
90 /** Flag to signal that the activity will is finishing to enforce the creation of an ownCloud {@link Account} */
91 private boolean mRedirectingToSetupAccount
= false
;
93 /** Flag to signal when the value of mAccount was set */
94 private boolean mAccountWasSet
;
96 /** Flag to signal when the value of mAccount was restored from a saved state */
97 private boolean mAccountWasRestored
;
99 /** Flag to signal if the activity is launched by a notification */
100 private boolean mFromNotification
;
102 /** Messages handler associated to the main thread and the life cycle of the activity */
103 private Handler mHandler
;
105 /** Access point to the cached database for the current ownCloud {@link Account} */
106 private FileDataStorageManager mStorageManager
= null
;
108 private FileOperationsHelper mFileOperationsHelper
;
110 private ServiceConnection mOperationsServiceConnection
= null
;
112 private OperationsServiceBinder mOperationsServiceBinder
= null
;
114 protected FileDownloaderBinder mDownloaderBinder
= null
;
115 protected FileUploaderBinder mUploaderBinder
= null
;
116 private ServiceConnection mDownloadServiceConnection
, mUploadServiceConnection
= null
;
120 * Loads the ownCloud {@link Account} and main {@link OCFile} to be handled by the instance of
121 * the {@link FileActivity}.
123 * Grants that a valid ownCloud {@link Account} is associated to the instance, or that the user
124 * is requested to create a new one.
127 protected void onCreate(Bundle savedInstanceState
) {
128 super.onCreate(savedInstanceState
);
129 mHandler
= new Handler();
130 mFileOperationsHelper
= new FileOperationsHelper(this);
132 if(savedInstanceState
!= null
) {
133 account
= savedInstanceState
.getParcelable(FileActivity
.EXTRA_ACCOUNT
);
134 mFile
= savedInstanceState
.getParcelable(FileActivity
.EXTRA_FILE
);
135 mFromNotification
= savedInstanceState
.getBoolean(FileActivity
.EXTRA_FROM_NOTIFICATION
);
136 mFileOperationsHelper
.setOpIdWaitingFor(
137 savedInstanceState
.getLong(KEY_WAITING_FOR_OP_ID
, Long
.MAX_VALUE
)
140 account
= getIntent().getParcelableExtra(FileActivity
.EXTRA_ACCOUNT
);
141 mFile
= getIntent().getParcelableExtra(FileActivity
.EXTRA_FILE
);
142 mFromNotification
= getIntent().getBooleanExtra(FileActivity
.EXTRA_FROM_NOTIFICATION
, false
);
145 setAccount(account
, savedInstanceState
!= null
);
147 mOperationsServiceConnection
= new OperationsServiceConnection();
148 bindService(new Intent(this, OperationsService
.class), mOperationsServiceConnection
, Context
.BIND_AUTO_CREATE
);
150 mDownloadServiceConnection
= newTransferenceServiceConnection();
151 if (mDownloadServiceConnection
!= null
) {
152 bindService(new Intent(this, FileDownloader
.class), mDownloadServiceConnection
, Context
.BIND_AUTO_CREATE
);
154 mUploadServiceConnection
= newTransferenceServiceConnection();
155 if (mUploadServiceConnection
!= null
) {
156 bindService(new Intent(this, FileUploader
.class), mUploadServiceConnection
, Context
.BIND_AUTO_CREATE
);
163 * Since ownCloud {@link Account}s can be managed from the system setting menu,
164 * the existence of the {@link Account} associated to the instance must be checked
165 * every time it is restarted.
168 protected void onRestart() {
170 boolean validAccount
= (mAccount
!= null
&& AccountUtils
.setCurrentOwnCloudAccount(getApplicationContext(), mAccount
.name
));
172 swapToDefaultAccount();
178 protected void onStart() {
181 if (mAccountWasSet
) {
182 onAccountSet(mAccountWasRestored
);
187 protected void onResume() {
190 if (mOperationsServiceBinder
!= null
) {
191 doOnResumeAndBound();
197 protected void onPause() {
198 if (mOperationsServiceBinder
!= null
) {
199 mOperationsServiceBinder
.removeOperationListener(this);
207 protected void onDestroy() {
208 if (mOperationsServiceConnection
!= null
) {
209 unbindService(mOperationsServiceConnection
);
210 mOperationsServiceBinder
= null
;
212 if (mDownloadServiceConnection
!= null
) {
213 unbindService(mDownloadServiceConnection
);
214 mDownloadServiceConnection
= null
;
216 if (mUploadServiceConnection
!= null
) {
217 unbindService(mUploadServiceConnection
);
218 mUploadServiceConnection
= null
;
225 * Sets and validates the ownCloud {@link Account} associated to the Activity.
227 * If not valid, tries to swap it for other valid and existing ownCloud {@link Account}.
229 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
231 * @param account New {@link Account} to set.
232 * @param savedAccount When 'true', account was retrieved from a saved instance state.
234 private void setAccount(Account account
, boolean savedAccount
) {
235 Account oldAccount
= mAccount
;
236 boolean validAccount
= (account
!= null
&& AccountUtils
.setCurrentOwnCloudAccount(getApplicationContext(), account
.name
));
239 mAccountWasSet
= true
;
240 mAccountWasRestored
= (savedAccount
|| mAccount
.equals(oldAccount
));
243 swapToDefaultAccount();
249 * Tries to swap the current ownCloud {@link Account} for other valid and existing.
251 * If no valid ownCloud {@link Account} exists, the the user is requested
252 * to create a new ownCloud {@link Account}.
254 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
256 * @return 'True' if the checked {@link Account} was valid.
258 private void swapToDefaultAccount() {
259 // default to the most recently used account
260 Account newAccount
= AccountUtils
.getCurrentOwnCloudAccount(getApplicationContext());
261 if (newAccount
== null
) {
262 /// no account available: force account creation
263 createFirstAccount();
264 mRedirectingToSetupAccount
= true
;
265 mAccountWasSet
= false
;
266 mAccountWasRestored
= false
;
269 mAccountWasSet
= true
;
270 mAccountWasRestored
= (newAccount
.equals(mAccount
));
271 mAccount
= newAccount
;
277 * Launches the account creation activity. To use when no ownCloud account is available
279 private void createFirstAccount() {
280 AccountManager am
= AccountManager
.get(getApplicationContext());
281 am
.addAccount(MainApp
.getAccountType(),
286 new AccountCreationCallback(),
295 protected void onSaveInstanceState(Bundle outState
) {
296 super.onSaveInstanceState(outState
);
297 outState
.putParcelable(FileActivity
.EXTRA_FILE
, mFile
);
298 outState
.putParcelable(FileActivity
.EXTRA_ACCOUNT
, mAccount
);
299 outState
.putBoolean(FileActivity
.EXTRA_FROM_NOTIFICATION
, mFromNotification
);
300 outState
.putLong(KEY_WAITING_FOR_OP_ID
, mFileOperationsHelper
.getOpIdWaitingFor());
305 * Getter for the main {@link OCFile} handled by the activity.
307 * @return Main {@link OCFile} handled by the activity.
309 public OCFile
getFile() {
315 * Setter for the main {@link OCFile} handled by the activity.
317 * @param file Main {@link OCFile} to be handled by the activity.
319 public void setFile(OCFile file
) {
325 * Getter for the ownCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
327 * @return OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
329 public Account
getAccount() {
334 * @return Value of mFromNotification: True if the Activity is launched by a notification
336 public boolean fromNotification() {
337 return mFromNotification
;
341 * @return 'True' when the Activity is finishing to enforce the setup of a new account.
343 protected boolean isRedirectingToSetupAccount() {
344 return mRedirectingToSetupAccount
;
348 public OperationsServiceBinder
getOperationsServiceBinder() {
349 return mOperationsServiceBinder
;
352 protected ServiceConnection
newTransferenceServiceConnection() {
358 * Helper class handling a callback from the {@link AccountManager} after the creation of
359 * a new ownCloud {@link Account} finished, successfully or not.
361 * At this moment, only called after the creation of the first account.
363 * @author David A. Velasco
365 public class AccountCreationCallback
implements AccountManagerCallback
<Bundle
> {
368 public void run(AccountManagerFuture
<Bundle
> future
) {
369 FileActivity
.this.mRedirectingToSetupAccount
= false
;
370 boolean accountWasSet
= false
;
371 if (future
!= null
) {
374 result
= future
.getResult();
375 String name
= result
.getString(AccountManager
.KEY_ACCOUNT_NAME
);
376 String type
= result
.getString(AccountManager
.KEY_ACCOUNT_TYPE
);
377 if (AccountUtils
.setCurrentOwnCloudAccount(getApplicationContext(), name
)) {
378 setAccount(new Account(name
, type
), false
);
379 accountWasSet
= true
;
381 } catch (OperationCanceledException e
) {
382 Log_OC
.d(TAG
, "Account creation canceled");
384 } catch (Exception e
) {
385 Log_OC
.e(TAG
, "Account creation finished in exception: ", e
);
389 Log_OC
.e(TAG
, "Account creation callback with null bundle");
391 if (!accountWasSet
) {
392 moveTaskToBack(true
);
400 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
402 * Child classes must grant that state depending on the {@link Account} is updated.
404 protected void onAccountSet(boolean stateWasRecovered
) {
405 if (getAccount() != null
) {
406 mStorageManager
= new FileDataStorageManager(getAccount(), getContentResolver());
409 Log_OC
.wtf(TAG
, "onAccountChanged was called with NULL account associated!");
414 public FileDataStorageManager
getStorageManager() {
415 return mStorageManager
;
419 public OnRemoteOperationListener
getRemoteOperationListener() {
424 public Handler
getHandler() {
428 public FileOperationsHelper
getFileOperationsHelper() {
429 return mFileOperationsHelper
;
434 * @param operation Removal operation performed.
435 * @param result Result of the removal.
438 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
439 Log_OC
.d(TAG
, "Received result of operation in FileActivity - common behaviour for all the FileActivities ");
441 mFileOperationsHelper
.setOpIdWaitingFor(Long
.MAX_VALUE
);
443 if (!result
.isSuccess() && (
444 result
.getCode() == ResultCode
.UNAUTHORIZED
||
445 result
.isIdPRedirection() ||
446 (result
.isException() && result
.getException() instanceof AuthenticatorException
)
449 requestCredentialsUpdate();
451 } else if (operation
instanceof CreateShareOperation
) {
452 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
454 } else if (operation
instanceof UnshareLinkOperation
) {
455 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
460 private void requestCredentialsUpdate() {
461 Intent updateAccountCredentials
= new Intent(this, AuthenticatorActivity
.class);
462 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACCOUNT
, getAccount());
463 updateAccountCredentials
.putExtra(
464 AuthenticatorActivity
.EXTRA_ACTION
,
465 AuthenticatorActivity
.ACTION_UPDATE_EXPIRED_TOKEN
);
466 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
467 startActivity(updateAccountCredentials
);
471 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
472 dismissLoadingDialog();
473 if (result
.isSuccess()) {
476 Intent sendIntent
= operation
.getSendIntent();
477 startActivity(sendIntent
);
480 Toast t
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
487 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
488 dismissLoadingDialog();
490 if (result
.isSuccess()){
494 Toast t
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
501 private void updateFileFromDB(){
502 OCFile file
= getStorageManager().getFileByPath(getFile().getRemotePath());
509 * Show loading dialog
511 public void showLoadingDialog() {
513 LoadingDialog loading
= new LoadingDialog(getResources().getString(R
.string
.wait_a_moment
));
514 FragmentManager fm
= getSupportFragmentManager();
515 FragmentTransaction ft
= fm
.beginTransaction();
516 loading
.show(ft
, DIALOG_WAIT_TAG
);
522 * Dismiss loading dialog
524 public void dismissLoadingDialog(){
525 Fragment frag
= getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG
);
527 LoadingDialog loading
= (LoadingDialog
) frag
;
533 private void doOnResumeAndBound() {
534 mOperationsServiceBinder
.addOperationListener(FileActivity
.this, mHandler
);
535 long waitingForOpId
= mFileOperationsHelper
.getOpIdWaitingFor();
536 if (waitingForOpId
<= Integer
.MAX_VALUE
) {
537 boolean wait
= mOperationsServiceBinder
.dispatchResultIfFinished((int)waitingForOpId
, this);
539 dismissLoadingDialog();
546 * Implements callback methods for service binding. Passed as a parameter to {
548 private class OperationsServiceConnection
implements ServiceConnection
{
551 public void onServiceConnected(ComponentName component
, IBinder service
) {
552 if (component
.equals(new ComponentName(FileActivity
.this, OperationsService
.class))) {
553 Log_OC
.d(TAG
, "Operations service connected");
554 mOperationsServiceBinder
= (OperationsServiceBinder
) service
;
555 /*if (!mOperationsServiceBinder.isPerformingBlockingOperation()) {
556 dismissLoadingDialog();
558 doOnResumeAndBound();
567 public void onServiceDisconnected(ComponentName component
) {
568 if (component
.equals(new ComponentName(FileActivity
.this, OperationsService
.class))) {
569 Log_OC
.d(TAG
, "Operations service disconnected");
570 mOperationsServiceBinder
= null
;
571 // TODO whatever could be waiting for the service is unbound
578 public FileDownloaderBinder
getFileDownloaderBinder() {
579 return mDownloaderBinder
;
584 public FileUploaderBinder
getFileUploaderBinder() {
585 return mUploaderBinder
;