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