VerifyActivity.java

  1package eu.siacs.conversations.ui;
  2
  3import android.app.AlertDialog;
  4import android.content.ClipData;
  5import android.content.ClipDescription;
  6import android.content.ClipboardManager;
  7import android.content.Context;
  8import android.content.Intent;
  9import android.databinding.DataBindingUtil;
 10import android.os.Bundle;
 11import android.os.Handler;
 12import android.os.SystemClock;
 13import android.support.design.widget.Snackbar;
 14import android.support.v7.widget.Toolbar;
 15import android.text.Html;
 16import android.view.View;
 17
 18import eu.siacs.conversations.R;
 19import eu.siacs.conversations.databinding.ActivityVerifyBinding;
 20import eu.siacs.conversations.entities.Account;
 21import eu.siacs.conversations.services.QuickConversationsService;
 22import eu.siacs.conversations.ui.util.ApiDialogHelper;
 23import eu.siacs.conversations.ui.util.PinEntryWrapper;
 24import eu.siacs.conversations.utils.AccountUtils;
 25import eu.siacs.conversations.utils.PhoneNumberUtilWrapper;
 26import eu.siacs.conversations.utils.TimeframeUtils;
 27import io.michaelrocks.libphonenumber.android.NumberParseException;
 28
 29import static android.content.ClipDescription.MIMETYPE_TEXT_PLAIN;
 30
 31public class VerifyActivity extends XmppActivity implements ClipboardManager.OnPrimaryClipChangedListener, QuickConversationsService.OnVerification, QuickConversationsService.OnVerificationRequested {
 32
 33    public static final String EXTRA_RETRY_SMS_AFTER = "retry_sms_after";
 34    private static final String EXTRA_RETRY_VERIFICATION_AFTER = "retry_verification_after";
 35    private final Handler mHandler = new Handler();
 36    private ActivityVerifyBinding binding;
 37    private Account account;
 38    private PinEntryWrapper pinEntryWrapper;
 39    private ClipboardManager clipboardManager;
 40    private String pasted = null;
 41    private boolean verifying = false;
 42    private boolean requestingVerification = false;
 43    private long retrySmsAfter = 0;
 44    private final Runnable SMS_TIMEOUT_UPDATER = new Runnable() {
 45        @Override
 46        public void run() {
 47            if (setTimeoutLabelInResendButton()) {
 48                mHandler.postDelayed(this, 300);
 49            }
 50        }
 51    };
 52    private long retryVerificationAfter = 0;
 53    private final Runnable VERIFICATION_TIMEOUT_UPDATER = new Runnable() {
 54        @Override
 55        public void run() {
 56            if (setTimeoutLabelInNextButton()) {
 57                mHandler.postDelayed(this, 300);
 58            }
 59        }
 60    };
 61
 62    private boolean setTimeoutLabelInResendButton() {
 63        if (retrySmsAfter != 0) {
 64            long remaining = retrySmsAfter - SystemClock.elapsedRealtime();
 65            if (remaining >= 0) {
 66                binding.resendSms.setEnabled(false);
 67                binding.resendSms.setText(getString(R.string.resend_sms_in, TimeframeUtils.resolve(VerifyActivity.this, remaining)));
 68                return true;
 69            }
 70        }
 71        binding.resendSms.setEnabled(true);
 72        binding.resendSms.setText(R.string.resend_sms);
 73        return false;
 74    }
 75
 76    private boolean setTimeoutLabelInNextButton() {
 77        if (retryVerificationAfter != 0) {
 78            long remaining = retryVerificationAfter - SystemClock.elapsedRealtime();
 79            if (remaining >= 0) {
 80                binding.next.setEnabled(false);
 81                binding.next.setText(getString(R.string.wait_x, TimeframeUtils.resolve(VerifyActivity.this, remaining)));
 82                return true;
 83            }
 84        }
 85        this.binding.next.setEnabled(!verifying);
 86        this.binding.next.setText(verifying ? R.string.verifying : R.string.next);
 87        return false;
 88    }
 89
 90    @Override
 91    protected void onCreate(final Bundle savedInstanceState) {
 92        super.onCreate(savedInstanceState);
 93        String pin = savedInstanceState != null ? savedInstanceState.getString("pin") : null;
 94        boolean verifying = savedInstanceState != null && savedInstanceState.getBoolean("verifying");
 95        boolean requestingVerification = savedInstanceState != null && savedInstanceState.getBoolean("requesting_verification", false);
 96        this.pasted = savedInstanceState != null ? savedInstanceState.getString("pasted") : null;
 97        this.retrySmsAfter = savedInstanceState != null ? savedInstanceState.getLong(EXTRA_RETRY_SMS_AFTER, 0L) : 0L;
 98        this.retryVerificationAfter = savedInstanceState != null ? savedInstanceState.getLong(EXTRA_RETRY_VERIFICATION_AFTER, 0L) : 0L;
 99        this.binding = DataBindingUtil.setContentView(this, R.layout.activity_verify);
100        setSupportActionBar((Toolbar) this.binding.toolbar);
101        this.pinEntryWrapper = new PinEntryWrapper(binding.pinBox);
102        if (pin != null) {
103            this.pinEntryWrapper.setPin(pin);
104        }
105        binding.back.setOnClickListener(this::onBackButton);
106        binding.next.setOnClickListener(this::onNextButton);
107        binding.resendSms.setOnClickListener(this::onResendSmsButton);
108        clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
109        setVerifyingState(verifying);
110        setRequestingVerificationState(requestingVerification);
111    }
112
113    private void onBackButton(View view) {
114        if (this.verifying) {
115            setVerifyingState(false);
116            return;
117        }
118        final Intent intent = new Intent(this, EnterPhoneNumberActivity.class);
119        if (this.account != null) {
120            AlertDialog.Builder builder = new AlertDialog.Builder(this);
121            builder.setMessage(R.string.abort_registration_procedure);
122            builder.setPositiveButton(R.string.yes, (dialog, which) -> {
123                xmppConnectionService.deleteAccount(account);
124                startActivity(intent);
125                finish();
126            });
127            builder.setNegativeButton(R.string.no, null);
128            builder.create().show();
129        } else {
130            startActivity(intent);
131            finish();
132        }
133    }
134
135    private void onNextButton(View view) {
136        final String pin = pinEntryWrapper.getPin();
137        if (PinEntryWrapper.isValidPin(pin)) {
138            if (account != null && xmppConnectionService != null) {
139                setVerifyingState(true);
140                xmppConnectionService.getQuickConversationsService().verify(account, pin);
141            }
142        } else {
143            AlertDialog.Builder builder = new AlertDialog.Builder(this);
144            builder.setMessage(R.string.please_enter_pin);
145            builder.setPositiveButton(R.string.ok, null);
146            builder.create().show();
147        }
148    }
149
150    private void onResendSmsButton(View view) {
151        try {
152            xmppConnectionService.getQuickConversationsService().requestVerification(PhoneNumberUtilWrapper.toPhoneNumber(this, account.getJid()));
153            setRequestingVerificationState(true);
154        } catch (NumberParseException e) {
155
156        }
157    }
158
159    private void setVerifyingState(boolean verifying) {
160        this.verifying = verifying;
161        this.binding.back.setText(verifying ? R.string.cancel : R.string.back);
162        this.binding.next.setEnabled(!verifying);
163        this.binding.next.setText(verifying ? R.string.verifying : R.string.next);
164        this.binding.resendSms.setVisibility(verifying ? View.GONE : View.VISIBLE);
165        pinEntryWrapper.setEnabled(!verifying);
166        this.binding.progressBar.setVisibility(verifying ? View.VISIBLE : View.GONE);
167        this.binding.progressBar.setIndeterminate(verifying);
168    }
169
170    private void setRequestingVerificationState(boolean requesting) {
171        this.requestingVerification = requesting;
172        if (requesting) {
173            this.binding.resendSms.setEnabled(false);
174            this.binding.resendSms.setText(R.string.requesting_sms);
175        } else {
176            setTimeoutLabelInResendButton();
177        }
178
179    }
180
181    @Override
182    protected void refreshUiReal() {
183
184    }
185
186    @Override
187    void onBackendConnected() {
188        xmppConnectionService.getQuickConversationsService().addOnVerificationListener(this);
189        xmppConnectionService.getQuickConversationsService().addOnVerificationRequestedListener(this);
190        this.account = AccountUtils.getFirst(xmppConnectionService);
191        if (this.account == null) {
192            return;
193        }
194        this.binding.weHaveSent.setText(Html.fromHtml(getString(R.string.we_have_sent_you_an_sms_to_x, PhoneNumberUtilWrapper.toFormattedPhoneNumber(this, this.account.getJid()))));
195        setVerifyingState(xmppConnectionService.getQuickConversationsService().isVerifying());
196        setRequestingVerificationState(xmppConnectionService.getQuickConversationsService().isRequestingVerification());
197    }
198
199    @Override
200    public void onSaveInstanceState(Bundle savedInstanceState) {
201        savedInstanceState.putString("pin", this.pinEntryWrapper.getPin());
202        savedInstanceState.putBoolean("verifying", this.verifying);
203        savedInstanceState.putBoolean("requesting_verification", this.requestingVerification);
204        savedInstanceState.putLong(EXTRA_RETRY_SMS_AFTER, this.retrySmsAfter);
205        savedInstanceState.putLong(EXTRA_RETRY_VERIFICATION_AFTER, this.retryVerificationAfter);
206        if (this.pasted != null) {
207            savedInstanceState.putString("pasted", this.pasted);
208        }
209        super.onSaveInstanceState(savedInstanceState);
210    }
211
212    @Override
213    public void onStart() {
214        super.onStart();
215        clipboardManager.addPrimaryClipChangedListener(this);
216        final Intent intent = getIntent();
217        this.retrySmsAfter = intent != null ? intent.getLongExtra(EXTRA_RETRY_SMS_AFTER, this.retrySmsAfter) : this.retrySmsAfter;
218        if (this.retrySmsAfter > 0) {
219            mHandler.post(SMS_TIMEOUT_UPDATER);
220        }
221        if (this.retryVerificationAfter > 0) {
222            mHandler.post(VERIFICATION_TIMEOUT_UPDATER);
223        }
224    }
225
226    @Override
227    public void onStop() {
228        super.onStop();
229        mHandler.removeCallbacks(SMS_TIMEOUT_UPDATER);
230        mHandler.removeCallbacks(VERIFICATION_TIMEOUT_UPDATER);
231        clipboardManager.removePrimaryClipChangedListener(this);
232        if (xmppConnectionService != null) {
233            xmppConnectionService.getQuickConversationsService().removeOnVerificationListener(this);
234            xmppConnectionService.getQuickConversationsService().removeOnVerificationRequestedListener(this);
235        }
236    }
237
238    @Override
239    public void onResume() {
240        super.onResume();
241        if (pinEntryWrapper.isEmpty()) {
242            pastePinFromClipboard();
243        }
244    }
245
246    private void pastePinFromClipboard() {
247        final ClipDescription description = clipboardManager != null ? clipboardManager.getPrimaryClipDescription() : null;
248        if (description != null && description.hasMimeType(MIMETYPE_TEXT_PLAIN)) {
249            final ClipData primaryClip = clipboardManager.getPrimaryClip();
250            if (primaryClip != null && primaryClip.getItemCount() > 0) {
251                final CharSequence clip = primaryClip.getItemAt(0).getText();
252                if (PinEntryWrapper.isValidPin(clip) && !clip.toString().equals(this.pasted)) {
253                    this.pasted = clip.toString();
254                    pinEntryWrapper.setPin(clip.toString());
255                    final Snackbar snackbar = Snackbar.make(binding.coordinator, R.string.possible_pin, Snackbar.LENGTH_LONG);
256                    snackbar.setAction(R.string.undo, v -> pinEntryWrapper.clear());
257                    snackbar.show();
258                }
259            }
260        }
261    }
262
263    private void performPostVerificationRedirect() {
264        Intent intent = new Intent(this, PublishProfilePictureActivity.class);
265        intent.putExtra(PublishProfilePictureActivity.EXTRA_ACCOUNT, account.getJid().asBareJid().toEscapedString());
266        intent.putExtra("setup", true);
267        startActivity(intent);
268        finish();
269    }
270
271    @Override
272    public void onPrimaryClipChanged() {
273        this.pasted = null;
274        if (pinEntryWrapper.isEmpty()) {
275            pastePinFromClipboard();
276        }
277    }
278
279    @Override
280    public void onVerificationFailed(final int code) {
281        runOnUiThread(() -> {
282            setVerifyingState(false);
283            if (code == 401) {
284                AlertDialog.Builder builder = new AlertDialog.Builder(this);
285                builder.setMessage(R.string.incorrect_pin);
286                builder.setPositiveButton(R.string.ok, null);
287                builder.create().show();
288            } else {
289                ApiDialogHelper.createError(this, code).show();
290            }
291        });
292    }
293
294    @Override
295    public void onVerificationSucceeded() {
296        runOnUiThread(this::performPostVerificationRedirect);
297    }
298
299    @Override
300    public void onVerificationRetryAt(long timestamp) {
301        this.retryVerificationAfter = timestamp;
302        runOnUiThread(() -> {
303            ApiDialogHelper.createTooManyAttempts(this).show();
304            setVerifyingState(false);
305        });
306        mHandler.removeCallbacks(VERIFICATION_TIMEOUT_UPDATER);
307        runOnUiThread(VERIFICATION_TIMEOUT_UPDATER);
308    }
309
310    //send sms again button callback
311    @Override
312    public void onVerificationRequestFailed(int code) {
313        runOnUiThread(() -> {
314            setRequestingVerificationState(false);
315            ApiDialogHelper.createError(this, code).show();
316        });
317    }
318
319    //send sms again button callback
320    @Override
321    public void onVerificationRequested() {
322        runOnUiThread(() -> {
323            setRequestingVerificationState(false);
324            AlertDialog.Builder builder = new AlertDialog.Builder(this);
325            builder.setMessage(R.string.we_have_sent_you_another_sms);
326            builder.setPositiveButton(R.string.ok, null);
327            builder.create().show();
328        });
329    }
330
331    @Override
332    public void onVerificationRequestedRetryAt(long timestamp) {
333        this.retrySmsAfter = timestamp;
334        runOnUiThread(() -> {
335            ApiDialogHelper.createRateLimited(this, timestamp).show();
336            setRequestingVerificationState(false);
337        });
338        mHandler.removeCallbacks(SMS_TIMEOUT_UPDATER);
339        runOnUiThread(SMS_TIMEOUT_UPDATER);
340    }
341}