536800bd33536bf2748d3310148cc0b7dddc7f4b
[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.lib.common.utils.Log_OC;
56 import com.owncloud.android.operations.CreateShareOperation;
57 import com.owncloud.android.operations.SynchronizeFolderOperation;
58 import com.owncloud.android.operations.UnshareLinkOperation;
59
60 import com.owncloud.android.services.OperationsService;
61 import com.owncloud.android.services.OperationsService.OperationsServiceBinder;
62 import com.owncloud.android.ui.dialog.LoadingDialog;
63 import com.owncloud.android.utils.ErrorMessageAdapter;
64
65
66 /**
67 * Activity with common behaviour for activities handling {@link OCFile}s in ownCloud {@link Account}s .
68 *
69 * @author David A. Velasco
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 super.onDestroy();
225 }
226
227
228 /**
229 * Sets and validates the ownCloud {@link Account} associated to the Activity.
230 *
231 * If not valid, tries to swap it for other valid and existing ownCloud {@link Account}.
232 *
233 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
234 *
235 * @param account New {@link Account} to set.
236 * @param savedAccount When 'true', account was retrieved from a saved instance state.
237 */
238 private void setAccount(Account account, boolean savedAccount) {
239 Account oldAccount = mAccount;
240 boolean validAccount = (account != null && AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), account.name));
241 if (validAccount) {
242 mAccount = account;
243 mAccountWasSet = true;
244 mAccountWasRestored = (savedAccount || mAccount.equals(oldAccount));
245
246 } else {
247 swapToDefaultAccount();
248 }
249 }
250
251
252 /**
253 * Tries to swap the current ownCloud {@link Account} for other valid and existing.
254 *
255 * If no valid ownCloud {@link Account} exists, the the user is requested
256 * to create a new ownCloud {@link Account}.
257 *
258 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
259 *
260 * @return 'True' if the checked {@link Account} was valid.
261 */
262 private void swapToDefaultAccount() {
263 // default to the most recently used account
264 Account newAccount = AccountUtils.getCurrentOwnCloudAccount(getApplicationContext());
265 if (newAccount == null) {
266 /// no account available: force account creation
267 createFirstAccount();
268 mRedirectingToSetupAccount = true;
269 mAccountWasSet = false;
270 mAccountWasRestored = false;
271
272 } else {
273 mAccountWasSet = true;
274 mAccountWasRestored = (newAccount.equals(mAccount));
275 mAccount = newAccount;
276 }
277 }
278
279
280 /**
281 * Launches the account creation activity. To use when no ownCloud account is available
282 */
283 private void createFirstAccount() {
284 AccountManager am = AccountManager.get(getApplicationContext());
285 am.addAccount(MainApp.getAccountType(),
286 null,
287 null,
288 null,
289 this,
290 new AccountCreationCallback(),
291 null);
292 }
293
294
295 /**
296 * {@inheritDoc}
297 */
298 @Override
299 protected void onSaveInstanceState(Bundle outState) {
300 super.onSaveInstanceState(outState);
301 outState.putParcelable(FileActivity.EXTRA_FILE, mFile);
302 outState.putParcelable(FileActivity.EXTRA_ACCOUNT, mAccount);
303 outState.putBoolean(FileActivity.EXTRA_FROM_NOTIFICATION, mFromNotification);
304 outState.putLong(KEY_WAITING_FOR_OP_ID, mFileOperationsHelper.getOpIdWaitingFor());
305 }
306
307
308 /**
309 * Getter for the main {@link OCFile} handled by the activity.
310 *
311 * @return Main {@link OCFile} handled by the activity.
312 */
313 public OCFile getFile() {
314 return mFile;
315 }
316
317
318 /**
319 * Setter for the main {@link OCFile} handled by the activity.
320 *
321 * @param file Main {@link OCFile} to be handled by the activity.
322 */
323 public void setFile(OCFile file) {
324 mFile = file;
325 }
326
327
328 /**
329 * Getter for the ownCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
330 *
331 * @return OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
332 */
333 public Account getAccount() {
334 return mAccount;
335 }
336
337 /**
338 * @return Value of mFromNotification: True if the Activity is launched by a notification
339 */
340 public boolean fromNotification() {
341 return mFromNotification;
342 }
343
344 /**
345 * @return 'True' when the Activity is finishing to enforce the setup of a new account.
346 */
347 protected boolean isRedirectingToSetupAccount() {
348 return mRedirectingToSetupAccount;
349 }
350
351
352 public OperationsServiceBinder getOperationsServiceBinder() {
353 return mOperationsServiceBinder;
354 }
355
356 protected ServiceConnection newTransferenceServiceConnection() {
357 return null;
358 }
359
360
361 /**
362 * Helper class handling a callback from the {@link AccountManager} after the creation of
363 * a new ownCloud {@link Account} finished, successfully or not.
364 *
365 * At this moment, only called after the creation of the first account.
366 *
367 * @author David A. Velasco
368 */
369 public class AccountCreationCallback implements AccountManagerCallback<Bundle> {
370
371 @Override
372 public void run(AccountManagerFuture<Bundle> future) {
373 FileActivity.this.mRedirectingToSetupAccount = false;
374 boolean accountWasSet = false;
375 if (future != null) {
376 try {
377 Bundle result;
378 result = future.getResult();
379 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
380 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
381 if (AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), name)) {
382 setAccount(new Account(name, type), false);
383 accountWasSet = true;
384 }
385 } catch (OperationCanceledException e) {
386 Log_OC.d(TAG, "Account creation canceled");
387
388 } catch (Exception e) {
389 Log_OC.e(TAG, "Account creation finished in exception: ", e);
390 }
391
392 } else {
393 Log_OC.e(TAG, "Account creation callback with null bundle");
394 }
395 if (!accountWasSet) {
396 moveTaskToBack(true);
397 }
398 }
399
400 }
401
402
403 /**
404 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
405 *
406 * Child classes must grant that state depending on the {@link Account} is updated.
407 */
408 protected void onAccountSet(boolean stateWasRecovered) {
409 if (getAccount() != null) {
410 mStorageManager = new FileDataStorageManager(getAccount(), getContentResolver());
411
412 } else {
413 Log_OC.wtf(TAG, "onAccountChanged was called with NULL account associated!");
414 }
415 }
416
417
418 public FileDataStorageManager getStorageManager() {
419 return mStorageManager;
420 }
421
422
423 public OnRemoteOperationListener getRemoteOperationListener() {
424 return this;
425 }
426
427
428 public Handler getHandler() {
429 return mHandler;
430 }
431
432 public FileOperationsHelper getFileOperationsHelper() {
433 return mFileOperationsHelper;
434 }
435
436 /**
437 *
438 * @param operation Removal operation performed.
439 * @param result Result of the removal.
440 */
441 @Override
442 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
443 Log_OC.d(TAG, "Received result of operation in FileActivity - common behaviour for all the FileActivities ");
444
445 mFileOperationsHelper.setOpIdWaitingFor(Long.MAX_VALUE);
446
447 if (!result.isSuccess() && (
448 result.getCode() == ResultCode.UNAUTHORIZED ||
449 result.isIdPRedirection() ||
450 (result.isException() && result.getException() instanceof AuthenticatorException)
451 )) {
452
453 requestCredentialsUpdate();
454
455 if (result.getCode() == ResultCode.UNAUTHORIZED) {
456 dismissLoadingDialog();
457 Toast t = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
458 Toast.LENGTH_LONG);
459 t.show();
460 }
461
462 } else if (operation instanceof CreateShareOperation) {
463 onCreateShareOperationFinish((CreateShareOperation) operation, result);
464
465 } else if (operation instanceof UnshareLinkOperation) {
466 onUnshareLinkOperationFinish((UnshareLinkOperation)operation, result);
467
468 } else if (operation instanceof SynchronizeFolderOperation) {
469 onSynchronizeFolderOperationFinish((SynchronizeFolderOperation)operation, result);
470
471 }
472 }
473
474 protected void requestCredentialsUpdate() {
475 Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
476 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, getAccount());
477 updateAccountCredentials.putExtra(
478 AuthenticatorActivity.EXTRA_ACTION,
479 AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
480 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
481 startActivity(updateAccountCredentials);
482 }
483
484
485 private void onCreateShareOperationFinish(CreateShareOperation operation, RemoteOperationResult result) {
486 dismissLoadingDialog();
487 if (result.isSuccess()) {
488 updateFileFromDB();
489
490 Intent sendIntent = operation.getSendIntent();
491 startActivity(sendIntent);
492
493 } else {
494 Toast t = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
495 Toast.LENGTH_LONG);
496 t.show();
497 }
498 }
499
500
501 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation, RemoteOperationResult result) {
502 dismissLoadingDialog();
503
504 if (result.isSuccess()){
505 updateFileFromDB();
506
507 } else {
508 Toast t = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
509 Toast.LENGTH_LONG);
510 t.show();
511 }
512 }
513
514 private void onSynchronizeFolderOperationFinish(SynchronizeFolderOperation operation, RemoteOperationResult result) {
515 if (!result.isSuccess() && result.getCode() != ResultCode.CANCELLED){
516 Toast t = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
517 Toast.LENGTH_LONG);
518 t.show();
519 }
520 }
521
522 protected void updateFileFromDB(){
523 OCFile file = getFile();
524 if (file != null) {
525 file = getStorageManager().getFileByPath(file.getRemotePath());
526 setFile(file);
527 }
528 }
529
530 /**
531 * Show loading dialog
532 */
533 public void showLoadingDialog() {
534 // Construct dialog
535 LoadingDialog loading = new LoadingDialog(getResources().getString(R.string.wait_a_moment));
536 FragmentManager fm = getSupportFragmentManager();
537 FragmentTransaction ft = fm.beginTransaction();
538 loading.show(ft, DIALOG_WAIT_TAG);
539
540 }
541
542
543 /**
544 * Dismiss loading dialog
545 */
546 public void dismissLoadingDialog(){
547 Fragment frag = getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG);
548 if (frag != null) {
549 LoadingDialog loading = (LoadingDialog) frag;
550 loading.dismiss();
551 }
552 }
553
554
555 private void doOnResumeAndBound() {
556 mOperationsServiceBinder.addOperationListener(FileActivity.this, mHandler);
557 long waitingForOpId = mFileOperationsHelper.getOpIdWaitingFor();
558 if (waitingForOpId <= Integer.MAX_VALUE) {
559 boolean wait = mOperationsServiceBinder.dispatchResultIfFinished((int)waitingForOpId, this);
560 if (!wait ) {
561 dismissLoadingDialog();
562 }
563 }
564 }
565
566
567 /**
568 * Implements callback methods for service binding. Passed as a parameter to {
569 */
570 private class OperationsServiceConnection implements ServiceConnection {
571
572 @Override
573 public void onServiceConnected(ComponentName component, IBinder service) {
574 if (component.equals(new ComponentName(FileActivity.this, OperationsService.class))) {
575 Log_OC.d(TAG, "Operations service connected");
576 mOperationsServiceBinder = (OperationsServiceBinder) service;
577 /*if (!mOperationsServiceBinder.isPerformingBlockingOperation()) {
578 dismissLoadingDialog();
579 }*/
580 doOnResumeAndBound();
581
582 } else {
583 return;
584 }
585 }
586
587
588 @Override
589 public void onServiceDisconnected(ComponentName component) {
590 if (component.equals(new ComponentName(FileActivity.this, OperationsService.class))) {
591 Log_OC.d(TAG, "Operations service disconnected");
592 mOperationsServiceBinder = null;
593 // TODO whatever could be waiting for the service is unbound
594 }
595 }
596 }
597
598
599 @Override
600 public FileDownloaderBinder getFileDownloaderBinder() {
601 return mDownloaderBinder;
602 }
603
604
605 @Override
606 public FileUploaderBinder getFileUploaderBinder() {
607 return mUploaderBinder;
608 };
609
610
611 }