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