Fixed crash, error notified instead
[pub/Android/ownCloud.git] / src / com / owncloud / android / authentication / AuthenticatorActivity.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
3 * Copyright (C) 2012-2013 ownCloud Inc.
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 *
17 */
18
19 package com.owncloud.android.authentication;
20
21 import com.owncloud.android.Log_OC;
22 import com.owncloud.android.ui.dialog.SslValidatorDialog;
23 import com.owncloud.android.ui.dialog.SslValidatorDialog.OnSslValidatorListener;
24 import com.owncloud.android.utils.OwnCloudVersion;
25 import com.owncloud.android.network.OwnCloudClientUtils;
26 import com.owncloud.android.operations.OwnCloudServerCheckOperation;
27 import com.owncloud.android.operations.ExistenceCheckOperation;
28 import com.owncloud.android.operations.OAuth2GetAccessToken;
29 import com.owncloud.android.operations.OnRemoteOperationListener;
30 import com.owncloud.android.operations.RemoteOperation;
31 import com.owncloud.android.operations.RemoteOperationResult;
32 import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
33
34 import android.accounts.Account;
35 import android.accounts.AccountAuthenticatorActivity;
36 import android.accounts.AccountManager;
37 import android.app.AlertDialog;
38 import android.app.Dialog;
39 import android.app.ProgressDialog;
40 import android.content.ContentResolver;
41 import android.content.DialogInterface;
42 import android.content.Intent;
43 import android.content.SharedPreferences;
44 import android.graphics.Rect;
45 import android.graphics.drawable.Drawable;
46 import android.net.Uri;
47 import android.os.Bundle;
48 import android.os.Handler;
49 import android.preference.PreferenceManager;
50 import android.text.Editable;
51 import android.text.InputType;
52 import android.text.TextWatcher;
53 import android.view.KeyEvent;
54 import android.view.MotionEvent;
55 import android.view.View;
56 import android.view.View.OnFocusChangeListener;
57 import android.view.View.OnTouchListener;
58 import android.view.Window;
59 import android.view.inputmethod.EditorInfo;
60 import android.widget.CheckBox;
61 import android.widget.EditText;
62 import android.widget.Button;
63 import android.widget.TextView;
64 import android.widget.Toast;
65 import android.widget.TextView.OnEditorActionListener;
66
67 import com.owncloud.android.R;
68
69 import eu.alefzero.webdav.WebdavClient;
70
71 /**
72 * This Activity is used to add an ownCloud account to the App
73 *
74 * @author Bartek Przybylski
75 * @author David A. Velasco
76 */
77 public class AuthenticatorActivity extends AccountAuthenticatorActivity
78 implements OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeListener, OnEditorActionListener {
79
80 private static final String TAG = AuthenticatorActivity.class.getSimpleName();
81
82 public static final String EXTRA_ACCOUNT = "ACCOUNT";
83 public static final String EXTRA_USER_NAME = "USER_NAME";
84 public static final String EXTRA_HOST_NAME = "HOST_NAME";
85 public static final String EXTRA_ACTION = "ACTION";
86
87 private static final String KEY_HOST_URL_TEXT = "HOST_URL_TEXT";
88 private static final String KEY_OC_VERSION = "OC_VERSION";
89 private static final String KEY_ACCOUNT = "ACCOUNT";
90 private static final String KEY_SERVER_VALID = "SERVER_VALID";
91 private static final String KEY_SERVER_CHECKED = "SERVER_CHECKED";
92 private static final String KEY_SERVER_CHECK_IN_PROGRESS = "SERVER_CHECK_IN_PROGRESS";
93 private static final String KEY_SERVER_STATUS_TEXT = "SERVER_STATUS_TEXT";
94 private static final String KEY_SERVER_STATUS_ICON = "SERVER_STATUS_ICON";
95 private static final String KEY_IS_SSL_CONN = "IS_SSL_CONN";
96 private static final String KEY_PASSWORD_VISIBLE = "PASSWORD_VISIBLE";
97 private static final String KEY_AUTH_STATUS_TEXT = "AUTH_STATUS_TEXT";
98 private static final String KEY_AUTH_STATUS_ICON = "AUTH_STATUS_ICON";
99 private static final String KEY_REFRESH_BUTTON_ENABLED = "KEY_REFRESH_BUTTON_ENABLED";
100
101 private static final String OAUTH_MODE_ON = "on";
102 private static final String OAUTH_MODE_OFF = "off";
103 private static final String OAUTH_MODE_OPTIONAL = "optional";
104
105 private static final int DIALOG_LOGIN_PROGRESS = 0;
106 private static final int DIALOG_SSL_VALIDATOR = 1;
107 private static final int DIALOG_CERT_NOT_SAVED = 2;
108 private static final int DIALOG_OAUTH2_LOGIN_PROGRESS = 3;
109
110 public static final byte ACTION_CREATE = 0;
111 public static final byte ACTION_UPDATE_TOKEN = 1;
112
113 private String mHostBaseUrl;
114 private OwnCloudVersion mDiscoveredVersion;
115
116 private int mServerStatusText, mServerStatusIcon;
117 private boolean mServerIsChecked, mServerIsValid, mIsSslConn;
118 private int mAuthStatusText, mAuthStatusIcon;
119
120 private final Handler mHandler = new Handler();
121 private Thread mOperationThread;
122 private OwnCloudServerCheckOperation mOcServerChkOperation;
123 private ExistenceCheckOperation mAuthCheckOperation;
124 private RemoteOperationResult mLastSslUntrustedServerResult;
125
126 private Uri mNewCapturedUriFromOAuth2Redirection;
127
128 private AccountManager mAccountMgr;
129 private boolean mJustCreated;
130 private byte mAction;
131 private Account mAccount;
132
133 private EditText mHostUrlInput;
134 private EditText mUsernameInput;
135 private EditText mPasswordInput;
136 private CheckBox mOAuth2Check;
137 private String mOAuthAccessToken;
138 private View mOkButton;
139 private TextView mAuthStatusLayout;
140
141 private TextView mOAuthAuthEndpointText;
142 private TextView mOAuthTokenEndpointText;
143
144 private boolean mRefreshButtonEnabled;
145
146
147 /**
148 * {@inheritDoc}
149 *
150 * IMPORTANT ENTRY POINT 1: activity is shown to the user
151 */
152 @Override
153 protected void onCreate(Bundle savedInstanceState) {
154 super.onCreate(savedInstanceState);
155 getWindow().requestFeature(Window.FEATURE_NO_TITLE);
156
157 /// set view and get references to view elements
158 setContentView(R.layout.account_setup);
159 mHostUrlInput = (EditText) findViewById(R.id.hostUrlInput);
160 mUsernameInput = (EditText) findViewById(R.id.account_username);
161 mPasswordInput = (EditText) findViewById(R.id.account_password);
162 mOAuthAuthEndpointText = (TextView)findViewById(R.id.oAuthEntryPoint_1);
163 mOAuthTokenEndpointText = (TextView)findViewById(R.id.oAuthEntryPoint_2);
164 mOAuth2Check = (CheckBox) findViewById(R.id.oauth_onOff_check);
165 mOkButton = findViewById(R.id.buttonOK);
166 mAuthStatusLayout = (TextView) findViewById(R.id.auth_status_text);
167
168 /// complete label for 'register account' button
169 Button b = (Button) findViewById(R.id.account_register);
170 if (b != null) {
171 b.setText(String.format(getString(R.string.auth_register), getString(R.string.app_name)));
172 }
173
174 /// initialization
175 mAccountMgr = AccountManager.get(this);
176 mNewCapturedUriFromOAuth2Redirection = null;
177 mAction = getIntent().getByteExtra(EXTRA_ACTION, ACTION_CREATE);
178 mAccount = null;
179 mHostBaseUrl = "";
180
181 if (savedInstanceState == null) {
182 /// connection state and info
183 mServerStatusText = mServerStatusIcon = 0;
184 mServerIsValid = false;
185 mServerIsChecked = false;
186 mIsSslConn = false;
187 mAuthStatusText = mAuthStatusIcon = 0;
188
189 /// retrieve extras from intent
190 String tokenType = getIntent().getExtras().getString(AccountAuthenticator.KEY_AUTH_TOKEN_TYPE);
191 boolean oAuthRequired = AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN.equals(tokenType) || OAUTH_MODE_ON.equals(getString(R.string.oauth2_mode));
192
193 mAccount = getIntent().getExtras().getParcelable(EXTRA_ACCOUNT);
194 if (mAccount != null) {
195 String ocVersion = mAccountMgr.getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION);
196 if (ocVersion != null) {
197 mDiscoveredVersion = new OwnCloudVersion(ocVersion);
198 }
199 mHostBaseUrl = normalizeUrl(mAccountMgr.getUserData(mAccount, AccountAuthenticator.KEY_OC_BASE_URL));
200 mHostUrlInput.setText(mHostBaseUrl);
201 String userName = mAccount.name.substring(0, mAccount.name.lastIndexOf('@'));
202 mUsernameInput.setText(userName);
203 oAuthRequired = (mAccountMgr.getUserData(mAccount, AccountAuthenticator.KEY_SUPPORTS_OAUTH2) != null);
204 }
205 mOAuth2Check.setChecked(oAuthRequired);
206 changeViewByOAuth2Check(oAuthRequired);
207
208
209 } else {
210 /// connection state and info
211 mServerIsValid = savedInstanceState.getBoolean(KEY_SERVER_VALID);
212 mServerIsChecked = savedInstanceState.getBoolean(KEY_SERVER_CHECKED);
213 mServerStatusText = savedInstanceState.getInt(KEY_SERVER_STATUS_TEXT);
214 mServerStatusIcon = savedInstanceState.getInt(KEY_SERVER_STATUS_ICON);
215 mIsSslConn = savedInstanceState.getBoolean(KEY_IS_SSL_CONN);
216 mAuthStatusText = savedInstanceState.getInt(KEY_AUTH_STATUS_TEXT);
217 mAuthStatusIcon = savedInstanceState.getInt(KEY_AUTH_STATUS_ICON);
218 if (savedInstanceState.getBoolean(KEY_PASSWORD_VISIBLE, false)) {
219 showPassword();
220 }
221
222 /// server data
223 String ocVersion = savedInstanceState.getString(KEY_OC_VERSION);
224 if (ocVersion != null) {
225 mDiscoveredVersion = new OwnCloudVersion(ocVersion);
226 }
227 mHostBaseUrl = savedInstanceState.getString(KEY_HOST_URL_TEXT);
228
229 // account data, if updating
230 mAccount = savedInstanceState.getParcelable(KEY_ACCOUNT);
231
232 // check if server check was interrupted by a configuration change
233 if (savedInstanceState.getBoolean(KEY_SERVER_CHECK_IN_PROGRESS, false)) {
234 checkOcServer();
235 }
236
237 // refresh button enabled
238 mRefreshButtonEnabled = savedInstanceState.getBoolean(KEY_REFRESH_BUTTON_ENABLED);
239
240 }
241
242 showServerStatus();
243 showAuthStatus();
244 if (mServerIsChecked && !mServerIsValid && mRefreshButtonEnabled) showRefreshButton();
245 mOkButton.setEnabled(mServerIsValid); // state not automatically recovered in configuration changes
246
247 if (!OAUTH_MODE_OPTIONAL.equals(getString(R.string.oauth2_mode))) {
248 mOAuth2Check.setVisibility(View.GONE);
249 }
250
251 if (mAction == ACTION_UPDATE_TOKEN) {
252 /// lock things that should not change
253 mHostUrlInput.setEnabled(false);
254 mUsernameInput.setEnabled(false);
255 mOAuth2Check.setVisibility(View.GONE);
256 if (!mServerIsValid && mOcServerChkOperation == null) {
257 checkOcServer();
258 }
259 }
260
261 mPasswordInput.setText(""); // clean password to avoid social hacking (disadvantage: password in removed if the device is turned aside)
262 mJustCreated = true;
263
264 /// bind view elements to listeners
265 mHostUrlInput.setOnFocusChangeListener(this);
266 mHostUrlInput.setOnTouchListener(new RightDrawableOnTouchListener() {
267 @Override
268 public boolean onDrawableTouch(final MotionEvent event) {
269 if (event.getAction() == MotionEvent.ACTION_UP) {
270 AuthenticatorActivity.this.onRefreshClick();
271 }
272 return true;
273 }
274 });
275 mHostUrlInput.addTextChangedListener(new TextWatcher() {
276
277 @Override
278 public void afterTextChanged(Editable s) {
279 if (!mHostBaseUrl.equals(normalizeUrl(mHostUrlInput.getText().toString()))) {
280 mOkButton.setEnabled(false);
281 }
282 }
283
284 @Override
285 public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
286
287 @Override
288 public void onTextChanged(CharSequence s, int start, int before, int count) {}
289
290 });
291 mPasswordInput.setOnFocusChangeListener(this);
292 mPasswordInput.setImeOptions(EditorInfo.IME_ACTION_DONE);
293 mPasswordInput.setOnEditorActionListener(this);
294 mPasswordInput.setOnTouchListener(new RightDrawableOnTouchListener() {
295 @Override
296 public boolean onDrawableTouch(final MotionEvent event) {
297 if (event.getAction() == MotionEvent.ACTION_UP) {
298 AuthenticatorActivity.this.onViewPasswordClick();
299 }
300 return true;
301 }
302 });
303 }
304
305 /**
306 * Saves relevant state before {@link #onPause()}
307 *
308 * Do NOT save {@link #mNewCapturedUriFromOAuth2Redirection}; it keeps a temporal flag, intended to defer the
309 * processing of the redirection caught in {@link #onNewIntent(Intent)} until {@link #onResume()}
310 *
311 * See {@link #loadSavedInstanceState(Bundle)}
312 */
313 @Override
314 protected void onSaveInstanceState(Bundle outState) {
315 super.onSaveInstanceState(outState);
316
317 /// connection state and info
318 outState.putInt(KEY_SERVER_STATUS_TEXT, mServerStatusText);
319 outState.putInt(KEY_SERVER_STATUS_ICON, mServerStatusIcon);
320 outState.putBoolean(KEY_SERVER_VALID, mServerIsValid);
321 outState.putBoolean(KEY_SERVER_CHECKED, mServerIsChecked);
322 outState.putBoolean(KEY_SERVER_CHECK_IN_PROGRESS, (!mServerIsValid && mOcServerChkOperation != null));
323 outState.putBoolean(KEY_IS_SSL_CONN, mIsSslConn);
324 outState.putBoolean(KEY_PASSWORD_VISIBLE, isPasswordVisible());
325 outState.putInt(KEY_AUTH_STATUS_ICON, mAuthStatusIcon);
326 outState.putInt(KEY_AUTH_STATUS_TEXT, mAuthStatusText);
327
328 /// server data
329 if (mDiscoveredVersion != null) {
330 outState.putString(KEY_OC_VERSION, mDiscoveredVersion.toString());
331 }
332 outState.putString(KEY_HOST_URL_TEXT, mHostBaseUrl);
333
334 /// account data, if updating
335 if (mAccount != null) {
336 outState.putParcelable(KEY_ACCOUNT, mAccount);
337 }
338
339 // refresh button enabled
340 outState.putBoolean(KEY_REFRESH_BUTTON_ENABLED, mRefreshButtonEnabled);
341
342 }
343
344
345 /**
346 * The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION request
347 * is caught here.
348 *
349 * To make this possible, this activity needs to be qualified with android:launchMode = "singleTask" in the
350 * AndroidManifest.xml file.
351 */
352 @Override
353 protected void onNewIntent (Intent intent) {
354 Log_OC.d(TAG, "onNewIntent()");
355 Uri data = intent.getData();
356 if (data != null && data.toString().startsWith(getString(R.string.oauth2_redirect_uri))) {
357 mNewCapturedUriFromOAuth2Redirection = data;
358 }
359 }
360
361
362 /**
363 * The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION, and
364 * deferred in {@link #onNewIntent(Intent)}, is processed here.
365 */
366 @Override
367 protected void onResume() {
368 super.onResume();
369 // the state of mOAuth2Check is automatically recovered between configuration changes, but not before onCreate() finishes; so keep the next lines here
370 changeViewByOAuth2Check(mOAuth2Check.isChecked());
371 if (mAction == ACTION_UPDATE_TOKEN && mJustCreated) {
372 if (mOAuth2Check.isChecked())
373 Toast.makeText(this, R.string.auth_expired_oauth_token_toast, Toast.LENGTH_LONG).show();
374 else
375 Toast.makeText(this, R.string.auth_expired_basic_auth_toast, Toast.LENGTH_LONG).show();
376 }
377
378 if (mNewCapturedUriFromOAuth2Redirection != null) {
379 getOAuth2AccessTokenFromCapturedRedirection();
380 }
381
382 mJustCreated = false;
383 }
384
385
386 /**
387 * Parses the redirection with the response to the GET AUTHORIZATION request to the
388 * oAuth server and requests for the access token (GET ACCESS TOKEN)
389 */
390 private void getOAuth2AccessTokenFromCapturedRedirection() {
391 /// Parse data from OAuth redirection
392 String queryParameters = mNewCapturedUriFromOAuth2Redirection.getQuery();
393 mNewCapturedUriFromOAuth2Redirection = null;
394
395 /// Showing the dialog with instructions for the user.
396 showDialog(DIALOG_OAUTH2_LOGIN_PROGRESS);
397
398 /// GET ACCESS TOKEN to the oAuth server
399 RemoteOperation operation = new OAuth2GetAccessToken( getString(R.string.oauth2_client_id),
400 getString(R.string.oauth2_redirect_uri),
401 getString(R.string.oauth2_grant_type),
402 queryParameters);
403 //WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(getString(R.string.oauth2_url_endpoint_access)), getApplicationContext());
404 WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(mOAuthTokenEndpointText.getText().toString().trim()), getApplicationContext());
405 operation.execute(client, this, mHandler);
406 }
407
408
409
410 /**
411 * Handles the change of focus on the text inputs for the server URL and the password
412 */
413 public void onFocusChange(View view, boolean hasFocus) {
414 if (view.getId() == R.id.hostUrlInput) {
415 if (!hasFocus) {
416 onUrlInputFocusLost((TextView) view);
417 if (!mServerIsValid) {
418 showRefreshButton();
419 }
420 }
421 else {
422 hideRefreshButton();
423 }
424
425 } else if (view.getId() == R.id.account_password) {
426 onPasswordFocusChanged((TextView) view, hasFocus);
427 }
428 }
429
430
431 /**
432 * Handles changes in focus on the text input for the server URL.
433 *
434 * IMPORTANT ENTRY POINT 2: When (!hasFocus), user wrote the server URL and changed to
435 * other field. The operation to check the existence of the server in the entered URL is
436 * started.
437 *
438 * When hasFocus: user 'comes back' to write again the server URL.
439 *
440 * @param hostInput TextView with the URL input field receiving the change of focus.
441 */
442 private void onUrlInputFocusLost(TextView hostInput) {
443 if (!mHostBaseUrl.equals(normalizeUrl(mHostUrlInput.getText().toString()))) {
444 checkOcServer();
445 } else {
446 mOkButton.setEnabled(mServerIsValid);
447 }
448 }
449
450
451 private void checkOcServer() {
452 String uri = trimUrlWebdav(mHostUrlInput.getText().toString().trim());
453 mServerIsValid = false;
454 mServerIsChecked = false;
455 mOkButton.setEnabled(false);
456 mDiscoveredVersion = null;
457 hideRefreshButton();
458 if (uri.length() != 0) {
459 mServerStatusText = R.string.auth_testing_connection;
460 mServerStatusIcon = R.drawable.progress_small;
461 showServerStatus();
462 mOcServerChkOperation = new OwnCloudServerCheckOperation(uri, this);
463 WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(uri), this);
464 mOperationThread = mOcServerChkOperation.execute(client, this, mHandler);
465 } else {
466 mServerStatusText = 0;
467 mServerStatusIcon = 0;
468 showServerStatus();
469 }
470 }
471
472
473 /**
474 * Handles changes in focus on the text input for the password (basic authorization).
475 *
476 * When (hasFocus), the button to toggle password visibility is shown.
477 *
478 * When (!hasFocus), the button is made invisible and the password is hidden.
479 *
480 * @param passwordInput TextView with the password input field receiving the change of focus.
481 * @param hasFocus 'True' if focus is received, 'false' if is lost
482 */
483 private void onPasswordFocusChanged(TextView passwordInput, boolean hasFocus) {
484 if (hasFocus) {
485 showViewPasswordButton();
486 } else {
487 hidePassword();
488 hidePasswordButton();
489 }
490 }
491
492
493 private void showViewPasswordButton() {
494 //int drawable = android.R.drawable.ic_menu_view;
495 int drawable = R.drawable.ic_view;
496 if (isPasswordVisible()) {
497 //drawable = android.R.drawable.ic_secure;
498 drawable = R.drawable.ic_hide;
499 }
500 mPasswordInput.setCompoundDrawablesWithIntrinsicBounds(0, 0, drawable, 0);
501 }
502
503 private boolean isPasswordVisible() {
504 return ((mPasswordInput.getInputType() & InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
505 }
506
507 private void hidePasswordButton() {
508 mPasswordInput.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
509 }
510
511 private void showPassword() {
512 mPasswordInput.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
513 showViewPasswordButton();
514 }
515
516 private void hidePassword() {
517 mPasswordInput.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
518 showViewPasswordButton();
519 }
520
521
522 /**
523 * Cancels the authenticator activity
524 *
525 * IMPORTANT ENTRY POINT 3: Never underestimate the importance of cancellation
526 *
527 * This method is bound in the layout/acceoun_setup.xml resource file.
528 *
529 * @param view Cancel button
530 */
531 public void onCancelClick(View view) {
532 setResult(RESULT_CANCELED); // TODO review how is this related to AccountAuthenticator (debugging)
533 finish();
534 }
535
536
537
538 /**
539 * Checks the credentials of the user in the root of the ownCloud server
540 * before creating a new local account.
541 *
542 * For basic authorization, a check of existence of the root folder is
543 * performed.
544 *
545 * For OAuth, starts the flow to get an access token; the credentials test
546 * is postponed until it is available.
547 *
548 * IMPORTANT ENTRY POINT 4
549 *
550 * @param view OK button
551 */
552 public void onOkClick(View view) {
553 // this check should be unnecessary
554 if (mDiscoveredVersion == null || !mDiscoveredVersion.isVersionValid() || mHostBaseUrl == null || mHostBaseUrl.length() == 0) {
555 mServerStatusIcon = R.drawable.common_error;
556 mServerStatusText = R.string.auth_wtf_reenter_URL;
557 showServerStatus();
558 mOkButton.setEnabled(false);
559 Log_OC.wtf(TAG, "The user was allowed to click 'connect' to an unchecked server!!");
560 return;
561 }
562
563 if (mOAuth2Check.isChecked()) {
564 startOauthorization();
565
566 } else {
567 checkBasicAuthorization();
568 }
569 }
570
571
572 /**
573 * Tests the credentials entered by the user performing a check of existence on
574 * the root folder of the ownCloud server.
575 */
576 private void checkBasicAuthorization() {
577 /// get the path to the root folder through WebDAV from the version server
578 String webdav_path = AccountUtils.getWebdavPath(mDiscoveredVersion, false);
579
580 /// get basic credentials entered by user
581 String username = mUsernameInput.getText().toString();
582 String password = mPasswordInput.getText().toString();
583
584 /// be gentle with the user
585 showDialog(DIALOG_LOGIN_PROGRESS);
586
587 /// test credentials accessing the root folder
588 mAuthCheckOperation = new ExistenceCheckOperation("", this, false);
589 WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(mHostBaseUrl + webdav_path), this);
590 client.setBasicCredentials(username, password);
591 mOperationThread = mAuthCheckOperation.execute(client, this, mHandler);
592 }
593
594
595 /**
596 * Starts the OAuth 'grant type' flow to get an access token, with
597 * a GET AUTHORIZATION request to the BUILT-IN authorization server.
598 */
599 private void startOauthorization() {
600 // be gentle with the user
601 mAuthStatusIcon = R.drawable.progress_small;
602 mAuthStatusText = R.string.oauth_login_connection;
603 showAuthStatus();
604
605 // GET AUTHORIZATION request
606 //Uri uri = Uri.parse(getString(R.string.oauth2_url_endpoint_auth));
607 Uri uri = Uri.parse(mOAuthAuthEndpointText.getText().toString().trim());
608 Uri.Builder uriBuilder = uri.buildUpon();
609 uriBuilder.appendQueryParameter(OAuth2Constants.KEY_RESPONSE_TYPE, getString(R.string.oauth2_response_type));
610 uriBuilder.appendQueryParameter(OAuth2Constants.KEY_REDIRECT_URI, getString(R.string.oauth2_redirect_uri));
611 uriBuilder.appendQueryParameter(OAuth2Constants.KEY_CLIENT_ID, getString(R.string.oauth2_client_id));
612 uriBuilder.appendQueryParameter(OAuth2Constants.KEY_SCOPE, getString(R.string.oauth2_scope));
613 //uriBuilder.appendQueryParameter(OAuth2Constants.KEY_STATE, whateverwewant);
614 uri = uriBuilder.build();
615 Log_OC.d(TAG, "Starting browser to view " + uri.toString());
616 Intent i = new Intent(Intent.ACTION_VIEW, uri);
617 startActivity(i);
618 }
619
620
621 /**
622 * Callback method invoked when a RemoteOperation executed by this Activity finishes.
623 *
624 * Dispatches the operation flow to the right method.
625 */
626 @Override
627 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
628
629 if (operation instanceof OwnCloudServerCheckOperation) {
630 onOcServerCheckFinish((OwnCloudServerCheckOperation) operation, result);
631
632 } else if (operation instanceof OAuth2GetAccessToken) {
633 onGetOAuthAccessTokenFinish((OAuth2GetAccessToken)operation, result);
634
635 } else if (operation instanceof ExistenceCheckOperation) {
636 onAuthorizationCheckFinish((ExistenceCheckOperation)operation, result);
637
638 }
639 }
640
641
642 /**
643 * Processes the result of the server check performed when the user finishes the enter of the
644 * server URL.
645 *
646 * @param operation Server check performed.
647 * @param result Result of the check.
648 */
649 private void onOcServerCheckFinish(OwnCloudServerCheckOperation operation, RemoteOperationResult result) {
650 if (operation.equals(mOcServerChkOperation)) {
651 /// save result state
652 mServerIsChecked = true;
653 mServerIsValid = result.isSuccess();
654 mIsSslConn = (result.getCode() == ResultCode.OK_SSL);
655 mOcServerChkOperation = null;
656
657 /// update status icon and text
658 if (mServerIsValid) {
659 hideRefreshButton();
660 } else {
661 showRefreshButton();
662 }
663 updateServerStatusIconAndText(result);
664 showServerStatus();
665
666 /// very special case (TODO: move to a common place for all the remote operations)
667 if (result.getCode() == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) {
668 mLastSslUntrustedServerResult = result;
669 showDialog(DIALOG_SSL_VALIDATOR);
670 }
671
672 /// retrieve discovered version and normalize server URL
673 mDiscoveredVersion = operation.getDiscoveredVersion();
674 mHostBaseUrl = normalizeUrl(mHostUrlInput.getText().toString());
675
676 /// allow or not the user try to access the server
677 mOkButton.setEnabled(mServerIsValid);
678
679 } // else nothing ; only the last check operation is considered;
680 // multiple can be triggered if the user amends a URL before a previous check can be triggered
681 }
682
683
684 private String normalizeUrl(String url) {
685 if (url != null && url.length() > 0) {
686 url = url.trim();
687 if (!url.toLowerCase().startsWith("http://") &&
688 !url.toLowerCase().startsWith("https://")) {
689 if (mIsSslConn) {
690 url = "https://" + url;
691 } else {
692 url = "http://" + url;
693 }
694 }
695
696 // OC-208: Add suffix remote.php/webdav to normalize (OC-34)
697 url = trimUrlWebdav(url);
698
699 if (url.endsWith("/")) {
700 url = url.substring(0, url.length() - 1);
701 }
702
703 }
704 Log_OC.d(TAG, "URL Normalize " + url);
705 return (url != null ? url : "");
706 }
707
708
709 private String trimUrlWebdav(String url){
710 if(url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_4_0)){
711 url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_4_0.length());
712 } else if(url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_2_0)){
713 url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_2_0.length());
714 } else if (url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_1_2)){
715 url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_1_2.length());
716 }
717 return (url != null ? url : "");
718 }
719
720
721 /**
722 * Chooses the right icon and text to show to the user for the received operation result.
723 *
724 * @param result Result of a remote operation performed in this activity
725 */
726 private void updateServerStatusIconAndText(RemoteOperationResult result) {
727 mServerStatusIcon = R.drawable.common_error; // the most common case in the switch below
728
729 switch (result.getCode()) {
730 case OK_SSL:
731 mServerStatusIcon = android.R.drawable.ic_secure;
732 mServerStatusText = R.string.auth_secure_connection;
733 break;
734
735 case OK_NO_SSL:
736 case OK:
737 if (mHostUrlInput.getText().toString().trim().toLowerCase().startsWith("http://") ) {
738 mServerStatusText = R.string.auth_connection_established;
739 mServerStatusIcon = R.drawable.ic_ok;
740 } else {
741 mServerStatusText = R.string.auth_nossl_plain_ok_title;
742 mServerStatusIcon = android.R.drawable.ic_partial_secure;
743 }
744 break;
745
746 case NO_NETWORK_CONNECTION:
747 mServerStatusIcon = R.drawable.no_network;
748 mServerStatusText = R.string.auth_no_net_conn_title;
749 break;
750
751 case SSL_RECOVERABLE_PEER_UNVERIFIED:
752 mServerStatusText = R.string.auth_ssl_unverified_server_title;
753 break;
754 case BAD_OC_VERSION:
755 mServerStatusText = R.string.auth_bad_oc_version_title;
756 break;
757 case WRONG_CONNECTION:
758 mServerStatusText = R.string.auth_wrong_connection_title;
759 break;
760 case TIMEOUT:
761 mServerStatusText = R.string.auth_timeout_title;
762 break;
763 case INCORRECT_ADDRESS:
764 mServerStatusText = R.string.auth_incorrect_address_title;
765 break;
766 case SSL_ERROR:
767 mServerStatusText = R.string.auth_ssl_general_error_title;
768 break;
769 case UNAUTHORIZED:
770 mServerStatusText = R.string.auth_unauthorized;
771 break;
772 case HOST_NOT_AVAILABLE:
773 mServerStatusText = R.string.auth_unknown_host_title;
774 break;
775 case INSTANCE_NOT_CONFIGURED:
776 mServerStatusText = R.string.auth_not_configured_title;
777 break;
778 case FILE_NOT_FOUND:
779 mServerStatusText = R.string.auth_incorrect_path_title;
780 break;
781 case OAUTH2_ERROR:
782 mServerStatusText = R.string.auth_oauth_error;
783 break;
784 case OAUTH2_ERROR_ACCESS_DENIED:
785 mServerStatusText = R.string.auth_oauth_error_access_denied;
786 break;
787 case UNHANDLED_HTTP_CODE:
788 case UNKNOWN_ERROR:
789 mServerStatusText = R.string.auth_unknown_error_title;
790 break;
791 default:
792 mServerStatusText = 0;
793 mServerStatusIcon = 0;
794 }
795 }
796
797
798 /**
799 * Chooses the right icon and text to show to the user for the received operation result.
800 *
801 * @param result Result of a remote operation performed in this activity
802 */
803 private void updateAuthStatusIconAndText(RemoteOperationResult result) {
804 mAuthStatusIcon = R.drawable.common_error; // the most common case in the switch below
805
806 switch (result.getCode()) {
807 case OK_SSL:
808 mAuthStatusIcon = android.R.drawable.ic_secure;
809 mAuthStatusText = R.string.auth_secure_connection;
810 break;
811
812 case OK_NO_SSL:
813 case OK:
814 if (mHostUrlInput.getText().toString().trim().toLowerCase().startsWith("http://") ) {
815 mAuthStatusText = R.string.auth_connection_established;
816 mAuthStatusIcon = R.drawable.ic_ok;
817 } else {
818 mAuthStatusText = R.string.auth_nossl_plain_ok_title;
819 mAuthStatusIcon = android.R.drawable.ic_partial_secure;
820 }
821 break;
822
823 case NO_NETWORK_CONNECTION:
824 mAuthStatusIcon = R.drawable.no_network;
825 mAuthStatusText = R.string.auth_no_net_conn_title;
826 break;
827
828 case SSL_RECOVERABLE_PEER_UNVERIFIED:
829 mAuthStatusText = R.string.auth_ssl_unverified_server_title;
830 break;
831 case BAD_OC_VERSION:
832 mAuthStatusText = R.string.auth_bad_oc_version_title;
833 break;
834 case WRONG_CONNECTION:
835 mAuthStatusText = R.string.auth_wrong_connection_title;
836 break;
837 case TIMEOUT:
838 mAuthStatusText = R.string.auth_timeout_title;
839 break;
840 case INCORRECT_ADDRESS:
841 mAuthStatusText = R.string.auth_incorrect_address_title;
842 break;
843 case SSL_ERROR:
844 mAuthStatusText = R.string.auth_ssl_general_error_title;
845 break;
846 case UNAUTHORIZED:
847 mAuthStatusText = R.string.auth_unauthorized;
848 break;
849 case HOST_NOT_AVAILABLE:
850 mAuthStatusText = R.string.auth_unknown_host_title;
851 break;
852 case INSTANCE_NOT_CONFIGURED:
853 mAuthStatusText = R.string.auth_not_configured_title;
854 break;
855 case FILE_NOT_FOUND:
856 mAuthStatusText = R.string.auth_incorrect_path_title;
857 break;
858 case OAUTH2_ERROR:
859 mAuthStatusText = R.string.auth_oauth_error;
860 break;
861 case OAUTH2_ERROR_ACCESS_DENIED:
862 mAuthStatusText = R.string.auth_oauth_error_access_denied;
863 break;
864 case UNHANDLED_HTTP_CODE:
865 case UNKNOWN_ERROR:
866 mAuthStatusText = R.string.auth_unknown_error_title;
867 break;
868 default:
869 mAuthStatusText = 0;
870 mAuthStatusIcon = 0;
871 }
872 }
873
874
875 /**
876 * Processes the result of the request for and access token send
877 * to an OAuth authorization server.
878 *
879 * @param operation Operation performed requesting the access token.
880 * @param result Result of the operation.
881 */
882 private void onGetOAuthAccessTokenFinish(OAuth2GetAccessToken operation, RemoteOperationResult result) {
883 try {
884 dismissDialog(DIALOG_OAUTH2_LOGIN_PROGRESS);
885 } catch (IllegalArgumentException e) {
886 // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens
887 }
888
889 String webdav_path = AccountUtils.getWebdavPath(mDiscoveredVersion, true);
890 if (result.isSuccess() && webdav_path != null) {
891 /// be gentle with the user
892 showDialog(DIALOG_LOGIN_PROGRESS);
893
894 /// time to test the retrieved access token on the ownCloud server
895 mOAuthAccessToken = ((OAuth2GetAccessToken)operation).getResultTokenMap().get(OAuth2Constants.KEY_ACCESS_TOKEN);
896 Log_OC.d(TAG, "Got ACCESS TOKEN: " + mOAuthAccessToken);
897 mAuthCheckOperation = new ExistenceCheckOperation("", this, false);
898 WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(mHostBaseUrl + webdav_path), this);
899 client.setBearerCredentials(mOAuthAccessToken);
900 mAuthCheckOperation.execute(client, this, mHandler);
901
902 } else {
903 updateAuthStatusIconAndText(result);
904 showAuthStatus();
905 Log_OC.d(TAG, "Access failed: " + result.getLogMessage());
906 }
907 }
908
909
910 /**
911 * Processes the result of the access check performed to try the user credentials.
912 *
913 * Creates a new account through the AccountManager.
914 *
915 * @param operation Access check performed.
916 * @param result Result of the operation.
917 */
918 private void onAuthorizationCheckFinish(ExistenceCheckOperation operation, RemoteOperationResult result) {
919 try {
920 dismissDialog(DIALOG_LOGIN_PROGRESS);
921 } catch (IllegalArgumentException e) {
922 // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens
923 }
924
925 if (result.isSuccess()) {
926 Log_OC.d(TAG, "Successful access - time to save the account");
927
928 if (mAction == ACTION_CREATE) {
929 createAccount();
930
931 } else {
932 updateToken();
933 }
934
935 finish();
936
937 } else {
938 updateAuthStatusIconAndText(result);
939 showAuthStatus();
940 Log_OC.d(TAG, "Access failed: " + result.getLogMessage());
941 }
942 }
943
944
945 /**
946 * Sets the proper response to get that the Account Authenticator that started this activity saves
947 * a new authorization token for mAccount.
948 */
949 private void updateToken() {
950 Bundle response = new Bundle();
951 response.putString(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
952 response.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccount.type);
953 boolean isOAuth = mOAuth2Check.isChecked();
954 if (isOAuth) {
955 response.putString(AccountManager.KEY_AUTHTOKEN, mOAuthAccessToken);
956 // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention
957 mAccountMgr.setAuthToken(mAccount, AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN, mOAuthAccessToken);
958 } else {
959 response.putString(AccountManager.KEY_AUTHTOKEN, mPasswordInput.getText().toString());
960 mAccountMgr.setPassword(mAccount, mPasswordInput.getText().toString());
961 }
962 setAccountAuthenticatorResult(response);
963 }
964
965
966 /**
967 * Creates a new account through the Account Authenticator that started this activity.
968 *
969 * This makes the account permanent.
970 *
971 * TODO Decide how to name the OAuth accounts
972 */
973 private void createAccount() {
974 /// create and save new ownCloud account
975 boolean isOAuth = mOAuth2Check.isChecked();
976
977 Uri uri = Uri.parse(mHostBaseUrl);
978 String username = mUsernameInput.getText().toString().trim();
979 if (isOAuth) {
980 username = "OAuth_user" + (new java.util.Random(System.currentTimeMillis())).nextLong();
981 }
982 String accountName = username + "@" + uri.getHost();
983 if (uri.getPort() >= 0) {
984 accountName += ":" + uri.getPort();
985 }
986 mAccount = new Account(accountName, AccountAuthenticator.ACCOUNT_TYPE);
987 if (isOAuth) {
988 mAccountMgr.addAccountExplicitly(mAccount, "", null); // with our implementation, the password is never input in the app
989 } else {
990 mAccountMgr.addAccountExplicitly(mAccount, mPasswordInput.getText().toString(), null);
991 }
992
993 /// add the new account as default in preferences, if there is none already
994 Account defaultAccount = AccountUtils.getCurrentOwnCloudAccount(this);
995 if (defaultAccount == null) {
996 SharedPreferences.Editor editor = PreferenceManager
997 .getDefaultSharedPreferences(this).edit();
998 editor.putString("select_oc_account", accountName);
999 editor.commit();
1000 }
1001
1002 /// prepare result to return to the Authenticator
1003 // TODO check again what the Authenticator makes with it; probably has the same effect as addAccountExplicitly, but it's not well done
1004 final Intent intent = new Intent();
1005 intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, AccountAuthenticator.ACCOUNT_TYPE);
1006 intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
1007 if (!isOAuth)
1008 intent.putExtra(AccountManager.KEY_AUTHTOKEN, AccountAuthenticator.ACCOUNT_TYPE); // TODO check this; not sure it's right; maybe
1009 intent.putExtra(AccountManager.KEY_USERDATA, username);
1010 if (isOAuth) {
1011 mAccountMgr.setAuthToken(mAccount, AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN, mOAuthAccessToken);
1012 }
1013 /// add user data to the new account; TODO probably can be done in the last parameter addAccountExplicitly, or in KEY_USERDATA
1014 mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION, mDiscoveredVersion.toString());
1015 mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_OC_BASE_URL, mHostBaseUrl);
1016 if (isOAuth)
1017 mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_SUPPORTS_OAUTH2, "TRUE"); // TODO this flag should be unnecessary
1018
1019 setAccountAuthenticatorResult(intent.getExtras());
1020 setResult(RESULT_OK, intent);
1021
1022 /// immediately request for the synchronization of the new account
1023 Bundle bundle = new Bundle();
1024 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
1025 ContentResolver.requestSync(mAccount, AccountAuthenticator.AUTHORITY, bundle);
1026 }
1027
1028
1029 /**
1030 * {@inheritDoc}
1031 *
1032 * Necessary to update the contents of the SSL Dialog
1033 *
1034 * TODO move to some common place for all possible untrusted SSL failures
1035 */
1036 @Override
1037 protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
1038 switch (id) {
1039 case DIALOG_LOGIN_PROGRESS:
1040 case DIALOG_CERT_NOT_SAVED:
1041 case DIALOG_OAUTH2_LOGIN_PROGRESS:
1042 break;
1043 case DIALOG_SSL_VALIDATOR: {
1044 ((SslValidatorDialog)dialog).updateResult(mLastSslUntrustedServerResult);
1045 break;
1046 }
1047 default:
1048 Log_OC.e(TAG, "Incorrect dialog called with id = " + id);
1049 }
1050 }
1051
1052
1053 /**
1054 * {@inheritDoc}
1055 */
1056 @Override
1057 protected Dialog onCreateDialog(int id) {
1058 Dialog dialog = null;
1059 switch (id) {
1060 case DIALOG_LOGIN_PROGRESS: {
1061 /// simple progress dialog
1062 ProgressDialog working_dialog = new ProgressDialog(this);
1063 working_dialog.setMessage(getResources().getString(R.string.auth_trying_to_login));
1064 working_dialog.setIndeterminate(true);
1065 working_dialog.setCancelable(true);
1066 working_dialog
1067 .setOnCancelListener(new DialogInterface.OnCancelListener() {
1068 @Override
1069 public void onCancel(DialogInterface dialog) {
1070 /// TODO study if this is enough
1071 Log_OC.i(TAG, "Login canceled");
1072 if (mOperationThread != null) {
1073 mOperationThread.interrupt();
1074 finish();
1075 }
1076 }
1077 });
1078 dialog = working_dialog;
1079 break;
1080 }
1081 case DIALOG_OAUTH2_LOGIN_PROGRESS: {
1082 ProgressDialog working_dialog = new ProgressDialog(this);
1083 working_dialog.setMessage(String.format("Getting authorization"));
1084 working_dialog.setIndeterminate(true);
1085 working_dialog.setCancelable(true);
1086 working_dialog
1087 .setOnCancelListener(new DialogInterface.OnCancelListener() {
1088 @Override
1089 public void onCancel(DialogInterface dialog) {
1090 Log_OC.i(TAG, "Login canceled");
1091 finish();
1092 }
1093 });
1094 dialog = working_dialog;
1095 break;
1096 }
1097 case DIALOG_SSL_VALIDATOR: {
1098 /// TODO start to use new dialog interface, at least for this (it is a FragmentDialog already)
1099 dialog = SslValidatorDialog.newInstance(this, mLastSslUntrustedServerResult, this);
1100 break;
1101 }
1102 case DIALOG_CERT_NOT_SAVED: {
1103 AlertDialog.Builder builder = new AlertDialog.Builder(this);
1104 builder.setMessage(getResources().getString(R.string.ssl_validator_not_saved));
1105 builder.setCancelable(false);
1106 builder.setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {
1107 @Override
1108 public void onClick(DialogInterface dialog, int which) {
1109 dialog.dismiss();
1110 };
1111 });
1112 dialog = builder.create();
1113 break;
1114 }
1115 default:
1116 Log_OC.e(TAG, "Incorrect dialog called with id = " + id);
1117 }
1118 return dialog;
1119 }
1120
1121
1122 /**
1123 * Starts and activity to open the 'new account' page in the ownCloud web site
1124 *
1125 * @param view 'Account register' button
1126 */
1127 public void onRegisterClick(View view) {
1128 Intent register = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.url_account_register)));
1129 setResult(RESULT_CANCELED);
1130 startActivity(register);
1131 }
1132
1133
1134 /**
1135 * Updates the content and visibility state of the icon and text associated
1136 * to the last check on the ownCloud server.
1137 */
1138 private void showServerStatus() {
1139 TextView tv = (TextView) findViewById(R.id.server_status_text);
1140
1141 if (mServerStatusIcon == 0 && mServerStatusText == 0) {
1142 tv.setVisibility(View.INVISIBLE);
1143
1144 } else {
1145 tv.setText(mServerStatusText);
1146 tv.setCompoundDrawablesWithIntrinsicBounds(mServerStatusIcon, 0, 0, 0);
1147 tv.setVisibility(View.VISIBLE);
1148 }
1149
1150 }
1151
1152
1153 /**
1154 * Updates the content and visibility state of the icon and text associated
1155 * to the interactions with the OAuth authorization server.
1156 */
1157 private void showAuthStatus() {
1158 if (mAuthStatusIcon == 0 && mAuthStatusText == 0) {
1159 mAuthStatusLayout.setVisibility(View.INVISIBLE);
1160
1161 } else {
1162 mAuthStatusLayout.setText(mAuthStatusText);
1163 mAuthStatusLayout.setCompoundDrawablesWithIntrinsicBounds(mAuthStatusIcon, 0, 0, 0);
1164 mAuthStatusLayout.setVisibility(View.VISIBLE);
1165 }
1166 }
1167
1168
1169 private void showRefreshButton() {
1170 mHostUrlInput.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_action_refresh_black, 0);
1171 mRefreshButtonEnabled = true;
1172 }
1173
1174 private void hideRefreshButton() {
1175 mHostUrlInput.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
1176 mRefreshButtonEnabled = false;
1177 }
1178
1179 /**
1180 * Called when the refresh button in the input field for ownCloud host is clicked.
1181 *
1182 * Performs a new check on the URL in the input field.
1183 *
1184 * @param view Refresh 'button'
1185 */
1186 public void onRefreshClick() {
1187 checkOcServer();
1188 }
1189
1190
1191 /**
1192 * Called when the eye icon in the password field is clicked.
1193 *
1194 * Toggles the visibility of the password in the field.
1195 */
1196 public void onViewPasswordClick() {
1197 int selectionStart = mPasswordInput.getSelectionStart();
1198 int selectionEnd = mPasswordInput.getSelectionEnd();
1199 if (isPasswordVisible()) {
1200 hidePassword();
1201 } else {
1202 showPassword();
1203 }
1204 mPasswordInput.setSelection(selectionStart, selectionEnd);
1205 }
1206
1207
1208 /**
1209 * Called when the checkbox for OAuth authorization is clicked.
1210 *
1211 * Hides or shows the input fields for user & password.
1212 *
1213 * @param view 'View password' 'button'
1214 */
1215 public void onCheckClick(View view) {
1216 CheckBox oAuth2Check = (CheckBox)view;
1217 changeViewByOAuth2Check(oAuth2Check.isChecked());
1218
1219 }
1220
1221 /**
1222 * Changes the visibility of input elements depending upon the kind of authorization
1223 * chosen by the user: basic or OAuth
1224 *
1225 * @param checked 'True' when OAuth is selected.
1226 */
1227 public void changeViewByOAuth2Check(Boolean checked) {
1228
1229 if (checked) {
1230 mOAuthAuthEndpointText.setVisibility(View.VISIBLE);
1231 mOAuthTokenEndpointText.setVisibility(View.VISIBLE);
1232 mUsernameInput.setVisibility(View.GONE);
1233 mPasswordInput.setVisibility(View.GONE);
1234 } else {
1235 mOAuthAuthEndpointText.setVisibility(View.GONE);
1236 mOAuthTokenEndpointText.setVisibility(View.GONE);
1237 mUsernameInput.setVisibility(View.VISIBLE);
1238 mPasswordInput.setVisibility(View.VISIBLE);
1239 }
1240
1241 }
1242
1243 /**
1244 * Called from SslValidatorDialog when a new server certificate was correctly saved.
1245 */
1246 public void onSavedCertificate() {
1247 mOperationThread = mOcServerChkOperation.retry(this, mHandler);
1248 }
1249
1250 /**
1251 * Called from SslValidatorDialog when a new server certificate could not be saved
1252 * when the user requested it.
1253 */
1254 @Override
1255 public void onFailedSavingCertificate() {
1256 showDialog(DIALOG_CERT_NOT_SAVED);
1257 }
1258
1259
1260 /**
1261 * Called when the 'action' button in an IME is pressed ('enter' in software keyboard).
1262 *
1263 * Used to trigger the authorization check when the user presses 'enter' after writing the password.
1264 */
1265 @Override
1266 public boolean onEditorAction(TextView inputField, int actionId, KeyEvent event) {
1267 if (inputField != null && inputField.equals(mPasswordInput) &&
1268 actionId == EditorInfo.IME_ACTION_DONE) {
1269 if (mOkButton.isEnabled()) {
1270 mOkButton.performClick();
1271 }
1272 }
1273 return false; // always return false to grant that the software keyboard is hidden anyway
1274 }
1275
1276
1277 private abstract static class RightDrawableOnTouchListener implements OnTouchListener {
1278
1279 private int fuzz = 75;
1280
1281 /**
1282 * {@inheritDoc}
1283 */
1284 @Override
1285 public boolean onTouch(View view, MotionEvent event) {
1286 Drawable rightDrawable = null;
1287 if (view instanceof TextView) {
1288 Drawable[] drawables = ((TextView)view).getCompoundDrawables();
1289 if (drawables.length > 2) {
1290 rightDrawable = drawables[2];
1291 }
1292 }
1293 if (rightDrawable != null) {
1294 final int x = (int) event.getX();
1295 final int y = (int) event.getY();
1296 final Rect bounds = rightDrawable.getBounds();
1297 if (x >= (view.getRight() - bounds.width() - fuzz) && x <= (view.getRight() - view.getPaddingRight() + fuzz)
1298 && y >= (view.getPaddingTop() - fuzz) && y <= (view.getHeight() - view.getPaddingBottom()) + fuzz) {
1299
1300 return onDrawableTouch(event);
1301 }
1302 }
1303 return false;
1304 }
1305
1306 public abstract boolean onDrawableTouch(final MotionEvent event);
1307 }
1308
1309 }