EnterPhoneNumberActivity.java

  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    public 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        Activities.setStatusAndNavigationBarColors(this, binding.getRoot());
108        setSupportActionBar(this.binding.toolbar);
109        this.binding.countryCode.addTextChangedListener(this.countryCodeTextWatcher);
110        this.binding.countryCode.setText(String.valueOf(PhoneNumberUtilWrapper.getInstance(this).getCountryCodeForRegion(this.region)));
111        this.binding.number.setOnKeyListener((v, keyCode, event) -> {
112            if (event.getAction() != KeyEvent.ACTION_DOWN) {
113                return false;
114            }
115            final EditText editText = (EditText) v;
116            final boolean cursorAtZero = editText.getSelectionEnd() == 0 && editText.getSelectionStart() == 0;
117            if (keyCode == KeyEvent.KEYCODE_DEL && (cursorAtZero || editText.getText().length() == 0)) {
118                final Editable countryCode = this.binding.countryCode.getText();
119                if (countryCode.length() > 0) {
120                    countryCode.delete(countryCode.length() - 1, countryCode.length());
121                    this.binding.countryCode.setSelection(countryCode.length());
122                }
123                this.binding.countryCode.requestFocus();
124                return true;
125            }
126            return false;
127        });
128        setRequestingVerificationState(requestingVerification);
129    }
130
131    @Override
132    public void onSaveInstanceState(@NotNull Bundle savedInstanceState) {
133        if (this.region != null) {
134            savedInstanceState.putString("region", this.region);
135        }
136        savedInstanceState.putBoolean("requesting_verification", this.requestingVerification);
137        super.onSaveInstanceState(savedInstanceState);
138    }
139
140    @Override
141    public void onStop() {
142        if (xmppConnectionService != null) {
143            xmppConnectionService.getQuickConversationsService().removeOnVerificationRequestedListener(this);
144        }
145        super.onStop();
146    }
147
148    private void onNextClick(View v) {
149        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
150        try {
151            final Editable number = this.binding.number.getText();
152            final String input = number.toString();
153            final Phonenumber.PhoneNumber phoneNumber = PhoneNumberUtilWrapper.getInstance(this).parse(input, region);
154            this.binding.countryCode.setText(String.valueOf(phoneNumber.getCountryCode()));
155            number.clear();
156            number.append(String.valueOf(phoneNumber.getNationalNumber()));
157            final String formattedPhoneNumber = PhoneNumberUtilWrapper.getInstance(this).format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL).replace(' ','\u202F');
158
159            if (PhoneNumberUtilWrapper.getInstance(this).isValidNumber(phoneNumber)) {
160                builder.setMessage(Html.fromHtml(getString(R.string.we_will_be_verifying, formattedPhoneNumber)));
161                builder.setNegativeButton(R.string.edit, null);
162                builder.setPositiveButton(R.string.ok, (dialog, which) -> onPhoneNumberEntered(phoneNumber));
163            } else {
164                builder.setMessage(getString(R.string.not_a_valid_phone_number, formattedPhoneNumber));
165                builder.setPositiveButton(R.string.ok, null);
166            }
167            Log.d(Config.LOGTAG, phoneNumber.toString());
168        } catch (NumberParseException e) {
169            builder.setMessage(R.string.please_enter_your_phone_number);
170            builder.setPositiveButton(R.string.ok, null);
171        }
172        builder.create().show();
173    }
174
175    private void onSelectCountryClick(View view) {
176        final Intent intent = new Intent(this, ChooseCountryActivity.class);
177        startActivityForResult(intent, REQUEST_CHOOSE_COUNTRY);
178    }
179
180    private void onPhoneNumberEntered(Phonenumber.PhoneNumber phoneNumber) {
181        setRequestingVerificationState(true);
182        xmppConnectionService.getQuickConversationsService().requestVerification(phoneNumber);
183    }
184
185    private void setRequestingVerificationState(boolean requesting) {
186        this.requestingVerification = requesting;
187        this.binding.countryCode.setEnabled(!requesting);
188        this.binding.country.setEnabled(!requesting);
189        this.binding.number.setEnabled(!requesting);
190        this.binding.next.setEnabled(!requesting);
191        this.binding.next.setText(requesting ? R.string.requesting_sms : R.string.next);
192        this.binding.progressBar.setVisibility(requesting ? View.VISIBLE : View.GONE);
193        this.binding.progressBar.setIndeterminate(requesting);
194    }
195
196    @Override
197    public void onActivityResult(int requestCode, int resultCode, final Intent data) {
198        super.onActivityResult(requestCode, resultCode, data);
199        if (resultCode == RESULT_OK && requestCode == REQUEST_CHOOSE_COUNTRY) {
200            final String region = data.getStringExtra("region");
201            if (region != null) {
202                this.region = region;
203                final int countryCode = PhoneNumberUtilWrapper.getInstance(this).getCountryCodeForRegion(region);
204                this.binding.countryCode.setText(String.valueOf(countryCode));
205            }
206        }
207    }
208
209    private void performRedirectToVerificationActivity(long timestamp) {
210        if (redirectInProgress.compareAndSet(false, true)) {
211            Intent intent = new Intent(this, VerifyActivity.class);
212            intent.putExtra(VerifyActivity.EXTRA_RETRY_SMS_AFTER, timestamp);
213            startActivity(intent);
214            finish();
215        }
216    }
217
218    private void performRedirectToVerificationActivity() {
219        if (redirectInProgress.compareAndSet(false, true)) {
220            startActivity(new Intent(this, VerifyActivity.class));
221            finish();
222        }
223    }
224
225    @Override
226    public void onVerificationRequestFailed(int code) {
227        runOnUiThread(() -> {
228            setRequestingVerificationState(false);
229            ApiDialogHelper.createError(this, code).show();
230        });
231    }
232
233    @Override
234    public void onVerificationRequested() {
235        runOnUiThread(this::performRedirectToVerificationActivity);
236    }
237
238    @Override
239    public void onVerificationRequestedRetryAt(long timestamp) {
240        runOnUiThread(() -> performRedirectToVerificationActivity(timestamp));
241    }
242}