AuthenticatorActivity.java 53 KB

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