-
-
Notifications
You must be signed in to change notification settings - Fork 801
Expand file tree
/
Copy pathCreateAccountActivity.kt
More file actions
452 lines (420 loc) · 22 KB
/
CreateAccountActivity.kt
File metadata and controls
452 lines (420 loc) · 22 KB
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
package org.wikipedia.createaccount
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextWatcher
import android.util.Patterns
import android.view.KeyEvent
import android.view.View
import android.widget.EditText
import androidx.activity.addCallback
import androidx.activity.viewModels
import androidx.core.net.toUri
import androidx.core.view.isVisible
import androidx.core.widget.addTextChangedListener
import androidx.core.widget.doOnTextChanged
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.textfield.TextInputLayout
import kotlinx.coroutines.launch
import org.wikipedia.R
import org.wikipedia.WikipediaApp
import org.wikipedia.activity.BaseActivity
import org.wikipedia.analytics.eventplatform.YearInReviewEvent
import org.wikipedia.analytics.testkitchen.TestKitchenAdapter
import org.wikipedia.auth.AccountUtil
import org.wikipedia.captcha.CaptchaHandler
import org.wikipedia.captcha.CaptchaResult
import org.wikipedia.captcha.HCaptchaHelper
import org.wikipedia.databinding.ActivityCreateAccountBinding
import org.wikipedia.extensions.getInstrumentActionContext
import org.wikipedia.extensions.instrument
import org.wikipedia.login.LoginActivity
import org.wikipedia.page.LinkMovementMethodExt
import org.wikipedia.util.DeviceUtil
import org.wikipedia.util.FeedbackUtil
import org.wikipedia.util.StringUtil
import org.wikipedia.util.UriUtil
import org.wikipedia.util.log.L
import org.wikipedia.views.NonEmptyValidator
import java.util.regex.Pattern
class CreateAccountActivity : BaseActivity() {
enum class ValidateResult {
SUCCESS, INVALID_USERNAME, PASSWORD_TOO_SHORT, PASSWORD_IS_USERNAME, PASSWORD_MISMATCH, NO_EMAIL, INVALID_EMAIL
}
private lateinit var binding: ActivityCreateAccountBinding
private lateinit var captchaHandler: CaptchaHandler
private var wiki = WikipediaApp.instance.wikiSite
private var userNameTextWatcher: TextWatcher? = null
private var requestSource: String = ""
private val viewModel: CreateAccountActivityViewModel by viewModels()
private val textEnteredEventSent = mutableMapOf<View, Boolean>()
private val hCaptchaHelper = HCaptchaHelper(this, object : HCaptchaHelper.Callback {
override fun onShow() {
instrument?.submitInteraction("hcaptcha_show")
}
override fun onSuccess(token: String) {
instrument?.submitInteraction("hcaptcha_success")
doCreateAccount(viewModel.token.orEmpty(), hCaptchaToken = token)
}
override fun onError(e: Exception, code: Int) {
instrument?.submitInteraction("hcaptcha_error", actionContext = e.getInstrumentActionContext())
showProgressBar(false)
FeedbackUtil.showMessage(this@CreateAccountActivity, e.message.orEmpty())
}
})
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityCreateAccountBinding.inflate(layoutInflater)
setContentView(binding.root)
setSupportActionBar(binding.toolbar)
_instrument = TestKitchenAdapter.client.getInstrument("apps-authentication")
.startFunnel("create_account")
captchaHandler = CaptchaHandler(this, wiki, binding.captchaContainer.root, binding.createAccountPrimaryContainer,
getString(R.string.create_account_activity_title), getString(R.string.create_account_button),
instrument = instrument)
// Don't allow user to submit registration unless they've put in a username and password
NonEmptyValidator(binding.createAccountSubmitButton, binding.createAccountUsername, binding.createAccountPasswordInput)
// Don't allow user to continue when they're shown a captcha until they fill it in
NonEmptyValidator(binding.captchaContainer.captchaSubmitButton, binding.captchaContainer.captchaText)
setClickListeners()
requestSource = intent.getStringExtra(LOGIN_REQUEST_SOURCE).orEmpty()
_instrument = TestKitchenAdapter.client.getInstrument("apps-authentication")
.setDefaultActionSource("create_account_form")
.startFunnel("create_account")
// Only send event if the activity is created for the first time
if (savedInstanceState == null) {
instrument?.submitInteraction("impression", actionContext = mapOf("invoke_source" to requestSource))
}
addFirstKeystrokeInstrumentation(binding.createAccountUsername.editText, "username")
addFirstKeystrokeInstrumentation(binding.createAccountPasswordInput.editText, "password")
addFirstKeystrokeInstrumentation(binding.createAccountPasswordRepeat.editText, "confirm_password")
addFirstKeystrokeInstrumentation(binding.createAccountEmail.editText, "email")
if (AccountUtil.isTemporaryAccount) {
binding.footerContainer.tempAccountInfoContainer.isVisible = true
binding.footerContainer.tempAccountInfoText.text = StringUtil.fromHtml(getString(R.string.temp_account_login_status, AccountUtil.userName))
} else {
binding.footerContainer.tempAccountInfoContainer.isVisible = false
}
binding.footerContainer.hCaptchaDisclaimer.isVisible = false
onBackPressedDispatcher.addCallback(this) {
instrument?.submitInteraction("click", elementId = "back")
if (captchaHandler.isActive) {
captchaHandler.cancelCaptcha()
showProgressBar(false)
return@addCallback
}
DeviceUtil.hideSoftKeyboard(this@CreateAccountActivity)
finish()
}
// Set default result to failed, so we can override if it did not
setResult(RESULT_ACCOUNT_NOT_CREATED)
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.CREATED) {
launch {
viewModel.authManagerState.collect {
when (it) {
is CreateAccountActivityViewModel.AccountInfoState.HCaptchaDisclaimer -> {
binding.footerContainer.hCaptchaDisclaimer.text = StringUtil.fromHtml(it.disclaimerMessage)
binding.footerContainer.hCaptchaDisclaimer.isVisible = !binding.footerContainer.hCaptchaDisclaimer.text.isNullOrEmpty()
}
is CreateAccountActivityViewModel.AccountInfoState.Error -> {
L.e(it.throwable)
}
}
}
}
launch {
viewModel.createAccountInfoState.collect {
when (it) {
is CreateAccountActivityViewModel.AccountInfoState.DoCreateAccount -> {
doCreateAccount(it.token)
}
is CreateAccountActivityViewModel.AccountInfoState.HandleHCaptcha -> {
showProgressBar(true)
hCaptchaHelper.cleanup()
instrument?.submitInteraction("hcaptcha_load")
hCaptchaHelper.show()
}
is CreateAccountActivityViewModel.AccountInfoState.HandleCaptcha -> {
captchaHandler.handleCaptcha(it.token, CaptchaResult(it.captchaId))
}
is CreateAccountActivityViewModel.AccountInfoState.InvalidToken -> {
handleAccountCreationError(getString(R.string.create_account_generic_error))
}
is CreateAccountActivityViewModel.AccountInfoState.Error -> {
showError(it.throwable)
L.e(it.throwable)
}
}
}
}
launch {
viewModel.doCreateAccountState.collect {
when (it) {
is CreateAccountActivityViewModel.CreateAccountState.Pass -> {
finishWithUserResult(it.userName)
}
is CreateAccountActivityViewModel.CreateAccountState.Error -> {
L.e(it.throwable.toString())
showProgressBar(false)
showError(it.throwable)
}
}
}
}
launch {
viewModel.verifyUserNameState.collect {
when (it) {
CreateAccountActivityViewModel.UserNameState.Initial,
CreateAccountActivityViewModel.UserNameState.Success -> {
binding.createAccountUsername.isErrorEnabled = false
}
is CreateAccountActivityViewModel.UserNameState.Blocked -> {
instrument?.submitInteraction("error", actionContext = mapOf("validation_error" to "blocked"))
handleAccountCreationError(it.error)
}
is CreateAccountActivityViewModel.UserNameState.CannotCreate -> {
instrument?.submitInteraction("error", actionContext = mapOf("validation_error" to "username_unavailable"))
binding.createAccountUsername.error = getString(R.string.create_account_name_unavailable, it.userName)
}
}
}
}
}
}
}
private fun setClickListeners() {
binding.viewCreateAccountError.backClickListener = View.OnClickListener {
instrument?.submitInteraction("click", elementId = "error_back_button")
binding.viewCreateAccountError.visibility = View.GONE
captchaHandler.requestNewCaptcha()
}
binding.viewCreateAccountError.retryClickListener = View.OnClickListener {
instrument?.submitInteraction("click", elementId = "error_retry_button")
binding.viewCreateAccountError.visibility = View.GONE
}
binding.createAccountSubmitButton.setOnClickListener {
instrument?.submitInteraction("click", elementId = "create_account_button")
if (requestSource == LoginActivity.SOURCE_YEAR_IN_REVIEW) {
YearInReviewEvent.submit(action = "create_account_click", slide = "explore_prompt")
}
validateThenCreateAccount()
}
binding.captchaContainer.captchaSubmitButton.setOnClickListener {
instrument?.submitInteraction("click", elementId = "fancy_captcha_submit")
validateThenCreateAccount()
}
binding.createAccountLoginButton.setOnClickListener {
instrument?.submitInteraction("click", elementId = "login_button")
if (requestSource == LoginActivity.SOURCE_YEAR_IN_REVIEW) {
YearInReviewEvent.submit(action = "login_click", slide = "explore_prompt")
}
// This assumes that the CreateAccount activity was launched from the Login activity
// (since there's currently no other mechanism to invoke CreateAccountActivity),
// so finishing this activity will implicitly go back to Login.
setResult(RESULT_ACCOUNT_LOGIN)
finish()
}
binding.footerContainer.privacyPolicyLink.setOnClickListener {
instrument?.submitInteraction("click", elementId = "privacy_policy_link")
FeedbackUtil.showPrivacyPolicy(this)
}
binding.footerContainer.forgotPasswordLink.setOnClickListener {
instrument?.submitInteraction("click", elementId = "forgot_password_link")
val forgotPasswordUrl = WikipediaApp.instance.getString(R.string.forget_password_link, wiki.languageCode)
UriUtil.visitInExternalBrowser(this, forgotPasswordUrl.toUri())
}
// Add listener so that when the user taps enter, it submits the captcha
binding.captchaContainer.captchaText.setOnKeyListener { _: View, keyCode: Int, event: KeyEvent ->
if (event.action == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_ENTER) {
instrument?.submitInteraction("click", elementId = "fancy_captcha_submit")
validateThenCreateAccount()
return@setOnKeyListener true
}
false
}
userNameTextWatcher = binding.createAccountUsername.editText?.doOnTextChanged { text, _, _, _ ->
viewModel.verifyUserName(text)
}
binding.footerContainer.hCaptchaDisclaimer.movementMethod = LinkMovementMethodExt({
instrument?.submitInteraction("click", elementId = "hcaptcha_disclaimer")
UriUtil.visitInExternalBrowser(this, it.toUri())
})
}
private fun addFirstKeystrokeInstrumentation(view: EditText?, elementId: String) {
view?.addTextChangedListener {
if (!it.isNullOrEmpty() && !(textEnteredEventSent[view] ?: false)) {
instrument?.submitInteraction("type", elementId = elementId)
textEnteredEventSent[view] = true
}
}
}
private fun handleAccountCreationError(message: String) {
if (message.contains("blocked")) {
FeedbackUtil.makeSnackbar(this, getString(R.string.create_account_ip_block_message))
.setAction(R.string.create_account_ip_block_details) {
UriUtil.visitInExternalBrowser(this,
getString(R.string.create_account_ip_block_help_url).toUri())
}
.show()
} else {
FeedbackUtil.showMessage(this, StringUtil.fromHtml(message))
}
L.w("Account creation failed with result $message")
}
private fun doCreateAccount(token: String, hCaptchaToken: String? = null) {
showProgressBar(true)
val email = getText(binding.createAccountEmail).ifEmpty { null }
val password = getText(binding.createAccountPasswordInput)
val repeat = getText(binding.createAccountPasswordRepeat)
val userName = getText(binding.createAccountUsername)
viewModel.doCreateAccount(
token = token,
captchaId = captchaHandler.captchaId(),
captchaWord = if (hCaptchaToken.isNullOrEmpty()) captchaHandler.captchaWord() else hCaptchaToken,
userName = userName,
password = password,
repeat = repeat,
email = email)
}
public override fun onStop() {
showProgressBar(false)
super.onStop()
}
public override fun onDestroy() {
hCaptchaHelper.cleanup()
captchaHandler.dispose()
userNameTextWatcher?.let { binding.createAccountUsername.editText?.removeTextChangedListener(it) }
super.onDestroy()
}
private fun clearErrors() {
binding.createAccountUsername.isErrorEnabled = false
binding.createAccountPasswordInput.isErrorEnabled = false
binding.createAccountPasswordRepeat.isErrorEnabled = false
binding.createAccountEmail.isErrorEnabled = false
}
private fun validateThenCreateAccount() {
clearErrors()
val result = validateInput(getText(binding.createAccountUsername), getText(binding.createAccountPasswordInput),
getText(binding.createAccountPasswordRepeat), getText(binding.createAccountEmail))
when (result) {
ValidateResult.INVALID_USERNAME -> {
instrument?.submitInteraction("error", actionContext = mapOf("validation_error" to "username_invalid"))
binding.createAccountUsername.requestFocus()
binding.createAccountUsername.error = getString(R.string.create_account_username_error)
return
}
ValidateResult.PASSWORD_TOO_SHORT -> {
instrument?.submitInteraction("error", actionContext = mapOf("validation_error" to "password_too_short"))
binding.createAccountPasswordInput.requestFocus()
binding.createAccountPasswordInput.error = getString(R.string.create_account_password_error)
return
}
ValidateResult.PASSWORD_IS_USERNAME -> {
instrument?.submitInteraction("error", actionContext = mapOf("validation_error" to "password_is_username"))
binding.createAccountPasswordInput.requestFocus()
binding.createAccountPasswordInput.error = getString(R.string.create_account_password_is_username)
return
}
ValidateResult.PASSWORD_MISMATCH -> {
instrument?.submitInteraction("error", actionContext = mapOf("validation_error" to "password_mismatch"))
binding.createAccountPasswordRepeat.requestFocus()
binding.createAccountPasswordRepeat.error = getString(R.string.create_account_passwords_mismatch_error)
return
}
ValidateResult.INVALID_EMAIL -> {
instrument?.submitInteraction("error", actionContext = mapOf("validation_error" to "email_invalid"))
binding.createAccountEmail.requestFocus()
binding.createAccountEmail.error = getString(R.string.create_account_email_error)
return
}
ValidateResult.NO_EMAIL -> {
instrument?.submitInteraction("impression", actionSource = "create_account_email_form")
MaterialAlertDialogBuilder(this)
.setCancelable(false)
.setTitle(R.string.email_recommendation_dialog_title)
.setMessage(StringUtil.fromHtml(resources.getString(R.string.email_recommendation_dialog_message)))
.setPositiveButton(R.string.email_recommendation_dialog_create_without_email_action) { _, _ ->
instrument?.submitInteraction("click", actionSource = "create_account_email_form", elementId = "no_email")
createAccount()
}
.setNegativeButton(R.string.email_recommendation_dialog_create_with_email_action) { _, _ ->
instrument?.submitInteraction("click", actionSource = "create_account_email_form", elementId = "yes_email")
binding.createAccountEmail.requestFocus()
}
.show()
}
ValidateResult.SUCCESS -> createAccount()
}
}
private fun createAccount() {
if (captchaHandler.isActive && captchaHandler.token != null) {
doCreateAccount(captchaHandler.token!!)
} else {
viewModel.createAccountInfo()
}
}
private fun getText(input: TextInputLayout): String {
input.editText?.let {
return it.text.toString()
}
return ""
}
private fun finishWithUserResult(userName: String) {
val resultIntent = Intent()
resultIntent.putExtra(CREATE_ACCOUNT_RESULT_USERNAME, userName)
resultIntent.putExtra(CREATE_ACCOUNT_RESULT_PASSWORD, getText(binding.createAccountPasswordInput))
setResult(RESULT_ACCOUNT_CREATED, resultIntent)
showProgressBar(false)
captchaHandler.cancelCaptcha()
instrument?.submitInteraction("success", actionContext = mapOf("invoke_source" to requestSource))
DeviceUtil.hideSoftKeyboard(this@CreateAccountActivity)
finish()
}
private fun showProgressBar(enable: Boolean) {
binding.viewProgressBar.isVisible = enable
binding.captchaContainer.captchaSubmitButton.isEnabled = !enable
binding.captchaContainer.captchaSubmitButton.setText(if (enable) R.string.dialog_create_account_checking_progress else R.string.create_account_button)
}
private fun showError(caught: Throwable) {
instrument?.submitInteraction("error", actionContext = caught.getInstrumentActionContext())
binding.viewCreateAccountError.setError(caught)
binding.viewCreateAccountError.visibility = View.VISIBLE
}
companion object {
private const val PASSWORD_MIN_LENGTH = 8
const val RESULT_ACCOUNT_CREATED = 1
const val RESULT_ACCOUNT_NOT_CREATED = 2
const val RESULT_ACCOUNT_LOGIN = 3
const val LOGIN_REQUEST_SOURCE = "login_request_source"
const val CREATE_ACCOUNT_RESULT_USERNAME = "username"
const val CREATE_ACCOUNT_RESULT_PASSWORD = "password"
val USERNAME_PATTERN: Pattern = Pattern.compile("[^#<>\\[\\]|{}/@]*")
fun validateInput(username: CharSequence,
password: CharSequence,
passwordRepeat: CharSequence,
email: CharSequence): ValidateResult {
if (!USERNAME_PATTERN.matcher(username).matches()) {
return ValidateResult.INVALID_USERNAME
} else if (password.length < PASSWORD_MIN_LENGTH) {
return ValidateResult.PASSWORD_TOO_SHORT
} else if (password.toString().equals(username.toString(), true)) {
return ValidateResult.PASSWORD_IS_USERNAME
} else if (passwordRepeat.toString() != password.toString()) {
return ValidateResult.PASSWORD_MISMATCH
} else if (email.isNotEmpty() && !Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
return ValidateResult.INVALID_EMAIL
} else if (email.isEmpty()) {
return ValidateResult.NO_EMAIL
}
return ValidateResult.SUCCESS
}
fun newIntent(context: Context, source: String): Intent {
return Intent(context, CreateAccountActivity::class.java)
.putExtra(LOGIN_REQUEST_SOURCE, source)
}
}
}