EnterPhoneNumberActivity.java

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