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