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