Welcome to mirror list, hosted at ThFree Co, Russian Federation.

LoginActivity.java « activities « owncloud_sms « unix_experience « fr « java « main « src - github.com/nerzhul/ncsms-android.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: b5da4f47f77301b173260d0defa1c4121bdabad2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
package fr.unix_experience.owncloud_sms.activities;

/*
 *  Copyright (c) 2014-2015, Loic Blot <loic.blot@unix-experience.fr>
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *  
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import android.accounts.Account;
import android.accounts.AccountManager;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.dd.processbutton.iml.ActionProcessButton;

import java.net.MalformedURLException;
import java.net.URL;

import fr.unix_experience.owncloud_sms.R;
import fr.unix_experience.owncloud_sms.defines.DefaultPrefs;
import fr.unix_experience.owncloud_sms.engine.OCHttpClient;
import fr.unix_experience.owncloud_sms.exceptions.OCSyncException;

/**
 * A login screen that offers login via email/password.
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class LoginActivity extends AppCompatActivity {

	private static final String TAG = LoginActivity.class.getCanonicalName();

	/**
	 * Keep track of the login task to ensure we can cancel it if requested.
	 */
	private UserLoginTask mAuthTask = null;

	// UI references.
	private Spinner _protocolView;
	private EditText _loginView;
	private EditText _passwordView;
	private EditText _serverView;
	private ActionProcessButton _signInButton;
	private View mProgressView;
	private View mLoginFormView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);

		ActionBar actionBar = getSupportActionBar();
		actionBar.setDisplayHomeAsUpEnabled(true);

		// Set up the login form.
		_protocolView = findViewById(R.id.oc_protocol);
		_serverView = findViewById(R.id.oc_server);
		_loginView = findViewById(R.id.oc_login);

		_passwordView = findViewById(R.id.oc_password);
		_passwordView
				.setOnEditorActionListener(new TextView.OnEditorActionListener() {
					@Override
					public boolean onEditorAction(TextView textView, int id,
												  KeyEvent keyEvent) {
						if ((id == R.id.oc_login) || (id == EditorInfo.IME_NULL)) {
							attemptLogin();
							return true;
						}
						return false;
					}
				});

		_signInButton = findViewById(R.id.oc_signin_button);
		_signInButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				attemptLogin();
			}
		});

		mLoginFormView = findViewById(R.id.login_form);
		mProgressView = findViewById(R.id.login_progress);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		boolean retval = true;
		switch (item.getItemId()) {
			case android.R.id.home:
				finish();
				break;
			default:
				retval = super.onOptionsItemSelected(item);
		}
		return retval;
	}

	/**
	 * Attempts to sign in or register the account specified by the login form.
	 * If there are form errors (invalid email, missing fields, etc.), the
	 * errors are presented and no actual login attempt is made.
	 */
	public void attemptLogin() {
		if (mAuthTask != null) {
			return;
		}

		// Reset errors.
		_loginView.setError(null);
		_passwordView.setError(null);

		// Store values at the time of the login attempt.
		String protocol = _protocolView.getSelectedItem().toString();
		String login = _loginView.getText().toString();
		String password = _passwordView.getText().toString();
		String serverAddr = _serverView.getText().toString();

		boolean cancel = false;
		View focusView = null;

		// Check for a valid server address.
		if (TextUtils.isEmpty(protocol)) {
			cancel = true;
		}

		// Check for a valid server address.
		if (TextUtils.isEmpty(serverAddr)) {
			_serverView.setError(getString(R.string.error_field_required));
			focusView = _loginView;
			cancel = true;
		}

		// Check for a valid login address.
		if (TextUtils.isEmpty(login)) {
			_loginView.setError(getString(R.string.error_field_required));
			focusView = _loginView;
			cancel = true;
		}

		// Check for a valid password
		if (TextUtils.isEmpty(password)) {
			_passwordView.setError(getString(R.string.error_field_required));
			focusView = _passwordView;
			cancel = true;
		}

		if (!isPasswordValid(password)) {
			_passwordView.setError(getString(R.string.error_invalid_password));
			focusView = _passwordView;
			cancel = true;
		}

		if (cancel) {
			// There was an error; don't attempt login and focus the first
			// form field with an error.
			// reset the button progress
			_signInButton.setProgress(0);
			if (focusView != null) {
				focusView.requestFocus();
			}
		} else {
			// Show a progress spinner, and kick off a background task to
			// perform the user login attempt.
			_signInButton.setProgress(25);
			showProgress(true);
			String serverURL = protocol + serverAddr;
			try {
				mAuthTask = new UserLoginTask(serverURL, login, password);
				mAuthTask.execute((Void) null);
			} catch (MalformedURLException e) {
				Log.e(TAG, "Invalid server URL " + serverURL);
			}
		}
	}

	private boolean isPasswordValid(String password) {
		// TODO: Replace this with your own logic
		return password.length() > 4;
	}

	/**
	 * Shows the progress UI and hides the login form.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
	public void showProgress(final boolean show) {
		// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
		// for very easy animations. If available, use these APIs to fade-in
		// the progress spinner.
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
			int shortAnimTime = getResources().getInteger(
					android.R.integer.config_shortAnimTime);

			mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
			mLoginFormView.animate().setDuration(shortAnimTime)
					.alpha(show ? 0 : 1)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mLoginFormView.setVisibility(show ? View.GONE
									: View.VISIBLE);
						}
					});

			mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
			mProgressView.animate().setDuration(shortAnimTime)
					.alpha(show ? 1 : 0)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mProgressView.setVisibility(show ? View.VISIBLE
									: View.GONE);
						}
					});
		} else {
			// The ViewPropertyAnimator APIs are not available, so simply show
			// and hide the relevant UI components.
			mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
			mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
		}
	}

	/**
	 * Represents an asynchronous login/registration task used to authenticate
	 * the user.
	 */
	public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {

		UserLoginTask(String serverURL, String login, String password) throws MalformedURLException {
			_serverURL = new URL(serverURL);
			Log.i(TAG, "_serverURL = " + serverURL);
			_login = login;
			_password = password;
			_last_http_error = null;
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			_returnCode = 0;
			OCHttpClient http = new OCHttpClient(getBaseContext(), _serverURL, _login, _password);
			try {
				Pair<Integer, Integer> vPair = http.getVersion();
				_returnCode = vPair.first;
			} catch (IllegalArgumentException e) {
				Log.w(TAG, "Failed to getVersion, IllegalArgumentException occured: " + e.getMessage());
				_returnCode = 597;
			} catch (OCSyncException e) {
				Log.w(TAG, "Failed to login, OCSyncException occured: " + e.getMessage());
				_returnCode = 599;
			}

			_last_http_error = http.getLastError();
			return (_returnCode == 200);
		}

		@Override
		protected void onPostExecute(Boolean success) {
			mAuthTask = null;
			showProgress(false);
			_signInButton.setProgress(90);

			if (success) {
				_signInButton.setProgress(100);
				String accountType = getIntent().getStringExtra(UserLoginTask.PARAM_AUTHTOKEN_TYPE);
				if (accountType == null) {
					accountType = getString(R.string.account_type);
				}

				// Generate a label
				String accountLabel = _login + "@" + _serverURL.getHost();

				// We create the account
				Account account = new Account(accountLabel, accountType);
				Bundle accountBundle = new Bundle();
				accountBundle.putString("ocLogin", _login);
				accountBundle.putString("ocURI", _serverURL.toString());

				// And we push it to Android
				AccountManager accMgr = AccountManager.get(getApplicationContext());
				accMgr.addAccountExplicitly(account, _password, accountBundle);

				// Set sync options
				ContentResolver.setSyncAutomatically(account, getString(R.string.account_authority), true);

				Bundle b = new Bundle();
				b.putInt("synctype", 1);

				ContentResolver.addPeriodicSync(account, getString(R.string.account_authority), b, DefaultPrefs.syncInterval * 60);
				// Then it's finished
				finish();

				// Start sync settings, we have finished to configure account
				Intent settingsIntent = new Intent(Settings.ACTION_SYNC_SETTINGS);
				settingsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				getApplicationContext().startActivity(settingsIntent);
			} else {
				boolean serverViewRequestFocus = true;
				switch (_returnCode) {
					case 0:
						if (!_last_http_error.isEmpty()) {
							_serverView.setError("Low level error: " + _last_http_error);
						}
						else {
							_serverView.setError("Unknown error");
						}
						break;
					case 404:
						_serverView.setError(getString(R.string.error_connection_failed_not_found));
						break;
					case 597:
						_serverView.setError(getString(R.string.error_invalid_server_address));
						break;
					case 400:
					case 598:
						_serverView.setError(getString(R.string.error_connection_failed));
						break;
					case 599:
						_serverView.setError(getString(R.string.error_http_connection_failed));
						break;
					case 401:
					case 403:
						_passwordView.setError(getString(R.string.error_invalid_login));
						_passwordView.requestFocus();
						// Warning, there is no break here to disable serverViewRequestFocus too
					case 200:
					default:
						serverViewRequestFocus = false;
						break;
				}

				if (serverViewRequestFocus) {
					_serverView.requestFocus();
				}

				// If not ok, reset the progress
				if (_returnCode != 200) {
					_signInButton.setProgress(0);
				}
			}
		}

		@Override
		protected void onCancelled() {
			mAuthTask = null;
			showProgress(false);
		}

		private final URL _serverURL;
		private final String _login;
		private final String _password;
		private String _last_http_error;
		private int _returnCode;

		static final String PARAM_AUTHTOKEN_TYPE = "auth.token";
		private final String TAG = UserLoginTask.class.getCanonicalName();
	}
}