Prevent stuck progress dialog
[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-2013 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.OperationCanceledException;
26 import android.content.ComponentName;
27 import android.content.Context;
28 import android.content.Intent;
29 import android.content.ServiceConnection;
30 import android.os.Bundle;
31 import android.os.Handler;
32 import android.os.IBinder;
33 import android.support.v4.app.Fragment;
34 import android.support.v4.app.FragmentManager;
35 import android.support.v4.app.FragmentTransaction;
36 import android.widget.Toast;
37
38 import com.actionbarsherlock.app.SherlockFragmentActivity;
39 import com.owncloud.android.MainApp;
40 import com.owncloud.android.R;
41 import com.owncloud.android.authentication.AccountUtils;
42 import com.owncloud.android.datamodel.FileDataStorageManager;
43 import com.owncloud.android.datamodel.OCFile;
44 import com.owncloud.android.files.FileOperationsHelper;
45 import com.owncloud.android.lib.operations.common.OnRemoteOperationListener;
46 import com.owncloud.android.lib.operations.common.RemoteOperation;
47 import com.owncloud.android.lib.operations.common.RemoteOperationResult;
48 import com.owncloud.android.lib.operations.common.RemoteOperationResult.ResultCode;
49 import com.owncloud.android.operations.CreateShareOperation;
50 import com.owncloud.android.operations.UnshareLinkOperation;
51
52 import com.owncloud.android.services.OperationsService;
53 import com.owncloud.android.services.OperationsService.OperationsServiceBinder;
54 import com.owncloud.android.ui.dialog.LoadingDialog;
55 import com.owncloud.android.utils.Log_OC;
56
57
58 /**
59 * Activity with common behaviour for activities handling {@link OCFile}s in ownCloud {@link Account}s .
60 *
61 * @author David A. Velasco
62 */
63 public class FileActivity extends SherlockFragmentActivity implements OnRemoteOperationListener {
64
65 public static final String EXTRA_FILE = "com.owncloud.android.ui.activity.FILE";
66 public static final String EXTRA_ACCOUNT = "com.owncloud.android.ui.activity.ACCOUNT";
67 public static final String EXTRA_WAITING_TO_PREVIEW = "com.owncloud.android.ui.activity.WAITING_TO_PREVIEW";
68 public static final String EXTRA_FROM_NOTIFICATION= "com.owncloud.android.ui.activity.FROM_NOTIFICATION";
69
70 public static final String TAG = FileActivity.class.getSimpleName();
71
72 private static final String DIALOG_WAIT_TAG = "DIALOG_WAIT";
73
74
75 /** OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located. */
76 private Account mAccount;
77
78 /** Main {@link OCFile} handled by the activity.*/
79 private OCFile mFile;
80
81 /** Flag to signal that the activity will is finishing to enforce the creation of an ownCloud {@link Account} */
82 private boolean mRedirectingToSetupAccount = false;
83
84 /** Flag to signal when the value of mAccount was set */
85 private boolean mAccountWasSet;
86
87 /** Flag to signal when the value of mAccount was restored from a saved state */
88 private boolean mAccountWasRestored;
89
90 /** Flag to signal if the activity is launched by a notification */
91 private boolean mFromNotification;
92
93 /** Messages handler associated to the main thread and the life cycle of the activity */
94 private Handler mHandler;
95
96 /** Access point to the cached database for the current ownCloud {@link Account} */
97 private FileDataStorageManager mStorageManager = null;
98
99 private FileOperationsHelper mFileOperationsHelper;
100
101 private ServiceConnection mOperationsServiceConnection = null;
102
103 private OperationsServiceBinder mOperationsServiceBinder = null;
104
105
106 /**
107 * Loads the ownCloud {@link Account} and main {@link OCFile} to be handled by the instance of
108 * the {@link FileActivity}.
109 *
110 * Grants that a valid ownCloud {@link Account} is associated to the instance, or that the user
111 * is requested to create a new one.
112 */
113 @Override
114 protected void onCreate(Bundle savedInstanceState) {
115 super.onCreate(savedInstanceState);
116 mHandler = new Handler();
117 mFileOperationsHelper = new FileOperationsHelper();
118 Account account;
119 if(savedInstanceState != null) {
120 account = savedInstanceState.getParcelable(FileActivity.EXTRA_ACCOUNT);
121 mFile = savedInstanceState.getParcelable(FileActivity.EXTRA_FILE);
122 mFromNotification = savedInstanceState.getBoolean(FileActivity.EXTRA_FROM_NOTIFICATION);
123 } else {
124 account = getIntent().getParcelableExtra(FileActivity.EXTRA_ACCOUNT);
125 mFile = getIntent().getParcelableExtra(FileActivity.EXTRA_FILE);
126 mFromNotification = getIntent().getBooleanExtra(FileActivity.EXTRA_FROM_NOTIFICATION, false);
127 }
128
129 setAccount(account, savedInstanceState != null);
130
131 mOperationsServiceConnection = new OperationsServiceConnection();
132 bindService(new Intent(this, OperationsService.class), mOperationsServiceConnection, Context.BIND_AUTO_CREATE);
133 }
134
135
136 /**
137 * Since ownCloud {@link Account}s can be managed from the system setting menu,
138 * the existence of the {@link Account} associated to the instance must be checked
139 * every time it is restarted.
140 */
141 @Override
142 protected void onRestart() {
143 super.onRestart();
144 boolean validAccount = (mAccount != null && AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), mAccount.name));
145 if (!validAccount) {
146 swapToDefaultAccount();
147 }
148 }
149
150
151 @Override
152 protected void onStart() {
153 super.onStart();
154 if (mAccountWasSet) {
155 onAccountSet(mAccountWasRestored);
156 }
157 if (mOperationsServiceBinder != null) {
158 mOperationsServiceBinder.addOperationListener(FileActivity.this, mHandler);
159 if (!mOperationsServiceBinder.isPerformingBlockingOperation()) {
160 dismissLoadingDialog();
161 }
162 }
163 }
164
165
166 @Override
167 protected void onStop() {
168 super.onStop();
169 if (mOperationsServiceBinder != null) {
170 mOperationsServiceBinder.removeOperationListener(this);
171 mOperationsServiceBinder = null;
172 }
173 }
174
175
176 @Override
177 protected void onDestroy() {
178 super.onDestroy();
179 if (mOperationsServiceConnection != null) {
180 unbindService(mOperationsServiceConnection);
181 }
182 }
183
184
185 /**
186 * Sets and validates the ownCloud {@link Account} associated to the Activity.
187 *
188 * If not valid, tries to swap it for other valid and existing ownCloud {@link Account}.
189 *
190 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
191 *
192 * @param account New {@link Account} to set.
193 * @param savedAccount When 'true', account was retrieved from a saved instance state.
194 */
195 private void setAccount(Account account, boolean savedAccount) {
196 Account oldAccount = mAccount;
197 boolean validAccount = (account != null && AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), account.name));
198 if (validAccount) {
199 mAccount = account;
200 mAccountWasSet = true;
201 mAccountWasRestored = (savedAccount || mAccount.equals(oldAccount));
202
203 } else {
204 swapToDefaultAccount();
205 }
206 }
207
208
209 /**
210 * Tries to swap the current ownCloud {@link Account} for other valid and existing.
211 *
212 * If no valid ownCloud {@link Account} exists, the the user is requested
213 * to create a new ownCloud {@link Account}.
214 *
215 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
216 *
217 * @return 'True' if the checked {@link Account} was valid.
218 */
219 private void swapToDefaultAccount() {
220 // default to the most recently used account
221 Account newAccount = AccountUtils.getCurrentOwnCloudAccount(getApplicationContext());
222 if (newAccount == null) {
223 /// no account available: force account creation
224 createFirstAccount();
225 mRedirectingToSetupAccount = true;
226 mAccountWasSet = false;
227 mAccountWasRestored = false;
228
229 } else {
230 mAccountWasSet = true;
231 mAccountWasRestored = (newAccount.equals(mAccount));
232 mAccount = newAccount;
233 }
234 }
235
236
237 /**
238 * Launches the account creation activity. To use when no ownCloud account is available
239 */
240 private void createFirstAccount() {
241 AccountManager am = AccountManager.get(getApplicationContext());
242 am.addAccount(MainApp.getAccountType(),
243 null,
244 null,
245 null,
246 this,
247 new AccountCreationCallback(),
248 null);
249 }
250
251
252 /**
253 * {@inheritDoc}
254 */
255 @Override
256 protected void onSaveInstanceState(Bundle outState) {
257 super.onSaveInstanceState(outState);
258 outState.putParcelable(FileActivity.EXTRA_FILE, mFile);
259 outState.putParcelable(FileActivity.EXTRA_ACCOUNT, mAccount);
260 outState.putBoolean(FileActivity.EXTRA_FROM_NOTIFICATION, mFromNotification);
261 }
262
263
264 /**
265 * Getter for the main {@link OCFile} handled by the activity.
266 *
267 * @return Main {@link OCFile} handled by the activity.
268 */
269 public OCFile getFile() {
270 return mFile;
271 }
272
273
274 /**
275 * Setter for the main {@link OCFile} handled by the activity.
276 *
277 * @param file Main {@link OCFile} to be handled by the activity.
278 */
279 public void setFile(OCFile file) {
280 mFile = file;
281 }
282
283
284 /**
285 * Getter for the ownCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
286 *
287 * @return OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
288 */
289 public Account getAccount() {
290 return mAccount;
291 }
292
293 /**
294 * @return Value of mFromNotification: True if the Activity is launched by a notification
295 */
296 public boolean fromNotification() {
297 return mFromNotification;
298 }
299
300 /**
301 * @return 'True' when the Activity is finishing to enforce the setup of a new account.
302 */
303 protected boolean isRedirectingToSetupAccount() {
304 return mRedirectingToSetupAccount;
305 }
306
307
308 /**
309 * Helper class handling a callback from the {@link AccountManager} after the creation of
310 * a new ownCloud {@link Account} finished, successfully or not.
311 *
312 * At this moment, only called after the creation of the first account.
313 *
314 * @author David A. Velasco
315 */
316 public class AccountCreationCallback implements AccountManagerCallback<Bundle> {
317
318 @Override
319 public void run(AccountManagerFuture<Bundle> future) {
320 FileActivity.this.mRedirectingToSetupAccount = false;
321 boolean accountWasSet = false;
322 if (future != null) {
323 try {
324 Bundle result;
325 result = future.getResult();
326 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
327 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
328 if (AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), name)) {
329 setAccount(new Account(name, type), false);
330 accountWasSet = true;
331 }
332 } catch (OperationCanceledException e) {
333 Log_OC.d(TAG, "Account creation canceled");
334
335 } catch (Exception e) {
336 Log_OC.e(TAG, "Account creation finished in exception: ", e);
337 }
338
339 } else {
340 Log_OC.e(TAG, "Account creation callback with null bundle");
341 }
342 if (!accountWasSet) {
343 moveTaskToBack(true);
344 }
345 }
346
347 }
348
349
350 /**
351 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
352 *
353 * Child classes must grant that state depending on the {@link Account} is updated.
354 */
355 protected void onAccountSet(boolean stateWasRecovered) {
356 if (getAccount() != null) {
357 mStorageManager = new FileDataStorageManager(getAccount(), getContentResolver());
358
359 } else {
360 Log_OC.wtf(TAG, "onAccountChanged was called with NULL account associated!");
361 }
362 }
363
364
365 public FileDataStorageManager getStorageManager() {
366 return mStorageManager;
367 }
368
369
370 public OnRemoteOperationListener getRemoteOperationListener() {
371 return this;
372 }
373
374
375 public Handler getHandler() {
376 return mHandler;
377 }
378
379 public FileOperationsHelper getFileOperationsHelper() {
380 return mFileOperationsHelper;
381 }
382
383 /**
384 *
385 * @param operation Removal operation performed.
386 * @param result Result of the removal.
387 */
388 @Override
389 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
390 Log_OC.d(TAG, "Received result of operation in FileActivity - common behaviour for all the FileActivities ");
391 if (operation instanceof CreateShareOperation) {
392 onCreateShareOperationFinish((CreateShareOperation) operation, result);
393
394 } else if (operation instanceof UnshareLinkOperation) {
395 onUnshareLinkOperationFinish((UnshareLinkOperation)operation, result);
396
397 }
398 }
399
400 private void onCreateShareOperationFinish(CreateShareOperation operation, RemoteOperationResult result) {
401 dismissLoadingDialog();
402 if (result.isSuccess()) {
403 updateFileFromDB();
404
405 Intent sendIntent = operation.getSendIntent();
406 startActivity(sendIntent);
407
408 } else if (result.getCode() == ResultCode.SHARE_NOT_FOUND) { // Error --> SHARE_NOT_FOUND
409 Toast t = Toast.makeText(this, getString(R.string.share_link_file_no_exist), Toast.LENGTH_LONG);
410 t.show();
411 } else { // Generic error
412 // Show a Message, operation finished without success
413 Toast t = Toast.makeText(this, getString(R.string.share_link_file_error), Toast.LENGTH_LONG);
414 t.show();
415 }
416 }
417
418
419 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation, RemoteOperationResult result) {
420 dismissLoadingDialog();
421
422 if (result.isSuccess()){
423 updateFileFromDB();
424
425 } else if (result.getCode() == ResultCode.SHARE_NOT_FOUND) { // Error --> SHARE_NOT_FOUND
426 Toast t = Toast.makeText(this, getString(R.string.unshare_link_file_no_exist), Toast.LENGTH_LONG);
427 t.show();
428 } else { // Generic error
429 // Show a Message, operation finished without success
430 Toast t = Toast.makeText(this, getString(R.string.unshare_link_file_error), Toast.LENGTH_LONG);
431 t.show();
432 }
433
434 }
435
436
437 private void updateFileFromDB(){
438 OCFile file = getStorageManager().getFileByPath(getFile().getRemotePath());
439 if (file != null) {
440 setFile(file);
441 }
442 }
443
444 /**
445 * Show loading dialog
446 */
447 public void showLoadingDialog() {
448 // Construct dialog
449 LoadingDialog loading = new LoadingDialog(getResources().getString(R.string.wait_a_moment));
450 FragmentManager fm = getSupportFragmentManager();
451 FragmentTransaction ft = fm.beginTransaction();
452 loading.show(ft, DIALOG_WAIT_TAG);
453
454 }
455
456
457 /**
458 * Dismiss loading dialog
459 */
460 public void dismissLoadingDialog(){
461 Fragment frag = getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG);
462 if (frag != null) {
463 LoadingDialog loading = (LoadingDialog) frag;
464 loading.dismiss();
465 }
466 }
467
468
469 /**
470 * Implements callback methods for service binding. Passed as a parameter to {
471 */
472 private class OperationsServiceConnection implements ServiceConnection {
473
474 @Override
475 public void onServiceConnected(ComponentName component, IBinder service) {
476 if (component.equals(new ComponentName(FileActivity.this, OperationsService.class))) {
477 Log_OC.d(TAG, "Operations service connected");
478 mOperationsServiceBinder = (OperationsServiceBinder) service;
479 mOperationsServiceBinder.addOperationListener(FileActivity.this, mHandler);
480 if (!mOperationsServiceBinder.isPerformingBlockingOperation()) {
481 dismissLoadingDialog();
482 }
483
484 } else {
485 return;
486 }
487 }
488
489
490 @Override
491 public void onServiceDisconnected(ComponentName component) {
492 if (component.equals(new ComponentName(FileActivity.this, OperationsService.class))) {
493 Log_OC.d(TAG, "Operations service disconnected");
494 mOperationsServiceBinder = null;
495 // TODO whatever could be waiting for the service is unbound
496 }
497 }
498 };
499
500 }