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