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