Add code to handle ownCloud servers running on IDN
[pub/Android/ownCloud.git] / src / com / owncloud / android / authentication / AuthenticatorActivity.java
index ee9d9bc..9569a53 100644 (file)
@@ -43,7 +43,6 @@ import android.support.v4.app.FragmentTransaction;
 import android.text.Editable;\r
 import android.text.InputType;\r
 import android.text.TextWatcher;\r
 import android.text.Editable;\r
 import android.text.InputType;\r
 import android.text.TextWatcher;\r
-import android.util.Log;\r
 import android.view.KeyEvent;\r
 import android.view.MotionEvent;\r
 import android.view.View;\r
 import android.view.KeyEvent;\r
 import android.view.MotionEvent;\r
 import android.view.View;\r
@@ -51,7 +50,9 @@ import android.view.View.OnFocusChangeListener;
 import android.view.View.OnTouchListener;\r
 import android.view.Window;\r
 import android.view.inputmethod.EditorInfo;\r
 import android.view.View.OnTouchListener;\r
 import android.view.Window;\r
 import android.view.inputmethod.EditorInfo;\r
+import android.webkit.HttpAuthHandler;\r
 import android.webkit.SslErrorHandler;\r
 import android.webkit.SslErrorHandler;\r
+import android.webkit.WebView;\r
 import android.widget.Button;\r
 import android.widget.CheckBox;\r
 import android.widget.EditText;\r
 import android.widget.Button;\r
 import android.widget.CheckBox;\r
 import android.widget.EditText;\r
@@ -65,26 +66,26 @@ import com.owncloud.android.R;
 import com.owncloud.android.authentication.SsoWebViewClient.SsoWebViewClientListener;\r
 import com.owncloud.android.lib.common.accounts.AccountTypeUtils;\r
 import com.owncloud.android.lib.common.accounts.AccountUtils.Constants;\r
 import com.owncloud.android.authentication.SsoWebViewClient.SsoWebViewClientListener;\r
 import com.owncloud.android.lib.common.accounts.AccountTypeUtils;\r
 import com.owncloud.android.lib.common.accounts.AccountUtils.Constants;\r
-import com.owncloud.android.operations.DetectAuthenticationMethodOperation.AuthenticationMethod;\r
-import com.owncloud.android.operations.GetServerInfoOperation;\r
-import com.owncloud.android.operations.OAuth2GetAccessToken;\r
-
 import com.owncloud.android.lib.common.network.CertificateCombinedException;\r
 import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;\r
 import com.owncloud.android.lib.common.operations.RemoteOperation;\r
 import com.owncloud.android.lib.common.operations.RemoteOperationResult;\r
 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;\r
 import com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation;\r
 import com.owncloud.android.lib.common.network.CertificateCombinedException;\r
 import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;\r
 import com.owncloud.android.lib.common.operations.RemoteOperation;\r
 import com.owncloud.android.lib.common.operations.RemoteOperationResult;\r
 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;\r
 import com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation;\r
+import com.owncloud.android.lib.resources.status.OwnCloudVersion;\r
 import com.owncloud.android.lib.resources.users.GetRemoteUserNameOperation;\r
 import com.owncloud.android.lib.resources.users.GetRemoteUserNameOperation;\r
-\r
+import com.owncloud.android.operations.DetectAuthenticationMethodOperation.AuthenticationMethod;\r
+import com.owncloud.android.operations.GetServerInfoOperation;\r
+import com.owncloud.android.operations.OAuth2GetAccessToken;\r
 import com.owncloud.android.services.OperationsService;\r
 import com.owncloud.android.services.OperationsService.OperationsServiceBinder;\r
 import com.owncloud.android.services.OperationsService;\r
 import com.owncloud.android.services.OperationsService.OperationsServiceBinder;\r
+import com.owncloud.android.ui.dialog.CredentialsDialogFragment;\r
 import com.owncloud.android.ui.dialog.IndeterminateProgressDialog;\r
 import com.owncloud.android.ui.dialog.SamlWebViewDialog;\r
 import com.owncloud.android.ui.dialog.SslUntrustedCertDialog;\r
 import com.owncloud.android.ui.dialog.SslUntrustedCertDialog.OnSslUntrustedCertListener;\r
 import com.owncloud.android.ui.dialog.IndeterminateProgressDialog;\r
 import com.owncloud.android.ui.dialog.SamlWebViewDialog;\r
 import com.owncloud.android.ui.dialog.SslUntrustedCertDialog;\r
 import com.owncloud.android.ui.dialog.SslUntrustedCertDialog.OnSslUntrustedCertListener;\r
+import com.owncloud.android.utils.DisplayUtils;\r
 import com.owncloud.android.utils.Log_OC;\r
 import com.owncloud.android.utils.Log_OC;\r
-import com.owncloud.android.lib.resources.status.OwnCloudVersion;\r
 \r
 /**\r
  * This Activity is used to add an ownCloud account to the App\r
 \r
 /**\r
  * This Activity is used to add an ownCloud account to the App\r
@@ -115,7 +116,7 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
     private static final String KEY_AUTH_STATUS_TEXT = "AUTH_STATUS_TEXT";\r
     private static final String KEY_AUTH_STATUS_ICON = "AUTH_STATUS_ICON";\r
     private static final String KEY_SERVER_AUTH_METHOD = "SERVER_AUTH_METHOD";\r
     private static final String KEY_AUTH_STATUS_TEXT = "AUTH_STATUS_TEXT";\r
     private static final String KEY_AUTH_STATUS_ICON = "AUTH_STATUS_ICON";\r
     private static final String KEY_SERVER_AUTH_METHOD = "SERVER_AUTH_METHOD";\r
-    private static final String KEY_WAITING_FOR_OP_ID = "DETECT_AUTH_OP_ID";\r
+    private static final String KEY_WAITING_FOR_OP_ID = "WAITING_FOR_OP_ID";\r
     private static final String KEY_AUTH_TOKEN = "AUTH_TOKEN";\r
 \r
     private static final String AUTH_ON = "on";\r
     private static final String KEY_AUTH_TOKEN = "AUTH_TOKEN";\r
 \r
     private static final String AUTH_ON = "on";\r
@@ -128,6 +129,8 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
     private static final String UNTRUSTED_CERT_DIALOG_TAG = "UNTRUSTED_CERT_DIALOG";\r
     private static final String SAML_DIALOG_TAG = "SAML_DIALOG";\r
     private static final String WAIT_DIALOG_TAG = "WAIT_DIALOG";\r
     private static final String UNTRUSTED_CERT_DIALOG_TAG = "UNTRUSTED_CERT_DIALOG";\r
     private static final String SAML_DIALOG_TAG = "SAML_DIALOG";\r
     private static final String WAIT_DIALOG_TAG = "WAIT_DIALOG";\r
+    private static final String CREDENTIALS_DIALOG_TAG = "CREDENTIALS_DIALOG";\r
+    private static final String KEY_AUTH_IS_FIRST_ATTEMPT_TAG = "KEY_AUTH_IS_FIRST_ATTEMPT";\r
 \r
     \r
     /// parameters from EXTRAs in starter Intent\r
 \r
     \r
     /// parameters from EXTRAs in starter Intent\r
@@ -154,6 +157,7 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
     \r
     private boolean mServerIsChecked = false;\r
     private boolean mServerIsValid = false;\r
     \r
     private boolean mServerIsChecked = false;\r
     private boolean mServerIsValid = false;\r
+    private boolean mPendingAutoCheck = false;\r
 \r
     private GetServerInfoOperation.ServerInfo mServerInfo = \r
             new GetServerInfoOperation.ServerInfo();\r
 \r
     private GetServerInfoOperation.ServerInfo mServerInfo = \r
             new GetServerInfoOperation.ServerInfo();\r
@@ -172,10 +176,12 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
     \r
     private String mAuthToken = "";\r
 \r
     \r
     private String mAuthToken = "";\r
 \r
+    private boolean mIsFirstAuthAttempt;\r
+\r
     \r
     /// Identifier of operation in progress which result shouldn't be lost \r
     \r
     /// Identifier of operation in progress which result shouldn't be lost \r
-    private int mWaitingForOpId = -1;\r
-    \r
+    private long mWaitingForOpId = Long.MAX_VALUE;\r
+\r
     \r
     /**\r
      * {@inheritDoc}\r
     \r
     /**\r
      * {@inheritDoc}\r
@@ -184,10 +190,12 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
      */\r
     @Override\r
     protected void onCreate(Bundle savedInstanceState) {\r
      */\r
     @Override\r
     protected void onCreate(Bundle savedInstanceState) {\r
-        Log_OC.wtf(TAG,  "onCreate init");\r
+        //Log_OC.wtf(TAG,  "onCreate init");\r
         super.onCreate(savedInstanceState);\r
         getWindow().requestFeature(Window.FEATURE_NO_TITLE);\r
 \r
         super.onCreate(savedInstanceState);\r
         getWindow().requestFeature(Window.FEATURE_NO_TITLE);\r
 \r
+        mIsFirstAuthAttempt = true;\r
+\r
         // bind to Operations Service\r
         mOperationsServiceConnection = new OperationsServiceConnection();\r
         if (!bindService(new Intent(this, OperationsService.class), \r
         // bind to Operations Service\r
         mOperationsServiceConnection = new OperationsServiceConnection();\r
         if (!bindService(new Intent(this, OperationsService.class), \r
@@ -211,7 +219,8 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
             initAuthTokenType();\r
         } else {\r
             mAuthTokenType = savedInstanceState.getString(KEY_AUTH_TOKEN_TYPE);\r
             initAuthTokenType();\r
         } else {\r
             mAuthTokenType = savedInstanceState.getString(KEY_AUTH_TOKEN_TYPE);\r
-            mWaitingForOpId = savedInstanceState.getInt(KEY_WAITING_FOR_OP_ID);\r
+            mWaitingForOpId = savedInstanceState.getLong(KEY_WAITING_FOR_OP_ID);\r
+            mIsFirstAuthAttempt = savedInstanceState.getBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG);\r
         }\r
         \r
         /// load user interface\r
         }\r
         \r
         /// load user interface\r
@@ -220,13 +229,15 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
         /// initialize general UI elements\r
         initOverallUi(savedInstanceState);\r
         \r
         /// initialize general UI elements\r
         initOverallUi(savedInstanceState);\r
         \r
+        mOkButton = findViewById(R.id.buttonOK);\r
+\r
         /// initialize block to be moved to single Fragment to check server and get info about it \r
         initServerPreFragment(savedInstanceState);\r
         \r
         /// initialize block to be moved to single Fragment to retrieve and validate credentials \r
         initAuthorizationPreFragment(savedInstanceState);\r
 \r
         /// initialize block to be moved to single Fragment to check server and get info about it \r
         initServerPreFragment(savedInstanceState);\r
         \r
         /// initialize block to be moved to single Fragment to retrieve and validate credentials \r
         initAuthorizationPreFragment(savedInstanceState);\r
 \r
-        Log_OC.wtf(TAG,  "onCreate end");\r
+        //Log_OC.wtf(TAG,  "onCreate end");\r
     }\r
 \r
     private void initAuthTokenType() {\r
     }\r
 \r
     private void initAuthTokenType() {\r
@@ -308,7 +319,6 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
 \r
         /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)\r
         boolean isUrlInputAllowed = getResources().getBoolean(R.bool.show_server_url_input); \r
 \r
         /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)\r
         boolean isUrlInputAllowed = getResources().getBoolean(R.bool.show_server_url_input); \r
-        //boolean refreshButtonEnabled = false;\r
         if (savedInstanceState == null) {\r
             if (mAccount != null) {\r
                 mServerInfo.mBaseUrl = mAccountMgr.getUserData(mAccount, Constants.KEY_OC_BASE_URL);\r
         if (savedInstanceState == null) {\r
             if (mAccount != null) {\r
                 mServerInfo.mBaseUrl = mAccountMgr.getUserData(mAccount, Constants.KEY_OC_BASE_URL);\r
@@ -322,7 +332,6 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
                 mServerInfo.mIsSslConn = mServerInfo.mBaseUrl.startsWith("https://");\r
             }\r
         } else {\r
                 mServerInfo.mIsSslConn = mServerInfo.mBaseUrl.startsWith("https://");\r
             }\r
         } else {\r
-            //refreshButtonEnabled = savedInstanceState.getBoolean(KEY_REFRESH_BUTTON_ENABLED);\r
             mServerStatusText = savedInstanceState.getInt(KEY_SERVER_STATUS_TEXT);\r
             mServerStatusIcon = savedInstanceState.getInt(KEY_SERVER_STATUS_ICON);\r
             \r
             mServerStatusText = savedInstanceState.getInt(KEY_SERVER_STATUS_TEXT);\r
             mServerStatusIcon = savedInstanceState.getInt(KEY_SERVER_STATUS_ICON);\r
             \r
@@ -343,7 +352,8 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
         \r
         /// step 2 - set properties of UI elements (text, visibility, enabled...)\r
         mHostUrlInput = (EditText) findViewById(R.id.hostUrlInput);\r
         \r
         /// step 2 - set properties of UI elements (text, visibility, enabled...)\r
         mHostUrlInput = (EditText) findViewById(R.id.hostUrlInput);\r
-        mHostUrlInput.setText(mServerInfo.mBaseUrl);\r
+        // Convert IDN to Unicode\r
+        mHostUrlInput.setText(DisplayUtils.convertIdn(mServerInfo.mBaseUrl, false));\r
         if (mAction != ACTION_CREATE) {\r
             /// lock things that should not change\r
             mHostUrlInput.setEnabled(false);\r
         if (mAction != ACTION_CREATE) {\r
             /// lock things that should not change\r
             mHostUrlInput.setEnabled(false);\r
@@ -355,7 +365,8 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
             findViewById(R.id.hostUrlFrame).setVisibility(View.GONE);\r
             mRefreshButton = findViewById(R.id.centeredRefreshButton);\r
         }\r
             findViewById(R.id.hostUrlFrame).setVisibility(View.GONE);\r
             mRefreshButton = findViewById(R.id.centeredRefreshButton);\r
         }\r
-        showRefreshButton(mServerIsChecked && !mServerIsValid && mWaitingForOpId == -1);\r
+        showRefreshButton(mServerIsChecked && !mServerIsValid && \r
+                mWaitingForOpId > Integer.MAX_VALUE);\r
         mServerStatusView = (TextView) findViewById(R.id.server_status_text);\r
         showServerStatus();\r
         \r
         mServerStatusView = (TextView) findViewById(R.id.server_status_text);\r
         showServerStatus();\r
         \r
@@ -406,12 +417,9 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
         });\r
      \r
         \r
         });\r
      \r
         \r
-        /// step 4 - automatic actions to start\r
-        if (savedInstanceState == null) {\r
-            if (mAction != ACTION_CREATE || !isUrlInputAllowed) {\r
-                checkOcServer(); \r
-            }\r
-        }\r
+        /// step 4 - mark automatic check to be started when OperationsService is ready\r
+        mPendingAutoCheck = (savedInstanceState == null && \r
+                (mAction != ACTION_CREATE || !isUrlInputAllowed));\r
     }\r
     \r
     \r
     }\r
     \r
     \r
@@ -428,7 +436,6 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
         mUsernameInput = (EditText) findViewById(R.id.account_username);\r
         mPasswordInput = (EditText) findViewById(R.id.account_password);\r
         mAuthStatusView = (TextView) findViewById(R.id.auth_status_text); \r
         mUsernameInput = (EditText) findViewById(R.id.account_username);\r
         mPasswordInput = (EditText) findViewById(R.id.account_password);\r
         mAuthStatusView = (TextView) findViewById(R.id.auth_status_text); \r
-        mOkButton = findViewById(R.id.buttonOK);\r
         \r
         /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)\r
         String presetUserName = null;\r
         \r
         /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)\r
         String presetUserName = null;\r
@@ -536,12 +543,12 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
      */\r
     @Override\r
     protected void onSaveInstanceState(Bundle outState) {\r
      */\r
     @Override\r
     protected void onSaveInstanceState(Bundle outState) {\r
-        Log.wtf(TAG, "onSaveInstanceState init" );\r
+        //Log_OC.wtf(TAG, "onSaveInstanceState init" );\r
         super.onSaveInstanceState(outState);\r
 \r
         /// global state\r
         outState.putString(KEY_AUTH_TOKEN_TYPE, mAuthTokenType);\r
         super.onSaveInstanceState(outState);\r
 \r
         /// global state\r
         outState.putString(KEY_AUTH_TOKEN_TYPE, mAuthTokenType);\r
-        outState.putInt(KEY_WAITING_FOR_OP_ID, mWaitingForOpId);\r
+        outState.putLong(KEY_WAITING_FOR_OP_ID, mWaitingForOpId);\r
 \r
         /// Server PRE-fragment state\r
         outState.putInt(KEY_SERVER_STATUS_TEXT, mServerStatusText);\r
 \r
         /// Server PRE-fragment state\r
         outState.putInt(KEY_SERVER_STATUS_TEXT, mServerStatusText);\r
@@ -561,7 +568,10 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
         outState.putInt(KEY_AUTH_STATUS_TEXT, mAuthStatusText);\r
         outState.putString(KEY_AUTH_TOKEN, mAuthToken);\r
 \r
         outState.putInt(KEY_AUTH_STATUS_TEXT, mAuthStatusText);\r
         outState.putString(KEY_AUTH_TOKEN, mAuthToken);\r
 \r
-        Log.wtf(TAG, "onSaveInstanceState end" );\r
+        /// authentication\r
+        outState.putBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG, mIsFirstAuthAttempt);\r
+\r
+        //Log_OC.wtf(TAG, "onSaveInstanceState end" );\r
     }\r
 \r
 \r
     }\r
 \r
 \r
@@ -588,7 +598,7 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
      */\r
     @Override\r
     protected void onResume() {\r
      */\r
     @Override\r
     protected void onResume() {\r
-        Log_OC.wtf(TAG, "onResume init" );\r
+        //Log_OC.wtf(TAG, "onResume init" );\r
         super.onResume();\r
         \r
         // bound here to avoid spurious changes triggered by Android on device rotations\r
         super.onResume();\r
         \r
         // bound here to avoid spurious changes triggered by Android on device rotations\r
@@ -603,15 +613,15 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
             doOnResumeAndBound();\r
         }\r
         \r
             doOnResumeAndBound();\r
         }\r
         \r
-        Log_OC.wtf(TAG, "onResume end" );\r
+        //Log_OC.wtf(TAG, "onResume end" );\r
     }\r
 \r
     \r
     @Override\r
     protected void onPause() {\r
     }\r
 \r
     \r
     @Override\r
     protected void onPause() {\r
-        Log.wtf(TAG, "onPause init" );\r
+        //Log_OC.wtf(TAG, "onPause init" );\r
         if (mOperationsServiceBinder != null) {\r
         if (mOperationsServiceBinder != null) {\r
-            Log.wtf(TAG, "unregistering to listen for operation callbacks" );\r
+            //Log_OC.wtf(TAG, "unregistering to listen for operation callbacks" );\r
             mOperationsServiceBinder.removeOperationListener(this);\r
         }\r
         \r
             mOperationsServiceBinder.removeOperationListener(this);\r
         }\r
         \r
@@ -619,7 +629,7 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
         mHostUrlInput.setOnFocusChangeListener(null);\r
         \r
         super.onPause();\r
         mHostUrlInput.setOnFocusChangeListener(null);\r
         \r
         super.onPause();\r
-        Log.wtf(TAG, "onPause end" );\r
+        //Log_OC.wtf(TAG, "onPause end" );\r
     }\r
     \r
     @Override\r
     }\r
     \r
     @Override\r
@@ -719,6 +729,8 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
         showRefreshButton(false);\r
         \r
         if (uri.length() != 0) {\r
         showRefreshButton(false);\r
         \r
         if (uri.length() != 0) {\r
+            // Handle internationalized domain names\r
+            uri = DisplayUtils.convertIdn(uri, true);\r
             mServerStatusText = R.string.auth_testing_connection;\r
             mServerStatusIcon = R.drawable.progress_small;\r
             showServerStatus();\r
             mServerStatusText = R.string.auth_testing_connection;\r
             mServerStatusIcon = R.drawable.progress_small;\r
             showServerStatus();\r
@@ -726,10 +738,10 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
             Intent getServerInfoIntent = new Intent();\r
             getServerInfoIntent.setAction(OperationsService.ACTION_GET_SERVER_INFO);\r
             getServerInfoIntent.putExtra(OperationsService.EXTRA_SERVER_URL, uri);\r
             Intent getServerInfoIntent = new Intent();\r
             getServerInfoIntent.setAction(OperationsService.ACTION_GET_SERVER_INFO);\r
             getServerInfoIntent.putExtra(OperationsService.EXTRA_SERVER_URL, uri);\r
-            getServerInfoIntent.putExtra(OperationsService.EXTRA_AUTH_TOKEN_TYPE, mAuthTokenType);\r
             if (mOperationsServiceBinder != null) {\r
             if (mOperationsServiceBinder != null) {\r
-                //Log_OC.wtf(TAG, "checking server..." );\r
                 mWaitingForOpId = mOperationsServiceBinder.newOperation(getServerInfoIntent);\r
                 mWaitingForOpId = mOperationsServiceBinder.newOperation(getServerInfoIntent);\r
+            } else {\r
+              Log_OC.wtf(TAG, "Server check tried with OperationService unbound!" );\r
             }\r
             \r
         } else {\r
             }\r
             \r
         } else {\r
@@ -761,10 +773,8 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
 \r
 \r
     private void showViewPasswordButton() {\r
 \r
 \r
     private void showViewPasswordButton() {\r
-        //int drawable = android.R.drawable.ic_menu_view;\r
         int drawable = R.drawable.ic_view;\r
         if (isPasswordVisible()) {\r
         int drawable = R.drawable.ic_view;\r
         if (isPasswordVisible()) {\r
-            //drawable = android.R.drawable.ic_secure;\r
             drawable = R.drawable.ic_hide;\r
         }\r
         mPasswordInput.setCompoundDrawablesWithIntrinsicBounds(0, 0, drawable, 0);\r
             drawable = R.drawable.ic_hide;\r
         }\r
         mPasswordInput.setCompoundDrawablesWithIntrinsicBounds(0, 0, drawable, 0);\r
@@ -812,7 +822,7 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
             mServerStatusText = R.string.auth_wtf_reenter_URL;\r
             showServerStatus();\r
             mOkButton.setEnabled(false);\r
             mServerStatusText = R.string.auth_wtf_reenter_URL;\r
             showServerStatus();\r
             mOkButton.setEnabled(false);\r
-            Log_OC.wtf(TAG,  "The user was allowed to click 'connect' to an unchecked server!!");\r
+            //Log_OC.wtf(TAG,  "The user was allowed to click 'connect' to an unchecked server!!");\r
             return;\r
         }\r
 \r
             return;\r
         }\r
 \r
@@ -831,9 +841,6 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
      * the root folder of the ownCloud server.\r
      */\r
     private void checkBasicAuthorization() {\r
      * the root folder of the ownCloud server.\r
      */\r
     private void checkBasicAuthorization() {\r
-        /// get the path to the root folder through WebDAV from the version server\r
-        String webdav_path = AccountUtils.getWebdavPath(mServerInfo.mVersion, mAuthTokenType);\r
-\r
         /// get basic credentials entered by user\r
         String username = mUsernameInput.getText().toString();\r
         String password = mPasswordInput.getText().toString();\r
         /// get basic credentials entered by user\r
         String username = mUsernameInput.getText().toString();\r
         String password = mPasswordInput.getText().toString();\r
@@ -843,29 +850,22 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
                 IndeterminateProgressDialog.newInstance(R.string.auth_trying_to_login, true);\r
         dialog.show(getSupportFragmentManager(), WAIT_DIALOG_TAG);\r
 \r
                 IndeterminateProgressDialog.newInstance(R.string.auth_trying_to_login, true);\r
         dialog.show(getSupportFragmentManager(), WAIT_DIALOG_TAG);\r
 \r
-        /// test credentials accessing the root folder\r
-        String remotePath ="";\r
-        boolean successIfAbsent = false;\r
-        boolean followRedirects = true;\r
-        startExistenceCheckRemoteOperation(remotePath, this, successIfAbsent, webdav_path, username, password, followRedirects);\r
+        /// validate credentials accessing the root folder\r
+        accessRootFolderRemoteOperation(username, password);\r
         \r
     }\r
 \r
         \r
     }\r
 \r
-    private void startExistenceCheckRemoteOperation(String remotePath, Context context, boolean successIfAbsent, String webdav_path,\r
-            String username, String password, boolean followRedirects) {\r
+    private void accessRootFolderRemoteOperation(String username, String password) {\r
         Intent existenceCheckIntent = new Intent();\r
         existenceCheckIntent.setAction(OperationsService.ACTION_EXISTENCE_CHECK);\r
         existenceCheckIntent.putExtra(OperationsService.EXTRA_SERVER_URL, mServerInfo.mBaseUrl);\r
         Intent existenceCheckIntent = new Intent();\r
         existenceCheckIntent.setAction(OperationsService.ACTION_EXISTENCE_CHECK);\r
         existenceCheckIntent.putExtra(OperationsService.EXTRA_SERVER_URL, mServerInfo.mBaseUrl);\r
-        existenceCheckIntent.putExtra(OperationsService.EXTRA_REMOTE_PATH, remotePath);\r
-        existenceCheckIntent.putExtra(OperationsService.EXTRA_SUCCESS_IF_ABSENT, successIfAbsent);\r
-        existenceCheckIntent.putExtra(OperationsService.EXTRA_WEBDAV_PATH, webdav_path);\r
+        existenceCheckIntent.putExtra(OperationsService.EXTRA_REMOTE_PATH, "/");\r
         existenceCheckIntent.putExtra(OperationsService.EXTRA_USERNAME, username);\r
         existenceCheckIntent.putExtra(OperationsService.EXTRA_PASSWORD, password);\r
         existenceCheckIntent.putExtra(OperationsService.EXTRA_AUTH_TOKEN, mAuthToken);\r
         existenceCheckIntent.putExtra(OperationsService.EXTRA_USERNAME, username);\r
         existenceCheckIntent.putExtra(OperationsService.EXTRA_PASSWORD, password);\r
         existenceCheckIntent.putExtra(OperationsService.EXTRA_AUTH_TOKEN, mAuthToken);\r
-        existenceCheckIntent.putExtra(OperationsService.EXTRA_FOLLOW_REDIRECTS, followRedirects);\r
         \r
         if (mOperationsServiceBinder != null) {\r
         \r
         if (mOperationsServiceBinder != null) {\r
-            Log_OC.wtf(TAG, "starting existenceCheckRemoteOperation..." );\r
+            //Log_OC.wtf(TAG, "starting existenceCheckRemoteOperation..." );\r
             mWaitingForOpId = mOperationsServiceBinder.newOperation(existenceCheckIntent);\r
         }\r
     }\r
             mWaitingForOpId = mOperationsServiceBinder.newOperation(existenceCheckIntent);\r
         }\r
     }\r
@@ -881,14 +881,12 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
         showAuthStatus();\r
 \r
         // GET AUTHORIZATION request\r
         showAuthStatus();\r
 \r
         // GET AUTHORIZATION request\r
-        //Uri uri = Uri.parse(getString(R.string.oauth2_url_endpoint_auth));\r
         Uri uri = Uri.parse(mOAuthAuthEndpointText.getText().toString().trim());\r
         Uri.Builder uriBuilder = uri.buildUpon();\r
         uriBuilder.appendQueryParameter(OAuth2Constants.KEY_RESPONSE_TYPE, getString(R.string.oauth2_response_type));\r
         uriBuilder.appendQueryParameter(OAuth2Constants.KEY_REDIRECT_URI, getString(R.string.oauth2_redirect_uri));   \r
         uriBuilder.appendQueryParameter(OAuth2Constants.KEY_CLIENT_ID, getString(R.string.oauth2_client_id));\r
         uriBuilder.appendQueryParameter(OAuth2Constants.KEY_SCOPE, getString(R.string.oauth2_scope));\r
         Uri uri = Uri.parse(mOAuthAuthEndpointText.getText().toString().trim());\r
         Uri.Builder uriBuilder = uri.buildUpon();\r
         uriBuilder.appendQueryParameter(OAuth2Constants.KEY_RESPONSE_TYPE, getString(R.string.oauth2_response_type));\r
         uriBuilder.appendQueryParameter(OAuth2Constants.KEY_REDIRECT_URI, getString(R.string.oauth2_redirect_uri));   \r
         uriBuilder.appendQueryParameter(OAuth2Constants.KEY_CLIENT_ID, getString(R.string.oauth2_client_id));\r
         uriBuilder.appendQueryParameter(OAuth2Constants.KEY_SCOPE, getString(R.string.oauth2_scope));\r
-        //uriBuilder.appendQueryParameter(OAuth2Constants.KEY_STATE, whateverwewant);\r
         uri = uriBuilder.build();\r
         Log_OC.d(TAG, "Starting browser to view " + uri.toString());\r
         Intent i = new Intent(Intent.ACTION_VIEW, uri);\r
         uri = uriBuilder.build();\r
         Log_OC.d(TAG, "Starting browser to view " + uri.toString());\r
         Intent i = new Intent(Intent.ACTION_VIEW, uri);\r
@@ -909,14 +907,8 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
                 IndeterminateProgressDialog.newInstance(R.string.auth_trying_to_login, true);\r
         dialog.show(getSupportFragmentManager(), WAIT_DIALOG_TAG);\r
 \r
                 IndeterminateProgressDialog.newInstance(R.string.auth_trying_to_login, true);\r
         dialog.show(getSupportFragmentManager(), WAIT_DIALOG_TAG);\r
 \r
-        /// get the path to the root folder through WebDAV from the version server\r
-        String webdav_path = AccountUtils.getWebdavPath(mServerInfo.mVersion, mAuthTokenType);\r
-\r
-        /// test credentials accessing the root folder\r
-        String remotePath ="";\r
-        boolean successIfAbsent = false;\r
-        boolean followRedirections = false;\r
-        startExistenceCheckRemoteOperation(remotePath, this, successIfAbsent, webdav_path, "", "", followRedirections);\r
+        /// validate credentials accessing the root folder\r
+        accessRootFolderRemoteOperation("", "");\r
 \r
     }\r
 \r
 \r
     }\r
 \r
@@ -938,7 +930,7 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
             onGetOAuthAccessTokenFinish(result);\r
 \r
         } else if (operation instanceof ExistenceCheckRemoteOperation)  {\r
             onGetOAuthAccessTokenFinish(result);\r
 \r
         } else if (operation instanceof ExistenceCheckRemoteOperation)  {\r
-            Log_OC.wtf(TAG, "received detection response through callback" );\r
+            //Log_OC.wtf(TAG, "received detection response through callback" );\r
             if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType)) {\r
                 onSamlBasedFederatedSingleSignOnAuthorizationStart(result);\r
 \r
             if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType)) {\r
                 onSamlBasedFederatedSingleSignOnAuthorizationStart(result);\r
 \r
@@ -952,7 +944,7 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
     }\r
 \r
     private void onGetUserNameFinish(RemoteOperationResult result) {\r
     }\r
 \r
     private void onGetUserNameFinish(RemoteOperationResult result) {\r
-        mWaitingForOpId = -1;\r
+        mWaitingForOpId = Long.MAX_VALUE;\r
         if (result.isSuccess()) {\r
             boolean success = false;\r
             String username = (String) result.getData().get(0);\r
         if (result.isSuccess()) {\r
             boolean success = false;\r
             String username = (String) result.getData().get(0);\r
@@ -964,7 +956,15 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
 \r
                 if (!mUsernameInput.getText().toString().equals(username)) {\r
                     // fail - not a new account, but an existing one; disallow\r
 \r
                 if (!mUsernameInput.getText().toString().equals(username)) {\r
                     // fail - not a new account, but an existing one; disallow\r
-                    result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_THE_SAME); \r
+                    result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_THE_SAME);\r
+                    /*\r
+                    OwnCloudClientManagerFactory.getDefaultSingleton().removeClientFor(\r
+                            new OwnCloudAccount(\r
+                                    Uri.parse(mServerInfo.mBaseUrl),\r
+                                    OwnCloudCredentialsFactory.newSamlSsoCredentials(mAuthToken))\r
+                            );\r
+                            */\r
+                    mAuthToken = "";\r
                     updateAuthStatusIconAndText(result);\r
                     showAuthStatus();\r
                     Log_OC.d(TAG, result.getLogMessage());\r
                     updateAuthStatusIconAndText(result);\r
                     showAuthStatus();\r
                     Log_OC.d(TAG, result.getLogMessage());\r
@@ -985,10 +985,9 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
     }\r
 \r
     private void onSamlBasedFederatedSingleSignOnAuthorizationStart(RemoteOperationResult result) {\r
     }\r
 \r
     private void onSamlBasedFederatedSingleSignOnAuthorizationStart(RemoteOperationResult result) {\r
-        mWaitingForOpId = -1;\r
+        mWaitingForOpId = Long.MAX_VALUE;\r
         dismissDialog(WAIT_DIALOG_TAG);\r
 
         dismissDialog(WAIT_DIALOG_TAG);\r
 
-        //if (result.isTemporalRedirection() && result.isIdPRedirection()) {\r
         if (result.isIdPRedirection()) {
             String url = result.getRedirectedLocation();\r
             String targetUrl = mServerInfo.mBaseUrl \r
         if (result.isIdPRedirection()) {
             String url = result.getRedirectedLocation();\r
             String targetUrl = mServerInfo.mBaseUrl \r
@@ -1020,7 +1019,7 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
     private void onGetServerInfoFinish(RemoteOperationResult result) {\r
         /// update activity state\r
         mServerIsChecked = true;\r
     private void onGetServerInfoFinish(RemoteOperationResult result) {\r
         /// update activity state\r
         mServerIsChecked = true;\r
-        mWaitingForOpId = -1;\r
+        mWaitingForOpId = Long.MAX_VALUE;\r
         \r
         // update server status, but don't show it yet\r
         updateServerStatusIconAndText(result);\r
         \r
         // update server status, but don't show it yet\r
         updateServerStatusIconAndText(result);\r
@@ -1180,6 +1179,10 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
         case UNKNOWN_ERROR:\r
             mServerStatusText = R.string.auth_unknown_error_title;\r
             break;\r
         case UNKNOWN_ERROR:\r
             mServerStatusText = R.string.auth_unknown_error_title;\r
             break;\r
+        case OK_REDIRECT_TO_NON_SECURE_CONNECTION:\r
+            mServerStatusIcon = android.R.drawable.ic_partial_secure;\r
+            mServerStatusText = R.string.auth_redirect_non_secure_connection_title;\r
+            break;\r
         default:\r
             mServerStatusText = 0;\r
             mServerStatusIcon = 0;\r
         default:\r
             mServerStatusText = 0;\r
             mServerStatusIcon = 0;\r
@@ -1287,11 +1290,10 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
      * @param result        Result of the operation.\r
      */\r
     private void onGetOAuthAccessTokenFinish(RemoteOperationResult result) {\r
      * @param result        Result of the operation.\r
      */\r
     private void onGetOAuthAccessTokenFinish(RemoteOperationResult result) {\r
-        mWaitingForOpId = -1;\r
+        mWaitingForOpId = Long.MAX_VALUE;\r
         dismissDialog(WAIT_DIALOG_TAG);\r
 \r
         dismissDialog(WAIT_DIALOG_TAG);\r
 \r
-        String webdav_path = AccountUtils.getWebdavPath(mServerInfo.mVersion, mAuthTokenType);\r
-        if (result.isSuccess() && webdav_path != null) {\r
+        if (result.isSuccess()) {\r
             /// be gentle with the user\r
             IndeterminateProgressDialog dialog = \r
                     IndeterminateProgressDialog.newInstance(R.string.auth_trying_to_login, true);\r
             /// be gentle with the user\r
             IndeterminateProgressDialog dialog = \r
                     IndeterminateProgressDialog.newInstance(R.string.auth_trying_to_login, true);\r
@@ -1304,10 +1306,7 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
             //mAuthToken = ((OAuth2GetAccessToken)operation).getResultTokenMap().get(OAuth2Constants.KEY_ACCESS_TOKEN);\r
             Log_OC.d(TAG, "Got ACCESS TOKEN: " + mAuthToken);\r
             \r
             //mAuthToken = ((OAuth2GetAccessToken)operation).getResultTokenMap().get(OAuth2Constants.KEY_ACCESS_TOKEN);\r
             Log_OC.d(TAG, "Got ACCESS TOKEN: " + mAuthToken);\r
             \r
-            String remotePath ="";\r
-            boolean successIfAbsent = false;\r
-            boolean followRedirects = true;\r
-            startExistenceCheckRemoteOperation(remotePath, this, successIfAbsent, webdav_path, "", "", followRedirects);\r
+            accessRootFolderRemoteOperation("", "");\r
 \r
         } else {\r
             updateAuthStatusIconAndText(result);\r
 \r
         } else {\r
             updateAuthStatusIconAndText(result);\r
@@ -1326,10 +1325,9 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
      * @param result        Result of the operation.\r
      */\r
     private void onAuthorizationCheckFinish(RemoteOperationResult result) {\r
      * @param result        Result of the operation.\r
      */\r
     private void onAuthorizationCheckFinish(RemoteOperationResult result) {\r
-        mWaitingForOpId = -1;\r
+        mWaitingForOpId = Long.MAX_VALUE;\r
         dismissDialog(WAIT_DIALOG_TAG);\r
 \r
         dismissDialog(WAIT_DIALOG_TAG);\r
 \r
-        result = new RemoteOperationResult(new RuntimeException("FAKE"));\r
         if (result.isSuccess()) {\r
             Log_OC.d(TAG, "Successful access - time to save the account");\r
 \r
         if (result.isSuccess()) {\r
             Log_OC.d(TAG, "Successful access - time to save the account");\r
 \r
@@ -1351,12 +1349,6 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
             /// the server\r
             mServerIsChecked = true;\r
             mServerIsValid = false;\r
             /// the server\r
             mServerIsChecked = true;\r
             mServerIsValid = false;\r
-            /*\r
-            mServerInfo.mIsSslConn = false;\r
-            mServerInfo.mVersion = null;\r
-            mServerInfo.mBaseUrl = \r
-                    normalizeUrl(mHostUrlInput.getText().toString(), mServerInfo.mIsSslConn);    // TODO remove?\r
-                    */\r
             mServerInfo = new GetServerInfoOperation.ServerInfo();  \r
 \r
             // update status icon and text\r
             mServerInfo = new GetServerInfoOperation.ServerInfo();  \r
 \r
             // update status icon and text\r
@@ -1430,11 +1422,9 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
         String username = mUsernameInput.getText().toString().trim();\r
         if (isOAuth) {\r
             username = "OAuth_user" + (new java.util.Random(System.currentTimeMillis())).nextLong();\r
         String username = mUsernameInput.getText().toString().trim();\r
         if (isOAuth) {\r
             username = "OAuth_user" + (new java.util.Random(System.currentTimeMillis())).nextLong();\r
-        }            \r
-        String accountName = username + "@" + uri.getHost();\r
-        if (uri.getPort() >= 0) {\r
-            accountName += ":" + uri.getPort();\r
         }\r
         }\r
+        String accountName = com.owncloud.android.lib.common.accounts.AccountUtils.\r
+                buildAccountName(uri, username);\r
         Account newAccount = new Account(accountName, MainApp.getAccountType());\r
         if (AccountUtils.exists(newAccount, getApplicationContext())) {\r
             // fail - not a new account, but an existing one; disallow\r
         Account newAccount = new Account(accountName, MainApp.getAccountType());\r
         if (AccountUtils.exists(newAccount, getApplicationContext())) {\r
             // fail - not a new account, but an existing one; disallow\r
@@ -1655,7 +1645,6 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
         getUserNameIntent.setAction(OperationsService.ACTION_GET_USER_NAME);\r
         getUserNameIntent.putExtra(OperationsService.EXTRA_SERVER_URL, mServerInfo.mBaseUrl);\r
         getUserNameIntent.putExtra(OperationsService.EXTRA_COOKIE, sessionCookie);\r
         getUserNameIntent.setAction(OperationsService.ACTION_GET_USER_NAME);\r
         getUserNameIntent.putExtra(OperationsService.EXTRA_SERVER_URL, mServerInfo.mBaseUrl);\r
         getUserNameIntent.putExtra(OperationsService.EXTRA_COOKIE, sessionCookie);\r
-        getUserNameIntent.putExtra(OperationsService.EXTRA_FOLLOW_REDIRECTS, followRedirects);\r
         \r
         if (mOperationsServiceBinder != null) {\r
             //Log_OC.wtf(TAG, "starting getRemoteUserNameOperation..." );\r
         \r
         if (mOperationsServiceBinder != null) {\r
             //Log_OC.wtf(TAG, "starting getRemoteUserNameOperation..." );\r
@@ -1712,6 +1701,7 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
         dialog.show(ft, UNTRUSTED_CERT_DIALOG_TAG);\r
     }\r
 \r
         dialog.show(ft, UNTRUSTED_CERT_DIALOG_TAG);\r
     }\r
 \r
+\r
     /**\r
      * Show untrusted cert dialog \r
      */\r
     /**\r
      * Show untrusted cert dialog \r
      */\r
@@ -1753,10 +1743,14 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
 \r
 \r
     private void doOnResumeAndBound() {\r
 \r
 \r
     private void doOnResumeAndBound() {\r
-        Log.wtf(TAG, "registering to listen for operation callbacks" );\r
+        //Log_OC.wtf(TAG, "registering to listen for operation callbacks" );\r
         mOperationsServiceBinder.addOperationListener(AuthenticatorActivity.this, mHandler);\r
         mOperationsServiceBinder.addOperationListener(AuthenticatorActivity.this, mHandler);\r
-        if (mWaitingForOpId != -1) {\r
-            mOperationsServiceBinder.dispatchResultIfFinished(mWaitingForOpId, this);\r
+        if (mWaitingForOpId <= Integer.MAX_VALUE) {\r
+            mOperationsServiceBinder.dispatchResultIfFinished((int)mWaitingForOpId, this);\r
+        }\r
+        \r
+        if (mPendingAutoCheck) {\r
+            checkOcServer();\r
         }\r
     }\r
 \r
         }\r
     }\r
 \r
@@ -1778,7 +1772,7 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
         @Override\r
         public void onServiceConnected(ComponentName component, IBinder service) {\r
             if (component.equals(new ComponentName(AuthenticatorActivity.this, OperationsService.class))) {\r
         @Override\r
         public void onServiceConnected(ComponentName component, IBinder service) {\r
             if (component.equals(new ComponentName(AuthenticatorActivity.this, OperationsService.class))) {\r
-                Log_OC.wtf(TAG, "Operations service connected");\r
+                //Log_OC.wtf(TAG, "Operations service connected");\r
                 mOperationsServiceBinder = (OperationsServiceBinder) service;\r
                 \r
                 doOnResumeAndBound();\r
                 mOperationsServiceBinder = (OperationsServiceBinder) service;\r
                 \r
                 doOnResumeAndBound();\r
@@ -1798,5 +1792,33 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
         }\r
     \r
     }\r
         }\r
     \r
     }\r
-    \r
+\r
+    /**\r
+     * Create and show dialog for request authentication to the user\r
+     * @param webView\r
+     * @param handler\r
+     */\r
+    public void createAuthenticationDialog(WebView webView, HttpAuthHandler handler) {\r
+\r
+        // Show a dialog with the certificate info\r
+        CredentialsDialogFragment dialog = CredentialsDialogFragment.newInstanceForCredentials(webView, handler);\r
+        FragmentManager fm = getSupportFragmentManager();\r
+        FragmentTransaction ft = fm.beginTransaction();\r
+        ft.addToBackStack(null);\r
+        dialog.setCancelable(false);\r
+        dialog.show(ft, CREDENTIALS_DIALOG_TAG);\r
+\r
+        if (!mIsFirstAuthAttempt) {\r
+            Toast.makeText(getApplicationContext(), getText(R.string.saml_authentication_wrong_pass), Toast.LENGTH_LONG).show();\r
+        } else {\r
+            mIsFirstAuthAttempt = false;\r
+        }\r
+    }\r
+\r
+    /**\r
+     * For retrieving the clicking on authentication cancel button\r
+     */\r
+    public void doNegativeAuthenticatioDialogClick(){\r
+        mIsFirstAuthAttempt = true;\r
+    }\r
 }\r
 }\r