c37477cf565341dd82ea5d75934445c5454f9e79
[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.content.res.Configuration;
35 import android.os.Bundle;
36 import android.os.Handler;
37 import android.os.IBinder;
38 import android.support.v4.app.ActionBarDrawerToggle;
39 import android.support.v4.app.Fragment;
40 import android.support.v4.app.FragmentManager;
41 import android.support.v4.app.FragmentTransaction;
42 import android.support.v4.view.GravityCompat;
43 import android.support.v4.widget.DrawerLayout;
44 import android.support.v7.app.ActionBar;
45 import android.support.v7.app.ActionBarActivity;
46 import android.view.View;
47 import android.widget.AdapterView;
48 import android.widget.LinearLayout;
49 import android.widget.ListView;
50 import android.widget.Toast;
51
52 import com.owncloud.android.BuildConfig;
53 import com.owncloud.android.MainApp;
54 import com.owncloud.android.R;
55 import com.owncloud.android.authentication.AccountUtils;
56 import com.owncloud.android.authentication.AuthenticatorActivity;
57 import com.owncloud.android.datamodel.FileDataStorageManager;
58 import com.owncloud.android.datamodel.OCFile;
59 import com.owncloud.android.files.FileOperationsHelper;
60 import com.owncloud.android.files.services.FileDownloader;
61 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
62 import com.owncloud.android.files.services.FileUploader;
63 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
64 import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;
65 import com.owncloud.android.lib.common.operations.RemoteOperation;
66 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
67 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
68 import com.owncloud.android.lib.common.utils.Log_OC;
69 import com.owncloud.android.operations.CreateShareOperation;
70 import com.owncloud.android.operations.SynchronizeFolderOperation;
71 import com.owncloud.android.operations.UnshareLinkOperation;
72 import com.owncloud.android.services.OperationsService;
73 import com.owncloud.android.services.OperationsService.OperationsServiceBinder;
74 import com.owncloud.android.ui.NavigationDrawerItem;
75 import com.owncloud.android.ui.adapter.NavigationDrawerListAdapter;
76 import com.owncloud.android.ui.dialog.LoadingDialog;
77 import com.owncloud.android.ui.dialog.SharePasswordDialogFragment;
78 import com.owncloud.android.utils.ErrorMessageAdapter;
79
80 import java.util.ArrayList;
81
82
83 /**
84 * Activity with common behaviour for activities handling {@link OCFile}s in ownCloud
85 * {@link Account}s .
86 */
87 public class FileActivity extends ActionBarActivity
88 implements OnRemoteOperationListener, ComponentsGetter {
89
90 public static final String EXTRA_FILE = "com.owncloud.android.ui.activity.FILE";
91 public static final String EXTRA_ACCOUNT = "com.owncloud.android.ui.activity.ACCOUNT";
92 public static final String EXTRA_WAITING_TO_PREVIEW =
93 "com.owncloud.android.ui.activity.WAITING_TO_PREVIEW";
94 public static final String EXTRA_FROM_NOTIFICATION =
95 "com.owncloud.android.ui.activity.FROM_NOTIFICATION";
96
97 public static final String TAG = FileActivity.class.getSimpleName();
98
99 private static final String DIALOG_WAIT_TAG = "DIALOG_WAIT";
100 private static final String KEY_WAITING_FOR_OP_ID = "WAITING_FOR_OP_ID";
101 private static final String DIALOG_SHARE_PASSWORD = "DIALOG_SHARE_PASSWORD";
102 private static final String KEY_TRY_SHARE_AGAIN = "TRY_SHARE_AGAIN";
103 private static final String KEY_ACTION_BAR_TITLE = "ACTION_BAR_TITLE";
104
105 protected static final long DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS = 200;
106
107
108 /** OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located.*/
109 private Account mAccount;
110
111 /** Main {@link OCFile} handled by the activity.*/
112 private OCFile mFile;
113
114 /** Flag to signal that the activity will is finishing to enforce the creation of an ownCloud
115 * {@link Account} */
116 private boolean mRedirectingToSetupAccount = false;
117
118 /** Flag to signal when the value of mAccount was set */
119 protected boolean mAccountWasSet;
120
121 /** Flag to signal when the value of mAccount was restored from a saved state */
122 protected boolean mAccountWasRestored;
123
124 /** Flag to signal if the activity is launched by a notification */
125 private boolean mFromNotification;
126
127 /** Messages handler associated to the main thread and the life cycle of the activity */
128 private Handler mHandler;
129
130 /** Access point to the cached database for the current ownCloud {@link Account} */
131 private FileDataStorageManager mStorageManager = null;
132
133 private FileOperationsHelper mFileOperationsHelper;
134
135 private ServiceConnection mOperationsServiceConnection = null;
136
137 private OperationsServiceBinder mOperationsServiceBinder = null;
138
139 protected FileDownloaderBinder mDownloaderBinder = null;
140 protected FileUploaderBinder mUploaderBinder = null;
141 private ServiceConnection mDownloadServiceConnection, mUploadServiceConnection = null;
142
143 private boolean mTryShareAgain = false;
144
145 // Navigation Drawer
146 protected DrawerLayout mDrawerLayout;
147 protected ActionBarDrawerToggle mDrawerToggle;
148 protected ListView mDrawerList;
149
150 // Slide menu items
151 protected String[] mDrawerTitles;
152 protected String[] mDrawerContentDescriptions;
153
154 protected ArrayList<NavigationDrawerItem> mDrawerItems;
155
156 protected NavigationDrawerListAdapter mNavigationDrawerAdapter = null;
157
158
159 // TODO re-enable when "Accounts" is available in Navigation Drawer
160 // protected boolean mShowAccounts = false;
161
162 /**
163 * Loads the ownCloud {@link Account} and main {@link OCFile} to be handled by the instance of
164 * the {@link FileActivity}.
165 *
166 * Grants that a valid ownCloud {@link Account} is associated to the instance, or that the user
167 * is requested to create a new one.
168 */
169 @Override
170 protected void onCreate(Bundle savedInstanceState) {
171 super.onCreate(savedInstanceState);
172 mHandler = new Handler();
173 mFileOperationsHelper = new FileOperationsHelper(this);
174 Account account = null;
175 if(savedInstanceState != null) {
176 mFile = savedInstanceState.getParcelable(FileActivity.EXTRA_FILE);
177 mFromNotification = savedInstanceState.getBoolean(FileActivity.EXTRA_FROM_NOTIFICATION);
178 mFileOperationsHelper.setOpIdWaitingFor(
179 savedInstanceState.getLong(KEY_WAITING_FOR_OP_ID, Long.MAX_VALUE)
180 );
181 mTryShareAgain = savedInstanceState.getBoolean(KEY_TRY_SHARE_AGAIN);
182 getSupportActionBar().setTitle(savedInstanceState.getString(KEY_ACTION_BAR_TITLE));
183 } else {
184 account = getIntent().getParcelableExtra(FileActivity.EXTRA_ACCOUNT);
185 mFile = getIntent().getParcelableExtra(FileActivity.EXTRA_FILE);
186 mFromNotification = getIntent().getBooleanExtra(FileActivity.EXTRA_FROM_NOTIFICATION,
187 false);
188 }
189
190 AccountUtils.updateAccountVersion(this); // best place, before any access to AccountManager
191 // or database
192
193 setAccount(account, savedInstanceState != null);
194
195 mOperationsServiceConnection = new OperationsServiceConnection();
196 bindService(new Intent(this, OperationsService.class), mOperationsServiceConnection,
197 Context.BIND_AUTO_CREATE);
198
199 mDownloadServiceConnection = newTransferenceServiceConnection();
200 if (mDownloadServiceConnection != null) {
201 bindService(new Intent(this, FileDownloader.class), mDownloadServiceConnection,
202 Context.BIND_AUTO_CREATE);
203 }
204 mUploadServiceConnection = newTransferenceServiceConnection();
205 if (mUploadServiceConnection != null) {
206 bindService(new Intent(this, FileUploader.class), mUploadServiceConnection,
207 Context.BIND_AUTO_CREATE);
208 }
209
210 }
211
212 @Override
213 protected void onNewIntent (Intent intent) {
214 Log_OC.v(TAG, "onNewIntent() start");
215 Account current = AccountUtils.getCurrentOwnCloudAccount(this);
216 if (current != null && mAccount != null && !mAccount.name.equals(current.name)) {
217 mAccount = current;
218 }
219 Log_OC.v(TAG, "onNewIntent() stop");
220 }
221
222 /**
223 * Since ownCloud {@link Account}s can be managed from the system setting menu,
224 * the existence of the {@link Account} associated to the instance must be checked
225 * every time it is restarted.
226 */
227 @Override
228 protected void onRestart() {
229 Log_OC.v(TAG, "onRestart() start");
230 super.onRestart();
231 boolean validAccount = (mAccount != null && AccountUtils.exists(mAccount, this));
232 if (!validAccount) {
233 swapToDefaultAccount();
234 }
235 Log_OC.v(TAG, "onRestart() end");
236 }
237
238
239 @Override
240 protected void onStart() {
241 super.onStart();
242
243 if (mAccountWasSet) {
244 onAccountSet(mAccountWasRestored);
245 }
246 }
247
248 @Override
249 protected void onResume() {
250 super.onResume();
251
252 if (mOperationsServiceBinder != null) {
253 doOnResumeAndBound();
254 }
255 }
256
257 @Override
258 protected void onPause() {
259 if (mOperationsServiceBinder != null) {
260 mOperationsServiceBinder.removeOperationListener(this);
261 }
262
263 super.onPause();
264 }
265
266
267 @Override
268 protected void onDestroy() {
269 if (mOperationsServiceConnection != null) {
270 unbindService(mOperationsServiceConnection);
271 mOperationsServiceBinder = null;
272 }
273 if (mDownloadServiceConnection != null) {
274 unbindService(mDownloadServiceConnection);
275 mDownloadServiceConnection = null;
276 }
277 if (mUploadServiceConnection != null) {
278 unbindService(mUploadServiceConnection);
279 mUploadServiceConnection = null;
280 }
281
282 super.onDestroy();
283 }
284
285 @Override
286 protected void onPostCreate(Bundle savedInstanceState) {
287 super.onPostCreate(savedInstanceState);
288 // Sync the toggle state after onRestoreInstanceState has occurred.
289 if (mDrawerToggle != null) {
290 mDrawerToggle.syncState();
291 if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
292 getSupportActionBar().setTitle(R.string.app_name);
293 mDrawerToggle.setDrawerIndicatorEnabled(true);
294 }
295 }
296 }
297
298 @Override
299 public void onConfigurationChanged(Configuration newConfig) {
300 super.onConfigurationChanged(newConfig);
301 if (mDrawerToggle != null) {
302 mDrawerToggle.onConfigurationChanged(newConfig);
303 }
304 }
305
306 protected void initDrawer(){
307 // constant settings for action bar when navigation drawer is inited
308 getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
309
310
311 mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
312 // Notification Drawer
313 LinearLayout navigationDrawerLayout = (LinearLayout) findViewById(R.id.left_drawer);
314 mDrawerList = (ListView) navigationDrawerLayout.findViewById(R.id.drawer_list);
315
316 // TODO re-enable when "Accounts" is available in Navigation Drawer
317 // // load Account in the Drawer Title
318 // // User-Icon
319 // ImageView userIcon = (ImageView) navigationDrawerLayout.findViewById(R.id.drawer_userIcon);
320 // userIcon.setImageResource(DisplayUtils.getSeasonalIconId());
321 //
322 // // Username
323 // TextView username = (TextView) navigationDrawerLayout.findViewById(R.id.drawer_username);
324 // Account account = AccountUtils.getCurrentOwnCloudAccount(getApplicationContext());
325 //
326 // if (account != null) {
327 // int lastAtPos = account.name.lastIndexOf("@");
328 // username.setText(account.name.substring(0, lastAtPos));
329 // }
330
331 // load slide menu items
332 mDrawerTitles = getResources().getStringArray(R.array.drawer_items);
333
334 // nav drawer content description from resources
335 mDrawerContentDescriptions = getResources().
336 getStringArray(R.array.drawer_content_descriptions);
337
338 // nav drawer items
339 mDrawerItems = new ArrayList<NavigationDrawerItem>();
340 // adding nav drawer items to array
341 // TODO re-enable when "Accounts" is available in Navigation Drawer
342 // Accounts
343 // mDrawerItems.add(new NavigationDrawerItem(mDrawerTitles[0],
344 // mDrawerContentDescriptions[0]));
345 // All Files
346 mDrawerItems.add(new NavigationDrawerItem(mDrawerTitles[0], mDrawerContentDescriptions[0]));
347
348 // TODO Enable when "On Device" is recovered
349 // On Device
350 //mDrawerItems.add(new NavigationDrawerItem(mDrawerTitles[2],
351 // mDrawerContentDescriptions[2]));
352
353 // Settings
354 mDrawerItems.add(new NavigationDrawerItem(mDrawerTitles[1], mDrawerContentDescriptions[1]));
355 // Logs
356 if (BuildConfig.DEBUG) {
357 mDrawerItems.add(new NavigationDrawerItem(mDrawerTitles[2],
358 mDrawerContentDescriptions[2]));
359 }
360
361 // setting the nav drawer list adapter
362 mNavigationDrawerAdapter = new NavigationDrawerListAdapter(getApplicationContext(), this,
363 mDrawerItems);
364 mDrawerList.setAdapter(mNavigationDrawerAdapter);
365
366 mDrawerToggle = new ActionBarDrawerToggle(
367 this,
368 mDrawerLayout,
369 R.drawable.ic_drawer,
370 R.string.app_name,
371 R.string.drawer_close) {
372
373 /** Called when a drawer has settled in a completely closed state. */
374 public void onDrawerClosed(View view) {
375 super.onDrawerClosed(view);
376 updateActionBarTitleAndHomeButton(null);
377 invalidateOptionsMenu();
378 }
379
380 /** Called when a drawer has settled in a completely open state. */
381 public void onDrawerOpened(View drawerView) {
382 super.onDrawerOpened(drawerView);
383 getSupportActionBar().setTitle(R.string.app_name);
384 mDrawerToggle.setDrawerIndicatorEnabled(true);
385 invalidateOptionsMenu();
386 }
387 };
388
389 //mDrawerToggle.setDrawerIndicatorEnabled(true);
390 // Set the list's click listener
391 mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
392
393 // Set the drawer toggle as the DrawerListener
394 mDrawerLayout.setDrawerListener(mDrawerToggle);
395 }
396
397 /**
398 * Updates title bar and home buttons (state and icon).
399 *
400 * Assumes that navigation drawer is NOT visible.
401 */
402 protected void updateActionBarTitleAndHomeButton(OCFile chosenFile) {
403 String title = getString(R.string.default_display_name_for_root_folder); // default
404 boolean inRoot;
405
406 /// choose the appropiate title
407 if (chosenFile == null) {
408 // mFile determines the title
409 inRoot = (mFile == null || mFile.getParentId() == 0);
410 if (!inRoot) {
411 title = mFile.getFileName();
412 }
413
414 } else {
415 // chosenFile determines the title, instead of mFile
416 title = chosenFile.getFileName();
417 inRoot = false;
418 }
419
420 /// set the chosen title
421 ActionBar actionBar = getSupportActionBar();
422 actionBar.setTitle(title);
423 /// also as content description
424 View actionBarTitleView = getWindow().getDecorView().findViewById(
425 getResources().getIdentifier("action_bar_title", "id", "android")
426 );
427 if (actionBarTitleView != null) { // it's null in Android 2.x
428 actionBarTitleView.setContentDescription(title);
429 }
430
431 /// set home button properties
432 mDrawerToggle.setDrawerIndicatorEnabled(inRoot);
433 actionBar.setDisplayHomeAsUpEnabled(true);
434 actionBar.setDisplayShowTitleEnabled(true);
435
436 }
437
438
439 /**
440 * Sets and validates the ownCloud {@link Account} associated to the Activity.
441 *
442 * If not valid, tries to swap it for other valid and existing ownCloud {@link Account}.
443 *
444 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
445 *
446 * @param account New {@link Account} to set.
447 * @param savedAccount When 'true', account was retrieved from a saved instance state.
448 */
449 protected void setAccount(Account account, boolean savedAccount) {
450 Account oldAccount = mAccount;
451 boolean validAccount =
452 (account != null && AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(),
453 account.name));
454 if (validAccount) {
455 mAccount = account;
456 mAccountWasSet = true;
457 mAccountWasRestored = (savedAccount || mAccount.equals(oldAccount));
458
459 } else {
460 swapToDefaultAccount();
461 }
462 }
463
464
465 /**
466 * Tries to swap the current ownCloud {@link Account} for other valid and existing.
467 *
468 * If no valid ownCloud {@link Account} exists, the the user is requested
469 * to create a new ownCloud {@link Account}.
470 *
471 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
472 */
473 private void swapToDefaultAccount() {
474 // default to the most recently used account
475 Account newAccount = AccountUtils.getCurrentOwnCloudAccount(getApplicationContext());
476 if (newAccount == null) {
477 /// no account available: force account creation
478 createFirstAccount();
479 mRedirectingToSetupAccount = true;
480 mAccountWasSet = false;
481 mAccountWasRestored = false;
482
483 } else {
484 mAccountWasSet = true;
485 mAccountWasRestored = (newAccount.equals(mAccount));
486 mAccount = newAccount;
487 }
488 }
489
490
491 /**
492 * Launches the account creation activity. To use when no ownCloud account is available
493 */
494 private void createFirstAccount() {
495 AccountManager am = AccountManager.get(getApplicationContext());
496 am.addAccount(MainApp.getAccountType(),
497 null,
498 null,
499 null,
500 this,
501 new AccountCreationCallback(),
502 null);
503 }
504
505
506 /**
507 * {@inheritDoc}
508 */
509 @Override
510 protected void onSaveInstanceState(Bundle outState) {
511 super.onSaveInstanceState(outState);
512 outState.putParcelable(FileActivity.EXTRA_FILE, mFile);
513 outState.putBoolean(FileActivity.EXTRA_FROM_NOTIFICATION, mFromNotification);
514 outState.putLong(KEY_WAITING_FOR_OP_ID, mFileOperationsHelper.getOpIdWaitingFor());
515 outState.putBoolean(KEY_TRY_SHARE_AGAIN, mTryShareAgain);
516 outState.putString(KEY_ACTION_BAR_TITLE, getSupportActionBar().getTitle().toString());
517 }
518
519
520 /**
521 * Getter for the main {@link OCFile} handled by the activity.
522 *
523 * @return Main {@link OCFile} handled by the activity.
524 */
525 public OCFile getFile() {
526 return mFile;
527 }
528
529
530 /**
531 * Setter for the main {@link OCFile} handled by the activity.
532 *
533 * @param file Main {@link OCFile} to be handled by the activity.
534 */
535 public void setFile(OCFile file) {
536 mFile = file;
537 }
538
539
540 /**
541 * Getter for the ownCloud {@link Account} where the main {@link OCFile} handled by the activity
542 * is located.
543 *
544 * @return OwnCloud {@link Account} where the main {@link OCFile} handled by the activity
545 * is located.
546 */
547 public Account getAccount() {
548 return mAccount;
549 }
550
551 protected void setAccount(Account account) {
552 mAccount = account;
553 }
554
555 /**
556 * @return Value of mFromNotification: True if the Activity is launched by a notification
557 */
558 public boolean fromNotification() {
559 return mFromNotification;
560 }
561
562 /**
563 * @return 'True' when the Activity is finishing to enforce the setup of a new account.
564 */
565 protected boolean isRedirectingToSetupAccount() {
566 return mRedirectingToSetupAccount;
567 }
568
569 public boolean isTryShareAgain(){
570 return mTryShareAgain;
571 }
572
573 public void setTryShareAgain(boolean tryShareAgain) {
574 mTryShareAgain = tryShareAgain;
575 }
576
577 public OperationsServiceBinder getOperationsServiceBinder() {
578 return mOperationsServiceBinder;
579 }
580
581 protected ServiceConnection newTransferenceServiceConnection() {
582 return null;
583 }
584
585 /**
586 * Helper class handling a callback from the {@link AccountManager} after the creation of
587 * a new ownCloud {@link Account} finished, successfully or not.
588 *
589 * At this moment, only called after the creation of the first account.
590 */
591 public class AccountCreationCallback implements AccountManagerCallback<Bundle> {
592
593 @Override
594 public void run(AccountManagerFuture<Bundle> future) {
595 FileActivity.this.mRedirectingToSetupAccount = false;
596 boolean accountWasSet = false;
597 if (future != null) {
598 try {
599 Bundle result;
600 result = future.getResult();
601 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
602 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
603 if (AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), name)) {
604 setAccount(new Account(name, type), false);
605 accountWasSet = true;
606 }
607 } catch (OperationCanceledException e) {
608 Log_OC.d(TAG, "Account creation canceled");
609
610 } catch (Exception e) {
611 Log_OC.e(TAG, "Account creation finished in exception: ", e);
612 }
613
614 } else {
615 Log_OC.e(TAG, "Account creation callback with null bundle");
616 }
617 if (!accountWasSet) {
618 moveTaskToBack(true);
619 }
620 }
621
622 }
623
624
625 /**
626 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
627 *
628 * Child classes must grant that state depending on the {@link Account} is updated.
629 */
630 protected void onAccountSet(boolean stateWasRecovered) {
631 if (getAccount() != null) {
632 mStorageManager = new FileDataStorageManager(getAccount(), getContentResolver());
633
634 } else {
635 Log_OC.wtf(TAG, "onAccountChanged was called with NULL account associated!");
636 }
637 }
638
639
640 public FileDataStorageManager getStorageManager() {
641 return mStorageManager;
642 }
643
644
645 public OnRemoteOperationListener getRemoteOperationListener() {
646 return this;
647 }
648
649
650 public Handler getHandler() {
651 return mHandler;
652 }
653
654 public FileOperationsHelper getFileOperationsHelper() {
655 return mFileOperationsHelper;
656 }
657
658 /**
659 *
660 * @param operation Removal operation performed.
661 * @param result Result of the removal.
662 */
663 @Override
664 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
665 Log_OC.d(TAG, "Received result of operation in FileActivity - common behaviour for all the "
666 + "FileActivities ");
667
668 mFileOperationsHelper.setOpIdWaitingFor(Long.MAX_VALUE);
669
670 if (!result.isSuccess() && (
671 result.getCode() == ResultCode.UNAUTHORIZED ||
672 result.isIdPRedirection() ||
673 (result.isException() && result.getException() instanceof AuthenticatorException)
674 )) {
675
676 requestCredentialsUpdate();
677
678 if (result.getCode() == ResultCode.UNAUTHORIZED) {
679 dismissLoadingDialog();
680 Toast t = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result,
681 operation, getResources()),
682 Toast.LENGTH_LONG);
683 t.show();
684 }
685 mTryShareAgain = false;
686
687 } else if (operation instanceof CreateShareOperation) {
688 onCreateShareOperationFinish((CreateShareOperation) operation, result);
689
690 } else if (operation instanceof UnshareLinkOperation) {
691 onUnshareLinkOperationFinish((UnshareLinkOperation)operation, result);
692
693 } else if (operation instanceof SynchronizeFolderOperation) {
694 onSynchronizeFolderOperationFinish((SynchronizeFolderOperation)operation, result);
695
696 }
697 }
698
699 protected void requestCredentialsUpdate() {
700 Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
701 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, getAccount());
702 updateAccountCredentials.putExtra(
703 AuthenticatorActivity.EXTRA_ACTION,
704 AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
705 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
706 startActivity(updateAccountCredentials);
707 }
708
709
710 private void onCreateShareOperationFinish(CreateShareOperation operation,
711 RemoteOperationResult result) {
712 dismissLoadingDialog();
713 if (result.isSuccess()) {
714 mTryShareAgain = false;
715 updateFileFromDB();
716
717 Intent sendIntent = operation.getSendIntent();
718 startActivity(sendIntent);
719 } else {
720 // Detect Failure (403) --> needs Password
721 if (result.getCode() == ResultCode.SHARE_FORBIDDEN) {
722 if (!isTryShareAgain()) {
723 SharePasswordDialogFragment dialog =
724 SharePasswordDialogFragment.newInstance(new OCFile(operation.getPath()),
725 operation.getSendIntent());
726 dialog.show(getSupportFragmentManager(), DIALOG_SHARE_PASSWORD);
727 } else {
728 Toast t = Toast.makeText(this,
729 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
730 Toast.LENGTH_LONG);
731 t.show();
732 mTryShareAgain = false;
733 }
734 } else {
735 Toast t = Toast.makeText(this,
736 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
737 Toast.LENGTH_LONG);
738 t.show();
739 }
740 }
741 }
742
743
744 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation,
745 RemoteOperationResult result) {
746 dismissLoadingDialog();
747
748 if (result.isSuccess()){
749 updateFileFromDB();
750
751 } else {
752 Toast t = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result,
753 operation, getResources()), Toast.LENGTH_LONG);
754 t.show();
755 }
756 }
757
758 private void onSynchronizeFolderOperationFinish(
759 SynchronizeFolderOperation operation, RemoteOperationResult result
760 ) {
761 if (!result.isSuccess() && result.getCode() != ResultCode.CANCELLED){
762 Toast t = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result,
763 operation, getResources()), Toast.LENGTH_LONG);
764 t.show();
765 }
766 }
767
768 protected void updateFileFromDB(){
769 OCFile file = getFile();
770 if (file != null) {
771 file = getStorageManager().getFileByPath(file.getRemotePath());
772 setFile(file);
773 }
774 }
775
776 /**
777 * Show loading dialog
778 */
779 public void showLoadingDialog() {
780 // Construct dialog
781 LoadingDialog loading = new LoadingDialog(getResources().getString(R.string.wait_a_moment));
782 FragmentManager fm = getSupportFragmentManager();
783 FragmentTransaction ft = fm.beginTransaction();
784 loading.show(ft, DIALOG_WAIT_TAG);
785
786 }
787
788
789 /**
790 * Dismiss loading dialog
791 */
792 public void dismissLoadingDialog(){
793 Fragment frag = getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG);
794 if (frag != null) {
795 LoadingDialog loading = (LoadingDialog) frag;
796 loading.dismiss();
797 }
798 }
799
800
801 private void doOnResumeAndBound() {
802 mOperationsServiceBinder.addOperationListener(FileActivity.this, mHandler);
803 long waitingForOpId = mFileOperationsHelper.getOpIdWaitingFor();
804 if (waitingForOpId <= Integer.MAX_VALUE) {
805 boolean wait = mOperationsServiceBinder.dispatchResultIfFinished((int)waitingForOpId,
806 this);
807 if (!wait ) {
808 dismissLoadingDialog();
809 }
810 }
811 }
812
813
814 /**
815 * Implements callback methods for service binding. Passed as a parameter to {
816 */
817 private class OperationsServiceConnection implements ServiceConnection {
818
819 @Override
820 public void onServiceConnected(ComponentName component, IBinder service) {
821 if (component.equals(new ComponentName(FileActivity.this, OperationsService.class))) {
822 Log_OC.d(TAG, "Operations service connected");
823 mOperationsServiceBinder = (OperationsServiceBinder) service;
824 /*if (!mOperationsServiceBinder.isPerformingBlockingOperation()) {
825 dismissLoadingDialog();
826 }*/
827 doOnResumeAndBound();
828
829 } else {
830 return;
831 }
832 }
833
834
835 @Override
836 public void onServiceDisconnected(ComponentName component) {
837 if (component.equals(new ComponentName(FileActivity.this, OperationsService.class))) {
838 Log_OC.d(TAG, "Operations service disconnected");
839 mOperationsServiceBinder = null;
840 // TODO whatever could be waiting for the service is unbound
841 }
842 }
843 }
844
845
846 @Override
847 public FileDownloaderBinder getFileDownloaderBinder() {
848 return mDownloaderBinder;
849 }
850
851
852 @Override
853 public FileUploaderBinder getFileUploaderBinder() {
854 return mUploaderBinder;
855 }
856
857
858 public void restart(){
859 Intent i = new Intent(this, FileDisplayActivity.class);
860 i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
861 startActivity(i);
862 }
863
864 // TODO re-enable when "Accounts" is available in Navigation Drawer
865 // public void closeDrawer() {
866 // mDrawerLayout.closeDrawers();
867 // }
868
869 public void allFilesOption(){
870 restart();
871 }
872
873 private class DrawerItemClickListener implements ListView.OnItemClickListener {
874 @Override
875 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
876 // TODO re-enable when "Accounts" is available in Navigation Drawer
877 // if (mShowAccounts && position > 0){
878 // position = position - 1;
879 // }
880 switch (position){
881 // TODO re-enable when "Accounts" is available in Navigation Drawer
882 // case 0: // Accounts
883 // mShowAccounts = !mShowAccounts;
884 // mNavigationDrawerAdapter.setShowAccounts(mShowAccounts);
885 // mNavigationDrawerAdapter.notifyDataSetChanged();
886 // break;
887
888 case 0: // All Files
889 allFilesOption();
890 mDrawerLayout.closeDrawers();
891 break;
892
893 // TODO Enable when "On Device" is recovered ?
894 // case 2:
895 // MainApp.showOnlyFilesOnDevice(true);
896 // mDrawerLayout.closeDrawers();
897 // break;
898
899 case 1: // Settings
900 Intent settingsIntent = new Intent(getApplicationContext(),
901 Preferences.class);
902 startActivity(settingsIntent);
903 mDrawerLayout.closeDrawers();
904 break;
905
906 case 2: // Logs
907 Intent loggerIntent = new Intent(getApplicationContext(),
908 LogHistoryActivity.class);
909 startActivity(loggerIntent);
910 mDrawerLayout.closeDrawers();
911 break;
912 }
913 }
914 }
915 }