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