Merge branch 'develop' into share_password_support
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / activity / FileActivity.java
1 /**
2 * ownCloud Android client application
3 *
4 * @author David A. Velasco
5 * Copyright (C) 2011 Bartek Przybylski
6 * Copyright (C) 2015 ownCloud Inc.
7 *
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License version 2,
10 * as published by the Free Software Foundation.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 *
20 */
21
22 package com.owncloud.android.ui.activity;
23
24 import android.accounts.Account;
25 import android.accounts.AccountManager;
26 import android.accounts.AccountManagerCallback;
27 import android.accounts.AccountManagerFuture;
28 import android.accounts.AuthenticatorException;
29 import android.accounts.OperationCanceledException;
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.operations.OnRemoteOperationListener;
55 import com.owncloud.android.lib.common.operations.RemoteOperation;
56 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
57 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
58 import com.owncloud.android.lib.common.utils.Log_OC;
59 import com.owncloud.android.operations.CreateShareOperation;
60 import com.owncloud.android.operations.SynchronizeFolderOperation;
61 import com.owncloud.android.operations.UnshareLinkOperation;
62 import com.owncloud.android.services.OperationsService;
63 import com.owncloud.android.services.OperationsService.OperationsServiceBinder;
64 import com.owncloud.android.ui.dialog.CreateFolderDialogFragment;
65 import com.owncloud.android.ui.dialog.LoadingDialog;
66 import com.owncloud.android.ui.dialog.SharePasswordDialogFragment;
67 import com.owncloud.android.utils.ErrorMessageAdapter;
68
69
70 /**
71 * Activity with common behaviour for activities handling {@link OCFile}s in ownCloud {@link Account}s .
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 private static final String DIALOG_SHARE_PASSWORD = "DIALOG_SHARE_PASSWORD";
86
87 protected static final long DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS = 200;
88
89
90 /** OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located. */
91 private Account mAccount;
92
93 /** Main {@link OCFile} handled by the activity.*/
94 private OCFile mFile;
95
96 /** Flag to signal that the activity will is finishing to enforce the creation of an ownCloud {@link Account} */
97 private boolean mRedirectingToSetupAccount = false;
98
99 /** Flag to signal when the value of mAccount was set */
100 private boolean mAccountWasSet;
101
102 /** Flag to signal when the value of mAccount was restored from a saved state */
103 private boolean mAccountWasRestored;
104
105 /** Flag to signal if the activity is launched by a notification */
106 private boolean mFromNotification;
107
108 /** Messages handler associated to the main thread and the life cycle of the activity */
109 private Handler mHandler;
110
111 /** Access point to the cached database for the current ownCloud {@link Account} */
112 private FileDataStorageManager mStorageManager = null;
113
114 private FileOperationsHelper mFileOperationsHelper;
115
116 private ServiceConnection mOperationsServiceConnection = null;
117
118 private OperationsServiceBinder mOperationsServiceBinder = null;
119
120 protected FileDownloaderBinder mDownloaderBinder = null;
121 protected FileUploaderBinder mUploaderBinder = null;
122 private ServiceConnection mDownloadServiceConnection, mUploadServiceConnection = null;
123
124
125 /**
126 * Loads the ownCloud {@link Account} and main {@link OCFile} to be handled by the instance of
127 * the {@link FileActivity}.
128 *
129 * Grants that a valid ownCloud {@link Account} is associated to the instance, or that the user
130 * is requested to create a new one.
131 */
132 @Override
133 protected void onCreate(Bundle savedInstanceState) {
134 super.onCreate(savedInstanceState);
135 mHandler = new Handler();
136 mFileOperationsHelper = new FileOperationsHelper(this);
137 Account account;
138 if(savedInstanceState != null) {
139 account = savedInstanceState.getParcelable(FileActivity.EXTRA_ACCOUNT);
140 mFile = savedInstanceState.getParcelable(FileActivity.EXTRA_FILE);
141 mFromNotification = savedInstanceState.getBoolean(FileActivity.EXTRA_FROM_NOTIFICATION);
142 mFileOperationsHelper.setOpIdWaitingFor(
143 savedInstanceState.getLong(KEY_WAITING_FOR_OP_ID, Long.MAX_VALUE)
144 );
145 } else {
146 account = getIntent().getParcelableExtra(FileActivity.EXTRA_ACCOUNT);
147 mFile = getIntent().getParcelableExtra(FileActivity.EXTRA_FILE);
148 mFromNotification = getIntent().getBooleanExtra(FileActivity.EXTRA_FROM_NOTIFICATION, false);
149 }
150
151 setAccount(account, savedInstanceState != null);
152
153 mOperationsServiceConnection = new OperationsServiceConnection();
154 bindService(new Intent(this, OperationsService.class), mOperationsServiceConnection, Context.BIND_AUTO_CREATE);
155
156 mDownloadServiceConnection = newTransferenceServiceConnection();
157 if (mDownloadServiceConnection != null) {
158 bindService(new Intent(this, FileDownloader.class), mDownloadServiceConnection, Context.BIND_AUTO_CREATE);
159 }
160 mUploadServiceConnection = newTransferenceServiceConnection();
161 if (mUploadServiceConnection != null) {
162 bindService(new Intent(this, FileUploader.class), mUploadServiceConnection, Context.BIND_AUTO_CREATE);
163 }
164
165 }
166
167
168 /**
169 * Since ownCloud {@link Account}s can be managed from the system setting menu,
170 * the existence of the {@link Account} associated to the instance must be checked
171 * every time it is restarted.
172 */
173 @Override
174 protected void onRestart() {
175 super.onRestart();
176 boolean validAccount = (mAccount != null && AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), mAccount.name));
177 if (!validAccount) {
178 swapToDefaultAccount();
179 }
180 }
181
182
183 @Override
184 protected void onStart() {
185 super.onStart();
186
187 if (mAccountWasSet) {
188 onAccountSet(mAccountWasRestored);
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
205 if (mOperationsServiceBinder != null) {
206 mOperationsServiceBinder.removeOperationListener(this);
207 }
208
209 super.onPause();
210 }
211
212
213 @Override
214 protected void onDestroy() {
215 if (mOperationsServiceConnection != null) {
216 unbindService(mOperationsServiceConnection);
217 mOperationsServiceBinder = null;
218 }
219 if (mDownloadServiceConnection != null) {
220 unbindService(mDownloadServiceConnection);
221 mDownloadServiceConnection = null;
222 }
223 if (mUploadServiceConnection != null) {
224 unbindService(mUploadServiceConnection);
225 mUploadServiceConnection = null;
226 }
227
228 super.onDestroy();
229 }
230
231
232 /**
233 * Sets and validates the ownCloud {@link Account} associated to the Activity.
234 *
235 * If not valid, tries to swap it for other valid and existing ownCloud {@link Account}.
236 *
237 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
238 *
239 * @param account New {@link Account} to set.
240 * @param savedAccount When 'true', account was retrieved from a saved instance state.
241 */
242 private void setAccount(Account account, boolean savedAccount) {
243 Account oldAccount = mAccount;
244 boolean validAccount = (account != null && AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), account.name));
245 if (validAccount) {
246 mAccount = account;
247 mAccountWasSet = true;
248 mAccountWasRestored = (savedAccount || mAccount.equals(oldAccount));
249
250 } else {
251 swapToDefaultAccount();
252 }
253 }
254
255
256 /**
257 * Tries to swap the current ownCloud {@link Account} for other valid and existing.
258 *
259 * If no valid ownCloud {@link Account} exists, the the user is requested
260 * to create a new ownCloud {@link Account}.
261 *
262 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
263 */
264 private void swapToDefaultAccount() {
265 // default to the most recently used account
266 Account newAccount = AccountUtils.getCurrentOwnCloudAccount(getApplicationContext());
267 if (newAccount == null) {
268 /// no account available: force account creation
269 createFirstAccount();
270 mRedirectingToSetupAccount = true;
271 mAccountWasSet = false;
272 mAccountWasRestored = false;
273
274 } else {
275 mAccountWasSet = true;
276 mAccountWasRestored = (newAccount.equals(mAccount));
277 mAccount = newAccount;
278 }
279 }
280
281
282 /**
283 * Launches the account creation activity. To use when no ownCloud account is available
284 */
285 private void createFirstAccount() {
286 AccountManager am = AccountManager.get(getApplicationContext());
287 am.addAccount(MainApp.getAccountType(),
288 null,
289 null,
290 null,
291 this,
292 new AccountCreationCallback(),
293 null);
294 }
295
296
297 /**
298 * {@inheritDoc}
299 */
300 @Override
301 protected void onSaveInstanceState(Bundle outState) {
302 super.onSaveInstanceState(outState);
303 outState.putParcelable(FileActivity.EXTRA_FILE, mFile);
304 outState.putParcelable(FileActivity.EXTRA_ACCOUNT, mAccount);
305 outState.putBoolean(FileActivity.EXTRA_FROM_NOTIFICATION, mFromNotification);
306 outState.putLong(KEY_WAITING_FOR_OP_ID, mFileOperationsHelper.getOpIdWaitingFor());
307 }
308
309
310 /**
311 * Getter for the main {@link OCFile} handled by the activity.
312 *
313 * @return Main {@link OCFile} handled by the activity.
314 */
315 public OCFile getFile() {
316 return mFile;
317 }
318
319
320 /**
321 * Setter for the main {@link OCFile} handled by the activity.
322 *
323 * @param file Main {@link OCFile} to be handled by the activity.
324 */
325 public void setFile(OCFile file) {
326 mFile = file;
327 }
328
329
330 /**
331 * Getter for the ownCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
332 *
333 * @return OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
334 */
335 public Account getAccount() {
336 return mAccount;
337 }
338
339 /**
340 * @return Value of mFromNotification: True if the Activity is launched by a notification
341 */
342 public boolean fromNotification() {
343 return mFromNotification;
344 }
345
346 /**
347 * @return 'True' when the Activity is finishing to enforce the setup of a new account.
348 */
349 protected boolean isRedirectingToSetupAccount() {
350 return mRedirectingToSetupAccount;
351 }
352
353
354 public OperationsServiceBinder getOperationsServiceBinder() {
355 return mOperationsServiceBinder;
356 }
357
358 protected ServiceConnection newTransferenceServiceConnection() {
359 return null;
360 }
361
362 /**
363 * Helper class handling a callback from the {@link AccountManager} after the creation of
364 * a new ownCloud {@link Account} finished, successfully or not.
365 *
366 * At this moment, only called after the creation of the first account.
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 } else if (operation instanceof SynchronizeFolderOperation) {
468 onSynchronizeFolderOperationFinish((SynchronizeFolderOperation)operation, result);
469
470 }
471 }
472
473 protected void requestCredentialsUpdate() {
474 Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
475 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, getAccount());
476 updateAccountCredentials.putExtra(
477 AuthenticatorActivity.EXTRA_ACTION,
478 AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
479 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
480 startActivity(updateAccountCredentials);
481 }
482
483
484 private void onCreateShareOperationFinish(CreateShareOperation operation, RemoteOperationResult result) {
485 dismissLoadingDialog();
486 if (result.isSuccess()) {
487 updateFileFromDB();
488
489 Intent sendIntent = operation.getSendIntent();
490 startActivity(sendIntent);
491
492 } else {
493 // TODO Detect Failure (403) --> needs Password
494 if (result.getCode() == ResultCode.SHARE_FORBIDDEN) {
495 SharePasswordDialogFragment dialog =
496 SharePasswordDialogFragment.newInstance(getFile());
497 dialog.show(getSupportFragmentManager(), DIALOG_SHARE_PASSWORD);
498 } else {
499 Toast t = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
500 Toast.LENGTH_LONG);
501 t.show();
502 }
503 }
504 }
505
506
507 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation, RemoteOperationResult result) {
508 dismissLoadingDialog();
509
510 if (result.isSuccess()){
511 updateFileFromDB();
512
513 } else {
514 Toast t = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
515 Toast.LENGTH_LONG);
516 t.show();
517 }
518 }
519
520 private void onSynchronizeFolderOperationFinish(SynchronizeFolderOperation operation, RemoteOperationResult result) {
521 if (!result.isSuccess() && result.getCode() != ResultCode.CANCELLED){
522 Toast t = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
523 Toast.LENGTH_LONG);
524 t.show();
525 }
526 }
527
528 protected void updateFileFromDB(){
529 OCFile file = getFile();
530 if (file != null) {
531 file = getStorageManager().getFileByPath(file.getRemotePath());
532 setFile(file);
533 }
534 }
535
536 /**
537 * Show loading dialog
538 */
539 public void showLoadingDialog() {
540 // Construct dialog
541 LoadingDialog loading = new LoadingDialog(getResources().getString(R.string.wait_a_moment));
542 FragmentManager fm = getSupportFragmentManager();
543 FragmentTransaction ft = fm.beginTransaction();
544 loading.show(ft, DIALOG_WAIT_TAG);
545
546 }
547
548
549 /**
550 * Dismiss loading dialog
551 */
552 public void dismissLoadingDialog(){
553 Fragment frag = getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG);
554 if (frag != null) {
555 LoadingDialog loading = (LoadingDialog) frag;
556 loading.dismiss();
557 }
558 }
559
560
561 private void doOnResumeAndBound() {
562 mOperationsServiceBinder.addOperationListener(FileActivity.this, mHandler);
563 long waitingForOpId = mFileOperationsHelper.getOpIdWaitingFor();
564 if (waitingForOpId <= Integer.MAX_VALUE) {
565 boolean wait = mOperationsServiceBinder.dispatchResultIfFinished((int)waitingForOpId, this);
566 if (!wait ) {
567 dismissLoadingDialog();
568 }
569 }
570 }
571
572
573 /**
574 * Implements callback methods for service binding. Passed as a parameter to {
575 */
576 private class OperationsServiceConnection implements ServiceConnection {
577
578 @Override
579 public void onServiceConnected(ComponentName component, IBinder service) {
580 if (component.equals(new ComponentName(FileActivity.this, OperationsService.class))) {
581 Log_OC.d(TAG, "Operations service connected");
582 mOperationsServiceBinder = (OperationsServiceBinder) service;
583 /*if (!mOperationsServiceBinder.isPerformingBlockingOperation()) {
584 dismissLoadingDialog();
585 }*/
586 doOnResumeAndBound();
587
588 } else {
589 return;
590 }
591 }
592
593
594 @Override
595 public void onServiceDisconnected(ComponentName component) {
596 if (component.equals(new ComponentName(FileActivity.this, OperationsService.class))) {
597 Log_OC.d(TAG, "Operations service disconnected");
598 mOperationsServiceBinder = null;
599 // TODO whatever could be waiting for the service is unbound
600 }
601 }
602 }
603
604
605 @Override
606 public FileDownloaderBinder getFileDownloaderBinder() {
607 return mDownloaderBinder;
608 }
609
610
611 @Override
612 public FileUploaderBinder getFileUploaderBinder() {
613 return mUploaderBinder;
614 }
615
616
617 }