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