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