e88d17f7f3b59772b68faa5ea076c582d53cec9c
[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 private boolean mAccountWasSet;
102
103 /** Flag to signal when the value of mAccount was restored from a saved state */
104 private 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 private 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 /**
345 * @return Value of mFromNotification: True if the Activity is launched by a notification
346 */
347 public boolean fromNotification() {
348 return mFromNotification;
349 }
350
351 /**
352 * @return 'True' when the Activity is finishing to enforce the setup of a new account.
353 */
354 protected boolean isRedirectingToSetupAccount() {
355 return mRedirectingToSetupAccount;
356 }
357
358 public boolean isTryShareAgain(){
359 return mTryShareAgain;
360 }
361
362 public void setTryShareAgain(boolean tryShareAgain) {
363 mTryShareAgain = tryShareAgain;
364 }
365
366 public OperationsServiceBinder getOperationsServiceBinder() {
367 return mOperationsServiceBinder;
368 }
369
370 protected ServiceConnection newTransferenceServiceConnection() {
371 return null;
372 }
373
374 /**
375 * Helper class handling a callback from the {@link AccountManager} after the creation of
376 * a new ownCloud {@link Account} finished, successfully or not.
377 *
378 * At this moment, only called after the creation of the first account.
379 */
380 public class AccountCreationCallback implements AccountManagerCallback<Bundle> {
381
382 @Override
383 public void run(AccountManagerFuture<Bundle> future) {
384 FileActivity.this.mRedirectingToSetupAccount = false;
385 boolean accountWasSet = false;
386 if (future != null) {
387 try {
388 Bundle result;
389 result = future.getResult();
390 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
391 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
392 if (AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), name)) {
393 setAccount(new Account(name, type), false);
394 accountWasSet = true;
395 }
396 } catch (OperationCanceledException e) {
397 Log_OC.d(TAG, "Account creation canceled");
398
399 } catch (Exception e) {
400 Log_OC.e(TAG, "Account creation finished in exception: ", e);
401 }
402
403 } else {
404 Log_OC.e(TAG, "Account creation callback with null bundle");
405 }
406 if (!accountWasSet) {
407 moveTaskToBack(true);
408 }
409 }
410
411 }
412
413
414 /**
415 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
416 *
417 * Child classes must grant that state depending on the {@link Account} is updated.
418 */
419 protected void onAccountSet(boolean stateWasRecovered) {
420 if (getAccount() != null) {
421 mStorageManager = new FileDataStorageManager(getAccount(), getContentResolver());
422
423 } else {
424 Log_OC.wtf(TAG, "onAccountChanged was called with NULL account associated!");
425 }
426 }
427
428
429 public FileDataStorageManager getStorageManager() {
430 return mStorageManager;
431 }
432
433
434 public OnRemoteOperationListener getRemoteOperationListener() {
435 return this;
436 }
437
438
439 public Handler getHandler() {
440 return mHandler;
441 }
442
443 public FileOperationsHelper getFileOperationsHelper() {
444 return mFileOperationsHelper;
445 }
446
447 /**
448 *
449 * @param operation Removal operation performed.
450 * @param result Result of the removal.
451 */
452 @Override
453 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
454 Log_OC.d(TAG, "Received result of operation in FileActivity - common behaviour for all the FileActivities ");
455
456 mFileOperationsHelper.setOpIdWaitingFor(Long.MAX_VALUE);
457
458 if (!result.isSuccess() && (
459 result.getCode() == ResultCode.UNAUTHORIZED ||
460 result.isIdPRedirection() ||
461 (result.isException() && result.getException() instanceof AuthenticatorException)
462 )) {
463
464 requestCredentialsUpdate();
465
466 if (result.getCode() == ResultCode.UNAUTHORIZED) {
467 dismissLoadingDialog();
468 Toast t = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result,
469 operation, getResources()),
470 Toast.LENGTH_LONG);
471 t.show();
472 }
473
474 } else if (operation instanceof CreateShareOperation) {
475 onCreateShareOperationFinish((CreateShareOperation) operation, result);
476
477 } else if (operation instanceof UnshareLinkOperation) {
478 onUnshareLinkOperationFinish((UnshareLinkOperation)operation, result);
479
480 } else if (operation instanceof SynchronizeFolderOperation) {
481 onSynchronizeFolderOperationFinish((SynchronizeFolderOperation)operation, result);
482
483 }
484 }
485
486 protected void requestCredentialsUpdate() {
487 Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
488 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, getAccount());
489 updateAccountCredentials.putExtra(
490 AuthenticatorActivity.EXTRA_ACTION,
491 AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
492 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
493 startActivity(updateAccountCredentials);
494 }
495
496
497 private void onCreateShareOperationFinish(CreateShareOperation operation,
498 RemoteOperationResult result) {
499 dismissLoadingDialog();
500 if (result.isSuccess()) {
501 mTryShareAgain = false;
502 updateFileFromDB();
503
504 Intent sendIntent = operation.getSendIntent();
505 startActivity(sendIntent);
506 } else {
507 // Detect Failure (403) --> needs Password
508 if (result.getCode() == ResultCode.SHARE_FORBIDDEN) {
509 if (!isTryShareAgain()) {
510 SharePasswordDialogFragment dialog =
511 SharePasswordDialogFragment.newInstance(new OCFile(operation.getPath()),
512 operation.getSendIntent());
513 dialog.show(getSupportFragmentManager(), DIALOG_SHARE_PASSWORD);
514 } else {
515 Toast t = Toast.makeText(this,
516 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
517 Toast.LENGTH_LONG);
518 t.show();
519 mTryShareAgain = false;
520 }
521 } else {
522 Toast t = Toast.makeText(this,
523 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
524 Toast.LENGTH_LONG);
525 t.show();
526 }
527 }
528 }
529
530
531 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation, RemoteOperationResult result) {
532 dismissLoadingDialog();
533
534 if (result.isSuccess()){
535 updateFileFromDB();
536
537 } else {
538 Toast t = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
539 Toast.LENGTH_LONG);
540 t.show();
541 }
542 }
543
544 private void onSynchronizeFolderOperationFinish(SynchronizeFolderOperation operation, RemoteOperationResult result) {
545 if (!result.isSuccess() && result.getCode() != ResultCode.CANCELLED){
546 Toast t = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
547 Toast.LENGTH_LONG);
548 t.show();
549 }
550 }
551
552 protected void updateFileFromDB(){
553 OCFile file = getFile();
554 if (file != null) {
555 file = getStorageManager().getFileByPath(file.getRemotePath());
556 setFile(file);
557 }
558 }
559
560 /**
561 * Show loading dialog
562 */
563 public void showLoadingDialog() {
564 // Construct dialog
565 LoadingDialog loading = new LoadingDialog(getResources().getString(R.string.wait_a_moment));
566 FragmentManager fm = getSupportFragmentManager();
567 FragmentTransaction ft = fm.beginTransaction();
568 loading.show(ft, DIALOG_WAIT_TAG);
569
570 }
571
572
573 /**
574 * Dismiss loading dialog
575 */
576 public void dismissLoadingDialog(){
577 Fragment frag = getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG);
578 if (frag != null) {
579 LoadingDialog loading = (LoadingDialog) frag;
580 loading.dismiss();
581 }
582 }
583
584
585 private void doOnResumeAndBound() {
586 mOperationsServiceBinder.addOperationListener(FileActivity.this, mHandler);
587 long waitingForOpId = mFileOperationsHelper.getOpIdWaitingFor();
588 if (waitingForOpId <= Integer.MAX_VALUE) {
589 boolean wait = mOperationsServiceBinder.dispatchResultIfFinished((int)waitingForOpId, this);
590 if (!wait ) {
591 dismissLoadingDialog();
592 }
593 }
594 }
595
596
597 /**
598 * Implements callback methods for service binding. Passed as a parameter to {
599 */
600 private class OperationsServiceConnection implements ServiceConnection {
601
602 @Override
603 public void onServiceConnected(ComponentName component, IBinder service) {
604 if (component.equals(new ComponentName(FileActivity.this, OperationsService.class))) {
605 Log_OC.d(TAG, "Operations service connected");
606 mOperationsServiceBinder = (OperationsServiceBinder) service;
607 /*if (!mOperationsServiceBinder.isPerformingBlockingOperation()) {
608 dismissLoadingDialog();
609 }*/
610 doOnResumeAndBound();
611
612 } else {
613 return;
614 }
615 }
616
617
618 @Override
619 public void onServiceDisconnected(ComponentName component) {
620 if (component.equals(new ComponentName(FileActivity.this, OperationsService.class))) {
621 Log_OC.d(TAG, "Operations service disconnected");
622 mOperationsServiceBinder = null;
623 // TODO whatever could be waiting for the service is unbound
624 }
625 }
626 }
627
628
629 @Override
630 public FileDownloaderBinder getFileDownloaderBinder() {
631 return mDownloaderBinder;
632 }
633
634
635 @Override
636 public FileUploaderBinder getFileUploaderBinder() {
637 return mUploaderBinder;
638 }
639
640
641 }