Save cookies in FileActivity#onPause
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / activity / FileActivity.java
1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2014 ownCloud Inc.
4 *
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.
8 *
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.
13 *
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/>.
16 *
17 */
18
19 package com.owncloud.android.ui.activity;
20
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;
38
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.OwnCloudClientMap;
52 import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;
53 import com.owncloud.android.lib.common.operations.RemoteOperation;
54 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
55 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
56 import com.owncloud.android.operations.CreateShareOperation;
57 import com.owncloud.android.operations.UnshareLinkOperation;
58
59 import com.owncloud.android.services.OperationsService;
60 import com.owncloud.android.services.OperationsService.OperationsServiceBinder;
61 import com.owncloud.android.ui.dialog.LoadingDialog;
62 import com.owncloud.android.utils.ErrorMessageAdapter;
63 import com.owncloud.android.utils.Log_OC;
64
65
66 /**
67 * Activity with common behaviour for activities handling {@link OCFile}s in ownCloud {@link Account}s .
68 *
69 * @author David A. Velasco
70 */
71 public class FileActivity extends SherlockFragmentActivity
72 implements OnRemoteOperationListener, ComponentsGetter {
73
74 public static final String EXTRA_FILE = "com.owncloud.android.ui.activity.FILE";
75 public static final String EXTRA_ACCOUNT = "com.owncloud.android.ui.activity.ACCOUNT";
76 public static final String EXTRA_WAITING_TO_PREVIEW = "com.owncloud.android.ui.activity.WAITING_TO_PREVIEW";
77 public static final String EXTRA_FROM_NOTIFICATION= "com.owncloud.android.ui.activity.FROM_NOTIFICATION";
78
79 public static final String TAG = FileActivity.class.getSimpleName();
80
81 private static final String DIALOG_WAIT_TAG = "DIALOG_WAIT";
82 private static final String KEY_WAITING_FOR_OP_ID = "WAITING_FOR_OP_ID";;
83
84
85 /** OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located. */
86 private Account mAccount;
87
88 /** Main {@link OCFile} handled by the activity.*/
89 private OCFile mFile;
90
91 /** Flag to signal that the activity will is finishing to enforce the creation of an ownCloud {@link Account} */
92 private boolean mRedirectingToSetupAccount = false;
93
94 /** Flag to signal when the value of mAccount was set */
95 private boolean mAccountWasSet;
96
97 /** Flag to signal when the value of mAccount was restored from a saved state */
98 private boolean mAccountWasRestored;
99
100 /** Flag to signal if the activity is launched by a notification */
101 private boolean mFromNotification;
102
103 /** Messages handler associated to the main thread and the life cycle of the activity */
104 private Handler mHandler;
105
106 /** Access point to the cached database for the current ownCloud {@link Account} */
107 private FileDataStorageManager mStorageManager = null;
108
109 private FileOperationsHelper mFileOperationsHelper;
110
111 private ServiceConnection mOperationsServiceConnection = null;
112
113 private OperationsServiceBinder mOperationsServiceBinder = null;
114
115 protected FileDownloaderBinder mDownloaderBinder = null;
116 protected FileUploaderBinder mUploaderBinder = null;
117 private ServiceConnection mDownloadServiceConnection, mUploadServiceConnection = null;
118
119
120 /**
121 * Loads the ownCloud {@link Account} and main {@link OCFile} to be handled by the instance of
122 * the {@link FileActivity}.
123 *
124 * Grants that a valid ownCloud {@link Account} is associated to the instance, or that the user
125 * is requested to create a new one.
126 */
127 @Override
128 protected void onCreate(Bundle savedInstanceState) {
129 super.onCreate(savedInstanceState);
130 mHandler = new Handler();
131 mFileOperationsHelper = new FileOperationsHelper(this);
132 Account account;
133 if(savedInstanceState != null) {
134 account = savedInstanceState.getParcelable(FileActivity.EXTRA_ACCOUNT);
135 mFile = savedInstanceState.getParcelable(FileActivity.EXTRA_FILE);
136 mFromNotification = savedInstanceState.getBoolean(FileActivity.EXTRA_FROM_NOTIFICATION);
137 mFileOperationsHelper.setOpIdWaitingFor(
138 savedInstanceState.getLong(KEY_WAITING_FOR_OP_ID, Long.MAX_VALUE)
139 );
140 } else {
141 account = getIntent().getParcelableExtra(FileActivity.EXTRA_ACCOUNT);
142 mFile = getIntent().getParcelableExtra(FileActivity.EXTRA_FILE);
143 mFromNotification = getIntent().getBooleanExtra(FileActivity.EXTRA_FROM_NOTIFICATION, false);
144 }
145
146 setAccount(account, savedInstanceState != null);
147
148 mOperationsServiceConnection = new OperationsServiceConnection();
149 bindService(new Intent(this, OperationsService.class), mOperationsServiceConnection, Context.BIND_AUTO_CREATE);
150
151 mDownloadServiceConnection = newTransferenceServiceConnection();
152 if (mDownloadServiceConnection != null) {
153 bindService(new Intent(this, FileDownloader.class), mDownloadServiceConnection, Context.BIND_AUTO_CREATE);
154 }
155 mUploadServiceConnection = newTransferenceServiceConnection();
156 if (mUploadServiceConnection != null) {
157 bindService(new Intent(this, FileUploader.class), mUploadServiceConnection, Context.BIND_AUTO_CREATE);
158 }
159
160 }
161
162
163 /**
164 * Since ownCloud {@link Account}s can be managed from the system setting menu,
165 * the existence of the {@link Account} associated to the instance must be checked
166 * every time it is restarted.
167 */
168 @Override
169 protected void onRestart() {
170 super.onRestart();
171 boolean validAccount = (mAccount != null && AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), mAccount.name));
172 if (!validAccount) {
173 swapToDefaultAccount();
174 }
175 }
176
177
178 @Override
179 protected void onStart() {
180 super.onStart();
181
182 if (mAccountWasSet) {
183 onAccountSet(mAccountWasRestored);
184 }
185 }
186
187 @Override
188 protected void onResume() {
189 super.onResume();
190
191 if (mOperationsServiceBinder != null) {
192 doOnResumeAndBound();
193 }
194
195 }
196
197 @Override
198 protected void onPause() {
199 // Save cookies here
200 Log_OC.wtf(TAG, "Saving Cookies" );
201 if (mAccount != null) {
202 OwnCloudClientMap.saveClient(mAccount, this);
203 }
204
205 if (mOperationsServiceBinder != null) {
206 mOperationsServiceBinder.removeOperationListener(this);
207 }
208
209 super.onPause();
210 }
211
212
213 @Override
214 protected void onDestroy() {
215 if (mOperationsServiceConnection != null) {
216 unbindService(mOperationsServiceConnection);
217 mOperationsServiceBinder = null;
218 }
219 if (mDownloadServiceConnection != null) {
220 unbindService(mDownloadServiceConnection);
221 mDownloadServiceConnection = null;
222 }
223 if (mUploadServiceConnection != null) {
224 unbindService(mUploadServiceConnection);
225 mUploadServiceConnection = null;
226 }
227 super.onDestroy();
228 }
229
230
231 /**
232 * Sets and validates the ownCloud {@link Account} associated to the Activity.
233 *
234 * If not valid, tries to swap it for other valid and existing ownCloud {@link Account}.
235 *
236 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
237 *
238 * @param account New {@link Account} to set.
239 * @param savedAccount When 'true', account was retrieved from a saved instance state.
240 */
241 private void setAccount(Account account, boolean savedAccount) {
242 Account oldAccount = mAccount;
243 boolean validAccount = (account != null && AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), account.name));
244 if (validAccount) {
245 mAccount = account;
246 mAccountWasSet = true;
247 mAccountWasRestored = (savedAccount || mAccount.equals(oldAccount));
248
249 } else {
250 swapToDefaultAccount();
251 }
252 }
253
254
255 /**
256 * Tries to swap the current ownCloud {@link Account} for other valid and existing.
257 *
258 * If no valid ownCloud {@link Account} exists, the the user is requested
259 * to create a new ownCloud {@link Account}.
260 *
261 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
262 *
263 * @return 'True' if the checked {@link Account} was valid.
264 */
265 private void swapToDefaultAccount() {
266 // default to the most recently used account
267 Account newAccount = AccountUtils.getCurrentOwnCloudAccount(getApplicationContext());
268 if (newAccount == null) {
269 /// no account available: force account creation
270 createFirstAccount();
271 mRedirectingToSetupAccount = true;
272 mAccountWasSet = false;
273 mAccountWasRestored = false;
274
275 } else {
276 mAccountWasSet = true;
277 mAccountWasRestored = (newAccount.equals(mAccount));
278 mAccount = newAccount;
279 }
280 }
281
282
283 /**
284 * Launches the account creation activity. To use when no ownCloud account is available
285 */
286 private void createFirstAccount() {
287 AccountManager am = AccountManager.get(getApplicationContext());
288 am.addAccount(MainApp.getAccountType(),
289 null,
290 null,
291 null,
292 this,
293 new AccountCreationCallback(),
294 null);
295 }
296
297
298 /**
299 * {@inheritDoc}
300 */
301 @Override
302 protected void onSaveInstanceState(Bundle outState) {
303 super.onSaveInstanceState(outState);
304 outState.putParcelable(FileActivity.EXTRA_FILE, mFile);
305 outState.putParcelable(FileActivity.EXTRA_ACCOUNT, mAccount);
306 outState.putBoolean(FileActivity.EXTRA_FROM_NOTIFICATION, mFromNotification);
307 outState.putLong(KEY_WAITING_FOR_OP_ID, mFileOperationsHelper.getOpIdWaitingFor());
308 }
309
310
311 /**
312 * Getter for the main {@link OCFile} handled by the activity.
313 *
314 * @return Main {@link OCFile} handled by the activity.
315 */
316 public OCFile getFile() {
317 return mFile;
318 }
319
320
321 /**
322 * Setter for the main {@link OCFile} handled by the activity.
323 *
324 * @param file Main {@link OCFile} to be handled by the activity.
325 */
326 public void setFile(OCFile file) {
327 mFile = file;
328 }
329
330
331 /**
332 * Getter for the ownCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
333 *
334 * @return OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
335 */
336 public Account getAccount() {
337 return mAccount;
338 }
339
340 /**
341 * @return Value of mFromNotification: True if the Activity is launched by a notification
342 */
343 public boolean fromNotification() {
344 return mFromNotification;
345 }
346
347 /**
348 * @return 'True' when the Activity is finishing to enforce the setup of a new account.
349 */
350 protected boolean isRedirectingToSetupAccount() {
351 return mRedirectingToSetupAccount;
352 }
353
354
355 public OperationsServiceBinder getOperationsServiceBinder() {
356 return mOperationsServiceBinder;
357 }
358
359 protected ServiceConnection newTransferenceServiceConnection() {
360 return null;
361 }
362
363
364 /**
365 * Helper class handling a callback from the {@link AccountManager} after the creation of
366 * a new ownCloud {@link Account} finished, successfully or not.
367 *
368 * At this moment, only called after the creation of the first account.
369 *
370 * @author David A. Velasco
371 */
372 public class AccountCreationCallback implements AccountManagerCallback<Bundle> {
373
374 @Override
375 public void run(AccountManagerFuture<Bundle> future) {
376 FileActivity.this.mRedirectingToSetupAccount = false;
377 boolean accountWasSet = false;
378 if (future != null) {
379 try {
380 Bundle result;
381 result = future.getResult();
382 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
383 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
384 if (AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), name)) {
385 setAccount(new Account(name, type), false);
386 accountWasSet = true;
387 }
388 } catch (OperationCanceledException e) {
389 Log_OC.d(TAG, "Account creation canceled");
390
391 } catch (Exception e) {
392 Log_OC.e(TAG, "Account creation finished in exception: ", e);
393 }
394
395 } else {
396 Log_OC.e(TAG, "Account creation callback with null bundle");
397 }
398 if (!accountWasSet) {
399 moveTaskToBack(true);
400 }
401 }
402
403 }
404
405
406 /**
407 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
408 *
409 * Child classes must grant that state depending on the {@link Account} is updated.
410 */
411 protected void onAccountSet(boolean stateWasRecovered) {
412 if (getAccount() != null) {
413 mStorageManager = new FileDataStorageManager(getAccount(), getContentResolver());
414
415 } else {
416 Log_OC.wtf(TAG, "onAccountChanged was called with NULL account associated!");
417 }
418 }
419
420
421 public FileDataStorageManager getStorageManager() {
422 return mStorageManager;
423 }
424
425
426 public OnRemoteOperationListener getRemoteOperationListener() {
427 return this;
428 }
429
430
431 public Handler getHandler() {
432 return mHandler;
433 }
434
435 public FileOperationsHelper getFileOperationsHelper() {
436 return mFileOperationsHelper;
437 }
438
439 /**
440 *
441 * @param operation Removal operation performed.
442 * @param result Result of the removal.
443 */
444 @Override
445 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
446 Log_OC.d(TAG, "Received result of operation in FileActivity - common behaviour for all the FileActivities ");
447
448 mFileOperationsHelper.setOpIdWaitingFor(Long.MAX_VALUE);
449
450 if (!result.isSuccess() && (
451 result.getCode() == ResultCode.UNAUTHORIZED ||
452 result.isIdPRedirection() ||
453 (result.isException() && result.getException() instanceof AuthenticatorException)
454 )) {
455
456 requestCredentialsUpdate();
457
458 if (result.getCode() == ResultCode.UNAUTHORIZED) {
459 dismissLoadingDialog();
460 Toast t = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
461 Toast.LENGTH_LONG);
462 t.show();
463 }
464
465 } else if (operation instanceof CreateShareOperation) {
466 onCreateShareOperationFinish((CreateShareOperation) operation, result);
467
468 } else if (operation instanceof UnshareLinkOperation) {
469 onUnshareLinkOperationFinish((UnshareLinkOperation)operation, result);
470
471 }
472 }
473
474 protected void requestCredentialsUpdate() {
475 Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
476 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, getAccount());
477 updateAccountCredentials.putExtra(
478 AuthenticatorActivity.EXTRA_ACTION,
479 AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
480 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
481 startActivity(updateAccountCredentials);
482 }
483
484
485 private void onCreateShareOperationFinish(CreateShareOperation operation, RemoteOperationResult result) {
486 dismissLoadingDialog();
487 if (result.isSuccess()) {
488 updateFileFromDB();
489
490 Intent sendIntent = operation.getSendIntent();
491 startActivity(sendIntent);
492
493 } else {
494 Toast t = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
495 Toast.LENGTH_LONG);
496 t.show();
497 }
498 }
499
500
501 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation, RemoteOperationResult result) {
502 dismissLoadingDialog();
503
504 if (result.isSuccess()){
505 updateFileFromDB();
506
507 } else {
508 Toast t = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
509 Toast.LENGTH_LONG);
510 t.show();
511 }
512 }
513
514
515 private void updateFileFromDB(){
516 OCFile file = getStorageManager().getFileByPath(getFile().getRemotePath());
517 if (file != null) {
518 setFile(file);
519 }
520 }
521
522 /**
523 * Show loading dialog
524 */
525 public void showLoadingDialog() {
526 // Construct dialog
527 LoadingDialog loading = new LoadingDialog(getResources().getString(R.string.wait_a_moment));
528 FragmentManager fm = getSupportFragmentManager();
529 FragmentTransaction ft = fm.beginTransaction();
530 loading.show(ft, DIALOG_WAIT_TAG);
531
532 }
533
534
535 /**
536 * Dismiss loading dialog
537 */
538 public void dismissLoadingDialog(){
539 Fragment frag = getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG);
540 if (frag != null) {
541 LoadingDialog loading = (LoadingDialog) frag;
542 loading.dismiss();
543 }
544 }
545
546
547 private void doOnResumeAndBound() {
548 mOperationsServiceBinder.addOperationListener(FileActivity.this, mHandler);
549 long waitingForOpId = mFileOperationsHelper.getOpIdWaitingFor();
550 if (waitingForOpId <= Integer.MAX_VALUE) {
551 boolean wait = mOperationsServiceBinder.dispatchResultIfFinished((int)waitingForOpId, this);
552 if (!wait ) {
553 dismissLoadingDialog();
554 }
555 }
556 }
557
558
559 /**
560 * Implements callback methods for service binding. Passed as a parameter to {
561 */
562 private class OperationsServiceConnection implements ServiceConnection {
563
564 @Override
565 public void onServiceConnected(ComponentName component, IBinder service) {
566 if (component.equals(new ComponentName(FileActivity.this, OperationsService.class))) {
567 Log_OC.d(TAG, "Operations service connected");
568 mOperationsServiceBinder = (OperationsServiceBinder) service;
569 /*if (!mOperationsServiceBinder.isPerformingBlockingOperation()) {
570 dismissLoadingDialog();
571 }*/
572 doOnResumeAndBound();
573
574 } else {
575 return;
576 }
577 }
578
579
580 @Override
581 public void onServiceDisconnected(ComponentName component) {
582 if (component.equals(new ComponentName(FileActivity.this, OperationsService.class))) {
583 Log_OC.d(TAG, "Operations service disconnected");
584 mOperationsServiceBinder = null;
585 // TODO whatever could be waiting for the service is unbound
586 }
587 }
588 }
589
590
591 @Override
592 public FileDownloaderBinder getFileDownloaderBinder() {
593 return mDownloaderBinder;
594 }
595
596
597 @Override
598 public FileUploaderBinder getFileUploaderBinder() {
599 return mUploaderBinder;
600 };
601
602
603 }