Fixed. App crash when setting a path without slash
[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.UnshareLinkOperation;
58
59 import com.owncloud.android.services.OperationsService;
60 import com.owncloud.android.services.OperationsService.OperationsServiceBinder;
61 import com.owncloud.android.ui.dialog.LoadingDialog;
62 import com.owncloud.android.utils.ErrorMessageAdapter;
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 protected static final long DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS = 200;
84
85
86 /** OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located. */
87 private Account mAccount;
88
89 /** Main {@link OCFile} handled by the activity.*/
90 private OCFile mFile;
91
92 /** Flag to signal that the activity will is finishing to enforce the creation of an ownCloud {@link Account} */
93 private boolean mRedirectingToSetupAccount = false;
94
95 /** Flag to signal when the value of mAccount was set */
96 private boolean mAccountWasSet;
97
98 /** Flag to signal when the value of mAccount was restored from a saved state */
99 private boolean mAccountWasRestored;
100
101 /** Flag to signal if the activity is launched by a notification */
102 private boolean mFromNotification;
103
104 /** Messages handler associated to the main thread and the life cycle of the activity */
105 private Handler mHandler;
106
107 /** Access point to the cached database for the current ownCloud {@link Account} */
108 private FileDataStorageManager mStorageManager = null;
109
110 private FileOperationsHelper mFileOperationsHelper;
111
112 private ServiceConnection mOperationsServiceConnection = null;
113
114 private OperationsServiceBinder mOperationsServiceBinder = null;
115
116 protected FileDownloaderBinder mDownloaderBinder = null;
117 protected FileUploaderBinder mUploaderBinder = null;
118 private ServiceConnection mDownloadServiceConnection, mUploadServiceConnection = null;
119
120
121 /**
122 * Loads the ownCloud {@link Account} and main {@link OCFile} to be handled by the instance of
123 * the {@link FileActivity}.
124 *
125 * Grants that a valid ownCloud {@link Account} is associated to the instance, or that the user
126 * is requested to create a new one.
127 */
128 @Override
129 protected void onCreate(Bundle savedInstanceState) {
130 super.onCreate(savedInstanceState);
131 mHandler = new Handler();
132 mFileOperationsHelper = new FileOperationsHelper(this);
133 Account account;
134 if(savedInstanceState != null) {
135 account = savedInstanceState.getParcelable(FileActivity.EXTRA_ACCOUNT);
136 mFile = savedInstanceState.getParcelable(FileActivity.EXTRA_FILE);
137 mFromNotification = savedInstanceState.getBoolean(FileActivity.EXTRA_FROM_NOTIFICATION);
138 mFileOperationsHelper.setOpIdWaitingFor(
139 savedInstanceState.getLong(KEY_WAITING_FOR_OP_ID, Long.MAX_VALUE)
140 );
141 } else {
142 account = getIntent().getParcelableExtra(FileActivity.EXTRA_ACCOUNT);
143 mFile = getIntent().getParcelableExtra(FileActivity.EXTRA_FILE);
144 mFromNotification = getIntent().getBooleanExtra(FileActivity.EXTRA_FROM_NOTIFICATION, false);
145 }
146
147 setAccount(account, savedInstanceState != null);
148
149 mOperationsServiceConnection = new OperationsServiceConnection();
150 bindService(new Intent(this, OperationsService.class), mOperationsServiceConnection, Context.BIND_AUTO_CREATE);
151
152 mDownloadServiceConnection = newTransferenceServiceConnection();
153 if (mDownloadServiceConnection != null) {
154 bindService(new Intent(this, FileDownloader.class), mDownloadServiceConnection, Context.BIND_AUTO_CREATE);
155 }
156 mUploadServiceConnection = newTransferenceServiceConnection();
157 if (mUploadServiceConnection != null) {
158 bindService(new Intent(this, FileUploader.class), mUploadServiceConnection, Context.BIND_AUTO_CREATE);
159 }
160
161 }
162
163
164 /**
165 * Since ownCloud {@link Account}s can be managed from the system setting menu,
166 * the existence of the {@link Account} associated to the instance must be checked
167 * every time it is restarted.
168 */
169 @Override
170 protected void onRestart() {
171 super.onRestart();
172 boolean validAccount = (mAccount != null && AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), mAccount.name));
173 if (!validAccount) {
174 swapToDefaultAccount();
175 }
176 }
177
178
179 @Override
180 protected void onStart() {
181 super.onStart();
182
183 if (mAccountWasSet) {
184 onAccountSet(mAccountWasRestored);
185 }
186 }
187
188 @Override
189 protected void onResume() {
190 super.onResume();
191
192 if (mOperationsServiceBinder != null) {
193 doOnResumeAndBound();
194 }
195
196 }
197
198 @Override
199 protected void onPause() {
200
201 if (mOperationsServiceBinder != null) {
202 mOperationsServiceBinder.removeOperationListener(this);
203 }
204
205 super.onPause();
206 }
207
208
209 @Override
210 protected void onDestroy() {
211 if (mOperationsServiceConnection != null) {
212 unbindService(mOperationsServiceConnection);
213 mOperationsServiceBinder = null;
214 }
215 if (mDownloadServiceConnection != null) {
216 unbindService(mDownloadServiceConnection);
217 mDownloadServiceConnection = null;
218 }
219 if (mUploadServiceConnection != null) {
220 unbindService(mUploadServiceConnection);
221 mUploadServiceConnection = null;
222 }
223 super.onDestroy();
224 }
225
226
227 /**
228 * Sets and validates the ownCloud {@link Account} associated to the Activity.
229 *
230 * If not valid, tries to swap it for other valid and existing ownCloud {@link Account}.
231 *
232 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
233 *
234 * @param account New {@link Account} to set.
235 * @param savedAccount When 'true', account was retrieved from a saved instance state.
236 */
237 private void setAccount(Account account, boolean savedAccount) {
238 Account oldAccount = mAccount;
239 boolean validAccount = (account != null && AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), account.name));
240 if (validAccount) {
241 mAccount = account;
242 mAccountWasSet = true;
243 mAccountWasRestored = (savedAccount || mAccount.equals(oldAccount));
244
245 } else {
246 swapToDefaultAccount();
247 }
248 }
249
250
251 /**
252 * Tries to swap the current ownCloud {@link Account} for other valid and existing.
253 *
254 * If no valid ownCloud {@link Account} exists, the the user is requested
255 * to create a new ownCloud {@link Account}.
256 *
257 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
258 *
259 * @return 'True' if the checked {@link Account} was valid.
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 /**
361 * Helper class handling a callback from the {@link AccountManager} after the creation of
362 * a new ownCloud {@link Account} finished, successfully or not.
363 *
364 * At this moment, only called after the creation of the first account.
365 *
366 * @author David A. Velasco
367 */
368 public class AccountCreationCallback implements AccountManagerCallback<Bundle> {
369
370 @Override
371 public void run(AccountManagerFuture<Bundle> future) {
372 FileActivity.this.mRedirectingToSetupAccount = false;
373 boolean accountWasSet = false;
374 if (future != null) {
375 try {
376 Bundle result;
377 result = future.getResult();
378 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
379 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
380 if (AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), name)) {
381 setAccount(new Account(name, type), false);
382 accountWasSet = true;
383 }
384 } catch (OperationCanceledException e) {
385 Log_OC.d(TAG, "Account creation canceled");
386
387 } catch (Exception e) {
388 Log_OC.e(TAG, "Account creation finished in exception: ", e);
389 }
390
391 } else {
392 Log_OC.e(TAG, "Account creation callback with null bundle");
393 }
394 if (!accountWasSet) {
395 moveTaskToBack(true);
396 }
397 }
398
399 }
400
401
402 /**
403 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
404 *
405 * Child classes must grant that state depending on the {@link Account} is updated.
406 */
407 protected void onAccountSet(boolean stateWasRecovered) {
408 if (getAccount() != null) {
409 mStorageManager = new FileDataStorageManager(getAccount(), getContentResolver());
410
411 } else {
412 Log_OC.wtf(TAG, "onAccountChanged was called with NULL account associated!");
413 }
414 }
415
416
417 public FileDataStorageManager getStorageManager() {
418 return mStorageManager;
419 }
420
421
422 public OnRemoteOperationListener getRemoteOperationListener() {
423 return this;
424 }
425
426
427 public Handler getHandler() {
428 return mHandler;
429 }
430
431 public FileOperationsHelper getFileOperationsHelper() {
432 return mFileOperationsHelper;
433 }
434
435 /**
436 *
437 * @param operation Removal operation performed.
438 * @param result Result of the removal.
439 */
440 @Override
441 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
442 Log_OC.d(TAG, "Received result of operation in FileActivity - common behaviour for all the FileActivities ");
443
444 mFileOperationsHelper.setOpIdWaitingFor(Long.MAX_VALUE);
445
446 if (!result.isSuccess() && (
447 result.getCode() == ResultCode.UNAUTHORIZED ||
448 result.isIdPRedirection() ||
449 (result.isException() && result.getException() instanceof AuthenticatorException)
450 )) {
451
452 requestCredentialsUpdate();
453
454 if (result.getCode() == ResultCode.UNAUTHORIZED) {
455 dismissLoadingDialog();
456 Toast t = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
457 Toast.LENGTH_LONG);
458 t.show();
459 }
460
461 } else if (operation instanceof CreateShareOperation) {
462 onCreateShareOperationFinish((CreateShareOperation) operation, result);
463
464 } else if (operation instanceof UnshareLinkOperation) {
465 onUnshareLinkOperationFinish((UnshareLinkOperation)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
511 protected void updateFileFromDB(){
512 OCFile file = getFile();
513 if (file != null) {
514 file = getStorageManager().getFileByPath(file.getRemotePath());
515 setFile(file);
516 }
517 }
518
519 /**
520 * Show loading dialog
521 */
522 public void showLoadingDialog() {
523 // Construct dialog
524 LoadingDialog loading = new LoadingDialog(getResources().getString(R.string.wait_a_moment));
525 FragmentManager fm = getSupportFragmentManager();
526 FragmentTransaction ft = fm.beginTransaction();
527 loading.show(ft, DIALOG_WAIT_TAG);
528
529 }
530
531
532 /**
533 * Dismiss loading dialog
534 */
535 public void dismissLoadingDialog(){
536 Fragment frag = getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG);
537 if (frag != null) {
538 LoadingDialog loading = (LoadingDialog) frag;
539 loading.dismiss();
540 }
541 }
542
543
544 private void doOnResumeAndBound() {
545 mOperationsServiceBinder.addOperationListener(FileActivity.this, mHandler);
546 long waitingForOpId = mFileOperationsHelper.getOpIdWaitingFor();
547 if (waitingForOpId <= Integer.MAX_VALUE) {
548 boolean wait = mOperationsServiceBinder.dispatchResultIfFinished((int)waitingForOpId, this);
549 if (!wait ) {
550 dismissLoadingDialog();
551 }
552 }
553 }
554
555
556 /**
557 * Implements callback methods for service binding. Passed as a parameter to {
558 */
559 private class OperationsServiceConnection implements ServiceConnection {
560
561 @Override
562 public void onServiceConnected(ComponentName component, IBinder service) {
563 if (component.equals(new ComponentName(FileActivity.this, OperationsService.class))) {
564 Log_OC.d(TAG, "Operations service connected");
565 mOperationsServiceBinder = (OperationsServiceBinder) service;
566 /*if (!mOperationsServiceBinder.isPerformingBlockingOperation()) {
567 dismissLoadingDialog();
568 }*/
569 doOnResumeAndBound();
570
571 } else {
572 return;
573 }
574 }
575
576
577 @Override
578 public void onServiceDisconnected(ComponentName component) {
579 if (component.equals(new ComponentName(FileActivity.this, OperationsService.class))) {
580 Log_OC.d(TAG, "Operations service disconnected");
581 mOperationsServiceBinder = null;
582 // TODO whatever could be waiting for the service is unbound
583 }
584 }
585 }
586
587
588 @Override
589 public FileDownloaderBinder getFileDownloaderBinder() {
590 return mDownloaderBinder;
591 }
592
593
594 @Override
595 public FileUploaderBinder getFileUploaderBinder() {
596 return mUploaderBinder;
597 };
598
599
600 }