2 * ownCloud Android client application
4 * @author David A. Velasco
5 * Copyright (C) 2011 Bartek Przybylski
6 * Copyright (C) 2015 ownCloud Inc.
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License version 2,
10 * as published by the Free Software Foundation.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
22 package com
.owncloud
.android
.ui
.activity
;
24 import android
.accounts
.Account
;
25 import android
.accounts
.AccountManager
;
26 import android
.accounts
.AccountManagerCallback
;
27 import android
.accounts
.AccountManagerFuture
;
28 import android
.accounts
.AuthenticatorException
;
29 import android
.accounts
.OperationCanceledException
;
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
.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
.lib
.common
.utils
.Log_OC
;
59 import com
.owncloud
.android
.operations
.CreateShareOperation
;
60 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
61 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
.ui
.dialog
.SharePasswordDialogFragment
;
66 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
70 * Activity with common behaviour for activities handling {@link OCFile}s in ownCloud {@link Account}s .
72 public class FileActivity
extends SherlockFragmentActivity
73 implements OnRemoteOperationListener
, ComponentsGetter
{
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";
84 private static final String DIALOG_SHARE_PASSWORD
= "DIALOG_SHARE_PASSWORD";
85 private static final String KEY_TRY_SHARE_AGAIN
= "TRY_SHARE_AGAIN";
87 protected static final long DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
= 200;
90 /** OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located. */
91 private Account mAccount
;
93 /** Main {@link OCFile} handled by the activity.*/
96 /** Flag to signal that the activity will is finishing to enforce the creation of an ownCloud {@link Account} */
97 private boolean mRedirectingToSetupAccount
= false
;
99 /** Flag to signal when the value of mAccount was set */
100 protected boolean mAccountWasSet
;
102 /** Flag to signal when the value of mAccount was restored from a saved state */
103 protected boolean mAccountWasRestored
;
105 /** Flag to signal if the activity is launched by a notification */
106 private boolean mFromNotification
;
108 /** Messages handler associated to the main thread and the life cycle of the activity */
109 private Handler mHandler
;
111 /** Access point to the cached database for the current ownCloud {@link Account} */
112 private FileDataStorageManager mStorageManager
= null
;
114 private FileOperationsHelper mFileOperationsHelper
;
116 private ServiceConnection mOperationsServiceConnection
= null
;
118 private OperationsServiceBinder mOperationsServiceBinder
= null
;
120 protected FileDownloaderBinder mDownloaderBinder
= null
;
121 protected FileUploaderBinder mUploaderBinder
= null
;
122 private ServiceConnection mDownloadServiceConnection
, mUploadServiceConnection
= null
;
124 private boolean mTryShareAgain
= false
;
128 * Loads the ownCloud {@link Account} and main {@link OCFile} to be handled by the instance of
129 * the {@link FileActivity}.
131 * Grants that a valid ownCloud {@link Account} is associated to the instance, or that the user
132 * is requested to create a new one.
135 protected void onCreate(Bundle savedInstanceState
) {
136 super.onCreate(savedInstanceState
);
137 mHandler
= new Handler();
138 mFileOperationsHelper
= new FileOperationsHelper(this);
140 if(savedInstanceState
!= null
) {
141 account
= savedInstanceState
.getParcelable(FileActivity
.EXTRA_ACCOUNT
);
142 mFile
= savedInstanceState
.getParcelable(FileActivity
.EXTRA_FILE
);
143 mFromNotification
= savedInstanceState
.getBoolean(FileActivity
.EXTRA_FROM_NOTIFICATION
);
144 mFileOperationsHelper
.setOpIdWaitingFor(
145 savedInstanceState
.getLong(KEY_WAITING_FOR_OP_ID
, Long
.MAX_VALUE
)
147 mTryShareAgain
= savedInstanceState
.getBoolean(KEY_TRY_SHARE_AGAIN
);
149 account
= getIntent().getParcelableExtra(FileActivity
.EXTRA_ACCOUNT
);
150 mFile
= getIntent().getParcelableExtra(FileActivity
.EXTRA_FILE
);
151 mFromNotification
= getIntent().getBooleanExtra(FileActivity
.EXTRA_FROM_NOTIFICATION
, false
);
154 AccountUtils
.updateAccountVersion(this); // best place, before any access to AccountManager or database
156 setAccount(account
, savedInstanceState
!= null
);
158 mOperationsServiceConnection
= new OperationsServiceConnection();
159 bindService(new Intent(this, OperationsService
.class), mOperationsServiceConnection
, Context
.BIND_AUTO_CREATE
);
161 mDownloadServiceConnection
= newTransferenceServiceConnection();
162 if (mDownloadServiceConnection
!= null
) {
163 bindService(new Intent(this, FileDownloader
.class), mDownloadServiceConnection
, Context
.BIND_AUTO_CREATE
);
165 mUploadServiceConnection
= newTransferenceServiceConnection();
166 if (mUploadServiceConnection
!= null
) {
167 bindService(new Intent(this, FileUploader
.class), mUploadServiceConnection
, Context
.BIND_AUTO_CREATE
);
173 protected void onNewIntent (Intent intent
) {
174 Log_OC
.v(TAG
, "onNewIntent() start");
175 Account current
= AccountUtils
.getCurrentOwnCloudAccount(this);
176 if (current
!= null
&& mAccount
!= null
&& !mAccount
.name
.equals(current
.name
)) {
179 Log_OC
.v(TAG
, "onNewIntent() stop");
183 * Since ownCloud {@link Account}s can be managed from the system setting menu,
184 * the existence of the {@link Account} associated to the instance must be checked
185 * every time it is restarted.
188 protected void onRestart() {
189 Log_OC
.v(TAG
, "onRestart() start");
191 boolean validAccount
= (mAccount
!= null
&& AccountUtils
.exists(mAccount
, this));
193 swapToDefaultAccount();
195 Log_OC
.v(TAG
, "onRestart() end");
200 protected void onStart() {
201 Log_OC
.v(TAG
, "onStart() start");
204 if (mAccountWasSet
) {
205 onAccountSet(mAccountWasRestored
);
207 Log_OC
.v(TAG
, "onStart() end");
211 protected void onResume() {
212 Log_OC
.v(TAG
, "onResume() start");
215 if (mOperationsServiceBinder
!= null
) {
216 doOnResumeAndBound();
218 Log_OC
.v(TAG
, "onResume() end");
222 protected void onPause() {
223 Log_OC
.v(TAG
, "onPause() start");
225 if (mOperationsServiceBinder
!= null
) {
226 mOperationsServiceBinder
.removeOperationListener(this);
230 Log_OC
.v(TAG
, "onPause() end");
235 protected void onDestroy() {
236 Log_OC
.v(TAG
, "onDestroy() start");
237 if (mOperationsServiceConnection
!= null
) {
238 unbindService(mOperationsServiceConnection
);
239 mOperationsServiceBinder
= null
;
241 if (mDownloadServiceConnection
!= null
) {
242 unbindService(mDownloadServiceConnection
);
243 mDownloadServiceConnection
= null
;
245 if (mUploadServiceConnection
!= null
) {
246 unbindService(mUploadServiceConnection
);
247 mUploadServiceConnection
= null
;
251 Log_OC
.v(TAG
, "onDestroy() end");
256 * Sets and validates the ownCloud {@link Account} associated to the Activity.
258 * If not valid, tries to swap it for other valid and existing ownCloud {@link Account}.
260 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
262 * @param account New {@link Account} to set.
263 * @param savedAccount When 'true', account was retrieved from a saved instance state.
265 protected void setAccount(Account account
, boolean savedAccount
) {
266 Account oldAccount
= mAccount
;
267 boolean validAccount
=
268 (account
!= null
&& AccountUtils
.setCurrentOwnCloudAccount(getApplicationContext(), account
.name
));
271 mAccountWasSet
= true
;
272 mAccountWasRestored
= (savedAccount
|| mAccount
.equals(oldAccount
));
275 swapToDefaultAccount();
281 * Tries to swap the current ownCloud {@link Account} for other valid and existing.
283 * If no valid ownCloud {@link Account} exists, the the user is requested
284 * to create a new ownCloud {@link Account}.
286 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
288 private void swapToDefaultAccount() {
289 // default to the most recently used account
290 Account newAccount
= AccountUtils
.getCurrentOwnCloudAccount(getApplicationContext());
291 if (newAccount
== null
) {
292 /// no account available: force account creation
293 createFirstAccount();
294 mRedirectingToSetupAccount
= true
;
295 mAccountWasSet
= false
;
296 mAccountWasRestored
= false
;
299 mAccountWasSet
= true
;
300 mAccountWasRestored
= (newAccount
.equals(mAccount
));
301 mAccount
= newAccount
;
307 * Launches the account creation activity. To use when no ownCloud account is available
309 private void createFirstAccount() {
310 AccountManager am
= AccountManager
.get(getApplicationContext());
311 am
.addAccount(MainApp
.getAccountType(),
316 new AccountCreationCallback(),
325 protected void onSaveInstanceState(Bundle outState
) {
326 super.onSaveInstanceState(outState
);
327 outState
.putParcelable(FileActivity
.EXTRA_FILE
, mFile
);
328 outState
.putParcelable(FileActivity
.EXTRA_ACCOUNT
, mAccount
);
329 outState
.putBoolean(FileActivity
.EXTRA_FROM_NOTIFICATION
, mFromNotification
);
330 outState
.putLong(KEY_WAITING_FOR_OP_ID
, mFileOperationsHelper
.getOpIdWaitingFor());
331 outState
.putBoolean(KEY_TRY_SHARE_AGAIN
, mTryShareAgain
);
336 * Getter for the main {@link OCFile} handled by the activity.
338 * @return Main {@link OCFile} handled by the activity.
340 public OCFile
getFile() {
346 * Setter for the main {@link OCFile} handled by the activity.
348 * @param file Main {@link OCFile} to be handled by the activity.
350 public void setFile(OCFile file
) {
356 * Getter for the ownCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
358 * @return OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
360 public Account
getAccount() {
364 protected void setAccount(Account account
) {
369 * @return Value of mFromNotification: True if the Activity is launched by a notification
371 public boolean fromNotification() {
372 return mFromNotification
;
376 * @return 'True' when the Activity is finishing to enforce the setup of a new account.
378 protected boolean isRedirectingToSetupAccount() {
379 return mRedirectingToSetupAccount
;
382 public boolean isTryShareAgain(){
383 return mTryShareAgain
;
386 public void setTryShareAgain(boolean tryShareAgain
) {
387 mTryShareAgain
= tryShareAgain
;
390 public OperationsServiceBinder
getOperationsServiceBinder() {
391 return mOperationsServiceBinder
;
394 protected ServiceConnection
newTransferenceServiceConnection() {
399 * Helper class handling a callback from the {@link AccountManager} after the creation of
400 * a new ownCloud {@link Account} finished, successfully or not.
402 * At this moment, only called after the creation of the first account.
404 public class AccountCreationCallback
implements AccountManagerCallback
<Bundle
> {
407 public void run(AccountManagerFuture
<Bundle
> future
) {
408 FileActivity
.this.mRedirectingToSetupAccount
= false
;
409 boolean accountWasSet
= false
;
410 if (future
!= null
) {
413 result
= future
.getResult();
414 String name
= result
.getString(AccountManager
.KEY_ACCOUNT_NAME
);
415 String type
= result
.getString(AccountManager
.KEY_ACCOUNT_TYPE
);
416 if (AccountUtils
.setCurrentOwnCloudAccount(getApplicationContext(), name
)) {
417 setAccount(new Account(name
, type
), false
);
418 accountWasSet
= true
;
420 } catch (OperationCanceledException e
) {
421 Log_OC
.d(TAG
, "Account creation canceled");
423 } catch (Exception e
) {
424 Log_OC
.e(TAG
, "Account creation finished in exception: ", e
);
428 Log_OC
.e(TAG
, "Account creation callback with null bundle");
430 if (!accountWasSet
) {
431 moveTaskToBack(true
);
439 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
441 * Child classes must grant that state depending on the {@link Account} is updated.
443 protected void onAccountSet(boolean stateWasRecovered
) {
444 if (getAccount() != null
) {
445 mStorageManager
= new FileDataStorageManager(getAccount(), getContentResolver());
448 Log_OC
.wtf(TAG
, "onAccountChanged was called with NULL account associated!");
453 public FileDataStorageManager
getStorageManager() {
454 return mStorageManager
;
458 public OnRemoteOperationListener
getRemoteOperationListener() {
463 public Handler
getHandler() {
467 public FileOperationsHelper
getFileOperationsHelper() {
468 return mFileOperationsHelper
;
473 * @param operation Removal operation performed.
474 * @param result Result of the removal.
477 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
478 Log_OC
.d(TAG
, "Received result of operation in FileActivity - common behaviour for all the FileActivities ");
480 mFileOperationsHelper
.setOpIdWaitingFor(Long
.MAX_VALUE
);
482 if (!result
.isSuccess() && (
483 result
.getCode() == ResultCode
.UNAUTHORIZED
||
484 result
.isIdPRedirection() ||
485 (result
.isException() && result
.getException() instanceof AuthenticatorException
)
488 requestCredentialsUpdate();
490 if (result
.getCode() == ResultCode
.UNAUTHORIZED
) {
491 dismissLoadingDialog();
492 Toast t
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
,
493 operation
, getResources()),
497 mTryShareAgain
= false
;
499 } else if (operation
instanceof CreateShareOperation
) {
500 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
502 } else if (operation
instanceof UnshareLinkOperation
) {
503 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
505 } else if (operation
instanceof SynchronizeFolderOperation
) {
506 onSynchronizeFolderOperationFinish((SynchronizeFolderOperation
)operation
, result
);
511 protected void requestCredentialsUpdate() {
512 Intent updateAccountCredentials
= new Intent(this, AuthenticatorActivity
.class);
513 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACCOUNT
, getAccount());
514 updateAccountCredentials
.putExtra(
515 AuthenticatorActivity
.EXTRA_ACTION
,
516 AuthenticatorActivity
.ACTION_UPDATE_EXPIRED_TOKEN
);
517 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
518 startActivity(updateAccountCredentials
);
522 private void onCreateShareOperationFinish(CreateShareOperation operation
,
523 RemoteOperationResult result
) {
524 dismissLoadingDialog();
525 if (result
.isSuccess()) {
526 mTryShareAgain
= false
;
529 Intent sendIntent
= operation
.getSendIntent();
530 startActivity(sendIntent
);
532 // Detect Failure (403) --> needs Password
533 if (result
.getCode() == ResultCode
.SHARE_FORBIDDEN
) {
534 if (!isTryShareAgain()) {
535 SharePasswordDialogFragment dialog
=
536 SharePasswordDialogFragment
.newInstance(new OCFile(operation
.getPath()),
537 operation
.getSendIntent());
538 dialog
.show(getSupportFragmentManager(), DIALOG_SHARE_PASSWORD
);
540 Toast t
= Toast
.makeText(this,
541 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
544 mTryShareAgain
= false
;
547 Toast t
= Toast
.makeText(this,
548 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
556 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
557 dismissLoadingDialog();
559 if (result
.isSuccess()){
563 Toast t
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
569 private void onSynchronizeFolderOperationFinish(
570 SynchronizeFolderOperation operation
, RemoteOperationResult result
572 if (!result
.isSuccess() && result
.getCode() != ResultCode
.CANCELLED
){
573 Toast t
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
579 protected void updateFileFromDB(){
580 OCFile file
= getFile();
582 file
= getStorageManager().getFileByPath(file
.getRemotePath());
588 * Show loading dialog
590 public void showLoadingDialog() {
592 LoadingDialog loading
= new LoadingDialog(getResources().getString(R
.string
.wait_a_moment
));
593 FragmentManager fm
= getSupportFragmentManager();
594 FragmentTransaction ft
= fm
.beginTransaction();
595 loading
.show(ft
, DIALOG_WAIT_TAG
);
601 * Dismiss loading dialog
603 public void dismissLoadingDialog(){
604 Fragment frag
= getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG
);
606 LoadingDialog loading
= (LoadingDialog
) frag
;
612 private void doOnResumeAndBound() {
613 mOperationsServiceBinder
.addOperationListener(FileActivity
.this, mHandler
);
614 long waitingForOpId
= mFileOperationsHelper
.getOpIdWaitingFor();
615 if (waitingForOpId
<= Integer
.MAX_VALUE
) {
616 boolean wait
= mOperationsServiceBinder
.dispatchResultIfFinished((int)waitingForOpId
, this);
618 dismissLoadingDialog();
625 * Implements callback methods for service binding. Passed as a parameter to {
627 private class OperationsServiceConnection
implements ServiceConnection
{
630 public void onServiceConnected(ComponentName component
, IBinder service
) {
631 if (component
.equals(new ComponentName(FileActivity
.this, OperationsService
.class))) {
632 Log_OC
.d(TAG
, "Operations service connected");
633 mOperationsServiceBinder
= (OperationsServiceBinder
) service
;
634 /*if (!mOperationsServiceBinder.isPerformingBlockingOperation()) {
635 dismissLoadingDialog();
637 doOnResumeAndBound();
646 public void onServiceDisconnected(ComponentName component
) {
647 if (component
.equals(new ComponentName(FileActivity
.this, OperationsService
.class))) {
648 Log_OC
.d(TAG
, "Operations service disconnected");
649 mOperationsServiceBinder
= null
;
650 // TODO whatever could be waiting for the service is unbound
657 public FileDownloaderBinder
getFileDownloaderBinder() {
658 return mDownloaderBinder
;
663 public FileUploaderBinder
getFileUploaderBinder() {
664 return mUploaderBinder
;