Merge remote-tracking branch 'origin/pinEnhancement' into pinEnhancement
[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.LoadingDialog;
65 import com.owncloud.android.ui.dialog.SharePasswordDialogFragment;
66 import com.owncloud.android.utils.ErrorMessageAdapter;
67
68
69 /**
70 * Activity with common behaviour for activities handling {@link OCFile}s in ownCloud {@link Account}s .
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 private static final String KEY_TRY_SHARE_AGAIN = "TRY_SHARE_AGAIN";
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 protected boolean mAccountWasSet;
101
102 /** Flag to signal when the value of mAccount was restored from a saved state */
103 protected 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 private boolean mTryShareAgain = false;
125
126
127 /**
128 * Loads the ownCloud {@link Account} and main {@link OCFile} to be handled by the instance of
129 * the {@link FileActivity}.
130 *
131 * Grants that a valid ownCloud {@link Account} is associated to the instance, or that the user
132 * is requested to create a new one.
133 */
134 @Override
135 protected void onCreate(Bundle savedInstanceState) {
136 super.onCreate(savedInstanceState);
137 mHandler = new Handler();
138 mFileOperationsHelper = new FileOperationsHelper(this);
139 Account account;
140 if(savedInstanceState != null) {
141 account = savedInstanceState.getParcelable(FileActivity.EXTRA_ACCOUNT);
142 mFile = savedInstanceState.getParcelable(FileActivity.EXTRA_FILE);
143 mFromNotification = savedInstanceState.getBoolean(FileActivity.EXTRA_FROM_NOTIFICATION);
144 mFileOperationsHelper.setOpIdWaitingFor(
145 savedInstanceState.getLong(KEY_WAITING_FOR_OP_ID, Long.MAX_VALUE)
146 );
147 mTryShareAgain = savedInstanceState.getBoolean(KEY_TRY_SHARE_AGAIN);
148 } else {
149 account = getIntent().getParcelableExtra(FileActivity.EXTRA_ACCOUNT);
150 mFile = getIntent().getParcelableExtra(FileActivity.EXTRA_FILE);
151 mFromNotification = getIntent().getBooleanExtra(FileActivity.EXTRA_FROM_NOTIFICATION, false);
152 }
153
154 AccountUtils.updateAccountVersion(this); // best place, before any access to AccountManager or database
155
156 setAccount(account, savedInstanceState != null);
157
158 mOperationsServiceConnection = new OperationsServiceConnection();
159 bindService(new Intent(this, OperationsService.class), mOperationsServiceConnection, Context.BIND_AUTO_CREATE);
160
161 mDownloadServiceConnection = newTransferenceServiceConnection();
162 if (mDownloadServiceConnection != null) {
163 bindService(new Intent(this, FileDownloader.class), mDownloadServiceConnection, Context.BIND_AUTO_CREATE);
164 }
165 mUploadServiceConnection = newTransferenceServiceConnection();
166 if (mUploadServiceConnection != null) {
167 bindService(new Intent(this, FileUploader.class), mUploadServiceConnection, Context.BIND_AUTO_CREATE);
168 }
169
170 }
171
172 @Override
173 protected void onNewIntent (Intent intent) {
174 Log_OC.v(TAG, "onNewIntent() start");
175 Account current = AccountUtils.getCurrentOwnCloudAccount(this);
176 if (current != null && mAccount != null && !mAccount.name.equals(current.name)) {
177 mAccount = current;
178 }
179 Log_OC.v(TAG, "onNewIntent() stop");
180 }
181
182 /**
183 * Since ownCloud {@link Account}s can be managed from the system setting menu,
184 * the existence of the {@link Account} associated to the instance must be checked
185 * every time it is restarted.
186 */
187 @Override
188 protected void onRestart() {
189 Log_OC.v(TAG, "onRestart() start");
190 super.onRestart();
191 boolean validAccount = (mAccount != null && AccountUtils.exists(mAccount, this));
192 if (!validAccount) {
193 swapToDefaultAccount();
194 }
195 Log_OC.v(TAG, "onRestart() end");
196 }
197
198
199 @Override
200 protected void onStart() {
201 super.onStart();
202
203 if (mAccountWasSet) {
204 onAccountSet(mAccountWasRestored);
205 }
206 }
207
208 @Override
209 protected void onResume() {
210 super.onResume();
211
212 if (mOperationsServiceBinder != null) {
213 doOnResumeAndBound();
214 }
215 }
216
217 @Override
218 protected void onPause() {
219 if (mOperationsServiceBinder != null) {
220 mOperationsServiceBinder.removeOperationListener(this);
221 }
222
223 super.onPause();
224 }
225
226
227 @Override
228 protected void onDestroy() {
229 if (mOperationsServiceConnection != null) {
230 unbindService(mOperationsServiceConnection);
231 mOperationsServiceBinder = null;
232 }
233 if (mDownloadServiceConnection != null) {
234 unbindService(mDownloadServiceConnection);
235 mDownloadServiceConnection = null;
236 }
237 if (mUploadServiceConnection != null) {
238 unbindService(mUploadServiceConnection);
239 mUploadServiceConnection = null;
240 }
241
242 super.onDestroy();
243 }
244
245
246 /**
247 * Sets and validates the ownCloud {@link Account} associated to the Activity.
248 *
249 * If not valid, tries to swap it for other valid and existing ownCloud {@link Account}.
250 *
251 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
252 *
253 * @param account New {@link Account} to set.
254 * @param savedAccount When 'true', account was retrieved from a saved instance state.
255 */
256 protected void setAccount(Account account, boolean savedAccount) {
257 Account oldAccount = mAccount;
258 boolean validAccount =
259 (account != null && AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), account.name));
260 if (validAccount) {
261 mAccount = account;
262 mAccountWasSet = true;
263 mAccountWasRestored = (savedAccount || mAccount.equals(oldAccount));
264
265 } else {
266 swapToDefaultAccount();
267 }
268 }
269
270
271 /**
272 * Tries to swap the current ownCloud {@link Account} for other valid and existing.
273 *
274 * If no valid ownCloud {@link Account} exists, the the user is requested
275 * to create a new ownCloud {@link Account}.
276 *
277 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
278 */
279 private void swapToDefaultAccount() {
280 // default to the most recently used account
281 Account newAccount = AccountUtils.getCurrentOwnCloudAccount(getApplicationContext());
282 if (newAccount == null) {
283 /// no account available: force account creation
284 createFirstAccount();
285 mRedirectingToSetupAccount = true;
286 mAccountWasSet = false;
287 mAccountWasRestored = false;
288
289 } else {
290 mAccountWasSet = true;
291 mAccountWasRestored = (newAccount.equals(mAccount));
292 mAccount = newAccount;
293 }
294 }
295
296
297 /**
298 * Launches the account creation activity. To use when no ownCloud account is available
299 */
300 private void createFirstAccount() {
301 AccountManager am = AccountManager.get(getApplicationContext());
302 am.addAccount(MainApp.getAccountType(),
303 null,
304 null,
305 null,
306 this,
307 new AccountCreationCallback(),
308 null);
309 }
310
311
312 /**
313 * {@inheritDoc}
314 */
315 @Override
316 protected void onSaveInstanceState(Bundle outState) {
317 super.onSaveInstanceState(outState);
318 outState.putParcelable(FileActivity.EXTRA_FILE, mFile);
319 outState.putParcelable(FileActivity.EXTRA_ACCOUNT, mAccount);
320 outState.putBoolean(FileActivity.EXTRA_FROM_NOTIFICATION, mFromNotification);
321 outState.putLong(KEY_WAITING_FOR_OP_ID, mFileOperationsHelper.getOpIdWaitingFor());
322 outState.putBoolean(KEY_TRY_SHARE_AGAIN, mTryShareAgain);
323 }
324
325
326 /**
327 * Getter for the main {@link OCFile} handled by the activity.
328 *
329 * @return Main {@link OCFile} handled by the activity.
330 */
331 public OCFile getFile() {
332 return mFile;
333 }
334
335
336 /**
337 * Setter for the main {@link OCFile} handled by the activity.
338 *
339 * @param file Main {@link OCFile} to be handled by the activity.
340 */
341 public void setFile(OCFile file) {
342 mFile = file;
343 }
344
345
346 /**
347 * Getter for the ownCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
348 *
349 * @return OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
350 */
351 public Account getAccount() {
352 return mAccount;
353 }
354
355 protected void setAccount(Account account) {
356 mAccount = account;
357 }
358
359 /**
360 * @return Value of mFromNotification: True if the Activity is launched by a notification
361 */
362 public boolean fromNotification() {
363 return mFromNotification;
364 }
365
366 /**
367 * @return 'True' when the Activity is finishing to enforce the setup of a new account.
368 */
369 protected boolean isRedirectingToSetupAccount() {
370 return mRedirectingToSetupAccount;
371 }
372
373 public boolean isTryShareAgain(){
374 return mTryShareAgain;
375 }
376
377 public void setTryShareAgain(boolean tryShareAgain) {
378 mTryShareAgain = tryShareAgain;
379 }
380
381 public OperationsServiceBinder getOperationsServiceBinder() {
382 return mOperationsServiceBinder;
383 }
384
385 protected ServiceConnection newTransferenceServiceConnection() {
386 return null;
387 }
388
389 /**
390 * Helper class handling a callback from the {@link AccountManager} after the creation of
391 * a new ownCloud {@link Account} finished, successfully or not.
392 *
393 * At this moment, only called after the creation of the first account.
394 */
395 public class AccountCreationCallback implements AccountManagerCallback<Bundle> {
396
397 @Override
398 public void run(AccountManagerFuture<Bundle> future) {
399 FileActivity.this.mRedirectingToSetupAccount = false;
400 boolean accountWasSet = false;
401 if (future != null) {
402 try {
403 Bundle result;
404 result = future.getResult();
405 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
406 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
407 if (AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), name)) {
408 setAccount(new Account(name, type), false);
409 accountWasSet = true;
410 }
411 } catch (OperationCanceledException e) {
412 Log_OC.d(TAG, "Account creation canceled");
413
414 } catch (Exception e) {
415 Log_OC.e(TAG, "Account creation finished in exception: ", e);
416 }
417
418 } else {
419 Log_OC.e(TAG, "Account creation callback with null bundle");
420 }
421 if (!accountWasSet) {
422 moveTaskToBack(true);
423 }
424 }
425
426 }
427
428
429 /**
430 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
431 *
432 * Child classes must grant that state depending on the {@link Account} is updated.
433 */
434 protected void onAccountSet(boolean stateWasRecovered) {
435 if (getAccount() != null) {
436 mStorageManager = new FileDataStorageManager(getAccount(), getContentResolver());
437
438 } else {
439 Log_OC.wtf(TAG, "onAccountChanged was called with NULL account associated!");
440 }
441 }
442
443
444 public FileDataStorageManager getStorageManager() {
445 return mStorageManager;
446 }
447
448
449 public OnRemoteOperationListener getRemoteOperationListener() {
450 return this;
451 }
452
453
454 public Handler getHandler() {
455 return mHandler;
456 }
457
458 public FileOperationsHelper getFileOperationsHelper() {
459 return mFileOperationsHelper;
460 }
461
462 /**
463 *
464 * @param operation Removal operation performed.
465 * @param result Result of the removal.
466 */
467 @Override
468 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
469 Log_OC.d(TAG, "Received result of operation in FileActivity - common behaviour for all the FileActivities ");
470
471 mFileOperationsHelper.setOpIdWaitingFor(Long.MAX_VALUE);
472
473 if (!result.isSuccess() && (
474 result.getCode() == ResultCode.UNAUTHORIZED ||
475 result.isIdPRedirection() ||
476 (result.isException() && result.getException() instanceof AuthenticatorException)
477 )) {
478
479 requestCredentialsUpdate();
480
481 if (result.getCode() == ResultCode.UNAUTHORIZED) {
482 dismissLoadingDialog();
483 Toast t = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result,
484 operation, getResources()),
485 Toast.LENGTH_LONG);
486 t.show();
487 }
488 mTryShareAgain = false;
489
490 } else if (operation instanceof CreateShareOperation) {
491 onCreateShareOperationFinish((CreateShareOperation) operation, result);
492
493 } else if (operation instanceof UnshareLinkOperation) {
494 onUnshareLinkOperationFinish((UnshareLinkOperation)operation, result);
495
496 } else if (operation instanceof SynchronizeFolderOperation) {
497 onSynchronizeFolderOperationFinish((SynchronizeFolderOperation)operation, result);
498
499 }
500 }
501
502 protected void requestCredentialsUpdate() {
503 Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
504 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, getAccount());
505 updateAccountCredentials.putExtra(
506 AuthenticatorActivity.EXTRA_ACTION,
507 AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
508 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
509 startActivity(updateAccountCredentials);
510 }
511
512
513 private void onCreateShareOperationFinish(CreateShareOperation operation,
514 RemoteOperationResult result) {
515 dismissLoadingDialog();
516 if (result.isSuccess()) {
517 mTryShareAgain = false;
518 updateFileFromDB();
519
520 Intent sendIntent = operation.getSendIntent();
521 startActivity(sendIntent);
522 } else {
523 // Detect Failure (403) --> needs Password
524 if (result.getCode() == ResultCode.SHARE_FORBIDDEN) {
525 if (!isTryShareAgain()) {
526 SharePasswordDialogFragment dialog =
527 SharePasswordDialogFragment.newInstance(new OCFile(operation.getPath()),
528 operation.getSendIntent());
529 dialog.show(getSupportFragmentManager(), DIALOG_SHARE_PASSWORD);
530 } else {
531 Toast t = Toast.makeText(this,
532 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
533 Toast.LENGTH_LONG);
534 t.show();
535 mTryShareAgain = false;
536 }
537 } else {
538 Toast t = Toast.makeText(this,
539 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
540 Toast.LENGTH_LONG);
541 t.show();
542 }
543 }
544 }
545
546
547 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation, RemoteOperationResult result) {
548 dismissLoadingDialog();
549
550 if (result.isSuccess()){
551 updateFileFromDB();
552
553 } else {
554 Toast t = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
555 Toast.LENGTH_LONG);
556 t.show();
557 }
558 }
559
560 private void onSynchronizeFolderOperationFinish(
561 SynchronizeFolderOperation operation, RemoteOperationResult result
562 ) {
563 if (!result.isSuccess() && result.getCode() != ResultCode.CANCELLED){
564 Toast t = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
565 Toast.LENGTH_LONG);
566 t.show();
567 }
568 }
569
570 protected void updateFileFromDB(){
571 OCFile file = getFile();
572 if (file != null) {
573 file = getStorageManager().getFileByPath(file.getRemotePath());
574 setFile(file);
575 }
576 }
577
578 /**
579 * Show loading dialog
580 */
581 public void showLoadingDialog() {
582 // Construct dialog
583 LoadingDialog loading = new LoadingDialog(getResources().getString(R.string.wait_a_moment));
584 FragmentManager fm = getSupportFragmentManager();
585 FragmentTransaction ft = fm.beginTransaction();
586 loading.show(ft, DIALOG_WAIT_TAG);
587
588 }
589
590
591 /**
592 * Dismiss loading dialog
593 */
594 public void dismissLoadingDialog(){
595 Fragment frag = getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG);
596 if (frag != null) {
597 LoadingDialog loading = (LoadingDialog) frag;
598 loading.dismiss();
599 }
600 }
601
602
603 private void doOnResumeAndBound() {
604 mOperationsServiceBinder.addOperationListener(FileActivity.this, mHandler);
605 long waitingForOpId = mFileOperationsHelper.getOpIdWaitingFor();
606 if (waitingForOpId <= Integer.MAX_VALUE) {
607 boolean wait = mOperationsServiceBinder.dispatchResultIfFinished((int)waitingForOpId, this);
608 if (!wait ) {
609 dismissLoadingDialog();
610 }
611 }
612 }
613
614
615 /**
616 * Implements callback methods for service binding. Passed as a parameter to {
617 */
618 private class OperationsServiceConnection implements ServiceConnection {
619
620 @Override
621 public void onServiceConnected(ComponentName component, IBinder service) {
622 if (component.equals(new ComponentName(FileActivity.this, OperationsService.class))) {
623 Log_OC.d(TAG, "Operations service connected");
624 mOperationsServiceBinder = (OperationsServiceBinder) service;
625 /*if (!mOperationsServiceBinder.isPerformingBlockingOperation()) {
626 dismissLoadingDialog();
627 }*/
628 doOnResumeAndBound();
629
630 } else {
631 return;
632 }
633 }
634
635
636 @Override
637 public void onServiceDisconnected(ComponentName component) {
638 if (component.equals(new ComponentName(FileActivity.this, OperationsService.class))) {
639 Log_OC.d(TAG, "Operations service disconnected");
640 mOperationsServiceBinder = null;
641 // TODO whatever could be waiting for the service is unbound
642 }
643 }
644 }
645
646
647 @Override
648 public FileDownloaderBinder getFileDownloaderBinder() {
649 return mDownloaderBinder;
650 }
651
652
653 @Override
654 public FileUploaderBinder getFileUploaderBinder() {
655 return mUploaderBinder;
656 }
657
658
659 }