07c4d79249aaaf14e6dc801b887276140ca90f64
[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-2014 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 java.security.cert.X509Certificate;
22 import java.util.Map;
23
24 import android.accounts.Account;
25 import android.accounts.AccountManager;
26 import android.app.Dialog;
27 import android.content.ComponentName;
28 import android.content.Context;
29 import android.content.Intent;
30 import android.content.ServiceConnection;
31 import android.content.SharedPreferences;
32 import android.graphics.Rect;
33 import android.graphics.drawable.Drawable;
34 import android.net.Uri;
35 import android.net.http.SslError;
36 import android.os.Bundle;
37 import android.os.Handler;
38 import android.os.IBinder;
39 import android.preference.PreferenceManager;
40 import android.support.v4.app.Fragment;
41 import android.support.v4.app.FragmentManager;
42 import android.support.v4.app.FragmentTransaction;
43 import android.text.Editable;
44 import android.text.InputType;
45 import android.text.TextWatcher;
46 import android.view.KeyEvent;
47 import android.view.MotionEvent;
48 import android.view.View;
49 import android.view.View.OnFocusChangeListener;
50 import android.view.View.OnTouchListener;
51 import android.view.Window;
52 import android.view.inputmethod.EditorInfo;
53 import android.webkit.SslErrorHandler;
54 import android.widget.Button;
55 import android.widget.CheckBox;
56 import android.widget.EditText;
57 import android.widget.TextView;
58 import android.widget.TextView.OnEditorActionListener;
59 import android.widget.Toast;
60
61 import com.actionbarsherlock.app.SherlockDialogFragment;
62 import com.owncloud.android.MainApp;
63 import com.owncloud.android.R;
64 import com.owncloud.android.authentication.SsoWebViewClient.SsoWebViewClientListener;
65 import com.owncloud.android.lib.common.accounts.AccountTypeUtils;
66 import com.owncloud.android.lib.common.accounts.AccountUtils.Constants;
67 import com.owncloud.android.lib.common.network.CertificateCombinedException;
68 import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;
69 import com.owncloud.android.lib.common.operations.RemoteOperation;
70 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
71 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
72 import com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation;
73 import com.owncloud.android.lib.resources.status.OwnCloudVersion;
74 import com.owncloud.android.lib.resources.users.GetRemoteUserNameOperation;
75 import com.owncloud.android.operations.DetectAuthenticationMethodOperation.AuthenticationMethod;
76 import com.owncloud.android.operations.GetServerInfoOperation;
77 import com.owncloud.android.operations.OAuth2GetAccessToken;
78 import com.owncloud.android.services.OperationsService;
79 import com.owncloud.android.services.OperationsService.OperationsServiceBinder;
80 import com.owncloud.android.ui.dialog.IndeterminateProgressDialog;
81 import com.owncloud.android.ui.dialog.SamlWebViewDialog;
82 import com.owncloud.android.ui.dialog.SslUntrustedCertDialog;
83 import com.owncloud.android.ui.dialog.SslUntrustedCertDialog.OnSslUntrustedCertListener;
84 import com.owncloud.android.utils.Log_OC;
85
86 /**
87 * This Activity is used to add an ownCloud account to the App
88 *
89 * @author Bartek Przybylski
90 * @author David A. Velasco
91 * @author masensio
92 */
93 public class AuthenticatorActivity extends AccountAuthenticatorActivity
94 implements OnRemoteOperationListener, OnFocusChangeListener, OnEditorActionListener,
95 SsoWebViewClientListener, OnSslUntrustedCertListener {
96
97 private static final String TAG = AuthenticatorActivity.class.getSimpleName();
98
99 public static final String EXTRA_ACTION = "ACTION";
100 public static final String EXTRA_ACCOUNT = "ACCOUNT";
101
102 private static final String KEY_AUTH_TOKEN_TYPE = "AUTH_TOKEN_TYPE";
103
104 private static final String KEY_HOST_URL_TEXT = "HOST_URL_TEXT";
105 private static final String KEY_OC_VERSION = "OC_VERSION";
106 private static final String KEY_SERVER_VALID = "SERVER_VALID";
107 private static final String KEY_SERVER_CHECKED = "SERVER_CHECKED";
108 private static final String KEY_SERVER_STATUS_TEXT = "SERVER_STATUS_TEXT";
109 private static final String KEY_SERVER_STATUS_ICON = "SERVER_STATUS_ICON";
110 private static final String KEY_IS_SSL_CONN = "IS_SSL_CONN";
111 private static final String KEY_PASSWORD_EXPOSED = "PASSWORD_VISIBLE";
112 private static final String KEY_AUTH_STATUS_TEXT = "AUTH_STATUS_TEXT";
113 private static final String KEY_AUTH_STATUS_ICON = "AUTH_STATUS_ICON";
114 private static final String KEY_SERVER_AUTH_METHOD = "SERVER_AUTH_METHOD";
115 private static final String KEY_WAITING_FOR_OP_ID = "WAITING_FOR_OP_ID";
116 private static final String KEY_AUTH_TOKEN = "AUTH_TOKEN";
117
118 private static final String AUTH_ON = "on";
119 private static final String AUTH_OPTIONAL = "optional";
120
121 public static final byte ACTION_CREATE = 0;
122 public static final byte ACTION_UPDATE_TOKEN = 1; // requested by the user
123 public static final byte ACTION_UPDATE_EXPIRED_TOKEN = 2; // detected by the app
124
125 private static final String UNTRUSTED_CERT_DIALOG_TAG = "UNTRUSTED_CERT_DIALOG";
126 private static final String SAML_DIALOG_TAG = "SAML_DIALOG";
127 private static final String WAIT_DIALOG_TAG = "WAIT_DIALOG";
128
129
130 /// parameters from EXTRAs in starter Intent
131 private byte mAction;
132 private Account mAccount;
133 private String mAuthTokenType;
134
135
136 /// activity-level references / state
137 private final Handler mHandler = new Handler();
138 private ServiceConnection mOperationsServiceConnection = null;
139 private OperationsServiceBinder mOperationsServiceBinder = null;
140 private AccountManager mAccountMgr;
141 private Uri mNewCapturedUriFromOAuth2Redirection;
142
143
144 /// Server PRE-Fragment elements
145 private EditText mHostUrlInput;
146 private View mRefreshButton;
147 private TextView mServerStatusView;
148
149 private TextWatcher mHostUrlInputWatcher;
150 private int mServerStatusText = 0, mServerStatusIcon = 0;
151
152 private boolean mServerIsChecked = false;
153 private boolean mServerIsValid = false;
154 private boolean mPendingAutoCheck = false;
155
156 private GetServerInfoOperation.ServerInfo mServerInfo =
157 new GetServerInfoOperation.ServerInfo();
158
159
160 /// Authentication PRE-Fragment elements
161 private CheckBox mOAuth2Check;
162 private TextView mOAuthAuthEndpointText;
163 private TextView mOAuthTokenEndpointText;
164 private EditText mUsernameInput;
165 private EditText mPasswordInput;
166 private View mOkButton;
167 private TextView mAuthStatusView;
168
169 private int mAuthStatusText = 0, mAuthStatusIcon = 0;
170
171 private String mAuthToken = "";
172
173
174 /// Identifier of operation in progress which result shouldn't be lost
175 private long mWaitingForOpId = Long.MAX_VALUE;
176
177
178 /**
179 * {@inheritDoc}
180 *
181 * IMPORTANT ENTRY POINT 1: activity is shown to the user
182 */
183 @Override
184 protected void onCreate(Bundle savedInstanceState) {
185 //Log_OC.wtf(TAG, "onCreate init");
186 super.onCreate(savedInstanceState);
187 getWindow().requestFeature(Window.FEATURE_NO_TITLE);
188
189 // bind to Operations Service
190 mOperationsServiceConnection = new OperationsServiceConnection();
191 if (!bindService(new Intent(this, OperationsService.class),
192 mOperationsServiceConnection,
193 Context.BIND_AUTO_CREATE)) {
194 Toast.makeText(this,
195 R.string.error_cant_bind_to_operations_service,
196 Toast.LENGTH_LONG)
197 .show();
198 finish();
199 }
200
201 /// init activity state
202 mAccountMgr = AccountManager.get(this);
203 mNewCapturedUriFromOAuth2Redirection = null;
204
205 /// get input values
206 mAction = getIntent().getByteExtra(EXTRA_ACTION, ACTION_CREATE);
207 mAccount = getIntent().getExtras().getParcelable(EXTRA_ACCOUNT);
208 if (savedInstanceState == null) {
209 initAuthTokenType();
210 } else {
211 mAuthTokenType = savedInstanceState.getString(KEY_AUTH_TOKEN_TYPE);
212 mWaitingForOpId = savedInstanceState.getLong(KEY_WAITING_FOR_OP_ID);
213 }
214
215 /// load user interface
216 setContentView(R.layout.account_setup);
217
218 /// initialize general UI elements
219 initOverallUi(savedInstanceState);
220
221 mOkButton = findViewById(R.id.buttonOK);
222
223 /// initialize block to be moved to single Fragment to check server and get info about it
224 initServerPreFragment(savedInstanceState);
225
226 /// initialize block to be moved to single Fragment to retrieve and validate credentials
227 initAuthorizationPreFragment(savedInstanceState);
228
229 //Log_OC.wtf(TAG, "onCreate end");
230 }
231
232 private void initAuthTokenType() {
233 mAuthTokenType =
234 getIntent().getExtras().getString(AccountAuthenticator.KEY_AUTH_TOKEN_TYPE);
235 if (mAuthTokenType == null) {
236 if (mAccount != null) {
237 boolean oAuthRequired =
238 (mAccountMgr.getUserData(mAccount, Constants.KEY_SUPPORTS_OAUTH2) != null);
239 boolean samlWebSsoRequired =
240 (mAccountMgr.getUserData(mAccount, Constants.KEY_SUPPORTS_SAML_WEB_SSO) != null);
241 mAuthTokenType = chooseAuthTokenType(oAuthRequired, samlWebSsoRequired);
242
243 } else {
244 boolean oAuthSupported = AUTH_ON.equals(getString(R.string.auth_method_oauth2));
245 boolean samlWebSsoSupported = AUTH_ON.equals(getString(R.string.auth_method_saml_web_sso));
246 mAuthTokenType = chooseAuthTokenType(oAuthSupported, samlWebSsoSupported);
247 }
248 }
249 }
250
251 private String chooseAuthTokenType(boolean oauth, boolean saml) {
252 if (saml) {
253 return AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType());
254 } else if (oauth) {
255 return AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType());
256 } else {
257 return AccountTypeUtils.getAuthTokenTypePass(MainApp.getAccountType());
258 }
259 }
260
261
262 /**
263 * Configures elements in the user interface under direct control of the Activity.
264 *
265 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
266 */
267 private void initOverallUi(Bundle savedInstanceState) {
268
269 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
270 boolean isWelcomeLinkVisible = getResources().getBoolean(R.bool.show_welcome_link);
271
272 String instructionsMessageText = null;
273 if (mAction == ACTION_UPDATE_EXPIRED_TOKEN) {
274 if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType())
275 .equals(mAuthTokenType)) {
276 instructionsMessageText = getString(R.string.auth_expired_oauth_token_toast);
277
278 } else if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType())
279 .equals(mAuthTokenType)) {
280 instructionsMessageText = getString(R.string.auth_expired_saml_sso_token_toast);
281
282 } else {
283 instructionsMessageText = getString(R.string.auth_expired_basic_auth_toast);
284 }
285 }
286
287 /// step 2 - set properties of UI elements (text, visibility, enabled...)
288 Button welcomeLink = (Button) findViewById(R.id.welcome_link);
289 welcomeLink.setVisibility(isWelcomeLinkVisible ? View.VISIBLE : View.GONE);
290 welcomeLink.setText(
291 String.format(getString(R.string.auth_register), getString(R.string.app_name)));
292
293 TextView instructionsView = (TextView) findViewById(R.id.instructions_message);
294 if (instructionsMessageText != null) {
295 instructionsView.setVisibility(View.VISIBLE);
296 instructionsView.setText(instructionsMessageText);
297 } else {
298 instructionsView.setVisibility(View.GONE);
299 }
300 }
301
302
303 /**
304 *
305 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
306 */
307 private void initServerPreFragment(Bundle savedInstanceState) {
308
309 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
310 boolean isUrlInputAllowed = getResources().getBoolean(R.bool.show_server_url_input);
311 if (savedInstanceState == null) {
312 if (mAccount != null) {
313 mServerInfo.mBaseUrl = mAccountMgr.getUserData(mAccount, Constants.KEY_OC_BASE_URL);
314 mServerInfo.mIsSslConn = mServerInfo.mBaseUrl.startsWith("https://"); // TODO do this in a setter for mBaseUrl
315 String ocVersion = mAccountMgr.getUserData(mAccount, Constants.KEY_OC_VERSION);
316 if (ocVersion != null) {
317 mServerInfo.mVersion = new OwnCloudVersion(ocVersion);
318 }
319 } else {
320 mServerInfo.mBaseUrl = getString(R.string.server_url).trim();
321 mServerInfo.mIsSslConn = mServerInfo.mBaseUrl.startsWith("https://");
322 }
323 } else {
324 mServerStatusText = savedInstanceState.getInt(KEY_SERVER_STATUS_TEXT);
325 mServerStatusIcon = savedInstanceState.getInt(KEY_SERVER_STATUS_ICON);
326
327 mServerIsValid = savedInstanceState.getBoolean(KEY_SERVER_VALID);
328 mServerIsChecked = savedInstanceState.getBoolean(KEY_SERVER_CHECKED);
329
330 // TODO parcelable
331 mServerInfo.mIsSslConn = savedInstanceState.getBoolean(KEY_IS_SSL_CONN);
332 mServerInfo.mBaseUrl = savedInstanceState.getString(KEY_HOST_URL_TEXT);
333 String ocVersion = savedInstanceState.getString(KEY_OC_VERSION);
334 if (ocVersion != null) {
335 mServerInfo.mVersion = new OwnCloudVersion(ocVersion);
336 }
337 mServerInfo.mAuthMethod = AuthenticationMethod.valueOf(
338 savedInstanceState.getString(KEY_SERVER_AUTH_METHOD));
339
340 }
341
342 /// step 2 - set properties of UI elements (text, visibility, enabled...)
343 mHostUrlInput = (EditText) findViewById(R.id.hostUrlInput);
344 mHostUrlInput.setText(mServerInfo.mBaseUrl);
345 if (mAction != ACTION_CREATE) {
346 /// lock things that should not change
347 mHostUrlInput.setEnabled(false);
348 mHostUrlInput.setFocusable(false);
349 }
350 if (isUrlInputAllowed) {
351 mRefreshButton = findViewById(R.id.embeddedRefreshButton);
352 } else {
353 findViewById(R.id.hostUrlFrame).setVisibility(View.GONE);
354 mRefreshButton = findViewById(R.id.centeredRefreshButton);
355 }
356 showRefreshButton(mServerIsChecked && !mServerIsValid &&
357 mWaitingForOpId > Integer.MAX_VALUE);
358 mServerStatusView = (TextView) findViewById(R.id.server_status_text);
359 showServerStatus();
360
361 /// step 3 - bind some listeners and options
362 mHostUrlInput.setImeOptions(EditorInfo.IME_ACTION_NEXT);
363 mHostUrlInput.setOnEditorActionListener(this);
364
365 /// step 4 - create listeners that will be bound at onResume
366 mHostUrlInputWatcher = new TextWatcher() {
367
368 @Override
369 public void afterTextChanged(Editable s) {
370 if (mOkButton.isEnabled() &&
371 !mServerInfo.mBaseUrl.equals(
372 normalizeUrl(s.toString(), mServerInfo.mIsSslConn))) {
373 mOkButton.setEnabled(false);
374 }
375 }
376
377 @Override
378 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
379 }
380
381 @Override
382 public void onTextChanged(CharSequence s, int start, int before, int count) {
383 if (mAuthStatusIcon != 0) {
384 Log_OC.d(TAG, "onTextChanged: hiding authentication status");
385 mAuthStatusIcon = 0;
386 mAuthStatusText = 0;
387 showAuthStatus();
388 }
389 }
390 };
391
392
393 // TODO find out if this is really necessary, or if it can done in a different way
394 findViewById(R.id.scroll).setOnTouchListener(new OnTouchListener() {
395 @Override
396 public boolean onTouch(View view, MotionEvent event) {
397 if (event.getAction() == MotionEvent.ACTION_DOWN) {
398 if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType) &&
399 mHostUrlInput.hasFocus()) {
400 checkOcServer();
401 }
402 }
403 return false;
404 }
405 });
406
407
408 /// step 4 - mark automatic check to be started when OperationsService is ready
409 mPendingAutoCheck = (savedInstanceState == null &&
410 (mAction != ACTION_CREATE || !isUrlInputAllowed));
411 }
412
413
414 /**
415 *
416 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
417 */
418 private void initAuthorizationPreFragment(Bundle savedInstanceState) {
419
420 /// step 0 - get UI elements in layout
421 mOAuth2Check = (CheckBox) findViewById(R.id.oauth_onOff_check);
422 mOAuthAuthEndpointText = (TextView)findViewById(R.id.oAuthEntryPoint_1);
423 mOAuthTokenEndpointText = (TextView)findViewById(R.id.oAuthEntryPoint_2);
424 mUsernameInput = (EditText) findViewById(R.id.account_username);
425 mPasswordInput = (EditText) findViewById(R.id.account_password);
426 mAuthStatusView = (TextView) findViewById(R.id.auth_status_text);
427
428 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
429 String presetUserName = null;
430 boolean isPasswordExposed = false;
431 if (savedInstanceState == null) {
432 if (mAccount != null) {
433 presetUserName = mAccount.name.substring(0, mAccount.name.lastIndexOf('@'));
434 }
435
436 } else {
437 isPasswordExposed = savedInstanceState.getBoolean(KEY_PASSWORD_EXPOSED, false);
438 mAuthStatusText = savedInstanceState.getInt(KEY_AUTH_STATUS_TEXT);
439 mAuthStatusIcon = savedInstanceState.getInt(KEY_AUTH_STATUS_ICON);
440 mAuthToken = savedInstanceState.getString(KEY_AUTH_TOKEN);
441 }
442
443 /// step 2 - set properties of UI elements (text, visibility, enabled...)
444 mOAuth2Check.setChecked(
445 AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType())
446 .equals(mAuthTokenType));
447 if (presetUserName != null) {
448 mUsernameInput.setText(presetUserName);
449 }
450 if (mAction != ACTION_CREATE) {
451 mUsernameInput.setEnabled(false);
452 mUsernameInput.setFocusable(false);
453 }
454 mPasswordInput.setText(""); // clean password to avoid social hacking
455 if (isPasswordExposed) {
456 showPassword();
457 }
458 updateAuthenticationPreFragmentVisibility();
459 showAuthStatus();
460 mOkButton.setEnabled(mServerIsValid);
461
462
463 /// step 3 - bind listeners
464 // bindings for password input field
465 mPasswordInput.setOnFocusChangeListener(this);
466 mPasswordInput.setImeOptions(EditorInfo.IME_ACTION_DONE);
467 mPasswordInput.setOnEditorActionListener(this);
468 mPasswordInput.setOnTouchListener(new RightDrawableOnTouchListener() {
469 @Override
470 public boolean onDrawableTouch(final MotionEvent event) {
471 if (event.getAction() == MotionEvent.ACTION_UP) {
472 AuthenticatorActivity.this.onViewPasswordClick();
473 }
474 return true;
475 }
476 });
477
478 }
479
480
481 /**
482 * Changes the visibility of input elements depending on
483 * the current authorization method.
484 */
485 private void updateAuthenticationPreFragmentVisibility () {
486 if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).
487 equals(mAuthTokenType)) {
488 // SAML-based web Single Sign On
489 mOAuth2Check.setVisibility(View.GONE);
490 mOAuthAuthEndpointText.setVisibility(View.GONE);
491 mOAuthTokenEndpointText.setVisibility(View.GONE);
492 mUsernameInput.setVisibility(View.GONE);
493 mPasswordInput.setVisibility(View.GONE);
494
495 } else {
496 if (mAction == ACTION_CREATE &&
497 AUTH_OPTIONAL.equals(getString(R.string.auth_method_oauth2))) {
498 mOAuth2Check.setVisibility(View.VISIBLE);
499 } else {
500 mOAuth2Check.setVisibility(View.GONE);
501 }
502
503 if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).
504 equals(mAuthTokenType)) {
505 // OAuth 2 authorization
506
507 mOAuthAuthEndpointText.setVisibility(View.VISIBLE);
508 mOAuthTokenEndpointText.setVisibility(View.VISIBLE);
509 mUsernameInput.setVisibility(View.GONE);
510 mPasswordInput.setVisibility(View.GONE);
511
512 } else {
513 // basic HTTP authorization
514 mOAuthAuthEndpointText.setVisibility(View.GONE);
515 mOAuthTokenEndpointText.setVisibility(View.GONE);
516 mUsernameInput.setVisibility(View.VISIBLE);
517 mPasswordInput.setVisibility(View.VISIBLE);
518 }
519 }
520 }
521
522
523
524 /**
525 * Saves relevant state before {@link #onPause()}
526 *
527 * Do NOT save {@link #mNewCapturedUriFromOAuth2Redirection}; it keeps a temporal flag, intended to defer the
528 * processing of the redirection caught in {@link #onNewIntent(Intent)} until {@link #onResume()}
529 *
530 * See {@link #loadSavedInstanceState(Bundle)}
531 */
532 @Override
533 protected void onSaveInstanceState(Bundle outState) {
534 //Log_OC.wtf(TAG, "onSaveInstanceState init" );
535 super.onSaveInstanceState(outState);
536
537 /// global state
538 outState.putString(KEY_AUTH_TOKEN_TYPE, mAuthTokenType);
539 outState.putLong(KEY_WAITING_FOR_OP_ID, mWaitingForOpId);
540
541 /// Server PRE-fragment state
542 outState.putInt(KEY_SERVER_STATUS_TEXT, mServerStatusText);
543 outState.putInt(KEY_SERVER_STATUS_ICON, mServerStatusIcon);
544 outState.putBoolean(KEY_SERVER_CHECKED, mServerIsChecked);
545 outState.putBoolean(KEY_SERVER_VALID, mServerIsValid);
546 outState.putBoolean(KEY_IS_SSL_CONN, mServerInfo.mIsSslConn);
547 outState.putString(KEY_HOST_URL_TEXT, mServerInfo.mBaseUrl);
548 if (mServerInfo.mVersion != null) {
549 outState.putString(KEY_OC_VERSION, mServerInfo.mVersion.getVersion());
550 }
551 outState.putString(KEY_SERVER_AUTH_METHOD, mServerInfo.mAuthMethod.name());
552
553 /// Authentication PRE-fragment state
554 outState.putBoolean(KEY_PASSWORD_EXPOSED, isPasswordVisible());
555 outState.putInt(KEY_AUTH_STATUS_ICON, mAuthStatusIcon);
556 outState.putInt(KEY_AUTH_STATUS_TEXT, mAuthStatusText);
557 outState.putString(KEY_AUTH_TOKEN, mAuthToken);
558
559 //Log_OC.wtf(TAG, "onSaveInstanceState end" );
560 }
561
562
563 /**
564 * The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION request
565 * is caught here.
566 *
567 * To make this possible, this activity needs to be qualified with android:launchMode = "singleTask" in the
568 * AndroidManifest.xml file.
569 */
570 @Override
571 protected void onNewIntent (Intent intent) {
572 Log_OC.d(TAG, "onNewIntent()");
573 Uri data = intent.getData();
574 if (data != null && data.toString().startsWith(getString(R.string.oauth2_redirect_uri))) {
575 mNewCapturedUriFromOAuth2Redirection = data;
576 }
577 }
578
579
580 /**
581 * The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION, and
582 * deferred in {@link #onNewIntent(Intent)}, is processed here.
583 */
584 @Override
585 protected void onResume() {
586 //Log_OC.wtf(TAG, "onResume init" );
587 super.onResume();
588
589 // bound here to avoid spurious changes triggered by Android on device rotations
590 mHostUrlInput.setOnFocusChangeListener(this);
591 mHostUrlInput.addTextChangedListener(mHostUrlInputWatcher);
592
593 if (mNewCapturedUriFromOAuth2Redirection != null) {
594 getOAuth2AccessTokenFromCapturedRedirection();
595 }
596
597 if (mOperationsServiceBinder != null) {
598 doOnResumeAndBound();
599 }
600
601 //Log_OC.wtf(TAG, "onResume end" );
602 }
603
604
605 @Override
606 protected void onPause() {
607 //Log_OC.wtf(TAG, "onPause init" );
608 if (mOperationsServiceBinder != null) {
609 //Log_OC.wtf(TAG, "unregistering to listen for operation callbacks" );
610 mOperationsServiceBinder.removeOperationListener(this);
611 }
612
613 mHostUrlInput.removeTextChangedListener(mHostUrlInputWatcher);
614 mHostUrlInput.setOnFocusChangeListener(null);
615
616 super.onPause();
617 //Log_OC.wtf(TAG, "onPause end" );
618 }
619
620 @Override
621 protected void onDestroy() {
622
623 mHostUrlInputWatcher = null;
624
625 if (mOperationsServiceConnection != null) {
626 unbindService(mOperationsServiceConnection);
627 mOperationsServiceBinder = null;
628 }
629 super.onDestroy();
630 }
631
632
633 /**
634 * Parses the redirection with the response to the GET AUTHORIZATION request to the
635 * oAuth server and requests for the access token (GET ACCESS TOKEN)
636 */
637 private void getOAuth2AccessTokenFromCapturedRedirection() {
638 /// Parse data from OAuth redirection
639 String queryParameters = mNewCapturedUriFromOAuth2Redirection.getQuery();
640 mNewCapturedUriFromOAuth2Redirection = null;
641
642 /// Showing the dialog with instructions for the user.
643 IndeterminateProgressDialog dialog =
644 IndeterminateProgressDialog.newInstance(R.string.auth_getting_authorization, true);
645 dialog.show(getSupportFragmentManager(), WAIT_DIALOG_TAG);
646
647 /// GET ACCESS TOKEN to the oAuth server
648 Intent getServerInfoIntent = new Intent();
649 getServerInfoIntent.setAction(OperationsService.ACTION_OAUTH2_GET_ACCESS_TOKEN);
650
651 getServerInfoIntent.putExtra(
652 OperationsService.EXTRA_SERVER_URL,
653 mOAuthTokenEndpointText.getText().toString().trim());
654
655 getServerInfoIntent.putExtra(
656 OperationsService.EXTRA_OAUTH2_QUERY_PARAMETERS,
657 queryParameters);
658
659 if (mOperationsServiceBinder != null) {
660 //Log_OC.wtf(TAG, "getting access token..." );
661 mWaitingForOpId = mOperationsServiceBinder.newOperation(getServerInfoIntent);
662 }
663 }
664
665
666
667 /**
668 * Handles the change of focus on the text inputs for the server URL and the password
669 */
670 public void onFocusChange(View view, boolean hasFocus) {
671 if (view.getId() == R.id.hostUrlInput) {
672 if (!hasFocus) {
673 onUrlInputFocusLost((TextView) view);
674 }
675 else {
676 showRefreshButton(false);
677 }
678
679 } else if (view.getId() == R.id.account_password) {
680 onPasswordFocusChanged((TextView) view, hasFocus);
681 }
682 }
683
684
685 /**
686 * Handles changes in focus on the text input for the server URL.
687 *
688 * IMPORTANT ENTRY POINT 2: When (!hasFocus), user wrote the server URL and changed to
689 * other field. The operation to check the existence of the server in the entered URL is
690 * started.
691 *
692 * When hasFocus: user 'comes back' to write again the server URL.
693 *
694 * @param hostInput TextView with the URL input field receiving the change of focus.
695 */
696 private void onUrlInputFocusLost(TextView hostInput) {
697 if (!mServerInfo.mBaseUrl.equals(
698 normalizeUrl(mHostUrlInput.getText().toString(), mServerInfo.mIsSslConn))) {
699 // check server again only if the user changed something in the field
700 checkOcServer();
701 } else {
702 mOkButton.setEnabled(mServerIsValid);
703 showRefreshButton(!mServerIsValid);
704 }
705 }
706
707
708 private void checkOcServer() {
709 String uri = mHostUrlInput.getText().toString().trim();
710 mServerIsValid = false;
711 mServerIsChecked = false;
712 mOkButton.setEnabled(false);
713 mServerInfo = new GetServerInfoOperation.ServerInfo();
714 showRefreshButton(false);
715
716 if (uri.length() != 0) {
717 mServerStatusText = R.string.auth_testing_connection;
718 mServerStatusIcon = R.drawable.progress_small;
719 showServerStatus();
720
721 Intent getServerInfoIntent = new Intent();
722 getServerInfoIntent.setAction(OperationsService.ACTION_GET_SERVER_INFO);
723 getServerInfoIntent.putExtra(OperationsService.EXTRA_SERVER_URL, uri);
724 if (mOperationsServiceBinder != null) {
725 mWaitingForOpId = mOperationsServiceBinder.newOperation(getServerInfoIntent);
726 } else {
727 Log_OC.wtf(TAG, "Server check tried with OperationService unbound!" );
728 }
729
730 } else {
731 mServerStatusText = 0;
732 mServerStatusIcon = 0;
733 showServerStatus();
734 }
735 }
736
737
738 /**
739 * Handles changes in focus on the text input for the password (basic authorization).
740 *
741 * When (hasFocus), the button to toggle password visibility is shown.
742 *
743 * When (!hasFocus), the button is made invisible and the password is hidden.
744 *
745 * @param passwordInput TextView with the password input field receiving the change of focus.
746 * @param hasFocus 'True' if focus is received, 'false' if is lost
747 */
748 private void onPasswordFocusChanged(TextView passwordInput, boolean hasFocus) {
749 if (hasFocus) {
750 showViewPasswordButton();
751 } else {
752 hidePassword();
753 hidePasswordButton();
754 }
755 }
756
757
758 private void showViewPasswordButton() {
759 int drawable = R.drawable.ic_view;
760 if (isPasswordVisible()) {
761 drawable = R.drawable.ic_hide;
762 }
763 mPasswordInput.setCompoundDrawablesWithIntrinsicBounds(0, 0, drawable, 0);
764 }
765
766 private boolean isPasswordVisible() {
767 return ((mPasswordInput.getInputType() & InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
768 }
769
770 private void hidePasswordButton() {
771 mPasswordInput.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
772 }
773
774 private void showPassword() {
775 mPasswordInput.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
776 showViewPasswordButton();
777 }
778
779 private void hidePassword() {
780 mPasswordInput.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
781 showViewPasswordButton();
782 }
783
784 /**
785 * Checks the credentials of the user in the root of the ownCloud server
786 * before creating a new local account.
787 *
788 * For basic authorization, a check of existence of the root folder is
789 * performed.
790 *
791 * For OAuth, starts the flow to get an access token; the credentials test
792 * is postponed until it is available.
793 *
794 * IMPORTANT ENTRY POINT 4
795 *
796 * @param view OK button
797 */
798 public void onOkClick(View view) {
799 // this check should be unnecessary
800 if (mServerInfo.mVersion == null ||
801 !mServerInfo.mVersion.isVersionValid() ||
802 mServerInfo.mBaseUrl == null ||
803 mServerInfo.mBaseUrl.length() == 0) {
804 mServerStatusIcon = R.drawable.common_error;
805 mServerStatusText = R.string.auth_wtf_reenter_URL;
806 showServerStatus();
807 mOkButton.setEnabled(false);
808 //Log_OC.wtf(TAG, "The user was allowed to click 'connect' to an unchecked server!!");
809 return;
810 }
811
812 if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).equals(mAuthTokenType)) {
813 startOauthorization();
814 } else if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType)) {
815 startSamlBasedFederatedSingleSignOnAuthorization();
816 } else {
817 checkBasicAuthorization();
818 }
819 }
820
821
822 /**
823 * Tests the credentials entered by the user performing a check of existence on
824 * the root folder of the ownCloud server.
825 */
826 private void checkBasicAuthorization() {
827 /// get basic credentials entered by user
828 String username = mUsernameInput.getText().toString();
829 String password = mPasswordInput.getText().toString();
830
831 /// be gentle with the user
832 IndeterminateProgressDialog dialog =
833 IndeterminateProgressDialog.newInstance(R.string.auth_trying_to_login, true);
834 dialog.show(getSupportFragmentManager(), WAIT_DIALOG_TAG);
835
836 /// validate credentials accessing the root folder
837 accessRootFolderRemoteOperation(username, password);
838
839 }
840
841 private void accessRootFolderRemoteOperation(String username, String password) {
842 Intent existenceCheckIntent = new Intent();
843 existenceCheckIntent.setAction(OperationsService.ACTION_EXISTENCE_CHECK);
844 existenceCheckIntent.putExtra(OperationsService.EXTRA_SERVER_URL, mServerInfo.mBaseUrl);
845 existenceCheckIntent.putExtra(OperationsService.EXTRA_REMOTE_PATH, "/");
846 existenceCheckIntent.putExtra(OperationsService.EXTRA_USERNAME, username);
847 existenceCheckIntent.putExtra(OperationsService.EXTRA_PASSWORD, password);
848 existenceCheckIntent.putExtra(OperationsService.EXTRA_AUTH_TOKEN, mAuthToken);
849
850 if (mOperationsServiceBinder != null) {
851 //Log_OC.wtf(TAG, "starting existenceCheckRemoteOperation..." );
852 mWaitingForOpId = mOperationsServiceBinder.newOperation(existenceCheckIntent);
853 }
854 }
855
856 /**
857 * Starts the OAuth 'grant type' flow to get an access token, with
858 * a GET AUTHORIZATION request to the BUILT-IN authorization server.
859 */
860 private void startOauthorization() {
861 // be gentle with the user
862 mAuthStatusIcon = R.drawable.progress_small;
863 mAuthStatusText = R.string.oauth_login_connection;
864 showAuthStatus();
865
866 // GET AUTHORIZATION request
867 Uri uri = Uri.parse(mOAuthAuthEndpointText.getText().toString().trim());
868 Uri.Builder uriBuilder = uri.buildUpon();
869 uriBuilder.appendQueryParameter(OAuth2Constants.KEY_RESPONSE_TYPE, getString(R.string.oauth2_response_type));
870 uriBuilder.appendQueryParameter(OAuth2Constants.KEY_REDIRECT_URI, getString(R.string.oauth2_redirect_uri));
871 uriBuilder.appendQueryParameter(OAuth2Constants.KEY_CLIENT_ID, getString(R.string.oauth2_client_id));
872 uriBuilder.appendQueryParameter(OAuth2Constants.KEY_SCOPE, getString(R.string.oauth2_scope));
873 uri = uriBuilder.build();
874 Log_OC.d(TAG, "Starting browser to view " + uri.toString());
875 Intent i = new Intent(Intent.ACTION_VIEW, uri);
876 startActivity(i);
877 }
878
879
880 /**
881 * Starts the Web Single Sign On flow to get access to the root folder
882 * in the server.
883 */
884 private void startSamlBasedFederatedSingleSignOnAuthorization() {
885 // be gentle with the user
886 mAuthStatusIcon = R.drawable.progress_small;
887 mAuthStatusText = R.string.auth_connecting_auth_server;
888 showAuthStatus();
889 IndeterminateProgressDialog dialog =
890 IndeterminateProgressDialog.newInstance(R.string.auth_trying_to_login, true);
891 dialog.show(getSupportFragmentManager(), WAIT_DIALOG_TAG);
892
893 /// validate credentials accessing the root folder
894 accessRootFolderRemoteOperation("", "");
895
896 }
897
898 /**
899 * Callback method invoked when a RemoteOperation executed by this Activity finishes.
900 *
901 * Dispatches the operation flow to the right method.
902 */
903 @Override
904 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
905
906 if (operation instanceof GetServerInfoOperation) {
907 if (operation.hashCode() == mWaitingForOpId) {
908 onGetServerInfoFinish(result);
909 } // else nothing ; only the last check operation is considered;
910 // multiple can be started if the user amends a URL quickly
911
912 } else if (operation instanceof OAuth2GetAccessToken) {
913 onGetOAuthAccessTokenFinish(result);
914
915 } else if (operation instanceof ExistenceCheckRemoteOperation) {
916 //Log_OC.wtf(TAG, "received detection response through callback" );
917 if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType)) {
918 onSamlBasedFederatedSingleSignOnAuthorizationStart(result);
919
920 } else {
921 onAuthorizationCheckFinish(result);
922 }
923 } else if (operation instanceof GetRemoteUserNameOperation) {
924 onGetUserNameFinish(result);
925 }
926
927 }
928
929 private void onGetUserNameFinish(RemoteOperationResult result) {
930 mWaitingForOpId = Long.MAX_VALUE;
931 if (result.isSuccess()) {
932 boolean success = false;
933 String username = (String) result.getData().get(0);
934
935 if ( mAction == ACTION_CREATE) {
936 mUsernameInput.setText(username);
937 success = createAccount();
938 } else {
939
940 if (!mUsernameInput.getText().toString().equals(username)) {
941 // fail - not a new account, but an existing one; disallow
942 result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_THE_SAME);
943 /*
944 OwnCloudClientManagerFactory.getDefaultSingleton().removeClientFor(
945 new OwnCloudAccount(
946 Uri.parse(mServerInfo.mBaseUrl),
947 OwnCloudCredentialsFactory.newSamlSsoCredentials(mAuthToken))
948 );
949 */
950 mAuthToken = "";
951 updateAuthStatusIconAndText(result);
952 showAuthStatus();
953 Log_OC.d(TAG, result.getLogMessage());
954 } else {
955 updateToken();
956 success = true;
957 }
958 }
959
960 if (success)
961 finish();
962 } else {
963 updateStatusIconFailUserName();
964 showAuthStatus();
965 Log_OC.e(TAG, "Access to user name failed: " + result.getLogMessage());
966 }
967
968 }
969
970 private void onSamlBasedFederatedSingleSignOnAuthorizationStart(RemoteOperationResult result) {
971 mWaitingForOpId = Long.MAX_VALUE;
972 dismissDialog(WAIT_DIALOG_TAG);
973
974 if (result.isIdPRedirection()) {
975 String url = result.getRedirectedLocation();
976 String targetUrl = mServerInfo.mBaseUrl
977 + AccountUtils.getWebdavPath(mServerInfo.mVersion, mAuthTokenType);
978
979 // Show dialog
980 SamlWebViewDialog dialog = SamlWebViewDialog.newInstance(url, targetUrl);
981 dialog.show(getSupportFragmentManager(), SAML_DIALOG_TAG);
982
983 mAuthStatusIcon = 0;
984 mAuthStatusText = 0;
985
986 } else {
987 mAuthStatusIcon = R.drawable.common_error;
988 mAuthStatusText = R.string.auth_unsupported_auth_method;
989
990 }
991 showAuthStatus();
992 }
993
994
995 /**
996 * Processes the result of the server check performed when the user finishes the enter of the
997 * server URL.
998 *
999 * @param operation Server check performed.
1000 * @param result Result of the check.
1001 */
1002 private void onGetServerInfoFinish(RemoteOperationResult result) {
1003 /// update activity state
1004 mServerIsChecked = true;
1005 mWaitingForOpId = Long.MAX_VALUE;
1006
1007 // update server status, but don't show it yet
1008 updateServerStatusIconAndText(result);
1009
1010 if (result.isSuccess()) {
1011 /// SUCCESS means:
1012 // 1. connection succeeded, and we know if it's SSL or not
1013 // 2. server is installed
1014 // 3. we got the server version
1015 // 4. we got the authentication method required by the server
1016 mServerInfo = (GetServerInfoOperation.ServerInfo) (result.getData().get(0));
1017
1018 if (!authSupported(mServerInfo.mAuthMethod)) {
1019
1020 updateServerStatusIconNoRegularAuth(); // overrides updateServerStatusIconAndText()
1021 mServerIsValid = false;
1022
1023 } else {
1024 mServerIsValid = true;
1025 }
1026
1027 } else {
1028 mServerIsValid = false;
1029 }
1030
1031 // refresh UI
1032 showRefreshButton(!mServerIsValid);
1033 showServerStatus();
1034 mOkButton.setEnabled(mServerIsValid);
1035
1036 /// very special case (TODO: move to a common place for all the remote operations)
1037 if (result.getCode() == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) {
1038 showUntrustedCertDialog(result);
1039 }
1040 }
1041
1042
1043 private boolean authSupported(AuthenticationMethod authMethod) {
1044 String basic = AccountTypeUtils.getAuthTokenTypePass(MainApp.getAccountType());
1045 String oAuth = AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType());
1046 String saml = AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType());
1047
1048 return (( mAuthTokenType.equals(basic) &&
1049 authMethod.equals(AuthenticationMethod.BASIC_HTTP_AUTH) ) ||
1050 ( mAuthTokenType.equals(oAuth) &&
1051 authMethod.equals(AuthenticationMethod.BEARER_TOKEN)) ||
1052 ( mAuthTokenType.equals(saml) &&
1053 authMethod.equals(AuthenticationMethod.SAML_WEB_SSO))
1054 );
1055 }
1056
1057
1058 // TODO remove, if possible
1059 private String normalizeUrl(String url, boolean sslWhenUnprefixed) {
1060 if (url != null && url.length() > 0) {
1061 url = url.trim();
1062 if (!url.toLowerCase().startsWith("http://") &&
1063 !url.toLowerCase().startsWith("https://")) {
1064 if (sslWhenUnprefixed) {
1065 url = "https://" + url;
1066 } else {
1067 url = "http://" + url;
1068 }
1069 }
1070
1071 url = trimUrlWebdav(url);
1072
1073 if (url.endsWith("/")) {
1074 url = url.substring(0, url.length() - 1);
1075 }
1076
1077 }
1078 return (url != null ? url : "");
1079 }
1080
1081
1082 // TODO remove, if possible
1083 private String trimUrlWebdav(String url){
1084 if(url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_4_0)){
1085 url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_4_0.length());
1086 } else if(url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_2_0)){
1087 url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_2_0.length());
1088 } else if (url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_1_2)){
1089 url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_1_2.length());
1090 }
1091 return (url != null ? url : "");
1092 }
1093
1094
1095 /**
1096 * Chooses the right icon and text to show to the user for the received operation result.
1097 *
1098 * @param result Result of a remote operation performed in this activity
1099 */
1100 private void updateServerStatusIconAndText(RemoteOperationResult result) {
1101 mServerStatusIcon = R.drawable.common_error; // the most common case in the switch below
1102
1103 switch (result.getCode()) {
1104 case OK_SSL:
1105 mServerStatusIcon = android.R.drawable.ic_secure;
1106 mServerStatusText = R.string.auth_secure_connection;
1107 break;
1108
1109 case OK_NO_SSL:
1110 case OK:
1111 if (mHostUrlInput.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1112 mServerStatusText = R.string.auth_connection_established;
1113 mServerStatusIcon = R.drawable.ic_ok;
1114 } else {
1115 mServerStatusText = R.string.auth_nossl_plain_ok_title;
1116 mServerStatusIcon = android.R.drawable.ic_partial_secure;
1117 }
1118 break;
1119
1120 case NO_NETWORK_CONNECTION:
1121 mServerStatusIcon = R.drawable.no_network;
1122 mServerStatusText = R.string.auth_no_net_conn_title;
1123 break;
1124
1125 case SSL_RECOVERABLE_PEER_UNVERIFIED:
1126 mServerStatusText = R.string.auth_ssl_unverified_server_title;
1127 break;
1128 case BAD_OC_VERSION:
1129 mServerStatusText = R.string.auth_bad_oc_version_title;
1130 break;
1131 case WRONG_CONNECTION:
1132 mServerStatusText = R.string.auth_wrong_connection_title;
1133 break;
1134 case TIMEOUT:
1135 mServerStatusText = R.string.auth_timeout_title;
1136 break;
1137 case INCORRECT_ADDRESS:
1138 mServerStatusText = R.string.auth_incorrect_address_title;
1139 break;
1140 case SSL_ERROR:
1141 mServerStatusText = R.string.auth_ssl_general_error_title;
1142 break;
1143 case UNAUTHORIZED:
1144 mServerStatusText = R.string.auth_unauthorized;
1145 break;
1146 case HOST_NOT_AVAILABLE:
1147 mServerStatusText = R.string.auth_unknown_host_title;
1148 break;
1149 case INSTANCE_NOT_CONFIGURED:
1150 mServerStatusText = R.string.auth_not_configured_title;
1151 break;
1152 case FILE_NOT_FOUND:
1153 mServerStatusText = R.string.auth_incorrect_path_title;
1154 break;
1155 case OAUTH2_ERROR:
1156 mServerStatusText = R.string.auth_oauth_error;
1157 break;
1158 case OAUTH2_ERROR_ACCESS_DENIED:
1159 mServerStatusText = R.string.auth_oauth_error_access_denied;
1160 break;
1161 case UNHANDLED_HTTP_CODE:
1162 case UNKNOWN_ERROR:
1163 mServerStatusText = R.string.auth_unknown_error_title;
1164 break;
1165 case OK_REDIRECT_TO_NON_SECURE_CONNECTION:
1166 mServerStatusIcon = android.R.drawable.ic_partial_secure;
1167 mServerStatusText = R.string.auth_redirect_non_secure_connection_title;
1168 break;
1169 default:
1170 mServerStatusText = 0;
1171 mServerStatusIcon = 0;
1172 }
1173 }
1174
1175
1176 /**
1177 * Chooses the right icon and text to show to the user for the received operation result.
1178 *
1179 * @param result Result of a remote operation performed in this activity
1180 */
1181 private void updateAuthStatusIconAndText(RemoteOperationResult result) {
1182 mAuthStatusIcon = R.drawable.common_error; // the most common case in the switch below
1183
1184 switch (result.getCode()) {
1185 case OK_SSL:
1186 mAuthStatusIcon = android.R.drawable.ic_secure;
1187 mAuthStatusText = R.string.auth_secure_connection;
1188 break;
1189
1190 case OK_NO_SSL:
1191 case OK:
1192 if (mHostUrlInput.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1193 mAuthStatusText = R.string.auth_connection_established;
1194 mAuthStatusIcon = R.drawable.ic_ok;
1195 } else {
1196 mAuthStatusText = R.string.auth_nossl_plain_ok_title;
1197 mAuthStatusIcon = android.R.drawable.ic_partial_secure;
1198 }
1199 break;
1200
1201 case NO_NETWORK_CONNECTION:
1202 mAuthStatusIcon = R.drawable.no_network;
1203 mAuthStatusText = R.string.auth_no_net_conn_title;
1204 break;
1205
1206 case SSL_RECOVERABLE_PEER_UNVERIFIED:
1207 mAuthStatusText = R.string.auth_ssl_unverified_server_title;
1208 break;
1209 case BAD_OC_VERSION:
1210 mAuthStatusText = R.string.auth_bad_oc_version_title;
1211 break;
1212 case WRONG_CONNECTION:
1213 mAuthStatusText = R.string.auth_wrong_connection_title;
1214 break;
1215 case TIMEOUT:
1216 mAuthStatusText = R.string.auth_timeout_title;
1217 break;
1218 case INCORRECT_ADDRESS:
1219 mAuthStatusText = R.string.auth_incorrect_address_title;
1220 break;
1221 case SSL_ERROR:
1222 mAuthStatusText = R.string.auth_ssl_general_error_title;
1223 break;
1224 case UNAUTHORIZED:
1225 mAuthStatusText = R.string.auth_unauthorized;
1226 break;
1227 case HOST_NOT_AVAILABLE:
1228 mAuthStatusText = R.string.auth_unknown_host_title;
1229 break;
1230 case INSTANCE_NOT_CONFIGURED:
1231 mAuthStatusText = R.string.auth_not_configured_title;
1232 break;
1233 case FILE_NOT_FOUND:
1234 mAuthStatusText = R.string.auth_incorrect_path_title;
1235 break;
1236 case OAUTH2_ERROR:
1237 mAuthStatusText = R.string.auth_oauth_error;
1238 break;
1239 case OAUTH2_ERROR_ACCESS_DENIED:
1240 mAuthStatusText = R.string.auth_oauth_error_access_denied;
1241 break;
1242 case ACCOUNT_NOT_NEW:
1243 mAuthStatusText = R.string.auth_account_not_new;
1244 break;
1245 case ACCOUNT_NOT_THE_SAME:
1246 mAuthStatusText = R.string.auth_account_not_the_same;
1247 break;
1248 case UNHANDLED_HTTP_CODE:
1249 case UNKNOWN_ERROR:
1250 mAuthStatusText = R.string.auth_unknown_error_title;
1251 break;
1252 default:
1253 mAuthStatusText = 0;
1254 mAuthStatusIcon = 0;
1255 }
1256 }
1257
1258
1259 private void updateStatusIconFailUserName(){
1260 mAuthStatusIcon = R.drawable.common_error;
1261 mAuthStatusText = R.string.auth_fail_get_user_name;
1262 }
1263
1264 private void updateServerStatusIconNoRegularAuth(){
1265 mServerStatusIcon = R.drawable.common_error;
1266 mServerStatusText = R.string.auth_can_not_auth_against_server;
1267 }
1268
1269 /**
1270 * Processes the result of the request for and access token send
1271 * to an OAuth authorization server.
1272 *
1273 * @param result Result of the operation.
1274 */
1275 private void onGetOAuthAccessTokenFinish(RemoteOperationResult result) {
1276 mWaitingForOpId = Long.MAX_VALUE;
1277 dismissDialog(WAIT_DIALOG_TAG);
1278
1279 if (result.isSuccess()) {
1280 /// be gentle with the user
1281 IndeterminateProgressDialog dialog =
1282 IndeterminateProgressDialog.newInstance(R.string.auth_trying_to_login, true);
1283 dialog.show(getSupportFragmentManager(), WAIT_DIALOG_TAG);
1284
1285 /// time to test the retrieved access token on the ownCloud server
1286 @SuppressWarnings("unchecked")
1287 Map<String, String> tokens = (Map<String, String>)(result.getData().get(0));
1288 mAuthToken = tokens.get(OAuth2Constants.KEY_ACCESS_TOKEN);
1289 //mAuthToken = ((OAuth2GetAccessToken)operation).getResultTokenMap().get(OAuth2Constants.KEY_ACCESS_TOKEN);
1290 Log_OC.d(TAG, "Got ACCESS TOKEN: " + mAuthToken);
1291
1292 accessRootFolderRemoteOperation("", "");
1293
1294 } else {
1295 updateAuthStatusIconAndText(result);
1296 showAuthStatus();
1297 Log_OC.d(TAG, "Access failed: " + result.getLogMessage());
1298 }
1299 }
1300
1301
1302 /**
1303 * Processes the result of the access check performed to try the user credentials.
1304 *
1305 * Creates a new account through the AccountManager.
1306 *
1307 * @param operation Access check performed.
1308 * @param result Result of the operation.
1309 */
1310 private void onAuthorizationCheckFinish(RemoteOperationResult result) {
1311 mWaitingForOpId = Long.MAX_VALUE;
1312 dismissDialog(WAIT_DIALOG_TAG);
1313
1314 if (result.isSuccess()) {
1315 Log_OC.d(TAG, "Successful access - time to save the account");
1316
1317 boolean success = false;
1318 if (mAction == ACTION_CREATE) {
1319 success = createAccount();
1320
1321 } else {
1322 updateToken();
1323 success = true;
1324 }
1325
1326 if (success) {
1327 finish();
1328 }
1329
1330 } else if (result.isServerFail() || result.isException()) {
1331 /// server errors or exceptions in authorization take to requiring a new check of
1332 /// the server
1333 mServerIsChecked = true;
1334 mServerIsValid = false;
1335 mServerInfo = new GetServerInfoOperation.ServerInfo();
1336
1337 // update status icon and text
1338 updateServerStatusIconAndText(result);
1339 showServerStatus();
1340 mAuthStatusIcon = 0;
1341 mAuthStatusText = 0;
1342 showAuthStatus();
1343
1344 // update input controls state
1345 showRefreshButton(true);
1346 mOkButton.setEnabled(false);
1347
1348 // very special case (TODO: move to a common place for all the remote operations) (dangerous here?)
1349 if (result.getCode() == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) {
1350 showUntrustedCertDialog(result);
1351 }
1352
1353 } else { // authorization fail due to client side - probably wrong credentials
1354 updateAuthStatusIconAndText(result);
1355 showAuthStatus();
1356 Log_OC.d(TAG, "Access failed: " + result.getLogMessage());
1357 }
1358 }
1359
1360
1361
1362
1363 /**
1364 * Sets the proper response to get that the Account Authenticator that started this activity saves
1365 * a new authorization token for mAccount.
1366 */
1367 private void updateToken() {
1368 Bundle response = new Bundle();
1369 response.putString(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
1370 response.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccount.type);
1371
1372 if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).equals(mAuthTokenType)) {
1373 response.putString(AccountManager.KEY_AUTHTOKEN, mAuthToken);
1374 // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention
1375 mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);
1376
1377 } else if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType)) {
1378
1379 response.putString(AccountManager.KEY_AUTHTOKEN, mAuthToken);
1380 // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention
1381 mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);
1382
1383 } else {
1384 response.putString(AccountManager.KEY_AUTHTOKEN, mPasswordInput.getText().toString());
1385 mAccountMgr.setPassword(mAccount, mPasswordInput.getText().toString());
1386 }
1387 setAccountAuthenticatorResult(response);
1388
1389 }
1390
1391
1392 /**
1393 * Creates a new account through the Account Authenticator that started this activity.
1394 *
1395 * This makes the account permanent.
1396 *
1397 * TODO Decide how to name the OAuth accounts
1398 */
1399 private boolean createAccount() {
1400 /// create and save new ownCloud account
1401 boolean isOAuth = AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).equals(mAuthTokenType);
1402 boolean isSaml = AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType);
1403
1404 Uri uri = Uri.parse(mServerInfo.mBaseUrl);
1405 String username = mUsernameInput.getText().toString().trim();
1406 if (isOAuth) {
1407 username = "OAuth_user" + (new java.util.Random(System.currentTimeMillis())).nextLong();
1408 }
1409 String accountName = com.owncloud.android.lib.common.accounts.AccountUtils.
1410 buildAccountName(uri, username);
1411 Account newAccount = new Account(accountName, MainApp.getAccountType());
1412 if (AccountUtils.exists(newAccount, getApplicationContext())) {
1413 // fail - not a new account, but an existing one; disallow
1414 RemoteOperationResult result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_NEW);
1415 updateAuthStatusIconAndText(result);
1416 showAuthStatus();
1417 Log_OC.d(TAG, result.getLogMessage());
1418 return false;
1419
1420 } else {
1421 mAccount = newAccount;
1422
1423 if (isOAuth || isSaml) {
1424 mAccountMgr.addAccountExplicitly(mAccount, "", null); // with external authorizations, the password is never input in the app
1425 } else {
1426 mAccountMgr.addAccountExplicitly(mAccount, mPasswordInput.getText().toString(), null);
1427 }
1428
1429 /// add the new account as default in preferences, if there is none already
1430 Account defaultAccount = AccountUtils.getCurrentOwnCloudAccount(this);
1431 if (defaultAccount == null) {
1432 SharedPreferences.Editor editor = PreferenceManager
1433 .getDefaultSharedPreferences(this).edit();
1434 editor.putString("select_oc_account", accountName);
1435 editor.commit();
1436 }
1437
1438 /// prepare result to return to the Authenticator
1439 // TODO check again what the Authenticator makes with it; probably has the same effect as addAccountExplicitly, but it's not well done
1440 final Intent intent = new Intent();
1441 intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, MainApp.getAccountType());
1442 intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
1443 /*if (!isOAuth)
1444 intent.putExtra(AccountManager.KEY_AUTHTOKEN, MainApp.getAccountType()); */
1445 intent.putExtra(AccountManager.KEY_USERDATA, username);
1446 if (isOAuth || isSaml) {
1447 mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);
1448 }
1449 /// add user data to the new account; TODO probably can be done in the last parameter addAccountExplicitly, or in KEY_USERDATA
1450 mAccountMgr.setUserData(mAccount, Constants.KEY_OC_VERSION, mServerInfo.mVersion.getVersion());
1451 mAccountMgr.setUserData(mAccount, Constants.KEY_OC_BASE_URL, mServerInfo.mBaseUrl);
1452
1453 if (isSaml) {
1454 mAccountMgr.setUserData(mAccount, Constants.KEY_SUPPORTS_SAML_WEB_SSO, "TRUE");
1455 } else if (isOAuth) {
1456 mAccountMgr.setUserData(mAccount, Constants.KEY_SUPPORTS_OAUTH2, "TRUE");
1457 }
1458
1459 setAccountAuthenticatorResult(intent.getExtras());
1460 setResult(RESULT_OK, intent);
1461
1462 return true;
1463 }
1464 }
1465
1466
1467 /**
1468 * Starts and activity to open the 'new account' page in the ownCloud web site
1469 *
1470 * @param view 'Account register' button
1471 */
1472 public void onRegisterClick(View view) {
1473 Intent register = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.welcome_link_url)));
1474 setResult(RESULT_CANCELED);
1475 startActivity(register);
1476 }
1477
1478
1479 /**
1480 * Updates the content and visibility state of the icon and text associated
1481 * to the last check on the ownCloud server.
1482 *
1483 * @param serverStatusText Resource identifier of the text to show.
1484 * @param serverStatusIcon Resource identifier of the icon to show.
1485 */
1486 private void showServerStatus() {
1487 if (mServerStatusIcon == 0 && mServerStatusText == 0) {
1488 mServerStatusView.setVisibility(View.INVISIBLE);
1489
1490 } else {
1491 mServerStatusView.setText(mServerStatusText);
1492 mServerStatusView.setCompoundDrawablesWithIntrinsicBounds(mServerStatusIcon, 0, 0, 0);
1493 mServerStatusView.setVisibility(View.VISIBLE);
1494 }
1495
1496 }
1497
1498
1499 /**
1500 * Updates the content and visibility state of the icon and text associated
1501 * to the interactions with the OAuth authorization server.
1502 */
1503 private void showAuthStatus() {
1504 if (mAuthStatusIcon == 0 && mAuthStatusText == 0) {
1505 mAuthStatusView.setVisibility(View.INVISIBLE);
1506
1507 } else {
1508 mAuthStatusView.setText(mAuthStatusText);
1509 mAuthStatusView.setCompoundDrawablesWithIntrinsicBounds(mAuthStatusIcon, 0, 0, 0);
1510 mAuthStatusView.setVisibility(View.VISIBLE);
1511 }
1512 }
1513
1514
1515 private void showRefreshButton (boolean show) {
1516 if (show) {
1517 mRefreshButton.setVisibility(View.VISIBLE);
1518 } else {
1519 mRefreshButton.setVisibility(View.GONE);
1520 }
1521 }
1522
1523 /**
1524 * Called when the refresh button in the input field for ownCloud host is clicked.
1525 *
1526 * Performs a new check on the URL in the input field.
1527 *
1528 * @param view Refresh 'button'
1529 */
1530 public void onRefreshClick(View view) {
1531 checkOcServer();
1532 }
1533
1534
1535 /**
1536 * Called when the eye icon in the password field is clicked.
1537 *
1538 * Toggles the visibility of the password in the field.
1539 */
1540 public void onViewPasswordClick() {
1541 int selectionStart = mPasswordInput.getSelectionStart();
1542 int selectionEnd = mPasswordInput.getSelectionEnd();
1543 if (isPasswordVisible()) {
1544 hidePassword();
1545 } else {
1546 showPassword();
1547 }
1548 mPasswordInput.setSelection(selectionStart, selectionEnd);
1549 }
1550
1551
1552 /**
1553 * Called when the checkbox for OAuth authorization is clicked.
1554 *
1555 * Hides or shows the input fields for user & password.
1556 *
1557 * @param view 'View password' 'button'
1558 */
1559 public void onCheckClick(View view) {
1560 CheckBox oAuth2Check = (CheckBox)view;
1561 if (oAuth2Check.isChecked()) {
1562 mAuthTokenType = AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType());
1563 } else {
1564 mAuthTokenType = AccountTypeUtils.getAuthTokenTypePass(MainApp.getAccountType());
1565 }
1566 updateAuthenticationPreFragmentVisibility();
1567 }
1568
1569
1570 /**
1571 * Called when the 'action' button in an IME is pressed ('enter' in software keyboard).
1572 *
1573 * Used to trigger the authentication check when the user presses 'enter' after writing the password,
1574 * or to throw the server test when the only field on screen is the URL input field.
1575 */
1576 @Override
1577 public boolean onEditorAction(TextView inputField, int actionId, KeyEvent event) {
1578 if (actionId == EditorInfo.IME_ACTION_DONE && inputField != null && inputField.equals(mPasswordInput)) {
1579 if (mOkButton.isEnabled()) {
1580 mOkButton.performClick();
1581 }
1582
1583 } else if (actionId == EditorInfo.IME_ACTION_NEXT && inputField != null && inputField.equals(mHostUrlInput)) {
1584 if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType)) {
1585 checkOcServer();
1586 }
1587 }
1588 return false; // always return false to grant that the software keyboard is hidden anyway
1589 }
1590
1591
1592 private abstract static class RightDrawableOnTouchListener implements OnTouchListener {
1593
1594 private int fuzz = 75;
1595
1596 /**
1597 * {@inheritDoc}
1598 */
1599 @Override
1600 public boolean onTouch(View view, MotionEvent event) {
1601 Drawable rightDrawable = null;
1602 if (view instanceof TextView) {
1603 Drawable[] drawables = ((TextView)view).getCompoundDrawables();
1604 if (drawables.length > 2) {
1605 rightDrawable = drawables[2];
1606 }
1607 }
1608 if (rightDrawable != null) {
1609 final int x = (int) event.getX();
1610 final int y = (int) event.getY();
1611 final Rect bounds = rightDrawable.getBounds();
1612 if (x >= (view.getRight() - bounds.width() - fuzz) && x <= (view.getRight() - view.getPaddingRight() + fuzz)
1613 && y >= (view.getPaddingTop() - fuzz) && y <= (view.getHeight() - view.getPaddingBottom()) + fuzz) {
1614
1615 return onDrawableTouch(event);
1616 }
1617 }
1618 return false;
1619 }
1620
1621 public abstract boolean onDrawableTouch(final MotionEvent event);
1622 }
1623
1624
1625 private void getRemoteUserNameOperation(String sessionCookie, boolean followRedirects) {
1626
1627 Intent getUserNameIntent = new Intent();
1628 getUserNameIntent.setAction(OperationsService.ACTION_GET_USER_NAME);
1629 getUserNameIntent.putExtra(OperationsService.EXTRA_SERVER_URL, mServerInfo.mBaseUrl);
1630 getUserNameIntent.putExtra(OperationsService.EXTRA_COOKIE, sessionCookie);
1631
1632 if (mOperationsServiceBinder != null) {
1633 //Log_OC.wtf(TAG, "starting getRemoteUserNameOperation..." );
1634 mWaitingForOpId = mOperationsServiceBinder.newOperation(getUserNameIntent);
1635 }
1636 }
1637
1638
1639 @Override
1640 public void onSsoFinished(String sessionCookie) {
1641 if (sessionCookie != null && sessionCookie.length() > 0) {
1642 Log_OC.d(TAG, "Successful SSO - time to save the account");
1643 mAuthToken = sessionCookie;
1644 getRemoteUserNameOperation(sessionCookie, true);
1645 Fragment fd = getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG);
1646 if (fd != null && fd instanceof SherlockDialogFragment) {
1647 Dialog d = ((SherlockDialogFragment)fd).getDialog();
1648 if (d != null && d.isShowing()) {
1649 d.dismiss();
1650 }
1651 }
1652
1653 } else {
1654 // TODO - show fail
1655 Log_OC.d(TAG, "SSO failed");
1656 }
1657
1658 }
1659
1660 @Override
1661 public boolean onTouchEvent(MotionEvent event) {
1662 if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType) &&
1663 mHostUrlInput.hasFocus() && event.getAction() == MotionEvent.ACTION_DOWN) {
1664 checkOcServer();
1665 }
1666 return super.onTouchEvent(event);
1667 }
1668
1669
1670 /**
1671 * Show untrusted cert dialog
1672 */
1673 public void showUntrustedCertDialog(X509Certificate x509Certificate, SslError error, SslErrorHandler handler) {
1674 // Show a dialog with the certificate info
1675 SslUntrustedCertDialog dialog = null;
1676 if (x509Certificate == null) {
1677 dialog = SslUntrustedCertDialog.newInstanceForEmptySslError(error, handler);
1678 } else {
1679 dialog = SslUntrustedCertDialog.newInstanceForFullSslError(x509Certificate, error, handler);
1680 }
1681 FragmentManager fm = getSupportFragmentManager();
1682 FragmentTransaction ft = fm.beginTransaction();
1683 ft.addToBackStack(null);
1684 dialog.show(ft, UNTRUSTED_CERT_DIALOG_TAG);
1685 }
1686
1687 /**
1688 * Show untrusted cert dialog
1689 */
1690 private void showUntrustedCertDialog(RemoteOperationResult result) {
1691 // Show a dialog with the certificate info
1692 SslUntrustedCertDialog dialog = SslUntrustedCertDialog.newInstanceForFullSslError((CertificateCombinedException)result.getException());
1693 FragmentManager fm = getSupportFragmentManager();
1694 FragmentTransaction ft = fm.beginTransaction();
1695 ft.addToBackStack(null);
1696 dialog.show(ft, UNTRUSTED_CERT_DIALOG_TAG);
1697
1698 }
1699
1700 /**
1701 * Called from SslValidatorDialog when a new server certificate was correctly saved.
1702 */
1703 public void onSavedCertificate() {
1704 Fragment fd = getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG);
1705 if (fd == null) {
1706 // if SAML dialog is not shown, the SslDialog was shown due to an SSL error in the server check
1707 checkOcServer();
1708 }
1709 }
1710
1711 /**
1712 * Called from SslValidatorDialog when a new server certificate could not be saved
1713 * when the user requested it.
1714 */
1715 @Override
1716 public void onFailedSavingCertificate() {
1717 dismissDialog(SAML_DIALOG_TAG);
1718 Toast.makeText(this, R.string.ssl_validator_not_saved, Toast.LENGTH_LONG).show();
1719 }
1720
1721 @Override
1722 public void onCancelCertificate() {
1723 dismissDialog(SAML_DIALOG_TAG);
1724 }
1725
1726
1727 private void doOnResumeAndBound() {
1728 //Log_OC.wtf(TAG, "registering to listen for operation callbacks" );
1729 mOperationsServiceBinder.addOperationListener(AuthenticatorActivity.this, mHandler);
1730 if (mWaitingForOpId <= Integer.MAX_VALUE) {
1731 mOperationsServiceBinder.dispatchResultIfFinished((int)mWaitingForOpId, this);
1732 }
1733
1734 if (mPendingAutoCheck) {
1735 checkOcServer();
1736 }
1737 }
1738
1739
1740 private void dismissDialog(String dialogTag){
1741 Fragment frag = getSupportFragmentManager().findFragmentByTag(dialogTag);
1742 if (frag != null && frag instanceof SherlockDialogFragment) {
1743 SherlockDialogFragment dialog = (SherlockDialogFragment) frag;
1744 dialog.dismiss();
1745 }
1746 }
1747
1748
1749 /**
1750 * Implements callback methods for service binding.
1751 */
1752 private class OperationsServiceConnection implements ServiceConnection {
1753
1754 @Override
1755 public void onServiceConnected(ComponentName component, IBinder service) {
1756 if (component.equals(new ComponentName(AuthenticatorActivity.this, OperationsService.class))) {
1757 //Log_OC.wtf(TAG, "Operations service connected");
1758 mOperationsServiceBinder = (OperationsServiceBinder) service;
1759
1760 doOnResumeAndBound();
1761
1762 } else {
1763 return;
1764 }
1765
1766 }
1767
1768 @Override
1769 public void onServiceDisconnected(ComponentName component) {
1770 if (component.equals(new ComponentName(AuthenticatorActivity.this, OperationsService.class))) {
1771 Log_OC.e(TAG, "Operations service crashed");
1772 mOperationsServiceBinder = null;
1773 }
1774 }
1775
1776 }
1777
1778 }