Use ErrorMessageAdapter to access the error string when an error in a finished foregr...
[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.operations.CreateShareOperation;
56 import com.owncloud.android.operations.UnshareLinkOperation;
57
58 import com.owncloud.android.services.OperationsService;
59 import com.owncloud.android.services.OperationsService.OperationsServiceBinder;
60 import com.owncloud.android.ui.dialog.LoadingDialog;
61 import com.owncloud.android.utils.ErrorMessageAdapter;
62 import com.owncloud.android.utils.Log_OC;
63
64
65 /**
66 * Activity with common behaviour for activities handling {@link OCFile}s in ownCloud {@link Account}s .
67 *
68 * @author David A. Velasco
69 */
70 public class FileActivity extends SherlockFragmentActivity
71 implements OnRemoteOperationListener, ComponentsGetter {
72
73 public static final String EXTRA_FILE = "com.owncloud.android.ui.activity.FILE";
74 public static final String EXTRA_ACCOUNT = "com.owncloud.android.ui.activity.ACCOUNT";
75 public static final String EXTRA_WAITING_TO_PREVIEW = "com.owncloud.android.ui.activity.WAITING_TO_PREVIEW";
76 public static final String EXTRA_FROM_NOTIFICATION= "com.owncloud.android.ui.activity.FROM_NOTIFICATION";
77
78 public static final String TAG = FileActivity.class.getSimpleName();
79
80 private static final String DIALOG_WAIT_TAG = "DIALOG_WAIT";
81 private static final String KEY_WAITING_FOR_OP_ID = "WAITING_FOR_OP_ID";;
82
83
84 /** OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located. */
85 private Account mAccount;
86
87 /** Main {@link OCFile} handled by the activity.*/
88 private OCFile mFile;
89
90 /** Flag to signal that the activity will is finishing to enforce the creation of an ownCloud {@link Account} */
91 private boolean mRedirectingToSetupAccount = false;
92
93 /** Flag to signal when the value of mAccount was set */
94 private boolean mAccountWasSet;
95
96 /** Flag to signal when the value of mAccount was restored from a saved state */
97 private boolean mAccountWasRestored;
98
99 /** Flag to signal if the activity is launched by a notification */
100 private boolean mFromNotification;
101
102 /** Messages handler associated to the main thread and the life cycle of the activity */
103 private Handler mHandler;
104
105 /** Access point to the cached database for the current ownCloud {@link Account} */
106 private FileDataStorageManager mStorageManager = null;
107
108 private FileOperationsHelper mFileOperationsHelper;
109
110 private ServiceConnection mOperationsServiceConnection = null;
111
112 private OperationsServiceBinder mOperationsServiceBinder = null;
113
114 protected FileDownloaderBinder mDownloaderBinder = null;
115 protected FileUploaderBinder mUploaderBinder = null;
116 private ServiceConnection mDownloadServiceConnection, mUploadServiceConnection = null;
117
118
119 /**
120 * Loads the ownCloud {@link Account} and main {@link OCFile} to be handled by the instance of
121 * the {@link FileActivity}.
122 *
123 * Grants that a valid ownCloud {@link Account} is associated to the instance, or that the user
124 * is requested to create a new one.
125 */
126 @Override
127 protected void onCreate(Bundle savedInstanceState) {
128 super.onCreate(savedInstanceState);
129 mHandler = new Handler();
130 mFileOperationsHelper = new FileOperationsHelper(this);
131 Account account;
132 if(savedInstanceState != null) {
133 account = savedInstanceState.getParcelable(FileActivity.EXTRA_ACCOUNT);
134 mFile = savedInstanceState.getParcelable(FileActivity.EXTRA_FILE);
135 mFromNotification = savedInstanceState.getBoolean(FileActivity.EXTRA_FROM_NOTIFICATION);
136 mFileOperationsHelper.setOpIdWaitingFor(
137 savedInstanceState.getLong(KEY_WAITING_FOR_OP_ID, Long.MAX_VALUE)
138 );
139 } else {
140 account = getIntent().getParcelableExtra(FileActivity.EXTRA_ACCOUNT);
141 mFile = getIntent().getParcelableExtra(FileActivity.EXTRA_FILE);
142 mFromNotification = getIntent().getBooleanExtra(FileActivity.EXTRA_FROM_NOTIFICATION, false);
143 }
144
145 setAccount(account, savedInstanceState != null);
146
147 mOperationsServiceConnection = new OperationsServiceConnection();
148 bindService(new Intent(this, OperationsService.class), mOperationsServiceConnection, Context.BIND_AUTO_CREATE);
149
150 mDownloadServiceConnection = newTransferenceServiceConnection();
151 if (mDownloadServiceConnection != null) {
152 bindService(new Intent(this, FileDownloader.class), mDownloadServiceConnection, Context.BIND_AUTO_CREATE);
153 }
154 mUploadServiceConnection = newTransferenceServiceConnection();
155 if (mUploadServiceConnection != null) {
156 bindService(new Intent(this, FileUploader.class), mUploadServiceConnection, Context.BIND_AUTO_CREATE);
157 }
158
159 }
160
161
162 /**
163 * Since ownCloud {@link Account}s can be managed from the system setting menu,
164 * the existence of the {@link Account} associated to the instance must be checked
165 * every time it is restarted.
166 */
167 @Override
168 protected void onRestart() {
169 super.onRestart();
170 boolean validAccount = (mAccount != null && AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), mAccount.name));
171 if (!validAccount) {
172 swapToDefaultAccount();
173 }
174 }
175
176
177 @Override
178 protected void onStart() {
179 super.onStart();
180
181 if (mAccountWasSet) {
182 onAccountSet(mAccountWasRestored);
183 }
184 }
185
186 @Override
187 protected void onResume() {
188 super.onResume();
189
190 if (mOperationsServiceBinder != null) {
191 doOnResumeAndBound();
192 }
193
194 }
195
196 @Override
197 protected void onPause() {
198 if (mOperationsServiceBinder != null) {
199 mOperationsServiceBinder.removeOperationListener(this);
200 }
201
202 super.onPause();
203 }
204
205
206 @Override
207 protected void onDestroy() {
208 if (mOperationsServiceConnection != null) {
209 unbindService(mOperationsServiceConnection);
210 mOperationsServiceBinder = null;
211 }
212 if (mDownloadServiceConnection != null) {
213 unbindService(mDownloadServiceConnection);
214 mDownloadServiceConnection = null;
215 }
216 if (mUploadServiceConnection != null) {
217 unbindService(mUploadServiceConnection);
218 mUploadServiceConnection = null;
219 }
220 super.onDestroy();
221 }
222
223
224 /**
225 * Sets and validates the ownCloud {@link Account} associated to the Activity.
226 *
227 * If not valid, tries to swap it for other valid and existing ownCloud {@link Account}.
228 *
229 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
230 *
231 * @param account New {@link Account} to set.
232 * @param savedAccount When 'true', account was retrieved from a saved instance state.
233 */
234 private void setAccount(Account account, boolean savedAccount) {
235 Account oldAccount = mAccount;
236 boolean validAccount = (account != null && AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), account.name));
237 if (validAccount) {
238 mAccount = account;
239 mAccountWasSet = true;
240 mAccountWasRestored = (savedAccount || mAccount.equals(oldAccount));
241
242 } else {
243 swapToDefaultAccount();
244 }
245 }
246
247
248 /**
249 * Tries to swap the current ownCloud {@link Account} for other valid and existing.
250 *
251 * If no valid ownCloud {@link Account} exists, the the user is requested
252 * to create a new ownCloud {@link Account}.
253 *
254 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
255 *
256 * @return 'True' if the checked {@link Account} was valid.
257 */
258 private void swapToDefaultAccount() {
259 // default to the most recently used account
260 Account newAccount = AccountUtils.getCurrentOwnCloudAccount(getApplicationContext());
261 if (newAccount == null) {
262 /// no account available: force account creation
263 createFirstAccount();
264 mRedirectingToSetupAccount = true;
265 mAccountWasSet = false;
266 mAccountWasRestored = false;
267
268 } else {
269 mAccountWasSet = true;
270 mAccountWasRestored = (newAccount.equals(mAccount));
271 mAccount = newAccount;
272 }
273 }
274
275
276 /**
277 * Launches the account creation activity. To use when no ownCloud account is available
278 */
279 private void createFirstAccount() {
280 AccountManager am = AccountManager.get(getApplicationContext());
281 am.addAccount(MainApp.getAccountType(),
282 null,
283 null,
284 null,
285 this,
286 new AccountCreationCallback(),
287 null);
288 }
289
290
291 /**
292 * {@inheritDoc}
293 */
294 @Override
295 protected void onSaveInstanceState(Bundle outState) {
296 super.onSaveInstanceState(outState);
297 outState.putParcelable(FileActivity.EXTRA_FILE, mFile);
298 outState.putParcelable(FileActivity.EXTRA_ACCOUNT, mAccount);
299 outState.putBoolean(FileActivity.EXTRA_FROM_NOTIFICATION, mFromNotification);
300 outState.putLong(KEY_WAITING_FOR_OP_ID, mFileOperationsHelper.getOpIdWaitingFor());
301 }
302
303
304 /**
305 * Getter for the main {@link OCFile} handled by the activity.
306 *
307 * @return Main {@link OCFile} handled by the activity.
308 */
309 public OCFile getFile() {
310 return mFile;
311 }
312
313
314 /**
315 * Setter for the main {@link OCFile} handled by the activity.
316 *
317 * @param file Main {@link OCFile} to be handled by the activity.
318 */
319 public void setFile(OCFile file) {
320 mFile = file;
321 }
322
323
324 /**
325 * Getter for the ownCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
326 *
327 * @return OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
328 */
329 public Account getAccount() {
330 return mAccount;
331 }
332
333 /**
334 * @return Value of mFromNotification: True if the Activity is launched by a notification
335 */
336 public boolean fromNotification() {
337 return mFromNotification;
338 }
339
340 /**
341 * @return 'True' when the Activity is finishing to enforce the setup of a new account.
342 */
343 protected boolean isRedirectingToSetupAccount() {
344 return mRedirectingToSetupAccount;
345 }
346
347
348 public OperationsServiceBinder getOperationsServiceBinder() {
349 return mOperationsServiceBinder;
350 }
351
352 protected ServiceConnection newTransferenceServiceConnection() {
353 return null;
354 }
355
356
357 /**
358 * Helper class handling a callback from the {@link AccountManager} after the creation of
359 * a new ownCloud {@link Account} finished, successfully or not.
360 *
361 * At this moment, only called after the creation of the first account.
362 *
363 * @author David A. Velasco
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 } else if (operation instanceof CreateShareOperation) {
452 onCreateShareOperationFinish((CreateShareOperation) operation, result);
453
454 } else if (operation instanceof UnshareLinkOperation) {
455 onUnshareLinkOperationFinish((UnshareLinkOperation)operation, result);
456
457 }
458 }
459
460 private void requestCredentialsUpdate() {
461 Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
462 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, getAccount());
463 updateAccountCredentials.putExtra(
464 AuthenticatorActivity.EXTRA_ACTION,
465 AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
466 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
467 startActivity(updateAccountCredentials);
468 }
469
470
471 private void onCreateShareOperationFinish(CreateShareOperation operation, RemoteOperationResult result) {
472 dismissLoadingDialog();
473 if (result.isSuccess()) {
474 updateFileFromDB();
475
476 Intent sendIntent = operation.getSendIntent();
477 startActivity(sendIntent);
478
479 } else {
480 Toast t = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
481 Toast.LENGTH_LONG);
482 t.show();
483 }
484 }
485
486
487 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation, RemoteOperationResult result) {
488 dismissLoadingDialog();
489
490 if (result.isSuccess()){
491 updateFileFromDB();
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 updateFileFromDB(){
502 OCFile file = getStorageManager().getFileByPath(getFile().getRemotePath());
503 if (file != null) {
504 setFile(file);
505 }
506 }
507
508 /**
509 * Show loading dialog
510 */
511 public void showLoadingDialog() {
512 // Construct dialog
513 LoadingDialog loading = new LoadingDialog(getResources().getString(R.string.wait_a_moment));
514 FragmentManager fm = getSupportFragmentManager();
515 FragmentTransaction ft = fm.beginTransaction();
516 loading.show(ft, DIALOG_WAIT_TAG);
517
518 }
519
520
521 /**
522 * Dismiss loading dialog
523 */
524 public void dismissLoadingDialog(){
525 Fragment frag = getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG);
526 if (frag != null) {
527 LoadingDialog loading = (LoadingDialog) frag;
528 loading.dismiss();
529 }
530 }
531
532
533 private void doOnResumeAndBound() {
534 mOperationsServiceBinder.addOperationListener(FileActivity.this, mHandler);
535 long waitingForOpId = mFileOperationsHelper.getOpIdWaitingFor();
536 if (waitingForOpId <= Integer.MAX_VALUE) {
537 boolean wait = mOperationsServiceBinder.dispatchResultIfFinished((int)waitingForOpId, this);
538 if (!wait ) {
539 dismissLoadingDialog();
540 }
541 }
542 }
543
544
545 /**
546 * Implements callback methods for service binding. Passed as a parameter to {
547 */
548 private class OperationsServiceConnection implements ServiceConnection {
549
550 @Override
551 public void onServiceConnected(ComponentName component, IBinder service) {
552 if (component.equals(new ComponentName(FileActivity.this, OperationsService.class))) {
553 Log_OC.d(TAG, "Operations service connected");
554 mOperationsServiceBinder = (OperationsServiceBinder) service;
555 /*if (!mOperationsServiceBinder.isPerformingBlockingOperation()) {
556 dismissLoadingDialog();
557 }*/
558 doOnResumeAndBound();
559
560 } else {
561 return;
562 }
563 }
564
565
566 @Override
567 public void onServiceDisconnected(ComponentName component) {
568 if (component.equals(new ComponentName(FileActivity.this, OperationsService.class))) {
569 Log_OC.d(TAG, "Operations service disconnected");
570 mOperationsServiceBinder = null;
571 // TODO whatever could be waiting for the service is unbound
572 }
573 }
574 }
575
576
577 @Override
578 public FileDownloaderBinder getFileDownloaderBinder() {
579 return mDownloaderBinder;
580 }
581
582
583 @Override
584 public FileUploaderBinder getFileUploaderBinder() {
585 return mUploaderBinder;
586 };
587
588
589 }