1package eu.siacs.conversations.ui;
2
3import android.app.AlertDialog;
4import android.content.Intent;
5import androidx.databinding.DataBindingUtil;
6import android.os.Bundle;
7import androidx.appcompat.widget.Toolbar;
8import android.text.Editable;
9import android.text.Html;
10import android.text.TextUtils;
11import android.text.TextWatcher;
12import android.util.Log;
13import android.view.KeyEvent;
14import android.view.View;
15import android.widget.EditText;
16
17import org.jetbrains.annotations.NotNull;
18
19import java.util.concurrent.atomic.AtomicBoolean;
20
21import eu.siacs.conversations.Config;
22import eu.siacs.conversations.R;
23import eu.siacs.conversations.databinding.ActivityEnterNumberBinding;
24import eu.siacs.conversations.entities.Account;
25import eu.siacs.conversations.services.QuickConversationsService;
26import eu.siacs.conversations.ui.drawable.TextDrawable;
27import eu.siacs.conversations.ui.util.ApiDialogHelper;
28import eu.siacs.conversations.utils.AccountUtils;
29import eu.siacs.conversations.utils.LocationProvider;
30import eu.siacs.conversations.utils.PhoneNumberUtilWrapper;
31import io.michaelrocks.libphonenumber.android.NumberParseException;
32import io.michaelrocks.libphonenumber.android.PhoneNumberUtil;
33import io.michaelrocks.libphonenumber.android.Phonenumber;
34
35public class EnterPhoneNumberActivity extends XmppActivity implements QuickConversationsService.OnVerificationRequested {
36
37 private static final int REQUEST_CHOOSE_COUNTRY = 0x1234;
38
39 private ActivityEnterNumberBinding binding;
40
41 private final AtomicBoolean redirectInProgress = new AtomicBoolean(false);
42
43 private String region = null;
44 private final TextWatcher countryCodeTextWatcher = new TextWatcher() {
45 @Override
46 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
47
48 }
49
50 @Override
51 public void onTextChanged(CharSequence s, int start, int before, int count) {
52
53 }
54
55 @Override
56 public void afterTextChanged(Editable editable) {
57 final String text = editable.toString();
58 try {
59 final int oldCode = region != null ? PhoneNumberUtilWrapper.getInstance(EnterPhoneNumberActivity.this).getCountryCodeForRegion(region) : 0;
60 final int code = Integer.parseInt(text);
61 if (oldCode != code) {
62 region = PhoneNumberUtilWrapper.getInstance(EnterPhoneNumberActivity.this).getRegionCodeForCountryCode(code);
63 }
64 if ("ZZ".equals(region)) {
65 binding.country.setText(TextUtils.isEmpty(text) ? R.string.choose_a_country : R.string.invalid_country_code);
66 } else {
67 binding.number.requestFocus();
68 binding.country.setText(PhoneNumberUtilWrapper.getCountryForCode(region));
69 }
70 } catch (NumberFormatException e) {
71 binding.country.setText(TextUtils.isEmpty(text) ? R.string.choose_a_country : R.string.invalid_country_code);
72 }
73 }
74 };
75 private boolean requestingVerification = false;
76
77 @Override
78 protected void refreshUiReal() {
79
80 }
81
82 @Override
83 void onBackendConnected() {
84 xmppConnectionService.getQuickConversationsService().addOnVerificationRequestedListener(this);
85 final Account account = AccountUtils.getFirst(xmppConnectionService);
86 if (account != null) {
87 runOnUiThread(this::performRedirectToVerificationActivity);
88 }
89 }
90
91 @Override
92 protected void onCreate(final Bundle savedInstanceState) {
93 super.onCreate(savedInstanceState);
94
95 String region = savedInstanceState != null ? savedInstanceState.getString("region") : null;
96 boolean requestingVerification = savedInstanceState != null && savedInstanceState.getBoolean("requesting_verification", false);
97 if (region != null) {
98 this.region = region;
99 } else {
100 this.region = LocationProvider.getUserCountry(this);
101 }
102
103 this.binding = DataBindingUtil.setContentView(this, R.layout.activity_enter_number);
104 this.binding.countryCode.setCompoundDrawables(new TextDrawable(this.binding.countryCode, "+"), null, null, null);
105 this.binding.country.setOnClickListener(this::onSelectCountryClick);
106 this.binding.next.setOnClickListener(this::onNextClick);
107 setSupportActionBar((Toolbar) this.binding.toolbar);
108 this.binding.countryCode.addTextChangedListener(this.countryCodeTextWatcher);
109 this.binding.countryCode.setText(String.valueOf(PhoneNumberUtilWrapper.getInstance(this).getCountryCodeForRegion(this.region)));
110 this.binding.number.setOnKeyListener((v, keyCode, event) -> {
111 if (event.getAction() != KeyEvent.ACTION_DOWN) {
112 return false;
113 }
114 final EditText editText = (EditText) v;
115 final boolean cursorAtZero = editText.getSelectionEnd() == 0 && editText.getSelectionStart() == 0;
116 if (keyCode == KeyEvent.KEYCODE_DEL && (cursorAtZero || editText.getText().length() == 0)) {
117 final Editable countryCode = this.binding.countryCode.getText();
118 if (countryCode.length() > 0) {
119 countryCode.delete(countryCode.length() - 1, countryCode.length());
120 this.binding.countryCode.setSelection(countryCode.length());
121 }
122 this.binding.countryCode.requestFocus();
123 return true;
124 }
125 return false;
126 });
127 setRequestingVerificationState(requestingVerification);
128 }
129
130 @Override
131 public void onSaveInstanceState(@NotNull Bundle savedInstanceState) {
132 if (this.region != null) {
133 savedInstanceState.putString("region", this.region);
134 }
135 savedInstanceState.putBoolean("requesting_verification", this.requestingVerification);
136 super.onSaveInstanceState(savedInstanceState);
137 }
138
139 @Override
140 public void onStop() {
141 if (xmppConnectionService != null) {
142 xmppConnectionService.getQuickConversationsService().removeOnVerificationRequestedListener(this);
143 }
144 super.onStop();
145 }
146
147 private void onNextClick(View v) {
148 final AlertDialog.Builder builder = new AlertDialog.Builder(this);
149 try {
150 final Editable number = this.binding.number.getText();
151 final String input = number.toString();
152 final Phonenumber.PhoneNumber phoneNumber = PhoneNumberUtilWrapper.getInstance(this).parse(input, region);
153 this.binding.countryCode.setText(String.valueOf(phoneNumber.getCountryCode()));
154 number.clear();
155 number.append(String.valueOf(phoneNumber.getNationalNumber()));
156 final String formattedPhoneNumber = PhoneNumberUtilWrapper.getInstance(this).format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL).replace(' ','\u202F');
157
158 if (PhoneNumberUtilWrapper.getInstance(this).isValidNumber(phoneNumber)) {
159 builder.setMessage(Html.fromHtml(getString(R.string.we_will_be_verifying, formattedPhoneNumber)));
160 builder.setNegativeButton(R.string.edit, null);
161 builder.setPositiveButton(R.string.ok, (dialog, which) -> onPhoneNumberEntered(phoneNumber));
162 } else {
163 builder.setMessage(getString(R.string.not_a_valid_phone_number, formattedPhoneNumber));
164 builder.setPositiveButton(R.string.ok, null);
165 }
166 Log.d(Config.LOGTAG, phoneNumber.toString());
167 } catch (NumberParseException e) {
168 builder.setMessage(R.string.please_enter_your_phone_number);
169 builder.setPositiveButton(R.string.ok, null);
170 }
171 builder.create().show();
172 }
173
174 private void onSelectCountryClick(View view) {
175 final Intent intent = new Intent(this, ChooseCountryActivity.class);
176 startActivityForResult(intent, REQUEST_CHOOSE_COUNTRY);
177 }
178
179 private void onPhoneNumberEntered(Phonenumber.PhoneNumber phoneNumber) {
180 setRequestingVerificationState(true);
181 xmppConnectionService.getQuickConversationsService().requestVerification(phoneNumber);
182 }
183
184 private void setRequestingVerificationState(boolean requesting) {
185 this.requestingVerification = requesting;
186 this.binding.countryCode.setEnabled(!requesting);
187 this.binding.country.setEnabled(!requesting);
188 this.binding.number.setEnabled(!requesting);
189 this.binding.next.setEnabled(!requesting);
190 this.binding.next.setText(requesting ? R.string.requesting_sms : R.string.next);
191 this.binding.progressBar.setVisibility(requesting ? View.VISIBLE : View.GONE);
192 this.binding.progressBar.setIndeterminate(requesting);
193 }
194
195 @Override
196 public void onActivityResult(int requestCode, int resultCode, final Intent data) {
197 super.onActivityResult(requestCode, resultCode, data);
198 if (resultCode == RESULT_OK && requestCode == REQUEST_CHOOSE_COUNTRY) {
199 final String region = data.getStringExtra("region");
200 if (region != null) {
201 this.region = region;
202 final int countryCode = PhoneNumberUtilWrapper.getInstance(this).getCountryCodeForRegion(region);
203 this.binding.countryCode.setText(String.valueOf(countryCode));
204 }
205 }
206 }
207
208 private void performRedirectToVerificationActivity(long timestamp) {
209 if (redirectInProgress.compareAndSet(false, true)) {
210 Intent intent = new Intent(this, VerifyActivity.class);
211 intent.putExtra(VerifyActivity.EXTRA_RETRY_SMS_AFTER, timestamp);
212 startActivity(intent);
213 finish();
214 }
215 }
216
217 private void performRedirectToVerificationActivity() {
218 if (redirectInProgress.compareAndSet(false, true)) {
219 startActivity(new Intent(this, VerifyActivity.class));
220 finish();
221 }
222 }
223
224 @Override
225 public void onVerificationRequestFailed(int code) {
226 runOnUiThread(() -> {
227 setRequestingVerificationState(false);
228 ApiDialogHelper.createError(this, code).show();
229 });
230 }
231
232 @Override
233 public void onVerificationRequested() {
234 runOnUiThread(this::performRedirectToVerificationActivity);
235 }
236
237 @Override
238 public void onVerificationRequestedRetryAt(long timestamp) {
239 runOnUiThread(() -> performRedirectToVerificationActivity(timestamp));
240 }
241}