1package eu.siacs.conversations.ui;
2
3import android.app.Activity;
4import android.app.PendingIntent;
5import android.content.ActivityNotFoundException;
6import android.content.Intent;
7import android.content.IntentSender;
8import android.content.SharedPreferences;
9import android.databinding.DataBindingUtil;
10import android.graphics.Bitmap;
11import android.net.Uri;
12import android.os.Bundle;
13import android.os.Handler;
14import android.preference.PreferenceManager;
15import android.provider.Settings;
16import android.security.KeyChain;
17import android.security.KeyChainAliasCallback;
18import android.support.design.widget.TextInputLayout;
19import android.support.v7.app.ActionBar;
20import android.support.v7.app.AlertDialog;
21import android.support.v7.app.AlertDialog.Builder;
22import android.support.v7.widget.Toolbar;
23import android.text.Editable;
24import android.text.TextUtils;
25import android.text.TextWatcher;
26import android.util.Log;
27import android.view.Menu;
28import android.view.MenuItem;
29import android.view.View;
30import android.view.View.OnClickListener;
31import android.widget.CompoundButton.OnCheckedChangeListener;
32import android.widget.EditText;
33import android.widget.ImageView;
34import android.widget.Toast;
35
36import com.google.common.base.CharMatcher;
37
38import org.openintents.openpgp.util.OpenPgpUtils;
39
40import java.net.URL;
41import java.util.Arrays;
42import java.util.List;
43import java.util.Set;
44import java.util.concurrent.atomic.AtomicBoolean;
45import java.util.concurrent.atomic.AtomicInteger;
46
47import eu.siacs.conversations.Config;
48import eu.siacs.conversations.R;
49import eu.siacs.conversations.crypto.axolotl.AxolotlService;
50import eu.siacs.conversations.crypto.axolotl.XmppAxolotlSession;
51import eu.siacs.conversations.databinding.ActivityEditAccountBinding;
52import eu.siacs.conversations.databinding.DialogPresenceBinding;
53import eu.siacs.conversations.entities.Account;
54import eu.siacs.conversations.entities.Presence;
55import eu.siacs.conversations.entities.PresenceTemplate;
56import eu.siacs.conversations.services.BarcodeProvider;
57import eu.siacs.conversations.services.QuickConversationsService;
58import eu.siacs.conversations.services.XmppConnectionService;
59import eu.siacs.conversations.services.XmppConnectionService.OnAccountUpdate;
60import eu.siacs.conversations.services.XmppConnectionService.OnCaptchaRequested;
61import eu.siacs.conversations.ui.adapter.KnownHostsAdapter;
62import eu.siacs.conversations.ui.adapter.PresenceTemplateAdapter;
63import eu.siacs.conversations.ui.util.AvatarWorkerTask;
64import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
65import eu.siacs.conversations.ui.util.PendingItem;
66import eu.siacs.conversations.ui.util.SoftKeyboardUtils;
67import eu.siacs.conversations.utils.CryptoHelper;
68import eu.siacs.conversations.utils.Resolver;
69import eu.siacs.conversations.utils.SignupUtils;
70import eu.siacs.conversations.utils.TorServiceUtils;
71import eu.siacs.conversations.utils.UIHelper;
72import eu.siacs.conversations.utils.XmppUri;
73import eu.siacs.conversations.xml.Element;
74import eu.siacs.conversations.xmpp.Jid;
75import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
76import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
77import eu.siacs.conversations.xmpp.XmppConnection;
78import eu.siacs.conversations.xmpp.XmppConnection.Features;
79import eu.siacs.conversations.xmpp.forms.Data;
80import eu.siacs.conversations.xmpp.pep.Avatar;
81
82public class EditAccountActivity extends OmemoActivity implements OnAccountUpdate, OnUpdateBlocklist,
83 OnKeyStatusUpdated, OnCaptchaRequested, KeyChainAliasCallback, XmppConnectionService.OnShowErrorToast, XmppConnectionService.OnMamPreferencesFetched {
84
85 public static final String EXTRA_OPENED_FROM_NOTIFICATION = "opened_from_notification";
86 public static final String EXTRA_FORCE_REGISTER = "force_register";
87
88 private static final int REQUEST_DATA_SAVER = 0xf244;
89 private static final int REQUEST_CHANGE_STATUS = 0xee11;
90 private static final int REQUEST_ORBOT = 0xff22;
91 private final PendingItem<PresenceTemplate> mPendingPresenceTemplate = new PendingItem<>();
92 private final AtomicBoolean mPendingReconnect = new AtomicBoolean(false);
93 private AlertDialog mCaptchaDialog = null;
94 private Jid jidToEdit;
95 private boolean mInitMode = false;
96 private Boolean mForceRegister = null;
97 private boolean mUsernameMode = Config.DOMAIN_LOCK != null;
98 private boolean mShowOptions = false;
99 private Account mAccount;
100 private final OnClickListener mCancelButtonClickListener = v -> {
101 deleteAccountAndReturnIfNecessary();
102 finish();
103 };
104 private final UiCallback<Avatar> mAvatarFetchCallback = new UiCallback<Avatar>() {
105
106 @Override
107 public void userInputRequired(final PendingIntent pi, final Avatar avatar) {
108 finishInitialSetup(avatar);
109 }
110
111 @Override
112 public void success(final Avatar avatar) {
113 finishInitialSetup(avatar);
114 }
115
116 @Override
117 public void error(final int errorCode, final Avatar avatar) {
118 finishInitialSetup(avatar);
119 }
120 };
121 private final OnClickListener mAvatarClickListener = new OnClickListener() {
122 @Override
123 public void onClick(final View view) {
124 if (mAccount != null) {
125 final Intent intent = new Intent(getApplicationContext(), PublishProfilePictureActivity.class);
126 intent.putExtra(EXTRA_ACCOUNT, mAccount.getJid().asBareJid().toEscapedString());
127 startActivity(intent);
128 }
129 }
130 };
131 private String messageFingerprint;
132 private boolean mFetchingAvatar = false;
133 private Toast mFetchingMamPrefsToast;
134 private String mSavedInstanceAccount;
135 private boolean mSavedInstanceInit = false;
136 private XmppUri pendingUri = null;
137 private boolean mUseTor;
138 private ActivityEditAccountBinding binding;
139 private final OnClickListener mSaveButtonClickListener = new OnClickListener() {
140
141 @Override
142 public void onClick(final View v) {
143 final String password = binding.accountPassword.getText().toString();
144 final boolean wasDisabled = mAccount != null && mAccount.getStatus() == Account.State.DISABLED;
145 final boolean accountInfoEdited = accountInfoEdited();
146
147 if (mInitMode && mAccount != null) {
148 mAccount.setOption(Account.OPTION_DISABLED, false);
149 }
150 if (mAccount != null && mAccount.getStatus() == Account.State.DISABLED && !accountInfoEdited) {
151 mAccount.setOption(Account.OPTION_DISABLED, false);
152 if (!xmppConnectionService.updateAccount(mAccount)) {
153 Toast.makeText(EditAccountActivity.this, R.string.unable_to_update_account, Toast.LENGTH_SHORT).show();
154 }
155 return;
156 }
157 final boolean registerNewAccount;
158 if (mForceRegister != null) {
159 registerNewAccount = mForceRegister;
160 } else {
161 registerNewAccount = binding.accountRegisterNew.isChecked() && !Config.DISALLOW_REGISTRATION_IN_UI;
162 }
163 if (mUsernameMode && binding.accountJid.getText().toString().contains("@")) {
164 binding.accountJidLayout.setError(getString(R.string.invalid_username));
165 removeErrorsOnAllBut(binding.accountJidLayout);
166 binding.accountJid.requestFocus();
167 return;
168 }
169
170 XmppConnection connection = mAccount == null ? null : mAccount.getXmppConnection();
171 final boolean startOrbot = mAccount != null && mAccount.getStatus() == Account.State.TOR_NOT_AVAILABLE;
172 if (startOrbot) {
173 if (TorServiceUtils.isOrbotInstalled(EditAccountActivity.this)) {
174 TorServiceUtils.startOrbot(EditAccountActivity.this, REQUEST_ORBOT);
175 } else {
176 TorServiceUtils.downloadOrbot(EditAccountActivity.this, REQUEST_ORBOT);
177 }
178 return;
179 }
180
181 if (inNeedOfSaslAccept()) {
182 mAccount.setKey(Account.PINNED_MECHANISM_KEY, String.valueOf(-1));
183 if (!xmppConnectionService.updateAccount(mAccount)) {
184 Toast.makeText(EditAccountActivity.this, R.string.unable_to_update_account, Toast.LENGTH_SHORT).show();
185 }
186 return;
187 }
188
189 final boolean openRegistrationUrl = registerNewAccount && !accountInfoEdited && mAccount != null && mAccount.getStatus() == Account.State.REGISTRATION_WEB;
190 final boolean openPaymentUrl = mAccount != null && mAccount.getStatus() == Account.State.PAYMENT_REQUIRED;
191 final boolean redirectionWorthyStatus = openPaymentUrl || openRegistrationUrl;
192 URL url = connection != null && redirectionWorthyStatus ? connection.getRedirectionUrl() : null;
193 if (url != null && !wasDisabled) {
194 try {
195 startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url.toString())));
196 return;
197 } catch (ActivityNotFoundException e) {
198 Toast.makeText(EditAccountActivity.this, R.string.application_found_to_open_website, Toast.LENGTH_SHORT).show();
199 return;
200 }
201 }
202
203 final Jid jid;
204 try {
205 if (mUsernameMode) {
206 jid = Jid.ofEscaped(binding.accountJid.getText().toString(), getUserModeDomain(), null);
207 } else {
208 jid = Jid.ofEscaped(binding.accountJid.getText().toString());
209 }
210 } catch (final NullPointerException | IllegalArgumentException e) {
211 if (mUsernameMode) {
212 binding.accountJidLayout.setError(getString(R.string.invalid_username));
213 } else {
214 binding.accountJidLayout.setError(getString(R.string.invalid_jid));
215 }
216 binding.accountJid.requestFocus();
217 removeErrorsOnAllBut(binding.accountJidLayout);
218 return;
219 }
220 final String hostname;
221 int numericPort = 5222;
222 if (mShowOptions) {
223 hostname = CharMatcher.whitespace().removeFrom(binding.hostname.getText());
224 final String port = CharMatcher.whitespace().removeFrom(binding.port.getText());
225 if (Resolver.invalidHostname(hostname)) {
226 binding.hostnameLayout.setError(getString(R.string.not_valid_hostname));
227 binding.hostname.requestFocus();
228 removeErrorsOnAllBut(binding.hostnameLayout);
229 return;
230 }
231 if (!hostname.isEmpty()) {
232 try {
233 numericPort = Integer.parseInt(port);
234 if (numericPort < 0 || numericPort > 65535) {
235 binding.portLayout.setError(getString(R.string.not_a_valid_port));
236 removeErrorsOnAllBut(binding.portLayout);
237 binding.port.requestFocus();
238 return;
239 }
240
241 } catch (NumberFormatException e) {
242 binding.portLayout.setError(getString(R.string.not_a_valid_port));
243 removeErrorsOnAllBut(binding.portLayout);
244 binding.port.requestFocus();
245 return;
246 }
247 }
248 } else {
249 hostname = null;
250 }
251
252 if (jid.getLocal() == null) {
253 if (mUsernameMode) {
254 binding.accountJidLayout.setError(getString(R.string.invalid_username));
255 } else {
256 binding.accountJidLayout.setError(getString(R.string.invalid_jid));
257 }
258 removeErrorsOnAllBut(binding.accountJidLayout);
259 binding.accountJid.requestFocus();
260 return;
261 }
262 if (mAccount != null) {
263 if (mAccount.isOptionSet(Account.OPTION_MAGIC_CREATE)) {
264 mAccount.setOption(Account.OPTION_MAGIC_CREATE, mAccount.getPassword().contains(password));
265 }
266 mAccount.setJid(jid);
267 mAccount.setPort(numericPort);
268 mAccount.setHostname(hostname);
269 binding.accountJidLayout.setError(null);
270 mAccount.setPassword(password);
271 mAccount.setOption(Account.OPTION_REGISTER, registerNewAccount);
272 if (!xmppConnectionService.updateAccount(mAccount)) {
273 Toast.makeText(EditAccountActivity.this, R.string.unable_to_update_account, Toast.LENGTH_SHORT).show();
274 return;
275 }
276 } else {
277 if (xmppConnectionService.findAccountByJid(jid) != null) {
278 binding.accountJidLayout.setError(getString(R.string.account_already_exists));
279 removeErrorsOnAllBut(binding.accountJidLayout);
280 binding.accountJid.requestFocus();
281 return;
282 }
283 mAccount = new Account(jid.asBareJid(), password);
284 mAccount.setPort(numericPort);
285 mAccount.setHostname(hostname);
286 mAccount.setOption(Account.OPTION_USETLS, true);
287 mAccount.setOption(Account.OPTION_USECOMPRESSION, true);
288 mAccount.setOption(Account.OPTION_REGISTER, registerNewAccount);
289 xmppConnectionService.createAccount(mAccount);
290 }
291 binding.hostnameLayout.setError(null);
292 binding.portLayout.setError(null);
293 if (mAccount.isEnabled()
294 && !registerNewAccount
295 && !mInitMode) {
296 finish();
297 } else {
298 updateSaveButton();
299 updateAccountInformation(true);
300 }
301
302 }
303 };
304 private final TextWatcher mTextWatcher = new TextWatcher() {
305
306 @Override
307 public void onTextChanged(final CharSequence s, final int start, final int before, final int count) {
308 updatePortLayout();
309 updateSaveButton();
310 }
311
312 @Override
313 public void beforeTextChanged(final CharSequence s, final int start, final int count, final int after) {
314 }
315
316 @Override
317 public void afterTextChanged(final Editable s) {
318
319 }
320 };
321 private View.OnFocusChangeListener mEditTextFocusListener = new View.OnFocusChangeListener() {
322 @Override
323 public void onFocusChange(View view, boolean b) {
324 EditText et = (EditText) view;
325 if (b) {
326 int resId = mUsernameMode ? R.string.username : R.string.account_settings_example_jabber_id;
327 if (view.getId() == R.id.hostname) {
328 resId = mUseTor ? R.string.hostname_or_onion : R.string.hostname_example;
329 }
330 final int res = resId;
331 new Handler().postDelayed(() -> et.setHint(res), 200);
332 } else {
333 et.setHint(null);
334 }
335 }
336 };
337
338 private static void setAvailabilityRadioButton(Presence.Status status, DialogPresenceBinding binding) {
339 if (status == null) {
340 binding.online.setChecked(true);
341 return;
342 }
343 switch (status) {
344 case DND:
345 binding.dnd.setChecked(true);
346 break;
347 case XA:
348 binding.xa.setChecked(true);
349 break;
350 case AWAY:
351 binding.away.setChecked(true);
352 break;
353 default:
354 binding.online.setChecked(true);
355 }
356 }
357
358 private static Presence.Status getAvailabilityRadioButton(DialogPresenceBinding binding) {
359 if (binding.dnd.isChecked()) {
360 return Presence.Status.DND;
361 } else if (binding.xa.isChecked()) {
362 return Presence.Status.XA;
363 } else if (binding.away.isChecked()) {
364 return Presence.Status.AWAY;
365 } else {
366 return Presence.Status.ONLINE;
367 }
368 }
369
370 public void refreshUiReal() {
371 invalidateOptionsMenu();
372 if (mAccount != null
373 && mAccount.getStatus() != Account.State.ONLINE
374 && mFetchingAvatar) {
375 Intent intent = new Intent(this, StartConversationActivity.class);
376 StartConversationActivity.addInviteUri(intent, getIntent());
377 startActivity(intent);
378 finish();
379 } else if (mInitMode && mAccount != null && mAccount.getStatus() == Account.State.ONLINE) {
380 if (!mFetchingAvatar) {
381 mFetchingAvatar = true;
382 xmppConnectionService.checkForAvatar(mAccount, mAvatarFetchCallback);
383 }
384 }
385 if (mAccount != null) {
386 updateAccountInformation(false);
387 }
388 updateSaveButton();
389 }
390
391 @Override
392 public boolean onNavigateUp() {
393 deleteAccountAndReturnIfNecessary();
394 return super.onNavigateUp();
395 }
396
397 @Override
398 public void onBackPressed() {
399 deleteAccountAndReturnIfNecessary();
400 super.onBackPressed();
401 }
402
403 private void deleteAccountAndReturnIfNecessary() {
404 if (mInitMode && mAccount != null && !mAccount.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY)) {
405 xmppConnectionService.deleteAccount(mAccount);
406 }
407
408 final boolean magicCreate = mAccount != null && mAccount.isOptionSet(Account.OPTION_MAGIC_CREATE) && !mAccount.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY);
409 final Jid jid = mAccount == null ? null : mAccount.getJid();
410
411 if (SignupUtils.isSupportTokenRegistry() && jid != null && magicCreate && !jid.getDomain().equals(Config.MAGIC_CREATE_DOMAIN)) {
412 final Jid preset;
413 if (mAccount.isOptionSet(Account.OPTION_FIXED_USERNAME)) {
414 preset = jid.asBareJid();
415 } else {
416 preset = jid.getDomain();
417 }
418 final Intent intent = SignupUtils.getTokenRegistrationIntent(this, preset, mAccount.getKey(Account.PRE_AUTH_REGISTRATION_TOKEN));
419 StartConversationActivity.addInviteUri(intent, getIntent());
420 startActivity(intent);
421 return;
422 }
423
424
425 final List<Account> accounts = xmppConnectionService == null ? null : xmppConnectionService.getAccounts();
426 if (accounts != null && accounts.size() == 0 && Config.MAGIC_CREATE_DOMAIN != null) {
427 Intent intent = SignupUtils.getSignUpIntent(this, mForceRegister != null && mForceRegister);
428 StartConversationActivity.addInviteUri(intent, getIntent());
429 startActivity(intent);
430 }
431 }
432
433 @Override
434 public void onAccountUpdate() {
435 refreshUi();
436 }
437
438 protected void finishInitialSetup(final Avatar avatar) {
439 runOnUiThread(() -> {
440 SoftKeyboardUtils.hideSoftKeyboard(EditAccountActivity.this);
441 final Intent intent;
442 final XmppConnection connection = mAccount.getXmppConnection();
443 final boolean wasFirstAccount = xmppConnectionService != null && xmppConnectionService.getAccounts().size() == 1;
444 if (avatar != null || (connection != null && !connection.getFeatures().pep())) {
445 intent = new Intent(getApplicationContext(), StartConversationActivity.class);
446 if (wasFirstAccount) {
447 intent.putExtra("init", true);
448 }
449 intent.putExtra(EXTRA_ACCOUNT, mAccount.getJid().asBareJid().toEscapedString());
450 } else {
451 intent = new Intent(getApplicationContext(), PublishProfilePictureActivity.class);
452 intent.putExtra(EXTRA_ACCOUNT, mAccount.getJid().asBareJid().toEscapedString());
453 intent.putExtra("setup", true);
454 }
455 if (wasFirstAccount) {
456 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
457 }
458 StartConversationActivity.addInviteUri(intent, getIntent());
459 startActivity(intent);
460 finish();
461 });
462 }
463
464 @Override
465 public void onActivityResult(int requestCode, int resultCode, Intent data) {
466 super.onActivityResult(requestCode, resultCode, data);
467 if (requestCode == REQUEST_BATTERY_OP || requestCode == REQUEST_DATA_SAVER) {
468 updateAccountInformation(mAccount == null);
469 }
470 if (requestCode == REQUEST_CHANGE_STATUS) {
471 PresenceTemplate template = mPendingPresenceTemplate.pop();
472 if (template != null && resultCode == Activity.RESULT_OK) {
473 generateSignature(data, template);
474 } else {
475 Log.d(Config.LOGTAG, "pgp result not ok");
476 }
477 }
478 if (requestCode == REQUEST_ORBOT) {
479 if (xmppConnectionService != null && mAccount != null) {
480 xmppConnectionService.reconnectAccountInBackground(mAccount);
481 } else {
482 mPendingReconnect.set(true);
483 }
484 }
485 }
486
487 @Override
488 protected void processFingerprintVerification(XmppUri uri) {
489 processFingerprintVerification(uri, true);
490 }
491
492 protected void processFingerprintVerification(XmppUri uri, boolean showWarningToast) {
493 if (mAccount != null && mAccount.getJid().asBareJid().equals(uri.getJid()) && uri.hasFingerprints()) {
494 if (xmppConnectionService.verifyFingerprints(mAccount, uri.getFingerprints())) {
495 Toast.makeText(this, R.string.verified_fingerprints, Toast.LENGTH_SHORT).show();
496 updateAccountInformation(false);
497 }
498 } else if (showWarningToast) {
499 Toast.makeText(this, R.string.invalid_barcode, Toast.LENGTH_SHORT).show();
500 }
501 }
502
503 private void updatePortLayout() {
504 final String hostname = this.binding.hostname.getText().toString();
505 if (TextUtils.isEmpty(hostname)) {
506 this.binding.portLayout.setEnabled(false);
507 this.binding.portLayout.setError(null);
508 } else {
509 this.binding.portLayout.setEnabled(true);
510 }
511 }
512
513 protected void updateSaveButton() {
514 boolean accountInfoEdited = accountInfoEdited();
515
516 if (accountInfoEdited && !mInitMode) {
517 this.binding.saveButton.setText(R.string.save);
518 this.binding.saveButton.setEnabled(true);
519 } else if (mAccount != null
520 && (mAccount.getStatus() == Account.State.CONNECTING || mAccount.getStatus() == Account.State.REGISTRATION_SUCCESSFUL || mFetchingAvatar)) {
521 this.binding.saveButton.setEnabled(false);
522 this.binding.saveButton.setText(R.string.account_status_connecting);
523 } else if (mAccount != null && mAccount.getStatus() == Account.State.DISABLED && !mInitMode) {
524 this.binding.saveButton.setEnabled(true);
525 this.binding.saveButton.setText(R.string.enable);
526 } else if (torNeedsInstall(mAccount)) {
527 this.binding.saveButton.setEnabled(true);
528 this.binding.saveButton.setText(R.string.install_orbot);
529 } else if (torNeedsStart(mAccount)) {
530 this.binding.saveButton.setEnabled(true);
531 this.binding.saveButton.setText(R.string.start_orbot);
532 } else {
533 this.binding.saveButton.setEnabled(true);
534 if (!mInitMode) {
535 if (mAccount != null && mAccount.isOnlineAndConnected()) {
536 this.binding.saveButton.setText(R.string.save);
537 if (!accountInfoEdited) {
538 this.binding.saveButton.setEnabled(false);
539 }
540 } else {
541 XmppConnection connection = mAccount == null ? null : mAccount.getXmppConnection();
542 URL url = connection != null && mAccount.getStatus() == Account.State.PAYMENT_REQUIRED ? connection.getRedirectionUrl() : null;
543 if (url != null) {
544 this.binding.saveButton.setText(R.string.open_website);
545 } else if (inNeedOfSaslAccept()) {
546 this.binding.saveButton.setText(R.string.accept);
547 } else {
548 this.binding.saveButton.setText(R.string.connect);
549 }
550 }
551 } else {
552 XmppConnection connection = mAccount == null ? null : mAccount.getXmppConnection();
553 URL url = connection != null && mAccount.getStatus() == Account.State.REGISTRATION_WEB ? connection.getRedirectionUrl() : null;
554 if (url != null && this.binding.accountRegisterNew.isChecked() && !accountInfoEdited) {
555 this.binding.saveButton.setText(R.string.open_website);
556 } else {
557 this.binding.saveButton.setText(R.string.next);
558 }
559 }
560 }
561 }
562
563 private boolean torNeedsInstall(final Account account) {
564 return account != null && account.getStatus() == Account.State.TOR_NOT_AVAILABLE && !TorServiceUtils.isOrbotInstalled(this);
565 }
566
567 private boolean torNeedsStart(final Account account) {
568 return account != null && account.getStatus() == Account.State.TOR_NOT_AVAILABLE;
569 }
570
571 protected boolean accountInfoEdited() {
572 if (this.mAccount == null) {
573 return false;
574 }
575 return jidEdited() ||
576 !this.mAccount.getPassword().equals(this.binding.accountPassword.getText().toString()) ||
577 !this.mAccount.getHostname().equals(this.binding.hostname.getText().toString()) ||
578 !String.valueOf(this.mAccount.getPort()).equals(this.binding.port.getText().toString());
579 }
580
581 protected boolean jidEdited() {
582 final String unmodified;
583 if (mUsernameMode) {
584 unmodified = this.mAccount.getJid().getEscapedLocal();
585 } else {
586 unmodified = this.mAccount.getJid().asBareJid().toEscapedString();
587 }
588 return !unmodified.equals(this.binding.accountJid.getText().toString());
589 }
590
591 @Override
592 protected String getShareableUri(boolean http) {
593 if (mAccount != null) {
594 return http ? mAccount.getShareableLink() : mAccount.getShareableUri();
595 } else {
596 return null;
597 }
598 }
599
600 @Override
601 protected void onCreate(final Bundle savedInstanceState) {
602 super.onCreate(savedInstanceState);
603 if (savedInstanceState != null) {
604 this.mSavedInstanceAccount = savedInstanceState.getString("account");
605 this.mSavedInstanceInit = savedInstanceState.getBoolean("initMode", false);
606 }
607 this.binding = DataBindingUtil.setContentView(this, R.layout.activity_edit_account);
608 setSupportActionBar((Toolbar) binding.toolbar);
609 binding.accountJid.addTextChangedListener(this.mTextWatcher);
610 binding.accountJid.setOnFocusChangeListener(this.mEditTextFocusListener);
611 this.binding.accountPassword.addTextChangedListener(this.mTextWatcher);
612
613 this.binding.avater.setOnClickListener(this.mAvatarClickListener);
614 this.binding.hostname.addTextChangedListener(mTextWatcher);
615 this.binding.hostname.setOnFocusChangeListener(mEditTextFocusListener);
616 this.binding.clearDevices.setOnClickListener(v -> showWipePepDialog());
617 this.binding.port.setText(String.valueOf(Resolver.DEFAULT_PORT_XMPP));
618 this.binding.port.addTextChangedListener(mTextWatcher);
619 this.binding.saveButton.setOnClickListener(this.mSaveButtonClickListener);
620 this.binding.cancelButton.setOnClickListener(this.mCancelButtonClickListener);
621 if (savedInstanceState != null && savedInstanceState.getBoolean("showMoreTable")) {
622 changeMoreTableVisibility(true);
623 }
624 final OnCheckedChangeListener OnCheckedShowConfirmPassword = (buttonView, isChecked) -> updateSaveButton();
625 this.binding.accountRegisterNew.setOnCheckedChangeListener(OnCheckedShowConfirmPassword);
626 if (Config.DISALLOW_REGISTRATION_IN_UI) {
627 this.binding.accountRegisterNew.setVisibility(View.GONE);
628 }
629 this.binding.actionEditYourName.setOnClickListener(this::onEditYourNameClicked);
630 }
631
632 private void onEditYourNameClicked(View view) {
633 quickEdit(mAccount.getDisplayName(), R.string.your_name, value -> {
634 final String displayName = value.trim();
635 updateDisplayName(displayName);
636 mAccount.setDisplayName(displayName);
637 xmppConnectionService.publishDisplayName(mAccount);
638 refreshAvatar();
639 return null;
640 }, true);
641 }
642
643 private void refreshAvatar() {
644 AvatarWorkerTask.loadAvatar(mAccount, binding.avater, R.dimen.avatar_on_details_screen_size);
645 }
646
647 @Override
648 public boolean onCreateOptionsMenu(final Menu menu) {
649 super.onCreateOptionsMenu(menu);
650 getMenuInflater().inflate(R.menu.editaccount, menu);
651 final MenuItem showBlocklist = menu.findItem(R.id.action_show_block_list);
652 final MenuItem showMoreInfo = menu.findItem(R.id.action_server_info_show_more);
653 final MenuItem changePassword = menu.findItem(R.id.action_change_password_on_server);
654 final MenuItem renewCertificate = menu.findItem(R.id.action_renew_certificate);
655 final MenuItem mamPrefs = menu.findItem(R.id.action_mam_prefs);
656 final MenuItem changePresence = menu.findItem(R.id.action_change_presence);
657 final MenuItem share = menu.findItem(R.id.action_share);
658 renewCertificate.setVisible(mAccount != null && mAccount.getPrivateKeyAlias() != null);
659
660 share.setVisible(mAccount != null && !mInitMode);
661
662 if (mAccount != null && mAccount.isOnlineAndConnected()) {
663 if (!mAccount.getXmppConnection().getFeatures().blocking()) {
664 showBlocklist.setVisible(false);
665 }
666
667 if (!mAccount.getXmppConnection().getFeatures().register()) {
668 changePassword.setVisible(false);
669 }
670 mamPrefs.setVisible(mAccount.getXmppConnection().getFeatures().mam());
671 changePresence.setVisible(!mInitMode);
672 } else {
673 showBlocklist.setVisible(false);
674 showMoreInfo.setVisible(false);
675 changePassword.setVisible(false);
676 mamPrefs.setVisible(false);
677 changePresence.setVisible(false);
678 }
679 return super.onCreateOptionsMenu(menu);
680 }
681
682 @Override
683 public boolean onPrepareOptionsMenu(Menu menu) {
684 final MenuItem showMoreInfo = menu.findItem(R.id.action_server_info_show_more);
685 if (showMoreInfo.isVisible()) {
686 showMoreInfo.setChecked(binding.serverInfoMore.getVisibility() == View.VISIBLE);
687 }
688 return super.onPrepareOptionsMenu(menu);
689 }
690
691 @Override
692 protected void onStart() {
693 super.onStart();
694 final Intent intent = getIntent();
695 final int theme = findTheme();
696 if (this.mTheme != theme) {
697 recreate();
698 } else if (intent != null) {
699 try {
700 this.jidToEdit = Jid.ofEscaped(intent.getStringExtra("jid"));
701 } catch (final IllegalArgumentException | NullPointerException ignored) {
702 this.jidToEdit = null;
703 }
704 if (jidToEdit != null && intent.getData() != null && intent.getBooleanExtra("scanned", false)) {
705 final XmppUri uri = new XmppUri(intent.getData());
706 if (xmppConnectionServiceBound) {
707 processFingerprintVerification(uri, false);
708 } else {
709 this.pendingUri = uri;
710 }
711 }
712 boolean init = intent.getBooleanExtra("init", false);
713 boolean openedFromNotification = intent.getBooleanExtra(EXTRA_OPENED_FROM_NOTIFICATION, false);
714 Log.d(Config.LOGTAG, "extras " + intent.getExtras());
715 this.mForceRegister = intent.hasExtra(EXTRA_FORCE_REGISTER) ? intent.getBooleanExtra(EXTRA_FORCE_REGISTER, false) : null;
716 Log.d(Config.LOGTAG, "force register=" + mForceRegister);
717 this.mInitMode = init || this.jidToEdit == null;
718 this.messageFingerprint = intent.getStringExtra("fingerprint");
719 if (!mInitMode) {
720 this.binding.accountRegisterNew.setVisibility(View.GONE);
721 setTitle(getString(R.string.account_details));
722 configureActionBar(getSupportActionBar(), !openedFromNotification);
723 } else {
724 this.binding.avater.setVisibility(View.GONE);
725 configureActionBar(getSupportActionBar(), !(init && Config.MAGIC_CREATE_DOMAIN == null));
726 if (mForceRegister != null) {
727 if (mForceRegister) {
728 setTitle(R.string.register_new_account);
729 } else {
730 setTitle(R.string.add_existing_account);
731 }
732 } else {
733 setTitle(R.string.action_add_account);
734 }
735 }
736 }
737 SharedPreferences preferences = getPreferences();
738 mUseTor = QuickConversationsService.isConversations() && preferences.getBoolean("use_tor", getResources().getBoolean(R.bool.use_tor));
739 this.mShowOptions = mUseTor || (QuickConversationsService.isConversations() && preferences.getBoolean("show_connection_options", getResources().getBoolean(R.bool.show_connection_options)));
740 this.binding.namePort.setVisibility(mShowOptions ? View.VISIBLE : View.GONE);
741 if (mForceRegister != null) {
742 this.binding.accountRegisterNew.setVisibility(View.GONE);
743 }
744 }
745
746 @Override
747 public void onNewIntent(Intent intent) {
748 if (intent != null && intent.getData() != null) {
749 final XmppUri uri = new XmppUri(intent.getData());
750 if (xmppConnectionServiceBound) {
751 processFingerprintVerification(uri, false);
752 } else {
753 this.pendingUri = uri;
754 }
755 }
756 }
757
758 @Override
759 public void onSaveInstanceState(final Bundle savedInstanceState) {
760 if (mAccount != null) {
761 savedInstanceState.putString("account", mAccount.getJid().asBareJid().toEscapedString());
762 savedInstanceState.putBoolean("initMode", mInitMode);
763 savedInstanceState.putBoolean("showMoreTable", binding.serverInfoMore.getVisibility() == View.VISIBLE);
764 }
765 super.onSaveInstanceState(savedInstanceState);
766 }
767
768 protected void onBackendConnected() {
769 boolean init = true;
770 if (mSavedInstanceAccount != null) {
771 try {
772 this.mAccount = xmppConnectionService.findAccountByJid(Jid.ofEscaped(mSavedInstanceAccount));
773 this.mInitMode = mSavedInstanceInit;
774 init = false;
775 } catch (IllegalArgumentException e) {
776 this.mAccount = null;
777 }
778
779 } else if (this.jidToEdit != null) {
780 this.mAccount = xmppConnectionService.findAccountByJid(jidToEdit);
781 }
782
783 if (mAccount != null) {
784
785 if (mPendingReconnect.compareAndSet(true, false)) {
786 xmppConnectionService.reconnectAccountInBackground(mAccount);
787 }
788
789 this.mInitMode |= this.mAccount.isOptionSet(Account.OPTION_REGISTER);
790 this.mUsernameMode |= mAccount.isOptionSet(Account.OPTION_MAGIC_CREATE) && mAccount.isOptionSet(Account.OPTION_REGISTER);
791 if (mPendingFingerprintVerificationUri != null) {
792 processFingerprintVerification(mPendingFingerprintVerificationUri, false);
793 mPendingFingerprintVerificationUri = null;
794 }
795 updateAccountInformation(init);
796 }
797
798
799 if (Config.MAGIC_CREATE_DOMAIN == null && this.xmppConnectionService.getAccounts().size() == 0) {
800 this.binding.cancelButton.setEnabled(false);
801 }
802 if (mUsernameMode) {
803 this.binding.accountJidLayout.setHint(getString(R.string.username_hint));
804 this.binding.accountJid.setHint(R.string.username_hint);
805 } else {
806 final KnownHostsAdapter mKnownHostsAdapter = new KnownHostsAdapter(this,
807 R.layout.simple_list_item,
808 xmppConnectionService.getKnownHosts());
809 this.binding.accountJid.setAdapter(mKnownHostsAdapter);
810 }
811
812 if (pendingUri != null) {
813 processFingerprintVerification(pendingUri, false);
814 pendingUri = null;
815 }
816 updatePortLayout();
817 updateSaveButton();
818 invalidateOptionsMenu();
819 }
820
821 private String getUserModeDomain() {
822 if (mAccount != null && mAccount.getJid().getDomain() != null) {
823 return mAccount.getServer();
824 } else {
825 return Config.DOMAIN_LOCK;
826 }
827 }
828
829 @Override
830 public boolean onOptionsItemSelected(final MenuItem item) {
831 if (MenuDoubleTabUtil.shouldIgnoreTap()) {
832 return false;
833 }
834 switch (item.getItemId()) {
835 case android.R.id.home:
836 deleteAccountAndReturnIfNecessary();
837 break;
838 case R.id.action_show_block_list:
839 final Intent showBlocklistIntent = new Intent(this, BlocklistActivity.class);
840 showBlocklistIntent.putExtra(EXTRA_ACCOUNT, mAccount.getJid().toEscapedString());
841 startActivity(showBlocklistIntent);
842 break;
843 case R.id.action_server_info_show_more:
844 changeMoreTableVisibility(!item.isChecked());
845 break;
846 case R.id.action_share_barcode:
847 shareBarcode();
848 break;
849 case R.id.action_share_http:
850 shareLink(true);
851 break;
852 case R.id.action_share_uri:
853 shareLink(false);
854 break;
855 case R.id.action_change_password_on_server:
856 gotoChangePassword(null);
857 break;
858 case R.id.action_mam_prefs:
859 editMamPrefs();
860 break;
861 case R.id.action_renew_certificate:
862 renewCertificate();
863 break;
864 case R.id.action_change_presence:
865 changePresence();
866 break;
867 }
868 return super.onOptionsItemSelected(item);
869 }
870
871 private boolean inNeedOfSaslAccept() {
872 return mAccount != null && mAccount.getLastErrorStatus() == Account.State.DOWNGRADE_ATTACK && mAccount.getKeyAsInt(Account.PINNED_MECHANISM_KEY, -1) >= 0 && !accountInfoEdited();
873 }
874
875 private void shareBarcode() {
876 Intent intent = new Intent(Intent.ACTION_SEND);
877 intent.putExtra(Intent.EXTRA_STREAM, BarcodeProvider.getUriForAccount(this, mAccount));
878 intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
879 intent.setType("image/png");
880 startActivity(Intent.createChooser(intent, getText(R.string.share_with)));
881 }
882
883 private void changeMoreTableVisibility(boolean visible) {
884 binding.serverInfoMore.setVisibility(visible ? View.VISIBLE : View.GONE);
885 }
886
887 private void gotoChangePassword(String newPassword) {
888 final Intent changePasswordIntent = new Intent(this, ChangePasswordActivity.class);
889 changePasswordIntent.putExtra(EXTRA_ACCOUNT, mAccount.getJid().toEscapedString());
890 if (newPassword != null) {
891 changePasswordIntent.putExtra("password", newPassword);
892 }
893 startActivity(changePasswordIntent);
894 }
895
896 private void renewCertificate() {
897 KeyChain.choosePrivateKeyAlias(this, this, null, null, null, -1, null);
898 }
899
900 private void changePresence() {
901 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
902 boolean manualStatus = sharedPreferences.getBoolean(SettingsActivity.MANUALLY_CHANGE_PRESENCE, getResources().getBoolean(R.bool.manually_change_presence));
903 AlertDialog.Builder builder = new AlertDialog.Builder(this);
904 final DialogPresenceBinding binding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.dialog_presence, null, false);
905 String current = mAccount.getPresenceStatusMessage();
906 if (current != null && !current.trim().isEmpty()) {
907 binding.statusMessage.append(current);
908 }
909 setAvailabilityRadioButton(mAccount.getPresenceStatus(), binding);
910 binding.show.setVisibility(manualStatus ? View.VISIBLE : View.GONE);
911 List<PresenceTemplate> templates = xmppConnectionService.getPresenceTemplates(mAccount);
912 PresenceTemplateAdapter presenceTemplateAdapter = new PresenceTemplateAdapter(this, R.layout.simple_list_item, templates);
913 binding.statusMessage.setAdapter(presenceTemplateAdapter);
914 binding.statusMessage.setOnItemClickListener((parent, view, position, id) -> {
915 PresenceTemplate template = (PresenceTemplate) parent.getItemAtPosition(position);
916 setAvailabilityRadioButton(template.getStatus(), binding);
917 });
918 builder.setTitle(R.string.edit_status_message_title);
919 builder.setView(binding.getRoot());
920 builder.setNegativeButton(R.string.cancel, null);
921 builder.setPositiveButton(R.string.confirm, (dialog, which) -> {
922 PresenceTemplate template = new PresenceTemplate(getAvailabilityRadioButton(binding), binding.statusMessage.getText().toString().trim());
923 if (mAccount.getPgpId() != 0 && hasPgp()) {
924 generateSignature(null, template);
925 } else {
926 xmppConnectionService.changeStatus(mAccount, template, null);
927 }
928 });
929 builder.create().show();
930 }
931
932 private void generateSignature(Intent intent, PresenceTemplate template) {
933 xmppConnectionService.getPgpEngine().generateSignature(intent, mAccount, template.getStatusMessage(), new UiCallback<String>() {
934 @Override
935 public void success(String signature) {
936 xmppConnectionService.changeStatus(mAccount, template, signature);
937 }
938
939 @Override
940 public void error(int errorCode, String object) {
941
942 }
943
944 @Override
945 public void userInputRequired(PendingIntent pi, String object) {
946 mPendingPresenceTemplate.push(template);
947 try {
948 startIntentSenderForResult(pi.getIntentSender(), REQUEST_CHANGE_STATUS, null, 0, 0, 0);
949 } catch (final IntentSender.SendIntentException ignored) {
950 }
951 }
952 });
953 }
954
955 @Override
956 public void alias(String alias) {
957 if (alias != null) {
958 xmppConnectionService.updateKeyInAccount(mAccount, alias);
959 }
960 }
961
962 private void updateAccountInformation(boolean init) {
963 if (init) {
964 this.binding.accountJid.getEditableText().clear();
965 if (mUsernameMode) {
966 this.binding.accountJid.getEditableText().append(this.mAccount.getJid().getEscapedLocal());
967 } else {
968 this.binding.accountJid.getEditableText().append(this.mAccount.getJid().asBareJid().toEscapedString());
969 }
970 this.binding.accountPassword.getEditableText().clear();
971 this.binding.accountPassword.getEditableText().append(this.mAccount.getPassword());
972 this.binding.hostname.setText("");
973 this.binding.hostname.getEditableText().append(this.mAccount.getHostname());
974 this.binding.port.setText("");
975 this.binding.port.getEditableText().append(String.valueOf(this.mAccount.getPort()));
976 this.binding.namePort.setVisibility(mShowOptions ? View.VISIBLE : View.GONE);
977
978 }
979
980 final boolean editable = !mAccount.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY) && !mAccount.isOptionSet(Account.OPTION_FIXED_USERNAME) && QuickConversationsService.isConversations();
981 this.binding.accountJid.setEnabled(editable);
982 this.binding.accountJid.setFocusable(editable);
983 this.binding.accountJid.setFocusableInTouchMode(editable);
984 this.binding.accountJid.setCursorVisible(editable);
985
986
987 final String displayName = mAccount.getDisplayName();
988 updateDisplayName(displayName);
989
990
991 final boolean tooglePassword = mAccount.isOptionSet(Account.OPTION_MAGIC_CREATE) || !mAccount.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY);
992 final boolean editPassword = !mAccount.isOptionSet(Account.OPTION_MAGIC_CREATE) || (!mAccount.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY) && QuickConversationsService.isConversations()) || mAccount.getLastErrorStatus() == Account.State.UNAUTHORIZED;
993
994 this.binding.accountPasswordLayout.setPasswordVisibilityToggleEnabled(tooglePassword);
995
996 this.binding.accountPassword.setFocusable(editPassword);
997 this.binding.accountPassword.setFocusableInTouchMode(editPassword);
998 this.binding.accountPassword.setCursorVisible(editPassword);
999 this.binding.accountPassword.setEnabled(editPassword);
1000
1001 if (!mInitMode) {
1002 this.binding.avater.setVisibility(View.VISIBLE);
1003 AvatarWorkerTask.loadAvatar(mAccount, binding.avater, R.dimen.avatar_on_details_screen_size);
1004 } else {
1005 this.binding.avater.setVisibility(View.GONE);
1006 }
1007 this.binding.accountRegisterNew.setChecked(this.mAccount.isOptionSet(Account.OPTION_REGISTER));
1008 if (this.mAccount.isOptionSet(Account.OPTION_MAGIC_CREATE)) {
1009 if (this.mAccount.isOptionSet(Account.OPTION_REGISTER)) {
1010 ActionBar actionBar = getSupportActionBar();
1011 if (actionBar != null) {
1012 actionBar.setTitle(R.string.create_account);
1013 }
1014 }
1015 this.binding.accountRegisterNew.setVisibility(View.GONE);
1016 } else if (this.mAccount.isOptionSet(Account.OPTION_REGISTER) && mForceRegister == null) {
1017 this.binding.accountRegisterNew.setVisibility(View.VISIBLE);
1018 } else {
1019 this.binding.accountRegisterNew.setVisibility(View.GONE);
1020 }
1021 if (this.mAccount.isOnlineAndConnected() && !this.mFetchingAvatar) {
1022 Features features = this.mAccount.getXmppConnection().getFeatures();
1023 this.binding.stats.setVisibility(View.VISIBLE);
1024 boolean showBatteryWarning = !xmppConnectionService.getPushManagementService().available(mAccount) && isOptimizingBattery();
1025 boolean showDataSaverWarning = isAffectedByDataSaver();
1026 showOsOptimizationWarning(showBatteryWarning, showDataSaverWarning);
1027 this.binding.sessionEst.setText(UIHelper.readableTimeDifferenceFull(this, this.mAccount.getXmppConnection()
1028 .getLastSessionEstablished()));
1029 if (features.rosterVersioning()) {
1030 this.binding.serverInfoRosterVersion.setText(R.string.server_info_available);
1031 } else {
1032 this.binding.serverInfoRosterVersion.setText(R.string.server_info_unavailable);
1033 }
1034 if (features.carbons()) {
1035 this.binding.serverInfoCarbons.setText(R.string.server_info_available);
1036 } else {
1037 this.binding.serverInfoCarbons.setText(R.string.server_info_unavailable);
1038 }
1039 if (features.mam()) {
1040 this.binding.serverInfoMam.setText(R.string.server_info_available);
1041 } else {
1042 this.binding.serverInfoMam.setText(R.string.server_info_unavailable);
1043 }
1044 if (features.csi()) {
1045 this.binding.serverInfoCsi.setText(R.string.server_info_available);
1046 } else {
1047 this.binding.serverInfoCsi.setText(R.string.server_info_unavailable);
1048 }
1049 if (features.blocking()) {
1050 this.binding.serverInfoBlocking.setText(R.string.server_info_available);
1051 } else {
1052 this.binding.serverInfoBlocking.setText(R.string.server_info_unavailable);
1053 }
1054 if (features.sm()) {
1055 this.binding.serverInfoSm.setText(R.string.server_info_available);
1056 } else {
1057 this.binding.serverInfoSm.setText(R.string.server_info_unavailable);
1058 }
1059 if (features.externalServiceDiscovery()) {
1060 this.binding.serverInfoExternalService.setText(R.string.server_info_available);
1061 } else {
1062 this.binding.serverInfoExternalService.setText(R.string.server_info_unavailable);
1063 }
1064 if (features.pep()) {
1065 AxolotlService axolotlService = this.mAccount.getAxolotlService();
1066 if (axolotlService != null && axolotlService.isPepBroken()) {
1067 this.binding.serverInfoPep.setText(R.string.server_info_broken);
1068 } else if (features.pepPublishOptions() || features.pepOmemoWhitelisted()) {
1069 this.binding.serverInfoPep.setText(R.string.server_info_available);
1070 } else {
1071 this.binding.serverInfoPep.setText(R.string.server_info_partial);
1072 }
1073 } else {
1074 this.binding.serverInfoPep.setText(R.string.server_info_unavailable);
1075 }
1076 if (features.httpUpload(0)) {
1077 final long maxFileSize = features.getMaxHttpUploadSize();
1078 if (maxFileSize > 0) {
1079 this.binding.serverInfoHttpUpload.setText(UIHelper.filesizeToString(maxFileSize));
1080 } else {
1081 this.binding.serverInfoHttpUpload.setText(R.string.server_info_available);
1082 }
1083 } else if (features.p1S3FileTransfer()) {
1084 this.binding.serverInfoHttpUploadDescription.setText(R.string.p1_s3_filetransfer);
1085 this.binding.serverInfoHttpUpload.setText(R.string.server_info_available);
1086 } else {
1087 this.binding.serverInfoHttpUpload.setText(R.string.server_info_unavailable);
1088 }
1089
1090 this.binding.pushRow.setVisibility(xmppConnectionService.getPushManagementService().isStub() ? View.GONE : View.VISIBLE);
1091
1092 if (xmppConnectionService.getPushManagementService().available(mAccount)) {
1093 this.binding.serverInfoPush.setText(R.string.server_info_available);
1094 } else {
1095 this.binding.serverInfoPush.setText(R.string.server_info_unavailable);
1096 }
1097 final long pgpKeyId = this.mAccount.getPgpId();
1098 if (pgpKeyId != 0 && Config.supportOpenPgp()) {
1099 OnClickListener openPgp = view -> launchOpenKeyChain(pgpKeyId);
1100 OnClickListener delete = view -> showDeletePgpDialog();
1101 this.binding.pgpFingerprintBox.setVisibility(View.VISIBLE);
1102 this.binding.pgpFingerprint.setText(OpenPgpUtils.convertKeyIdToHex(pgpKeyId));
1103 this.binding.pgpFingerprint.setOnClickListener(openPgp);
1104 if ("pgp".equals(messageFingerprint)) {
1105 this.binding.pgpFingerprintDesc.setTextAppearance(this, R.style.TextAppearance_Conversations_Caption_Highlight);
1106 }
1107 this.binding.pgpFingerprintDesc.setOnClickListener(openPgp);
1108 this.binding.actionDeletePgp.setOnClickListener(delete);
1109 } else {
1110 this.binding.pgpFingerprintBox.setVisibility(View.GONE);
1111 }
1112 final String ownAxolotlFingerprint = this.mAccount.getAxolotlService().getOwnFingerprint();
1113 if (ownAxolotlFingerprint != null && Config.supportOmemo()) {
1114 this.binding.axolotlFingerprintBox.setVisibility(View.VISIBLE);
1115 if (ownAxolotlFingerprint.equals(messageFingerprint)) {
1116 this.binding.ownFingerprintDesc.setTextAppearance(this, R.style.TextAppearance_Conversations_Caption_Highlight);
1117 this.binding.ownFingerprintDesc.setText(R.string.omemo_fingerprint_selected_message);
1118 } else {
1119 this.binding.ownFingerprintDesc.setTextAppearance(this, R.style.TextAppearance_Conversations_Caption);
1120 this.binding.ownFingerprintDesc.setText(R.string.omemo_fingerprint);
1121 }
1122 this.binding.axolotlFingerprint.setText(CryptoHelper.prettifyFingerprint(ownAxolotlFingerprint.substring(2)));
1123 this.binding.actionCopyAxolotlToClipboard.setVisibility(View.VISIBLE);
1124 this.binding.actionCopyAxolotlToClipboard.setOnClickListener(v -> copyOmemoFingerprint(ownAxolotlFingerprint));
1125 } else {
1126 this.binding.axolotlFingerprintBox.setVisibility(View.GONE);
1127 }
1128 boolean hasKeys = false;
1129 binding.otherDeviceKeys.removeAllViews();
1130 for (XmppAxolotlSession session : mAccount.getAxolotlService().findOwnSessions()) {
1131 if (!session.getTrust().isCompromised()) {
1132 boolean highlight = session.getFingerprint().equals(messageFingerprint);
1133 addFingerprintRow(binding.otherDeviceKeys, session, highlight);
1134 hasKeys = true;
1135 }
1136 }
1137 if (hasKeys && Config.supportOmemo()) { //TODO: either the button should be visible if we print an active device or the device list should be fed with reactived devices
1138 this.binding.otherDeviceKeysCard.setVisibility(View.VISIBLE);
1139 Set<Integer> otherDevices = mAccount.getAxolotlService().getOwnDeviceIds();
1140 if (otherDevices == null || otherDevices.isEmpty()) {
1141 binding.clearDevices.setVisibility(View.GONE);
1142 } else {
1143 binding.clearDevices.setVisibility(View.VISIBLE);
1144 }
1145 } else {
1146 this.binding.otherDeviceKeysCard.setVisibility(View.GONE);
1147 }
1148 } else {
1149 final TextInputLayout errorLayout;
1150 if (this.mAccount.errorStatus()) {
1151 if (this.mAccount.getStatus() == Account.State.UNAUTHORIZED || this.mAccount.getStatus() == Account.State.DOWNGRADE_ATTACK) {
1152 errorLayout = this.binding.accountPasswordLayout;
1153 } else if (mShowOptions
1154 && this.mAccount.getStatus() == Account.State.SERVER_NOT_FOUND
1155 && this.binding.hostname.getText().length() > 0) {
1156 errorLayout = this.binding.hostnameLayout;
1157 } else {
1158 errorLayout = this.binding.accountJidLayout;
1159 }
1160 errorLayout.setError(getString(this.mAccount.getStatus().getReadableId()));
1161 if (init || !accountInfoEdited()) {
1162 errorLayout.requestFocus();
1163 }
1164 } else {
1165 errorLayout = null;
1166 }
1167 removeErrorsOnAllBut(errorLayout);
1168 this.binding.stats.setVisibility(View.GONE);
1169 this.binding.otherDeviceKeysCard.setVisibility(View.GONE);
1170 }
1171 }
1172
1173 private void updateDisplayName(String displayName) {
1174 if (TextUtils.isEmpty(displayName)) {
1175 this.binding.yourName.setText(R.string.no_name_set_instructions);
1176 this.binding.yourName.setTextAppearance(this, R.style.TextAppearance_Conversations_Body1_Tertiary);
1177 } else {
1178 this.binding.yourName.setText(displayName);
1179 this.binding.yourName.setTextAppearance(this, R.style.TextAppearance_Conversations_Body1);
1180 }
1181 }
1182
1183 private void removeErrorsOnAllBut(TextInputLayout exception) {
1184 if (this.binding.accountJidLayout != exception) {
1185 this.binding.accountJidLayout.setErrorEnabled(false);
1186 this.binding.accountJidLayout.setError(null);
1187 }
1188 if (this.binding.accountPasswordLayout != exception) {
1189 this.binding.accountPasswordLayout.setErrorEnabled(false);
1190 this.binding.accountPasswordLayout.setError(null);
1191 }
1192 if (this.binding.hostnameLayout != exception) {
1193 this.binding.hostnameLayout.setErrorEnabled(false);
1194 this.binding.hostnameLayout.setError(null);
1195 }
1196 if (this.binding.portLayout != exception) {
1197 this.binding.portLayout.setErrorEnabled(false);
1198 this.binding.portLayout.setError(null);
1199 }
1200 }
1201
1202 private void showDeletePgpDialog() {
1203 AlertDialog.Builder builder = new AlertDialog.Builder(this);
1204 builder.setTitle(R.string.unpublish_pgp);
1205 builder.setMessage(R.string.unpublish_pgp_message);
1206 builder.setNegativeButton(R.string.cancel, null);
1207 builder.setPositiveButton(R.string.confirm, (dialogInterface, i) -> {
1208 mAccount.setPgpSignId(0);
1209 mAccount.unsetPgpSignature();
1210 xmppConnectionService.databaseBackend.updateAccount(mAccount);
1211 xmppConnectionService.sendPresence(mAccount);
1212 refreshUiReal();
1213 });
1214 builder.create().show();
1215 }
1216
1217 private void showOsOptimizationWarning(boolean showBatteryWarning, boolean showDataSaverWarning) {
1218 this.binding.osOptimization.setVisibility(showBatteryWarning || showDataSaverWarning ? View.VISIBLE : View.GONE);
1219 if (showDataSaverWarning && android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
1220 this.binding.osOptimizationHeadline.setText(R.string.data_saver_enabled);
1221 this.binding.osOptimizationBody.setText(R.string.data_saver_enabled_explained);
1222 this.binding.osOptimizationDisable.setText(R.string.allow);
1223 this.binding.osOptimizationDisable.setOnClickListener(v -> {
1224 Intent intent = new Intent(Settings.ACTION_IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS);
1225 Uri uri = Uri.parse("package:" + getPackageName());
1226 intent.setData(uri);
1227 try {
1228 startActivityForResult(intent, REQUEST_DATA_SAVER);
1229 } catch (ActivityNotFoundException e) {
1230 Toast.makeText(EditAccountActivity.this, R.string.device_does_not_support_data_saver, Toast.LENGTH_SHORT).show();
1231 }
1232 });
1233 } else if (showBatteryWarning && android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
1234 this.binding.osOptimizationDisable.setText(R.string.disable);
1235 this.binding.osOptimizationHeadline.setText(R.string.battery_optimizations_enabled);
1236 this.binding.osOptimizationBody.setText(R.string.battery_optimizations_enabled_explained);
1237 this.binding.osOptimizationDisable.setOnClickListener(v -> {
1238 Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
1239 Uri uri = Uri.parse("package:" + getPackageName());
1240 intent.setData(uri);
1241 try {
1242 startActivityForResult(intent, REQUEST_BATTERY_OP);
1243 } catch (ActivityNotFoundException e) {
1244 Toast.makeText(EditAccountActivity.this, R.string.device_does_not_support_battery_op, Toast.LENGTH_SHORT).show();
1245 }
1246 });
1247 }
1248 }
1249
1250 public void showWipePepDialog() {
1251 Builder builder = new Builder(this);
1252 builder.setTitle(getString(R.string.clear_other_devices));
1253 builder.setIconAttribute(android.R.attr.alertDialogIcon);
1254 builder.setMessage(getString(R.string.clear_other_devices_desc));
1255 builder.setNegativeButton(getString(R.string.cancel), null);
1256 builder.setPositiveButton(getString(R.string.accept),
1257 (dialog, which) -> mAccount.getAxolotlService().wipeOtherPepDevices());
1258 builder.create().show();
1259 }
1260
1261 private void editMamPrefs() {
1262 this.mFetchingMamPrefsToast = Toast.makeText(this, R.string.fetching_mam_prefs, Toast.LENGTH_LONG);
1263 this.mFetchingMamPrefsToast.show();
1264 xmppConnectionService.fetchMamPreferences(mAccount, this);
1265 }
1266
1267 @Override
1268 public void onKeyStatusUpdated(AxolotlService.FetchStatus report) {
1269 refreshUi();
1270 }
1271
1272 @Override
1273 public void onCaptchaRequested(final Account account, final String id, final Data data, final Bitmap captcha) {
1274 runOnUiThread(() -> {
1275 if (mCaptchaDialog != null && mCaptchaDialog.isShowing()) {
1276 mCaptchaDialog.dismiss();
1277 }
1278 final Builder builder = new Builder(EditAccountActivity.this);
1279 final View view = getLayoutInflater().inflate(R.layout.captcha, null);
1280 final ImageView imageView = view.findViewById(R.id.captcha);
1281 final EditText input = view.findViewById(R.id.input);
1282 imageView.setImageBitmap(captcha);
1283
1284 builder.setTitle(getString(R.string.captcha_required));
1285 builder.setView(view);
1286
1287 builder.setPositiveButton(getString(R.string.ok),
1288 (dialog, which) -> {
1289 String rc = input.getText().toString();
1290 data.put("username", account.getUsername());
1291 data.put("password", account.getPassword());
1292 data.put("ocr", rc);
1293 data.submit();
1294
1295 if (xmppConnectionServiceBound) {
1296 xmppConnectionService.sendCreateAccountWithCaptchaPacket(account, id, data);
1297 }
1298 });
1299 builder.setNegativeButton(getString(R.string.cancel), (dialog, which) -> {
1300 if (xmppConnectionService != null) {
1301 xmppConnectionService.sendCreateAccountWithCaptchaPacket(account, null, null);
1302 }
1303 });
1304
1305 builder.setOnCancelListener(dialog -> {
1306 if (xmppConnectionService != null) {
1307 xmppConnectionService.sendCreateAccountWithCaptchaPacket(account, null, null);
1308 }
1309 });
1310 mCaptchaDialog = builder.create();
1311 mCaptchaDialog.show();
1312 input.requestFocus();
1313 });
1314 }
1315
1316 public void onShowErrorToast(final int resId) {
1317 runOnUiThread(() -> Toast.makeText(EditAccountActivity.this, resId, Toast.LENGTH_SHORT).show());
1318 }
1319
1320 @Override
1321 public void onPreferencesFetched(final Element prefs) {
1322 runOnUiThread(() -> {
1323 if (mFetchingMamPrefsToast != null) {
1324 mFetchingMamPrefsToast.cancel();
1325 }
1326 Builder builder = new Builder(EditAccountActivity.this);
1327 builder.setTitle(R.string.server_side_mam_prefs);
1328 String defaultAttr = prefs.getAttribute("default");
1329 final List<String> defaults = Arrays.asList("never", "roster", "always");
1330 final AtomicInteger choice = new AtomicInteger(Math.max(0, defaults.indexOf(defaultAttr)));
1331 builder.setSingleChoiceItems(R.array.mam_prefs, choice.get(), (dialog, which) -> choice.set(which));
1332 builder.setNegativeButton(R.string.cancel, null);
1333 builder.setPositiveButton(R.string.ok, (dialog, which) -> {
1334 prefs.setAttribute("default", defaults.get(choice.get()));
1335 xmppConnectionService.pushMamPreferences(mAccount, prefs);
1336 });
1337 builder.create().show();
1338 });
1339 }
1340
1341 @Override
1342 public void onPreferencesFetchFailed() {
1343 runOnUiThread(() -> {
1344 if (mFetchingMamPrefsToast != null) {
1345 mFetchingMamPrefsToast.cancel();
1346 }
1347 Toast.makeText(EditAccountActivity.this, R.string.unable_to_fetch_mam_prefs, Toast.LENGTH_LONG).show();
1348 });
1349 }
1350
1351 @Override
1352 public void OnUpdateBlocklist(Status status) {
1353 refreshUi();
1354 }
1355}