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 java
.io
.IOException
;
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
.content
.ComponentName
;
30 import android
.content
.Context
;
31 import android
.content
.Intent
;
32 import android
.content
.ServiceConnection
;
33 import android
.os
.Bundle
;
34 import android
.os
.Handler
;
35 import android
.os
.IBinder
;
36 import android
.support
.v4
.app
.Fragment
;
37 import android
.support
.v4
.app
.FragmentManager
;
38 import android
.support
.v4
.app
.FragmentTransaction
;
39 import android
.widget
.Toast
;
41 import com
.actionbarsherlock
.app
.SherlockFragmentActivity
;
42 import com
.owncloud
.android
.MainApp
;
43 import com
.owncloud
.android
.R
;
44 import com
.owncloud
.android
.authentication
.AccountUtils
;
45 import com
.owncloud
.android
.authentication
.AuthenticatorActivity
;
46 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
47 import com
.owncloud
.android
.datamodel
.OCFile
;
48 import com
.owncloud
.android
.files
.FileOperationsHelper
;
49 import com
.owncloud
.android
.files
.services
.FileDownloader
;
50 import com
.owncloud
.android
.files
.services
.FileUploader
;
51 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
52 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
53 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
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
.operations
.CreateShareOperation
;
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
;
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
);
190 protected void onResume() {
193 if (mOperationsServiceBinder
!= null
) {
194 doOnResumeAndBound();
200 protected void onPause() {
202 Log_OC
.wtf(TAG
, "Saving Cookies" );
203 if (mAccount
!= null
) {
205 ((MainApp
)getApplicationContext()).getOwnCloudClientManager().
206 saveClient(mAccount
, this);
208 // TODO get rid of the exceptions
209 } catch (AccountNotFoundException e
) {
211 } catch (AuthenticatorException e
) {
213 } catch (OperationCanceledException e
) {
215 } catch (IOException e
) {
220 if (mOperationsServiceBinder
!= null
) {
221 mOperationsServiceBinder
.removeOperationListener(this);
229 protected void onDestroy() {
230 if (mOperationsServiceConnection
!= null
) {
231 unbindService(mOperationsServiceConnection
);
232 mOperationsServiceBinder
= null
;
234 if (mDownloadServiceConnection
!= null
) {
235 unbindService(mDownloadServiceConnection
);
236 mDownloadServiceConnection
= null
;
238 if (mUploadServiceConnection
!= null
) {
239 unbindService(mUploadServiceConnection
);
240 mUploadServiceConnection
= null
;
247 * Sets and validates the ownCloud {@link Account} associated to the Activity.
249 * If not valid, tries to swap it for other valid and existing ownCloud {@link Account}.
251 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
253 * @param account New {@link Account} to set.
254 * @param savedAccount When 'true', account was retrieved from a saved instance state.
256 private void setAccount(Account account
, boolean savedAccount
) {
257 Account oldAccount
= mAccount
;
258 boolean validAccount
= (account
!= null
&& AccountUtils
.setCurrentOwnCloudAccount(getApplicationContext(), account
.name
));
261 mAccountWasSet
= true
;
262 mAccountWasRestored
= (savedAccount
|| mAccount
.equals(oldAccount
));
265 swapToDefaultAccount();
271 * Tries to swap the current ownCloud {@link Account} for other valid and existing.
273 * If no valid ownCloud {@link Account} exists, the the user is requested
274 * to create a new ownCloud {@link Account}.
276 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
278 * @return 'True' if the checked {@link Account} was valid.
280 private void swapToDefaultAccount() {
281 // default to the most recently used account
282 Account newAccount
= AccountUtils
.getCurrentOwnCloudAccount(getApplicationContext());
283 if (newAccount
== null
) {
284 /// no account available: force account creation
285 createFirstAccount();
286 mRedirectingToSetupAccount
= true
;
287 mAccountWasSet
= false
;
288 mAccountWasRestored
= false
;
291 mAccountWasSet
= true
;
292 mAccountWasRestored
= (newAccount
.equals(mAccount
));
293 mAccount
= newAccount
;
299 * Launches the account creation activity. To use when no ownCloud account is available
301 private void createFirstAccount() {
302 AccountManager am
= AccountManager
.get(getApplicationContext());
303 am
.addAccount(MainApp
.getAccountType(),
308 new AccountCreationCallback(),
317 protected void onSaveInstanceState(Bundle outState
) {
318 super.onSaveInstanceState(outState
);
319 outState
.putParcelable(FileActivity
.EXTRA_FILE
, mFile
);
320 outState
.putParcelable(FileActivity
.EXTRA_ACCOUNT
, mAccount
);
321 outState
.putBoolean(FileActivity
.EXTRA_FROM_NOTIFICATION
, mFromNotification
);
322 outState
.putLong(KEY_WAITING_FOR_OP_ID
, mFileOperationsHelper
.getOpIdWaitingFor());
327 * Getter for the main {@link OCFile} handled by the activity.
329 * @return Main {@link OCFile} handled by the activity.
331 public OCFile
getFile() {
337 * Setter for the main {@link OCFile} handled by the activity.
339 * @param file Main {@link OCFile} to be handled by the activity.
341 public void setFile(OCFile file
) {
347 * Getter for the ownCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
349 * @return OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
351 public Account
getAccount() {
356 * @return Value of mFromNotification: True if the Activity is launched by a notification
358 public boolean fromNotification() {
359 return mFromNotification
;
363 * @return 'True' when the Activity is finishing to enforce the setup of a new account.
365 protected boolean isRedirectingToSetupAccount() {
366 return mRedirectingToSetupAccount
;
370 public OperationsServiceBinder
getOperationsServiceBinder() {
371 return mOperationsServiceBinder
;
374 protected ServiceConnection
newTransferenceServiceConnection() {
380 * Helper class handling a callback from the {@link AccountManager} after the creation of
381 * a new ownCloud {@link Account} finished, successfully or not.
383 * At this moment, only called after the creation of the first account.
385 * @author David A. Velasco
387 public class AccountCreationCallback
implements AccountManagerCallback
<Bundle
> {
390 public void run(AccountManagerFuture
<Bundle
> future
) {
391 FileActivity
.this.mRedirectingToSetupAccount
= false
;
392 boolean accountWasSet
= false
;
393 if (future
!= null
) {
396 result
= future
.getResult();
397 String name
= result
.getString(AccountManager
.KEY_ACCOUNT_NAME
);
398 String type
= result
.getString(AccountManager
.KEY_ACCOUNT_TYPE
);
399 if (AccountUtils
.setCurrentOwnCloudAccount(getApplicationContext(), name
)) {
400 setAccount(new Account(name
, type
), false
);
401 accountWasSet
= true
;
403 } catch (OperationCanceledException e
) {
404 Log_OC
.d(TAG
, "Account creation canceled");
406 } catch (Exception e
) {
407 Log_OC
.e(TAG
, "Account creation finished in exception: ", e
);
411 Log_OC
.e(TAG
, "Account creation callback with null bundle");
413 if (!accountWasSet
) {
414 moveTaskToBack(true
);
422 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
424 * Child classes must grant that state depending on the {@link Account} is updated.
426 protected void onAccountSet(boolean stateWasRecovered
) {
427 if (getAccount() != null
) {
428 mStorageManager
= new FileDataStorageManager(getAccount(), getContentResolver());
431 Log_OC
.wtf(TAG
, "onAccountChanged was called with NULL account associated!");
436 public FileDataStorageManager
getStorageManager() {
437 return mStorageManager
;
441 public OnRemoteOperationListener
getRemoteOperationListener() {
446 public Handler
getHandler() {
450 public FileOperationsHelper
getFileOperationsHelper() {
451 return mFileOperationsHelper
;
456 * @param operation Removal operation performed.
457 * @param result Result of the removal.
460 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
461 Log_OC
.d(TAG
, "Received result of operation in FileActivity - common behaviour for all the FileActivities ");
463 mFileOperationsHelper
.setOpIdWaitingFor(Long
.MAX_VALUE
);
465 if (!result
.isSuccess() && (
466 result
.getCode() == ResultCode
.UNAUTHORIZED
||
467 result
.isIdPRedirection() ||
468 (result
.isException() && result
.getException() instanceof AuthenticatorException
)
471 requestCredentialsUpdate();
473 if (result
.getCode() == ResultCode
.UNAUTHORIZED
) {
474 dismissLoadingDialog();
475 Toast t
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
480 } else if (operation
instanceof CreateShareOperation
) {
481 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
483 } else if (operation
instanceof UnshareLinkOperation
) {
484 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
489 protected void requestCredentialsUpdate() {
490 Intent updateAccountCredentials
= new Intent(this, AuthenticatorActivity
.class);
491 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACCOUNT
, getAccount());
492 updateAccountCredentials
.putExtra(
493 AuthenticatorActivity
.EXTRA_ACTION
,
494 AuthenticatorActivity
.ACTION_UPDATE_EXPIRED_TOKEN
);
495 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
496 startActivity(updateAccountCredentials
);
500 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
501 dismissLoadingDialog();
502 if (result
.isSuccess()) {
505 Intent sendIntent
= operation
.getSendIntent();
506 startActivity(sendIntent
);
509 Toast t
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
516 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
517 dismissLoadingDialog();
519 if (result
.isSuccess()){
523 Toast t
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
530 private void updateFileFromDB(){
531 OCFile file
= getStorageManager().getFileByPath(getFile().getRemotePath());
538 * Show loading dialog
540 public void showLoadingDialog() {
542 LoadingDialog loading
= new LoadingDialog(getResources().getString(R
.string
.wait_a_moment
));
543 FragmentManager fm
= getSupportFragmentManager();
544 FragmentTransaction ft
= fm
.beginTransaction();
545 loading
.show(ft
, DIALOG_WAIT_TAG
);
551 * Dismiss loading dialog
553 public void dismissLoadingDialog(){
554 Fragment frag
= getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG
);
556 LoadingDialog loading
= (LoadingDialog
) frag
;
562 private void doOnResumeAndBound() {
563 mOperationsServiceBinder
.addOperationListener(FileActivity
.this, mHandler
);
564 long waitingForOpId
= mFileOperationsHelper
.getOpIdWaitingFor();
565 if (waitingForOpId
<= Integer
.MAX_VALUE
) {
566 boolean wait
= mOperationsServiceBinder
.dispatchResultIfFinished((int)waitingForOpId
, this);
568 dismissLoadingDialog();
575 * Implements callback methods for service binding. Passed as a parameter to {
577 private class OperationsServiceConnection
implements ServiceConnection
{
580 public void onServiceConnected(ComponentName component
, IBinder service
) {
581 if (component
.equals(new ComponentName(FileActivity
.this, OperationsService
.class))) {
582 Log_OC
.d(TAG
, "Operations service connected");
583 mOperationsServiceBinder
= (OperationsServiceBinder
) service
;
584 /*if (!mOperationsServiceBinder.isPerformingBlockingOperation()) {
585 dismissLoadingDialog();
587 doOnResumeAndBound();
596 public void onServiceDisconnected(ComponentName component
) {
597 if (component
.equals(new ComponentName(FileActivity
.this, OperationsService
.class))) {
598 Log_OC
.d(TAG
, "Operations service disconnected");
599 mOperationsServiceBinder
= null
;
600 // TODO whatever could be waiting for the service is unbound
607 public FileDownloaderBinder
getFileDownloaderBinder() {
608 return mDownloaderBinder
;
613 public FileUploaderBinder
getFileUploaderBinder() {
614 return mUploaderBinder
;