bd0ddb0b243e1387897b325ef58d049dbed79c3c
[pub/Android/ownCloud.git] / src / eu / alefzero / owncloud / ui / activity / AuthenticatorActivity.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 *
17 */
18
19 package eu.alefzero.owncloud.ui.activity;
20
21 import java.net.MalformedURLException;
22 import java.net.URL;
23
24 import android.accounts.Account;
25 import android.accounts.AccountAuthenticatorActivity;
26 import android.accounts.AccountManager;
27 import android.app.Dialog;
28 import android.app.ProgressDialog;
29 import android.content.ContentResolver;
30 import android.content.DialogInterface;
31 import android.content.Intent;
32 import android.content.SharedPreferences;
33 import android.os.Bundle;
34 import android.os.Handler;
35 import android.preference.PreferenceManager;
36 import android.text.InputType;
37 import android.util.Log;
38 import android.view.View;
39 import android.view.View.OnClickListener;
40 import android.view.View.OnFocusChangeListener;
41 import android.view.Window;
42 import android.widget.ImageView;
43 import android.widget.TextView;
44 import eu.alefzero.owncloud.AccountUtils;
45 import eu.alefzero.owncloud.R;
46 import eu.alefzero.owncloud.authenticator.AccountAuthenticator;
47 import eu.alefzero.owncloud.authenticator.AuthenticationRunnable;
48 import eu.alefzero.owncloud.authenticator.ConnectionCheckerRunnable;
49 import eu.alefzero.owncloud.authenticator.OnAuthenticationResultListener;
50 import eu.alefzero.owncloud.authenticator.OnConnectCheckListener;
51 import eu.alefzero.owncloud.db.ProviderMeta.ProviderTableMeta;
52 import eu.alefzero.owncloud.extensions.ExtensionsAvailableActivity;
53 import eu.alefzero.owncloud.utils.OwnCloudVersion;
54
55 /**
56 * This Activity is used to add an ownCloud account to the App
57 *
58 * @author Bartek Przybylski
59 *
60 */
61 public class AuthenticatorActivity extends AccountAuthenticatorActivity
62 implements OnAuthenticationResultListener, OnConnectCheckListener,
63 OnFocusChangeListener, OnClickListener {
64 private static final int DIALOG_LOGIN_PROGRESS = 0;
65
66 private static final String TAG = "AuthActivity";
67
68 private Thread mAuthThread;
69 private AuthenticationRunnable mAuthRunnable;
70 private ConnectionCheckerRunnable mConnChkRunnable;
71 private final Handler mHandler = new Handler();
72 private String mBaseUrl;
73
74 private static final String STATUS_TEXT = "STATUS_TEXT";
75 private static final String STATUS_ICON = "STATUS_ICON";
76 private static final String STATUS_CORRECT = "STATUS_CORRECT";
77 private static final String IS_SSL_CONN = "IS_SSL_CONN";
78 private int mStatusText, mStatusIcon;
79 private boolean mStatusCorrect, mIsSslConn;
80
81 public static final String PARAM_USERNAME = "param_Username";
82 public static final String PARAM_HOSTNAME = "param_Hostname";
83
84 @Override
85 protected void onCreate(Bundle savedInstanceState) {
86 super.onCreate(savedInstanceState);
87 getWindow().requestFeature(Window.FEATURE_NO_TITLE);
88 setContentView(R.layout.account_setup);
89 ImageView iv = (ImageView) findViewById(R.id.refreshButton);
90 ImageView iv2 = (ImageView) findViewById(R.id.viewPassword);
91 TextView tv = (TextView) findViewById(R.id.host_URL);
92 TextView tv2 = (TextView) findViewById(R.id.account_password);
93
94 if (savedInstanceState != null) {
95 mStatusIcon = savedInstanceState.getInt(STATUS_ICON);
96 mStatusText = savedInstanceState.getInt(STATUS_TEXT);
97 mStatusCorrect = savedInstanceState.getBoolean(STATUS_CORRECT);
98 mIsSslConn = savedInstanceState.getBoolean(IS_SSL_CONN);
99 setResultIconAndText(mStatusIcon, mStatusText);
100 findViewById(R.id.buttonOK).setEnabled(mStatusCorrect);
101 if (!mStatusCorrect)
102 iv.setVisibility(View.VISIBLE);
103 else
104 iv.setVisibility(View.INVISIBLE);
105
106 } else {
107 mStatusText = mStatusIcon = 0;
108 mStatusCorrect = false;
109 mIsSslConn = false;
110 }
111 iv.setOnClickListener(this);
112 iv2.setOnClickListener(this);
113 tv.setOnFocusChangeListener(this);
114 tv2.setOnFocusChangeListener(this);
115 }
116
117 @Override
118 protected void onSaveInstanceState(Bundle outState) {
119 outState.putInt(STATUS_ICON, mStatusIcon);
120 outState.putInt(STATUS_TEXT, mStatusText);
121 outState.putBoolean(STATUS_CORRECT, mStatusCorrect);
122 super.onSaveInstanceState(outState);
123 }
124
125 @Override
126 protected Dialog onCreateDialog(int id) {
127 Dialog dialog = null;
128 switch (id) {
129 case DIALOG_LOGIN_PROGRESS: {
130 ProgressDialog working_dialog = new ProgressDialog(this);
131 working_dialog.setMessage(getResources().getString(
132 R.string.auth_trying_to_login));
133 working_dialog.setIndeterminate(true);
134 working_dialog.setCancelable(true);
135 working_dialog
136 .setOnCancelListener(new DialogInterface.OnCancelListener() {
137 @Override
138 public void onCancel(DialogInterface dialog) {
139 Log.i(TAG, "Login canceled");
140 if (mAuthThread != null) {
141 mAuthThread.interrupt();
142 finish();
143 }
144 }
145 });
146 dialog = working_dialog;
147 break;
148 }
149 default:
150 Log.e(TAG, "Incorrect dialog called with id = " + id);
151 }
152 return dialog;
153 }
154
155 public void onAuthenticationResult(boolean success, String message) {
156 if (success) {
157 TextView username_text = (TextView) findViewById(R.id.account_username), password_text = (TextView) findViewById(R.id.account_password);
158
159 URL url;
160 try {
161 url = new URL(message);
162 } catch (MalformedURLException e) {
163 // should never happen
164 Log.e(getClass().getName(), "Malformed URL: " + message);
165 return;
166 }
167
168 String username = username_text.getText().toString().trim();
169 String accountName = username + "@" + url.getHost();
170 Account account = new Account(accountName,
171 AccountAuthenticator.ACCOUNT_TYPE);
172 AccountManager accManager = AccountManager.get(this);
173 accManager.addAccountExplicitly(account, password_text.getText()
174 .toString(), null);
175
176 // Add this account as default in the preferences, if there is none
177 // already
178 Account defaultAccount = AccountUtils
179 .getCurrentOwnCloudAccount(this);
180 if (defaultAccount == null) {
181 SharedPreferences.Editor editor = PreferenceManager
182 .getDefaultSharedPreferences(this).edit();
183 editor.putString("select_oc_account", accountName);
184 editor.commit();
185 }
186
187 final Intent intent = new Intent();
188 intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE,
189 AccountAuthenticator.ACCOUNT_TYPE);
190 intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, account.name);
191 intent.putExtra(AccountManager.KEY_AUTHTOKEN,
192 AccountAuthenticator.ACCOUNT_TYPE);
193 intent.putExtra(AccountManager.KEY_USERDATA, username);
194
195 accManager.setUserData(account, AccountAuthenticator.KEY_OC_URL,
196 url.toString());
197 accManager.setUserData(account,
198 AccountAuthenticator.KEY_OC_VERSION, mConnChkRunnable
199 .getDiscoveredVersion().toString());
200 accManager.setUserData(account,
201 AccountAuthenticator.KEY_OC_BASE_URL, mBaseUrl);
202
203 setAccountAuthenticatorResult(intent.getExtras());
204 setResult(RESULT_OK, intent);
205 Bundle bundle = new Bundle();
206 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
207 getContentResolver().startSync(ProviderTableMeta.CONTENT_URI,
208 bundle);
209
210 /*
211 * if
212 * (mConnChkRunnable.getDiscoveredVersion().compareTo(OwnCloudVersion
213 * .owncloud_v2) >= 0) { Intent i = new Intent(this,
214 * ExtensionsAvailableActivity.class); startActivity(i); }
215 */
216
217 finish();
218 } else {
219 dismissDialog(DIALOG_LOGIN_PROGRESS);
220 TextView tv = (TextView) findViewById(R.id.account_username);
221 tv.setError(message);
222 }
223 }
224 public void onCancelClick(View view) {
225 finish();
226 }
227
228 public void onOkClick(View view) {
229 String prefix = "";
230 String url = ((TextView) findViewById(R.id.host_URL)).getText()
231 .toString();
232 if (mIsSslConn) {
233 prefix = "https://";
234 } else {
235 prefix = "http://";
236 }
237 if (url.toLowerCase().startsWith("http://")
238 || url.toLowerCase().startsWith("https://")) {
239 prefix = "";
240 }
241 continueConnection(prefix);
242 }
243
244 private void continueConnection(String prefix) {
245 String url = ((TextView) findViewById(R.id.host_URL)).getText()
246 .toString();
247 String username = ((TextView) findViewById(R.id.account_username))
248 .getText().toString();
249 String password = ((TextView) findViewById(R.id.account_password))
250 .getText().toString();
251 if (url.endsWith("/"))
252 url = url.substring(0, url.length() - 1);
253
254 URL uri = null;
255 String webdav_path = AccountUtils.getWebdavPath(mConnChkRunnable
256 .getDiscoveredVersion());
257
258 try {
259 mBaseUrl = prefix + url;
260 String url_str = prefix + url + webdav_path;
261 uri = new URL(url_str);
262 } catch (MalformedURLException e) {
263 // should not happend
264 e.printStackTrace();
265 }
266
267 showDialog(DIALOG_LOGIN_PROGRESS);
268 mAuthRunnable = new AuthenticationRunnable(uri, username, password);
269 mAuthRunnable.setOnAuthenticationResultListener(this, mHandler);
270 mAuthThread = new Thread(mAuthRunnable);
271 mAuthThread.start();
272 }
273
274 @Override
275 public void onConnectionCheckResult(ResultType type) {
276 mStatusText = mStatusIcon = 0;
277 mStatusCorrect = false;
278 String t_url = ((TextView) findViewById(R.id.host_URL)).getText()
279 .toString().toLowerCase();
280
281 switch (type) {
282 case OK:
283 // ugly as hell
284 if (t_url.startsWith("http://") || t_url.startsWith("https://")) {
285 mIsSslConn = t_url.startsWith("http://") ? false : true;
286 mStatusIcon = R.drawable.ic_ok;
287 mStatusText = R.string.auth_connection_established;
288 mStatusCorrect = true;
289 } else {
290 mIsSslConn = true;
291 mStatusIcon = android.R.drawable.ic_secure;
292 mStatusText = R.string.auth_secure_connection;
293 mStatusCorrect = true;
294 }
295 break;
296 case OK_NO_SSL:
297 mStatusIcon = android.R.drawable.ic_secure;
298 mStatusText = R.string.auth_nossl_plain_ok_title;
299 mStatusCorrect = true;
300 mIsSslConn = false;
301 break;
302 case TIMEOUT:
303 case INORRECT_ADDRESS:
304 case SSL_INIT_ERROR:
305 case HOST_NOT_AVAILABLE:
306 mStatusIcon = R.drawable.common_error;
307 mStatusText = R.string.auth_unknow_host_title;
308 break;
309 case NO_NETWORK_CONNECTION:
310 mStatusIcon = R.drawable.no_network;
311 mStatusText = R.string.auth_no_net_conn_title;
312 break;
313 case INSTANCE_NOT_CONFIGURED:
314 mStatusIcon = R.drawable.common_error;
315 mStatusText = R.string.auth_not_configured_title;
316 break;
317 case UNKNOWN_ERROR:
318 mStatusIcon = R.drawable.common_error;
319 mStatusText = R.string.auth_unknow_error;
320 break;
321 case FILE_NOT_FOUND:
322 mStatusIcon = R.drawable.common_error;
323 mStatusText = R.string.auth_incorrect_path_title;
324 break;
325 default:
326 Log.e(TAG, "Incorrect connection checker result type: " + type);
327 }
328 setResultIconAndText(mStatusIcon, mStatusText);
329 if (!mStatusCorrect)
330 findViewById(R.id.refreshButton).setVisibility(View.VISIBLE);
331 else
332 findViewById(R.id.refreshButton).setVisibility(View.INVISIBLE);
333 findViewById(R.id.buttonOK).setEnabled(mStatusCorrect);
334 }
335
336 @Override
337 public void onFocusChange(View view, boolean hasFocus) {
338 if (view.getId() == R.id.host_URL) {
339 if (!hasFocus) {
340 TextView tv = ((TextView) findViewById(R.id.host_URL));
341 String uri = tv.getText().toString();
342 if (uri.length() != 0) {
343 setResultIconAndText(R.drawable.progress_small,
344 R.string.auth_testing_connection);
345 mConnChkRunnable = new ConnectionCheckerRunnable(uri, this);
346 mConnChkRunnable.setListener(this, mHandler);
347 mAuthThread = new Thread(mConnChkRunnable);
348 mAuthThread.start();
349 } else {
350 findViewById(R.id.refreshButton).setVisibility(
351 View.INVISIBLE);
352 setResultIconAndText(0, 0);
353 }
354 }
355 } else if (view.getId() == R.id.account_password) {
356 ImageView iv = (ImageView) findViewById(R.id.viewPassword);
357 if (hasFocus) {
358 iv.setVisibility(View.VISIBLE);
359 } else {
360 TextView v = (TextView) findViewById(R.id.account_password);
361 int input_type = InputType.TYPE_CLASS_TEXT
362 | InputType.TYPE_TEXT_VARIATION_PASSWORD;
363 v.setInputType(input_type);
364 iv.setVisibility(View.INVISIBLE);
365 }
366 }
367 }
368
369 private void setResultIconAndText(int drawable_id, int text_id) {
370 ImageView iv = (ImageView) findViewById(R.id.action_indicator);
371 TextView tv = (TextView) findViewById(R.id.status_text);
372
373 if (drawable_id == 0 && text_id == 0) {
374 iv.setVisibility(View.INVISIBLE);
375 tv.setVisibility(View.INVISIBLE);
376 } else {
377 iv.setImageResource(drawable_id);
378 tv.setText(text_id);
379 iv.setVisibility(View.VISIBLE);
380 tv.setVisibility(View.VISIBLE);
381 }
382 }
383
384 @Override
385 public void onClick(View v) {
386 if (v.getId() == R.id.refreshButton) {
387 onFocusChange(findViewById(R.id.host_URL), false);
388 } else if (v.getId() == R.id.viewPassword) {
389 TextView view = (TextView) findViewById(R.id.account_password);
390 int input_type = InputType.TYPE_CLASS_TEXT
391 | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD;
392 view.setInputType(input_type);
393 }
394 }
395 }