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