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