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