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