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