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