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