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