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