1package eu.siacs.conversations.ui;
2
3import android.app.Activity;
4import android.app.PendingIntent;
5import android.content.ActivityNotFoundException;
6import android.content.DialogInterface;
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.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.CheckBox;
33import android.widget.CompoundButton;
34import android.widget.CompoundButton.OnCheckedChangeListener;
35import android.widget.EditText;
36import android.widget.ImageButton;
37import android.widget.ImageView;
38import android.widget.LinearLayout;
39import android.widget.RelativeLayout;
40import android.widget.TableLayout;
41import android.widget.TableRow;
42import android.widget.TextView;
43import android.widget.Toast;
44
45import org.openintents.openpgp.util.OpenPgpUtils;
46
47import java.net.URL;
48import java.util.Arrays;
49import java.util.List;
50import java.util.Set;
51import java.util.concurrent.atomic.AtomicInteger;
52
53import eu.siacs.conversations.Config;
54import eu.siacs.conversations.R;
55import eu.siacs.conversations.crypto.axolotl.AxolotlService;
56import eu.siacs.conversations.crypto.axolotl.XmppAxolotlSession;
57import eu.siacs.conversations.databinding.ActivityEditAccountBinding;
58import eu.siacs.conversations.databinding.DialogPresenceBinding;
59import eu.siacs.conversations.entities.Account;
60import eu.siacs.conversations.entities.Presence;
61import eu.siacs.conversations.entities.PresenceTemplate;
62import eu.siacs.conversations.services.BarcodeProvider;
63import eu.siacs.conversations.services.XmppConnectionService;
64import eu.siacs.conversations.services.XmppConnectionService.OnAccountUpdate;
65import eu.siacs.conversations.services.XmppConnectionService.OnCaptchaRequested;
66import eu.siacs.conversations.ui.adapter.KnownHostsAdapter;
67import eu.siacs.conversations.ui.adapter.PresenceTemplateAdapter;
68import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
69import eu.siacs.conversations.ui.util.PendingItem;
70import eu.siacs.conversations.ui.widget.DisabledActionModeCallback;
71import eu.siacs.conversations.utils.CryptoHelper;
72import eu.siacs.conversations.utils.UIHelper;
73import eu.siacs.conversations.utils.XmppUri;
74import eu.siacs.conversations.xml.Element;
75import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
76import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
77import eu.siacs.conversations.xmpp.XmppConnection;
78import eu.siacs.conversations.xmpp.XmppConnection.Features;
79import eu.siacs.conversations.xmpp.forms.Data;
80import eu.siacs.conversations.xmpp.pep.Avatar;
81import rocks.xmpp.addr.Jid;
82
83public class EditAccountActivity extends OmemoActivity implements OnAccountUpdate, OnUpdateBlocklist,
84 OnKeyStatusUpdated, OnCaptchaRequested, KeyChainAliasCallback, XmppConnectionService.OnShowErrorToast, XmppConnectionService.OnMamPreferencesFetched {
85
86 private static final int REQUEST_DATA_SAVER = 0xf244;
87 private static final int REQUEST_CHANGE_STATUS = 0xee11;
88 private TextInputLayout mAccountJidLayout;
89 private EditText mPassword;
90 private TextInputLayout mPasswordLayout;
91 private Button mCancelButton;
92 private Button mSaveButton;
93 private Button mDisableOsOptimizationsButton;
94 private TextView getmDisableOsOptimizationsBody;
95 private TableLayout mMoreTable;
96
97 private TextView mAxolotlFingerprint;
98 private TextView mPgpFingerprint;
99 private TextView mOwnFingerprintDesc;
100 private TextView getmPgpFingerprintDesc;
101 private ImageView mAvatar;
102 private RelativeLayout mAxolotlFingerprintBox;
103 private RelativeLayout mPgpFingerprintBox;
104 private ImageButton mAxolotlFingerprintToClipboardButton;
105 private ImageButton mPgpDeleteFingerprintButton;
106 private LinearLayout keys;
107 private LinearLayout mNamePort;
108 private EditText mHostname;
109 private TextInputLayout mHostnameLayout;
110 private EditText mPort;
111 private TextInputLayout mPortLayout;
112 private AlertDialog mCaptchaDialog = null;
113
114 private Jid jidToEdit;
115 private boolean mInitMode = false;
116 private boolean mUsernameMode = Config.DOMAIN_LOCK != null;
117 private boolean mShowOptions = false;
118 private Account mAccount;
119 private String messageFingerprint;
120
121 private final PendingItem<PresenceTemplate> mPendingPresenceTemplate = new PendingItem<>();
122
123 private boolean mFetchingAvatar = false;
124
125 private final OnClickListener mSaveButtonClickListener = new OnClickListener() {
126
127 @Override
128 public void onClick(final View v) {
129 final String password = mPassword.getText().toString();
130 final boolean wasDisabled = mAccount != null && mAccount.getStatus() == Account.State.DISABLED;
131
132 if (!mInitMode && passwordChangedInMagicCreateMode()) {
133 gotoChangePassword(password);
134 return;
135 }
136 if (mInitMode && mAccount != null) {
137 mAccount.setOption(Account.OPTION_DISABLED, false);
138 }
139 if (mAccount != null && mAccount.getStatus() == Account.State.DISABLED && !accountInfoEdited()) {
140 mAccount.setOption(Account.OPTION_DISABLED, false);
141 if (!xmppConnectionService.updateAccount(mAccount)) {
142 Toast.makeText(EditAccountActivity.this, R.string.unable_to_update_account, Toast.LENGTH_SHORT).show();
143 }
144 return;
145 }
146 final boolean registerNewAccount = binding.accountRegisterNew.isChecked() && !Config.DISALLOW_REGISTRATION_IN_UI;
147 if (mUsernameMode && binding.accountJid.getText().toString().contains("@")) {
148 mAccountJidLayout.setError(getString(R.string.invalid_username));
149 removeErrorsOnAllBut(mAccountJidLayout);
150 binding.accountJid.requestFocus();
151 return;
152 }
153
154 XmppConnection connection = mAccount == null ? null : mAccount.getXmppConnection();
155 boolean openRegistrationUrl = registerNewAccount && mAccount != null && mAccount.getStatus() == Account.State.REGISTRATION_WEB;
156 boolean openPaymentUrl = mAccount != null && mAccount.getStatus() == Account.State.PAYMENT_REQUIRED;
157 final boolean redirectionWorthyStatus = openPaymentUrl || openRegistrationUrl;
158 URL url = connection != null && redirectionWorthyStatus ? connection.getRedirectionUrl() : null;
159 if (url != null && redirectionWorthyStatus && !wasDisabled) {
160 try {
161 startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url.toString())));
162 return;
163 } catch (ActivityNotFoundException e) {
164 Toast.makeText(EditAccountActivity.this, R.string.application_found_to_open_website, Toast.LENGTH_SHORT);
165 return;
166 }
167 }
168
169 final Jid jid;
170 try {
171 if (mUsernameMode) {
172 jid = Jid.of(binding.accountJid.getText().toString(), getUserModeDomain(), null);
173 } else {
174 jid = Jid.of(binding.accountJid.getText().toString());
175 }
176 } catch (final IllegalArgumentException e) {
177 if (mUsernameMode) {
178 mAccountJidLayout.setError(getString(R.string.invalid_username));
179 } else {
180 mAccountJidLayout.setError(getString(R.string.invalid_jid));
181 }
182 binding.accountJid.requestFocus();
183 removeErrorsOnAllBut(mAccountJidLayout);
184 return;
185 }
186 String hostname = null;
187 int numericPort = 5222;
188 if (mShowOptions) {
189 hostname = mHostname.getText().toString().replaceAll("\\s", "");
190 final String port = mPort.getText().toString().replaceAll("\\s", "");
191 if (hostname.contains(" ")) {
192 mHostnameLayout.setError(getString(R.string.not_valid_hostname));
193 mHostname.requestFocus();
194 removeErrorsOnAllBut(mHostnameLayout);
195 return;
196 }
197 try {
198 numericPort = Integer.parseInt(port);
199 if (numericPort < 0 || numericPort > 65535) {
200 mPortLayout.setError(getString(R.string.not_a_valid_port));
201 removeErrorsOnAllBut(mPortLayout);
202 mPort.requestFocus();
203 return;
204 }
205
206 } catch (NumberFormatException e) {
207 mPortLayout.setError(getString(R.string.not_a_valid_port));
208 removeErrorsOnAllBut(mPortLayout);
209 mPort.requestFocus();
210 return;
211 }
212 }
213
214 if (jid.getLocal() == null) {
215 if (mUsernameMode) {
216 mAccountJidLayout.setError(getString(R.string.invalid_username));
217 } else {
218 mAccountJidLayout.setError(getString(R.string.invalid_jid));
219 }
220 removeErrorsOnAllBut(mAccountJidLayout);
221 binding.accountJid.requestFocus();
222 return;
223 }
224 if (mAccount != null) {
225 if (mInitMode && mAccount.isOptionSet(Account.OPTION_MAGIC_CREATE)) {
226 mAccount.setOption(Account.OPTION_MAGIC_CREATE, mAccount.getPassword().contains(password));
227 }
228 mAccount.setJid(jid);
229 mAccount.setPort(numericPort);
230 mAccount.setHostname(hostname);
231 mAccountJidLayout.setError(null);
232 mAccount.setPassword(password);
233 mAccount.setOption(Account.OPTION_REGISTER, registerNewAccount);
234 if (!xmppConnectionService.updateAccount(mAccount)) {
235 Toast.makeText(EditAccountActivity.this, R.string.unable_to_update_account, Toast.LENGTH_SHORT).show();
236 return;
237 }
238 } else {
239 if (xmppConnectionService.findAccountByJid(jid) != null) {
240 mAccountJidLayout.setError(getString(R.string.account_already_exists));
241 removeErrorsOnAllBut(mAccountJidLayout);
242 binding.accountJid.requestFocus();
243 return;
244 }
245 mAccount = new Account(jid.asBareJid(), password);
246 mAccount.setPort(numericPort);
247 mAccount.setHostname(hostname);
248 mAccount.setOption(Account.OPTION_USETLS, true);
249 mAccount.setOption(Account.OPTION_USECOMPRESSION, true);
250 mAccount.setOption(Account.OPTION_REGISTER, registerNewAccount);
251 xmppConnectionService.createAccount(mAccount);
252 }
253 mHostnameLayout.setError(null);
254 mPortLayout.setError(null);
255 if (mAccount.isEnabled()
256 && !registerNewAccount
257 && !mInitMode) {
258 finish();
259 } else {
260 updateSaveButton();
261 updateAccountInformation(true);
262 }
263
264 }
265 };
266 private final OnClickListener mCancelButtonClickListener = new OnClickListener() {
267
268 @Override
269 public void onClick(final View v) {
270 deleteAccountAndReturnIfNecessary();
271 finish();
272 }
273 };
274 private Toast mFetchingMamPrefsToast;
275 private String mSavedInstanceAccount;
276 private boolean mSavedInstanceInit = false;
277 private Button mClearDevicesButton;
278 private XmppUri pendingUri = null;
279 private boolean mUseTor;
280 private ActivityEditAccountBinding binding;
281
282 public void refreshUiReal() {
283 invalidateOptionsMenu();
284 if (mAccount != null
285 && mAccount.getStatus() != Account.State.ONLINE
286 && mFetchingAvatar) {
287 startActivity(new Intent(getApplicationContext(),
288 ManageAccountActivity.class));
289 finish();
290 } else if (mInitMode && mAccount != null && mAccount.getStatus() == Account.State.ONLINE) {
291 if (!mFetchingAvatar) {
292 mFetchingAvatar = true;
293 xmppConnectionService.checkForAvatar(mAccount, mAvatarFetchCallback);
294 }
295 }
296 if (mAccount != null) {
297 updateAccountInformation(false);
298 }
299 updateSaveButton();
300 }
301
302 @Override
303 public boolean onNavigateUp() {
304 deleteAccountAndReturnIfNecessary();
305 return super.onNavigateUp();
306 }
307
308 @Override
309 public void onBackPressed() {
310 deleteAccountAndReturnIfNecessary();
311 super.onBackPressed();
312 }
313
314 private void deleteAccountAndReturnIfNecessary() {
315 if (mInitMode && mAccount != null && !mAccount.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY)) {
316 xmppConnectionService.deleteAccount(mAccount);
317 }
318
319 if (xmppConnectionService.getAccounts().size() == 0) {
320 Intent intent = new Intent(EditAccountActivity.this, WelcomeActivity.class);
321 WelcomeActivity.addInviteUri(intent, getIntent());
322 startActivity(intent);
323 }
324 }
325
326 @Override
327 public void onAccountUpdate() {
328 refreshUi();
329 }
330
331 private final UiCallback<Avatar> mAvatarFetchCallback = new UiCallback<Avatar>() {
332
333 @Override
334 public void userInputRequried(final PendingIntent pi, final Avatar avatar) {
335 finishInitialSetup(avatar);
336 }
337
338 @Override
339 public void success(final Avatar avatar) {
340 finishInitialSetup(avatar);
341 }
342
343 @Override
344 public void error(final int errorCode, final Avatar avatar) {
345 finishInitialSetup(avatar);
346 }
347 };
348 private final TextWatcher mTextWatcher = new TextWatcher() {
349
350 @Override
351 public void onTextChanged(final CharSequence s, final int start, final int before, final int count) {
352 updateSaveButton();
353 }
354
355 @Override
356 public void beforeTextChanged(final CharSequence s, final int start, final int count, final int after) {
357 }
358
359 @Override
360 public void afterTextChanged(final Editable s) {
361
362 }
363 };
364
365 private View.OnFocusChangeListener mEditTextFocusListener = new View.OnFocusChangeListener() {
366 @Override
367 public void onFocusChange(View view, boolean b) {
368 EditText et = (EditText) view;
369 if (b) {
370 int resId = mUsernameMode ? R.string.username : R.string.account_settings_example_jabber_id;
371 if (view.getId() == R.id.hostname) {
372 resId = mUseTor ? R.string.hostname_or_onion : R.string.hostname_example;
373 }
374 final int res = resId;
375 new Handler().postDelayed(() -> et.setHint(res), 200);
376 } else {
377 et.setHint(null);
378 }
379 }
380 };
381
382
383 private final OnClickListener mAvatarClickListener = new OnClickListener() {
384 @Override
385 public void onClick(final View view) {
386 if (mAccount != null) {
387 final Intent intent = new Intent(getApplicationContext(), PublishProfilePictureActivity.class);
388 intent.putExtra(EXTRA_ACCOUNT, mAccount.getJid().asBareJid().toString());
389 startActivity(intent);
390 }
391 }
392 };
393
394 protected void finishInitialSetup(final Avatar avatar) {
395 runOnUiThread(() -> {
396 hideKeyboard();
397 final Intent intent;
398 final XmppConnection connection = mAccount.getXmppConnection();
399 final boolean wasFirstAccount = xmppConnectionService != null && xmppConnectionService.getAccounts().size() == 1;
400 if (avatar != null || (connection != null && !connection.getFeatures().pep())) {
401 intent = new Intent(getApplicationContext(), StartConversationActivity.class);
402 if (wasFirstAccount) {
403 intent.putExtra("init", true);
404 }
405 } else {
406 intent = new Intent(getApplicationContext(), PublishProfilePictureActivity.class);
407 intent.putExtra(EXTRA_ACCOUNT, mAccount.getJid().asBareJid().toString());
408 intent.putExtra("setup", true);
409 }
410 if (wasFirstAccount) {
411 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
412 }
413 WelcomeActivity.addInviteUri(intent, getIntent());
414 startActivity(intent);
415 finish();
416 });
417 }
418
419 @Override
420 public void onActivityResult(int requestCode, int resultCode, Intent data) {
421 super.onActivityResult(requestCode, resultCode, data);
422 if (requestCode == REQUEST_BATTERY_OP || requestCode == REQUEST_DATA_SAVER) {
423 updateAccountInformation(mAccount == null);
424 }
425 if (requestCode == REQUEST_CHANGE_STATUS) {
426 PresenceTemplate template = mPendingPresenceTemplate.pop();
427 if (template != null && resultCode == Activity.RESULT_OK) {
428 generateSignature(data,template);
429 } else {
430 Log.d(Config.LOGTAG,"pgp result not ok");
431 }
432 }
433 }
434
435 @Override
436 protected void processFingerprintVerification(XmppUri uri) {
437 processFingerprintVerification(uri, true);
438 }
439
440
441 protected void processFingerprintVerification(XmppUri uri, boolean showWarningToast) {
442 if (mAccount != null && mAccount.getJid().asBareJid().equals(uri.getJid()) && uri.hasFingerprints()) {
443 if (xmppConnectionService.verifyFingerprints(mAccount, uri.getFingerprints())) {
444 Toast.makeText(this, R.string.verified_fingerprints, Toast.LENGTH_SHORT).show();
445 updateAccountInformation(false);
446 }
447 } else if (showWarningToast) {
448 Toast.makeText(this, R.string.invalid_barcode, Toast.LENGTH_SHORT).show();
449 }
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.mHostname.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 = (LinearLayout) findViewById(R.id.other_device_keys);
563 this.mNamePort = (LinearLayout) findViewById(R.id.name_port);
564 this.mHostname = (EditText) findViewById(R.id.hostname);
565 this.mHostname.addTextChangedListener(mTextWatcher);
566 this.mHostname.setOnFocusChangeListener(mEditTextFocusListener);
567 this.mHostnameLayout = (TextInputLayout) findViewById(R.id.hostname_layout);
568 this.mClearDevicesButton = (Button) findViewById(R.id.clear_devices);
569 this.mClearDevicesButton.setOnClickListener(v -> showWipePepDialog());
570 this.mPort = (EditText) findViewById(R.id.port);
571 this.mPort.setText("5222");
572 this.mPort.addTextChangedListener(mTextWatcher);
573 this.mPortLayout = (TextInputLayout) findViewById(R.id.port_layout);
574 this.mSaveButton = (Button) findViewById(R.id.save_button);
575 this.mCancelButton = (Button) findViewById(R.id.cancel_button);
576 this.mSaveButton.setOnClickListener(this.mSaveButtonClickListener);
577 this.mCancelButton.setOnClickListener(this.mCancelButtonClickListener);
578 this.mMoreTable = (TableLayout) findViewById(R.id.server_info_more);
579 if (savedInstanceState != null && savedInstanceState.getBoolean("showMoreTable")) {
580 changeMoreTableVisibility(true);
581 }
582 final OnCheckedChangeListener OnCheckedShowConfirmPassword = new OnCheckedChangeListener() {
583 @Override
584 public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) {
585 updateSaveButton();
586 }
587 };
588 this.binding.accountRegisterNew.setOnCheckedChangeListener(OnCheckedShowConfirmPassword);
589 if (Config.DISALLOW_REGISTRATION_IN_UI) {
590 this.binding.accountRegisterNew.setVisibility(View.GONE);
591 }
592 }
593
594 @Override
595 public boolean onCreateOptionsMenu(final Menu menu) {
596 super.onCreateOptionsMenu(menu);
597 getMenuInflater().inflate(R.menu.editaccount, menu);
598 final MenuItem showBlocklist = menu.findItem(R.id.action_show_block_list);
599 final MenuItem showMoreInfo = menu.findItem(R.id.action_server_info_show_more);
600 final MenuItem changePassword = menu.findItem(R.id.action_change_password_on_server);
601 final MenuItem renewCertificate = menu.findItem(R.id.action_renew_certificate);
602 final MenuItem mamPrefs = menu.findItem(R.id.action_mam_prefs);
603 final MenuItem changePresence = menu.findItem(R.id.action_change_presence);
604 final MenuItem share = menu.findItem(R.id.action_share);
605 renewCertificate.setVisible(mAccount != null && mAccount.getPrivateKeyAlias() != null);
606
607 share.setVisible(mAccount != null && !mInitMode);
608
609 if (mAccount != null && mAccount.isOnlineAndConnected()) {
610 if (!mAccount.getXmppConnection().getFeatures().blocking()) {
611 showBlocklist.setVisible(false);
612 }
613
614 if (!mAccount.getXmppConnection().getFeatures().register()) {
615 changePassword.setVisible(false);
616 }
617 mamPrefs.setVisible(mAccount.getXmppConnection().getFeatures().mam());
618 changePresence.setVisible(!mInitMode);
619 } else {
620 showBlocklist.setVisible(false);
621 showMoreInfo.setVisible(false);
622 changePassword.setVisible(false);
623 mamPrefs.setVisible(false);
624 changePresence.setVisible(false);
625 }
626 return super.onCreateOptionsMenu(menu);
627 }
628
629 @Override
630 public boolean onPrepareOptionsMenu(Menu menu) {
631 final MenuItem showMoreInfo = menu.findItem(R.id.action_server_info_show_more);
632 if (showMoreInfo.isVisible()) {
633 showMoreInfo.setChecked(mMoreTable.getVisibility() == View.VISIBLE);
634 }
635 return super.onPrepareOptionsMenu(menu);
636 }
637
638 @Override
639 protected void onStart() {
640 super.onStart();
641 final int theme = findTheme();
642 if (this.mTheme != theme) {
643 recreate();
644 } else if (getIntent() != null) {
645 try {
646 this.jidToEdit = Jid.of(getIntent().getStringExtra("jid"));
647 } catch (final IllegalArgumentException | NullPointerException ignored) {
648 this.jidToEdit = null;
649 }
650 if (jidToEdit != null && getIntent().getData() != null) {
651 final XmppUri uri = new XmppUri(getIntent().getData());
652 if (xmppConnectionServiceBound) {
653 processFingerprintVerification(uri, false);
654 } else {
655 this.pendingUri = uri;
656 }
657 }
658 boolean init = getIntent().getBooleanExtra("init", false);
659 this.mInitMode = init || this.jidToEdit == null;
660 this.messageFingerprint = getIntent().getStringExtra("fingerprint");
661 if (!mInitMode) {
662 this.binding.accountRegisterNew.setVisibility(View.GONE);
663 if (getSupportActionBar() != null) {
664 getSupportActionBar().setTitle(getString(R.string.account_details));
665 }
666 } else {
667 this.mAvatar.setVisibility(View.GONE);
668 ActionBar ab = getSupportActionBar();
669 if (ab != null) {
670 if (init && Config.MAGIC_CREATE_DOMAIN == null) {
671 ab.setDisplayShowHomeEnabled(false);
672 ab.setDisplayHomeAsUpEnabled(false);
673 }
674 ab.setTitle(R.string.action_add_account);
675 }
676 }
677 }
678 SharedPreferences preferences = getPreferences();
679 mUseTor = Config.FORCE_ORBOT || preferences.getBoolean("use_tor", false);
680 this.mShowOptions = mUseTor || preferences.getBoolean("show_connection_options", false);
681 this.mNamePort.setVisibility(mShowOptions ? View.VISIBLE : View.GONE);
682 }
683
684 @Override
685 public void onNewIntent(Intent intent) {
686 if (intent != null && intent.getData() != null) {
687 final XmppUri uri = new XmppUri(intent.getData());
688 if (xmppConnectionServiceBound) {
689 processFingerprintVerification(uri, false);
690 } else {
691 this.pendingUri = uri;
692 }
693 }
694 }
695
696 @Override
697 public void onSaveInstanceState(final Bundle savedInstanceState) {
698 if (mAccount != null) {
699 savedInstanceState.putString("account", mAccount.getJid().asBareJid().toString());
700 savedInstanceState.putBoolean("initMode", mInitMode);
701 savedInstanceState.putBoolean("showMoreTable", mMoreTable.getVisibility() == View.VISIBLE);
702 }
703 super.onSaveInstanceState(savedInstanceState);
704 }
705
706 protected void onBackendConnected() {
707 boolean init = true;
708 if (mSavedInstanceAccount != null) {
709 try {
710 this.mAccount = xmppConnectionService.findAccountByJid(Jid.of(mSavedInstanceAccount));
711 this.mInitMode = mSavedInstanceInit;
712 init = false;
713 } catch (IllegalArgumentException e) {
714 this.mAccount = null;
715 }
716
717 } else if (this.jidToEdit != null) {
718 this.mAccount = xmppConnectionService.findAccountByJid(jidToEdit);
719 }
720
721 if (mAccount != null) {
722 this.mInitMode |= this.mAccount.isOptionSet(Account.OPTION_REGISTER);
723 this.mUsernameMode |= mAccount.isOptionSet(Account.OPTION_MAGIC_CREATE) && mAccount.isOptionSet(Account.OPTION_REGISTER);
724 if (this.mAccount.getPrivateKeyAlias() != null) {
725 this.mPassword.setHint(R.string.authenticate_with_certificate);
726 if (this.mInitMode) {
727 this.mPassword.requestFocus();
728 }
729 }
730 if (mPendingFingerprintVerificationUri != null) {
731 processFingerprintVerification(mPendingFingerprintVerificationUri, false);
732 mPendingFingerprintVerificationUri = null;
733 }
734 updateAccountInformation(init);
735 }
736
737
738 if (Config.MAGIC_CREATE_DOMAIN == null && this.xmppConnectionService.getAccounts().size() == 0) {
739 this.mCancelButton.setEnabled(false);
740 }
741 if (mUsernameMode) {
742 this.binding.accountJid.setHint(R.string.username_hint);
743 } else {
744 final KnownHostsAdapter mKnownHostsAdapter = new KnownHostsAdapter(this,
745 R.layout.simple_list_item,
746 xmppConnectionService.getKnownHosts());
747 this.binding.accountJid.setAdapter(mKnownHostsAdapter);
748 }
749
750 if (pendingUri != null) {
751 processFingerprintVerification(pendingUri, false);
752 pendingUri = null;
753 }
754
755 updateSaveButton();
756 invalidateOptionsMenu();
757 }
758
759 private String getUserModeDomain() {
760 if (mAccount != null) {
761 return mAccount.getJid().getDomain();
762 } else {
763 return Config.DOMAIN_LOCK;
764 }
765 }
766
767 @Override
768 public boolean onOptionsItemSelected(final MenuItem item) {
769 if (MenuDoubleTabUtil.shouldIgnoreTap()) {
770 return false;
771 }
772 switch (item.getItemId()) {
773 case R.id.action_show_block_list:
774 final Intent showBlocklistIntent = new Intent(this, BlocklistActivity.class);
775 showBlocklistIntent.putExtra(EXTRA_ACCOUNT, mAccount.getJid().toString());
776 startActivity(showBlocklistIntent);
777 break;
778 case R.id.action_server_info_show_more:
779 changeMoreTableVisibility(!item.isChecked());
780 break;
781 case R.id.action_share_barcode:
782 shareBarcode();
783 break;
784 case R.id.action_share_http:
785 shareLink(true);
786 break;
787 case R.id.action_share_uri:
788 shareLink(false);
789 break;
790 case R.id.action_change_password_on_server:
791 gotoChangePassword(null);
792 break;
793 case R.id.action_mam_prefs:
794 editMamPrefs();
795 break;
796 case R.id.action_renew_certificate:
797 renewCertificate();
798 break;
799 case R.id.action_change_presence:
800 changePresence();
801 break;
802 }
803 return super.onOptionsItemSelected(item);
804 }
805
806 private void shareBarcode() {
807 Intent intent = new Intent(Intent.ACTION_SEND);
808 intent.putExtra(Intent.EXTRA_STREAM, BarcodeProvider.getUriForAccount(this, mAccount));
809 intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
810 intent.setType("image/png");
811 startActivity(Intent.createChooser(intent, getText(R.string.share_with)));
812 }
813
814 private void changeMoreTableVisibility(boolean visible) {
815 mMoreTable.setVisibility(visible ? View.VISIBLE : View.GONE);
816 }
817
818 private void gotoChangePassword(String newPassword) {
819 final Intent changePasswordIntent = new Intent(this, ChangePasswordActivity.class);
820 changePasswordIntent.putExtra(EXTRA_ACCOUNT, mAccount.getJid().toString());
821 if (newPassword != null) {
822 changePasswordIntent.putExtra("password", newPassword);
823 }
824 startActivity(changePasswordIntent);
825 }
826
827 private void renewCertificate() {
828 KeyChain.choosePrivateKeyAlias(this, this, null, null, null, -1, null);
829 }
830
831 private void changePresence() {
832 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
833 boolean manualStatus = sharedPreferences.getBoolean(SettingsActivity.MANUALLY_CHANGE_PRESENCE, getResources().getBoolean(R.bool.manually_change_presence));
834 AlertDialog.Builder builder = new AlertDialog.Builder(this);
835 final DialogPresenceBinding binding = DataBindingUtil.inflate(getLayoutInflater(),R.layout.dialog_presence,null,false);
836 String current = mAccount.getPresenceStatusMessage();
837 if (current != null && !current.trim().isEmpty()) {
838 binding.statusMessage.append(current);
839 }
840 setAvailabilityRadioButton(mAccount.getPresenceStatus(),binding);
841 binding.show.setVisibility(manualStatus ? View.VISIBLE : View.GONE);
842 List<PresenceTemplate> templates = xmppConnectionService.getPresenceTemplates(mAccount);
843 PresenceTemplateAdapter presenceTemplateAdapter = new PresenceTemplateAdapter(this,R.layout.simple_list_item,templates);
844 binding.statusMessage.setAdapter(presenceTemplateAdapter);
845 binding.statusMessage.setOnItemClickListener((parent, view, position, id) -> {
846 PresenceTemplate template = (PresenceTemplate) parent.getItemAtPosition(position);
847 setAvailabilityRadioButton(template.getStatus(), binding);
848 });
849 builder.setTitle(R.string.edit_status_message_title);
850 builder.setView(binding.getRoot());
851 builder.setNegativeButton(R.string.cancel,null);
852 builder.setPositiveButton(R.string.confirm, (dialog, which) -> {
853 PresenceTemplate template = new PresenceTemplate(getAvailabilityRadioButton(binding),binding.statusMessage.getText().toString().trim());
854 if (mAccount.getPgpId() != 0 && hasPgp()) {
855 generateSignature(null, template);
856 } else {
857 xmppConnectionService.changeStatus(mAccount, template, null);
858 }
859 });
860 builder.create().show();
861 }
862
863 private void generateSignature(Intent intent, PresenceTemplate template) {
864 xmppConnectionService.getPgpEngine().generateSignature(intent, mAccount, template.getStatusMessage(), new UiCallback<String>() {
865 @Override
866 public void success(String signature) {
867 xmppConnectionService.changeStatus(mAccount,template,signature);
868 }
869
870 @Override
871 public void error(int errorCode, String object) {
872
873 }
874
875 @Override
876 public void userInputRequried(PendingIntent pi, String object) {
877 mPendingPresenceTemplate.push(template);
878 try {
879 startIntentSenderForResult(pi.getIntentSender(), REQUEST_CHANGE_STATUS, null, 0, 0, 0);
880 } catch (final IntentSender.SendIntentException ignored) {
881 }
882 }
883 });
884 }
885
886 private static void setAvailabilityRadioButton(Presence.Status status, DialogPresenceBinding binding) {
887 if (status == null) {
888 binding.online.setChecked(true);
889 return;
890 }
891 switch (status) {
892 case DND:
893 binding.dnd.setChecked(true);
894 break;
895 case XA:
896 binding.xa.setChecked(true);
897 break;
898 case AWAY:
899 binding.xa.setChecked(true);
900 break;
901 default:
902 binding.online.setChecked(true);
903 }
904 }
905
906 private static Presence.Status getAvailabilityRadioButton(DialogPresenceBinding binding) {
907 if (binding.dnd.isChecked()) {
908 return Presence.Status.DND;
909 } else if (binding.xa.isChecked()) {
910 return Presence.Status.XA;
911 } else if (binding.away.isChecked()) {
912 return Presence.Status.AWAY;
913 } else {
914 return Presence.Status.ONLINE;
915 }
916 }
917
918 @Override
919 public void alias(String alias) {
920 if (alias != null) {
921 xmppConnectionService.updateKeyInAccount(mAccount, alias);
922 }
923 }
924
925 private void updateAccountInformation(boolean init) {
926 if (init) {
927 this.binding.accountJid.getEditableText().clear();
928 if (mUsernameMode) {
929 this.binding.accountJid.getEditableText().append(this.mAccount.getJid().getLocal());
930 } else {
931 this.binding.accountJid.getEditableText().append(this.mAccount.getJid().asBareJid().toString());
932 }
933 this.mPassword.getEditableText().clear();
934 this.mPassword.getEditableText().append(this.mAccount.getPassword());
935 this.mHostname.setText("");
936 this.mHostname.getEditableText().append(this.mAccount.getHostname());
937 this.mPort.setText("");
938 this.mPort.getEditableText().append(String.valueOf(this.mAccount.getPort()));
939 this.mNamePort.setVisibility(mShowOptions ? View.VISIBLE : View.GONE);
940
941 }
942
943 final boolean editable = !mAccount.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY);
944 this.binding.accountJid.setEnabled(editable);
945 this.binding.accountJid.setFocusable(editable);
946 this.binding.accountJid.setFocusableInTouchMode(editable);
947
948
949 if (mAccount.isOptionSet(Account.OPTION_MAGIC_CREATE) || !mAccount.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY)) {
950 this.binding.accountPasswordLayout.setPasswordVisibilityToggleEnabled(true);
951 } else {
952 this.binding.accountPasswordLayout.setPasswordVisibilityToggleEnabled(false);
953 }
954
955 if (!mInitMode) {
956 this.mAvatar.setVisibility(View.VISIBLE);
957 this.mAvatar.setImageBitmap(avatarService().get(this.mAccount, getPixel(72)));
958 } else {
959 this.mAvatar.setVisibility(View.GONE);
960 }
961 this.binding.accountRegisterNew.setChecked(this.mAccount.isOptionSet(Account.OPTION_REGISTER));
962 if (this.mAccount.isOptionSet(Account.OPTION_MAGIC_CREATE)) {
963 if (this.mAccount.isOptionSet(Account.OPTION_REGISTER)) {
964 ActionBar actionBar = getSupportActionBar();
965 if (actionBar != null) {
966 actionBar.setTitle(R.string.create_account);
967 }
968 }
969 this.binding.accountRegisterNew.setVisibility(View.GONE);
970 } else if (this.mAccount.isOptionSet(Account.OPTION_REGISTER)) {
971 this.binding.accountRegisterNew.setVisibility(View.VISIBLE);
972 } else {
973 this.binding.accountRegisterNew.setVisibility(View.GONE);
974 }
975 if (this.mAccount.isOnlineAndConnected() && !this.mFetchingAvatar) {
976 Features features = this.mAccount.getXmppConnection().getFeatures();
977 this.binding.stats.setVisibility(View.VISIBLE);
978 boolean showBatteryWarning = !xmppConnectionService.getPushManagementService().available(mAccount) && isOptimizingBattery();
979 boolean showDataSaverWarning = isAffectedByDataSaver();
980 showOsOptimizationWarning(showBatteryWarning, showDataSaverWarning);
981 this.binding.sessionEst.setText(UIHelper.readableTimeDifferenceFull(this, this.mAccount.getXmppConnection()
982 .getLastSessionEstablished()));
983 if (features.rosterVersioning()) {
984 this.binding.serverInfoRosterVersion.setText(R.string.server_info_available);
985 } else {
986 this.binding.serverInfoRosterVersion.setText(R.string.server_info_unavailable);
987 }
988 if (features.carbons()) {
989 this.binding.serverInfoCarbons.setText(R.string.server_info_available);
990 } else {
991 this.binding.serverInfoCarbons.setText(R.string.server_info_unavailable);
992 }
993 if (features.mam()) {
994 this.binding.serverInfoMam.setText(R.string.server_info_available);
995 } else {
996 this.binding.serverInfoMam.setText(R.string.server_info_unavailable);
997 }
998 if (features.csi()) {
999 this.binding.serverInfoCsi.setText(R.string.server_info_available);
1000 } else {
1001 this.binding.serverInfoCsi.setText(R.string.server_info_unavailable);
1002 }
1003 if (features.blocking()) {
1004 this.binding.serverInfoBlocking.setText(R.string.server_info_available);
1005 } else {
1006 this.binding.serverInfoBlocking.setText(R.string.server_info_unavailable);
1007 }
1008 if (features.sm()) {
1009 this.binding.serverInfoSm.setText(R.string.server_info_available);
1010 } else {
1011 this.binding.serverInfoSm.setText(R.string.server_info_unavailable);
1012 }
1013 if (features.pep()) {
1014 AxolotlService axolotlService = this.mAccount.getAxolotlService();
1015 if (axolotlService != null && axolotlService.isPepBroken()) {
1016 this.binding.serverInfoPep.setText(R.string.server_info_broken);
1017 } else if (features.pepPublishOptions() || features.pepOmemoWhitelisted()) {
1018 this.binding.serverInfoPep.setText(R.string.server_info_available);
1019 } else {
1020 this.binding.serverInfoPep.setText(R.string.server_info_partial);
1021 }
1022 } else {
1023 this.binding.serverInfoPep.setText(R.string.server_info_unavailable);
1024 }
1025 if (features.httpUpload(0)) {
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.mHostname.getText().length() > 0) {
1097 errorLayout = this.mHostnameLayout;
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.mHostnameLayout != exception) {
1124 this.mHostnameLayout.setErrorEnabled(false);
1125 this.mHostnameLayout.setError(null);
1126 }
1127 if (this.mPortLayout != exception) {
1128 this.mPortLayout.setErrorEnabled(false);
1129 this.mPortLayout.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}