ConversationsActivity.java

   1/*
   2 * Copyright (c) 2018, Daniel Gultsch All rights reserved.
   3 *
   4 * Redistribution and use in source and binary forms, with or without modification,
   5 * are permitted provided that the following conditions are met:
   6 *
   7 * 1. Redistributions of source code must retain the above copyright notice, this
   8 * list of conditions and the following disclaimer.
   9 *
  10 * 2. Redistributions in binary form must reproduce the above copyright notice,
  11 * this list of conditions and the following disclaimer in the documentation and/or
  12 * other materials provided with the distribution.
  13 *
  14 * 3. Neither the name of the copyright holder nor the names of its contributors
  15 * may be used to endorse or promote products derived from this software without
  16 * specific prior written permission.
  17 *
  18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  19 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
  22 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  25 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  27 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28 */
  29
  30package eu.siacs.conversations.ui;
  31
  32import static eu.siacs.conversations.ui.ConversationFragment.REQUEST_DECRYPT_PGP;
  33
  34import android.Manifest;
  35import android.annotation.SuppressLint;
  36import android.app.Activity;
  37import android.app.Fragment;
  38import android.app.FragmentManager;
  39import android.app.FragmentTransaction;
  40import android.content.ActivityNotFoundException;
  41import android.content.ComponentName;
  42import android.content.Context;
  43import android.content.Intent;
  44import android.content.pm.PackageManager;
  45import android.graphics.Bitmap;
  46import android.net.Uri;
  47import android.os.Build;
  48import android.os.Bundle;
  49import android.provider.Settings;
  50import android.util.Log;
  51import android.util.Pair;
  52import android.view.KeyEvent;
  53import android.view.Menu;
  54import android.view.MenuItem;
  55import android.widget.Toast;
  56
  57import androidx.annotation.IdRes;
  58import androidx.annotation.NonNull;
  59import androidx.appcompat.app.ActionBar;
  60import androidx.appcompat.app.AlertDialog;
  61import androidx.core.app.ActivityCompat;
  62import androidx.core.content.ContextCompat;
  63import androidx.databinding.DataBindingUtil;
  64
  65import com.cheogram.android.DownloadDefaultStickers;
  66import com.cheogram.android.FinishOnboarding;
  67
  68import com.google.common.collect.ImmutableList;
  69
  70import io.michaelrocks.libphonenumber.android.NumberParseException;
  71import com.google.android.material.dialog.MaterialAlertDialogBuilder;
  72
  73import org.openintents.openpgp.util.OpenPgpApi;
  74
  75import java.util.Arrays;
  76import java.util.ArrayList;
  77import java.util.HashSet;
  78import java.util.HashMap;
  79import java.util.List;
  80import java.util.Objects;
  81import java.util.Set;
  82import java.util.TreeMap;
  83import java.util.concurrent.atomic.AtomicBoolean;
  84
  85import eu.siacs.conversations.Config;
  86import eu.siacs.conversations.R;
  87import eu.siacs.conversations.crypto.OmemoSetting;
  88import eu.siacs.conversations.databinding.ActivityConversationsBinding;
  89import eu.siacs.conversations.entities.Account;
  90import eu.siacs.conversations.entities.Contact;
  91import eu.siacs.conversations.entities.Conversation;
  92import eu.siacs.conversations.entities.Conversational;
  93import eu.siacs.conversations.entities.ListItem.Tag;
  94import eu.siacs.conversations.persistance.FileBackend;
  95import eu.siacs.conversations.services.XmppConnectionService;
  96import eu.siacs.conversations.ui.interfaces.OnBackendConnected;
  97import eu.siacs.conversations.ui.interfaces.OnConversationArchived;
  98import eu.siacs.conversations.ui.interfaces.OnConversationRead;
  99import eu.siacs.conversations.ui.interfaces.OnConversationSelected;
 100import eu.siacs.conversations.ui.interfaces.OnConversationsListItemUpdated;
 101import eu.siacs.conversations.ui.util.ActivityResult;
 102import eu.siacs.conversations.ui.util.ConversationMenuConfigurator;
 103import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
 104import eu.siacs.conversations.ui.util.PendingItem;
 105import eu.siacs.conversations.ui.util.ToolbarUtils;
 106import eu.siacs.conversations.utils.AccountUtils;
 107import eu.siacs.conversations.utils.ExceptionHelper;
 108import eu.siacs.conversations.utils.PhoneNumberUtilWrapper;
 109import eu.siacs.conversations.utils.SignupUtils;
 110import eu.siacs.conversations.utils.ThemeHelper;
 111import eu.siacs.conversations.utils.XmppUri;
 112import eu.siacs.conversations.xmpp.Jid;
 113import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
 114
 115public class ConversationsActivity extends XmppActivity implements OnConversationSelected, OnConversationArchived, OnConversationsListItemUpdated, OnConversationRead, XmppConnectionService.OnAccountUpdate, XmppConnectionService.OnConversationUpdate, XmppConnectionService.OnRosterUpdate, OnUpdateBlocklist, XmppConnectionService.OnShowErrorToast, XmppConnectionService.OnAffiliationChanged {
 116
 117    public static final String ACTION_VIEW_CONVERSATION = "eu.siacs.conversations.action.VIEW";
 118    public static final String EXTRA_CONVERSATION = "conversationUuid";
 119    public static final String EXTRA_DOWNLOAD_UUID = "eu.siacs.conversations.download_uuid";
 120    public static final String EXTRA_AS_QUOTE = "eu.siacs.conversations.as_quote";
 121    public static final String EXTRA_NICK = "nick";
 122    public static final String EXTRA_IS_PRIVATE_MESSAGE = "pm";
 123    public static final String EXTRA_DO_NOT_APPEND = "do_not_append";
 124    public static final String EXTRA_POST_INIT_ACTION = "post_init_action";
 125    public static final String POST_ACTION_RECORD_VOICE = "record_voice";
 126    public static final String EXTRA_THREAD = "threadId";
 127    public static final String EXTRA_TYPE = "type";
 128    public static final String EXTRA_NODE = "node";
 129    public static final String EXTRA_JID = "jid";
 130
 131    private static final List<String> VIEW_AND_SHARE_ACTIONS = Arrays.asList(
 132            ACTION_VIEW_CONVERSATION,
 133            Intent.ACTION_SEND,
 134            Intent.ACTION_SEND_MULTIPLE
 135    );
 136
 137    public static final int REQUEST_OPEN_MESSAGE = 0x9876;
 138    public static final int REQUEST_PLAY_PAUSE = 0x5432;
 139    public static final int REQUEST_MICROPHONE = 0x5432f;
 140    public static final int DIALLER_INTEGRATION = 0x5432ff;
 141    public static final int REQUEST_DOWNLOAD_STICKERS = 0xbf8702;
 142
 143    public static final long DRAWER_ALL_CHATS = 1;
 144    public static final long DRAWER_DIRECT_MESSAGES = 2;
 145    public static final long DRAWER_CHANNELS = 3;
 146    public static final long DRAWER_SETTINGS = 4;
 147    public static final long DRAWER_MANAGE_ACCOUNT = 5;
 148    public static final long DRAWER_MANAGE_PHONE_ACCOUNTS = 6;
 149
 150    //secondary fragment (when holding the conversation, must be initialized before refreshing the overview fragment
 151    private static final @IdRes
 152    int[] FRAGMENT_ID_NOTIFICATION_ORDER = {R.id.secondary_fragment, R.id.main_fragment};
 153    private final PendingItem<Intent> pendingViewIntent = new PendingItem<>();
 154    private final PendingItem<ActivityResult> postponedActivityResult = new PendingItem<>();
 155    private ActivityConversationsBinding binding;
 156    private boolean mActivityPaused = true;
 157    private final AtomicBoolean mRedirectInProcess = new AtomicBoolean(false);
 158    private boolean refreshForNewCaps = false;
 159    private Set<Jid> newCapsJids = new HashSet<>();
 160    private int mRequestCode = -1;
 161    private com.mikepenz.materialdrawer.widget.AccountHeaderView accountHeader;
 162    private Bundle savedState = null;
 163    private Tag selectedTag = null;
 164    private long mainFilter = DRAWER_ALL_CHATS;
 165
 166    private static boolean isViewOrShareIntent(Intent i) {
 167        Log.d(Config.LOGTAG, "action: " + (i == null ? null : i.getAction()));
 168        return i != null && VIEW_AND_SHARE_ACTIONS.contains(i.getAction()) && i.hasExtra(EXTRA_CONVERSATION);
 169    }
 170
 171    private static Intent createLauncherIntent(Context context) {
 172        final Intent intent = new Intent(context, ConversationsActivity.class);
 173        intent.setAction(Intent.ACTION_MAIN);
 174        intent.addCategory(Intent.CATEGORY_LAUNCHER);
 175        return intent;
 176    }
 177
 178    @Override
 179    protected void refreshUiReal() {
 180        invalidateOptionsMenu();
 181        for (@IdRes int id : FRAGMENT_ID_NOTIFICATION_ORDER) {
 182            refreshFragment(id);
 183        }
 184        refreshForNewCaps = false;
 185        newCapsJids.clear();
 186
 187        final var accounts = xmppConnectionService.getAccounts();
 188        final var inHeader = new HashSet<>();
 189        for (final var p : ImmutableList.copyOf(accountHeader.getProfiles())) {
 190            if (p instanceof com.mikepenz.materialdrawer.model.ProfileSettingDrawerItem) continue;
 191            if (accounts.contains(p.getTag()) || (accounts.size() > 1 && p.getTag() == null)) {
 192                inHeader.add(p.getTag());
 193            } else {
 194                accountHeader.removeProfile(p);
 195            }
 196        }
 197
 198        if (accounts.size() > 1 && !inHeader.contains(null)) {
 199            final var all = new com.mikepenz.materialdrawer.model.ProfileDrawerItem();
 200            all.setIdentifier(100);
 201            com.mikepenz.materialdrawer.model.interfaces.DescribableKt.setDescriptionText(all, "All Accounts");
 202            com.mikepenz.materialdrawer.model.interfaces.IconableKt.setIconRes(all, R.drawable.main_logo);
 203            accountHeader.addProfile(all, 0);
 204        }
 205
 206        var hasPhoneAccounts = false;
 207        accountHeader.removeProfileByIdentifier(DRAWER_MANAGE_PHONE_ACCOUNTS);
 208        outer:
 209        for (Account account : xmppConnectionService.getAccounts()) {
 210            for (Contact contact : account.getRoster().getContacts()) {
 211                if (contact.getPresences().anyIdentity("gateway", "pstn")) {
 212                    hasPhoneAccounts = true;
 213                    final var phoneAccounts = new com.mikepenz.materialdrawer.model.ProfileSettingDrawerItem();
 214                    phoneAccounts.setIdentifier(DRAWER_MANAGE_PHONE_ACCOUNTS);
 215                    com.mikepenz.materialdrawer.model.interfaces.NameableKt.setNameText(phoneAccounts, "Manage Phone Accounts");
 216                    com.mikepenz.materialdrawer.model.interfaces.IconableKt.setIconRes(phoneAccounts, R.drawable.ic_call_24dp);
 217                    accountHeader.addProfile(phoneAccounts, accountHeader.getProfiles().size() - 1);
 218                    break outer;
 219                }
 220            }
 221        }
 222
 223        long id = 101;
 224        for (final var a : accounts) {
 225            final var p = new com.mikepenz.materialdrawer.model.ProfileDrawerItem();
 226            p.setIdentifier(id++);
 227            p.setTag(a);
 228            com.mikepenz.materialdrawer.model.interfaces.NameableKt.setNameText(p, a.getDisplayName());
 229            com.mikepenz.materialdrawer.model.interfaces.DescribableKt.setDescriptionText(p, a.getJid().asBareJid().toString());
 230            com.mikepenz.materialdrawer.model.interfaces.IconableKt.setIconBitmap(p, FileBackend.drawDrawable(xmppConnectionService.getAvatarService().get(a, (int) getResources().getDimension(R.dimen.avatar_on_drawer), false)).copy(Bitmap.Config.ARGB_8888, false));
 231            if (inHeader.contains(a)) {
 232                accountHeader.updateProfile(p);
 233            } else {
 234                accountHeader.addProfile(p, accountHeader.getProfiles().size() - (hasPhoneAccounts ? 2 : 1));
 235            }
 236        }
 237
 238        final var items = binding.drawer.getItemAdapter().getAdapterItems();
 239        final var tags = new TreeMap<Tag, Integer>();
 240        final var conversations = new ArrayList<Conversation>();
 241        populateWithOrderedConversations(conversations, false);
 242        for (final var c : conversations) {
 243            for (final var tag : c.getTags(this)) {
 244                if ("Channel".equals(tag.getName())) continue;
 245                var count = tags.get(tag);
 246                if (count == null) count = 0;
 247                tags.put(tag, count + c.unreadCount());
 248            }
 249        }
 250
 251        id = 1000;
 252        final var inDrawer = new HashMap<Tag, Long>();
 253        for (final var item : ImmutableList.copyOf(items)) {
 254            if (item.getIdentifier() >= 1000 && !tags.containsKey(item.getTag())) {
 255                com.mikepenz.materialdrawer.util.MaterialDrawerSliderViewExtensionsKt.removeItems(binding.drawer, item);
 256            } else if (item.getIdentifier() >= 1000) {
 257                inDrawer.put((Tag)item.getTag(), item.getIdentifier());
 258                id = item.getIdentifier() + 1;
 259            }
 260        }
 261
 262        for (final var entry : tags.entrySet()) {
 263            final var badge = entry.getValue() > 0 ? entry.getValue().toString() : "";
 264            if (inDrawer.containsKey(entry.getKey())) {
 265                com.mikepenz.materialdrawer.util.MaterialDrawerSliderViewExtensionsKt.updateBadge(
 266                    binding.drawer,
 267                    inDrawer.get(entry.getKey()),
 268                    new com.mikepenz.materialdrawer.holder.StringHolder(badge)
 269                );
 270            } else {
 271                final var item = new com.mikepenz.materialdrawer.model.SecondaryDrawerItem();
 272                item.setIdentifier(id++);
 273                item.setTag(entry.getKey());
 274                com.mikepenz.materialdrawer.model.interfaces.NameableKt.setNameText(item, entry.getKey().getName());
 275                com.mikepenz.materialdrawer.model.interfaces.BadgeableKt.setBadgeText(item, badge);
 276                binding.drawer.getItemAdapter().add(item);
 277            }
 278        }
 279    }
 280
 281    @Override
 282    protected void onBackendConnected() {
 283        final var useSavedState = savedState;
 284        savedState = null;
 285        if (performRedirectIfNecessary(true)) {
 286            return;
 287        }
 288        xmppConnectionService.getNotificationService().setIsInForeground(true);
 289        final Intent intent = pendingViewIntent.pop();
 290        if (intent != null) {
 291            if (processViewIntent(intent)) {
 292                if (binding.secondaryFragment != null) {
 293                    notifyFragmentOfBackendConnected(R.id.main_fragment);
 294                }
 295                invalidateActionBarTitle();
 296                return;
 297            }
 298        }
 299        for (@IdRes int id : FRAGMENT_ID_NOTIFICATION_ORDER) {
 300            notifyFragmentOfBackendConnected(id);
 301        }
 302
 303        final ActivityResult activityResult = postponedActivityResult.pop();
 304        if (activityResult != null) {
 305            handleActivityResult(activityResult);
 306        }
 307
 308        if (binding.secondaryFragment != null && ConversationFragment.getConversation(this) == null) {
 309            Conversation conversation = ConversationsOverviewFragment.getSuggestion(this);
 310            if (conversation != null) {
 311                openConversation(conversation, null);
 312            }
 313        }
 314        showDialogsIfMainIsOverview();
 315
 316        if (accountHeader != null) {
 317            refreshUiReal();
 318            return;
 319        }
 320
 321        accountHeader = new com.mikepenz.materialdrawer.widget.AccountHeaderView(this);
 322        final var manageAccount = new com.mikepenz.materialdrawer.model.ProfileSettingDrawerItem();
 323        manageAccount.setIdentifier(DRAWER_MANAGE_ACCOUNT);
 324        com.mikepenz.materialdrawer.model.interfaces.NameableKt.setNameText(manageAccount, xmppConnectionService.getAccounts().size() > 1 ? "Manage Accounts" : "Manage Account");
 325        com.mikepenz.materialdrawer.model.interfaces.IconableKt.setIconRes(manageAccount, R.drawable.ic_settings_24dp);
 326        accountHeader.addProfiles(manageAccount);
 327
 328        final var allChats = new com.mikepenz.materialdrawer.model.PrimaryDrawerItem();
 329        allChats.setIdentifier(DRAWER_ALL_CHATS);
 330        com.mikepenz.materialdrawer.model.interfaces.NameableKt.setNameText(allChats, "All Chats");
 331
 332
 333        final var directMessages = new com.mikepenz.materialdrawer.model.PrimaryDrawerItem();
 334        directMessages.setIdentifier(DRAWER_DIRECT_MESSAGES);
 335        com.mikepenz.materialdrawer.model.interfaces.NameableKt.setNameText(directMessages, "Direct Messages");
 336
 337        final var channels = new com.mikepenz.materialdrawer.model.PrimaryDrawerItem();
 338        channels.setIdentifier(DRAWER_CHANNELS);
 339        com.mikepenz.materialdrawer.model.interfaces.NameableKt.setNameText(channels, "Channels");
 340
 341        binding.drawer.getItemAdapter().add(
 342            allChats,
 343            directMessages,
 344            channels,
 345            new com.mikepenz.materialdrawer.model.DividerDrawerItem()
 346        );
 347
 348        final var settings = new com.mikepenz.materialdrawer.model.PrimaryDrawerItem();
 349        settings.setIdentifier(DRAWER_SETTINGS);
 350        settings.setSelectable(false);
 351        com.mikepenz.materialdrawer.model.interfaces.NameableKt.setNameText(settings, "Settings");
 352        com.mikepenz.materialdrawer.model.interfaces.IconableKt.setIconRes(settings, R.drawable.ic_settings_24dp);
 353        com.mikepenz.materialdrawer.util.MaterialDrawerSliderViewExtensionsKt.addStickyDrawerItems(binding.drawer, settings);
 354
 355        refreshUiReal();
 356        if (useSavedState != null) binding.drawer.setSavedInstance(useSavedState);
 357        accountHeader.attachToSliderView(binding.drawer);
 358        if (useSavedState != null) accountHeader.withSavedInstance(useSavedState);
 359
 360        if (binding.drawer.getSelectedItemPosition() < 1) {
 361            binding.drawer.setSelectedItemIdentifier(DRAWER_ALL_CHATS);
 362        }
 363
 364        binding.drawer.setOnDrawerItemClickListener((v, drawerItem, pos) -> {
 365            final var id = drawerItem.getIdentifier();
 366            if (id == DRAWER_SETTINGS) {
 367                startActivity(new Intent(this, eu.siacs.conversations.ui.activity.SettingsActivity.class));
 368                return false;
 369            } else if (id == DRAWER_ALL_CHATS || id == DRAWER_DIRECT_MESSAGES || id == DRAWER_CHANNELS) {
 370                selectedTag = null;
 371                mainFilter = id;
 372            } else if (id >= 1000) {
 373                selectedTag = (Tag) drawerItem.getTag();
 374            }
 375            binding.drawer.getSelectExtension().selectByIdentifier(mainFilter, false, true);
 376            refreshUi();
 377            return false;
 378        });
 379
 380         accountHeader.setOnAccountHeaderListener((v, profile, isCurrent) -> {
 381            final var id = profile.getIdentifier();
 382            if (isCurrent) return false; // Ignore switching to already selected profile
 383
 384            if (id == DRAWER_MANAGE_ACCOUNT) {
 385                final Account account = (Account) accountHeader.getActiveProfile().getTag();
 386                if (account == null) {
 387                    AccountUtils.launchManageAccounts(this);
 388                } else {
 389                    switchToAccount(account);
 390                }
 391                return false;
 392            }
 393
 394            if (id == DRAWER_MANAGE_PHONE_ACCOUNTS) {
 395                final String[] permissions;
 396                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
 397                    permissions = new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.BLUETOOTH_CONNECT};
 398                } else {
 399                    permissions = new String[]{Manifest.permission.RECORD_AUDIO};
 400                }
 401                requestPermissions(permissions, REQUEST_MICROPHONE);
 402                return false;
 403            }
 404
 405            // Clicked on an actual profile
 406            if (profile.getTag() == null) {
 407                com.mikepenz.materialdrawer.model.interfaces.NameableKt.setNameText(manageAccount, "Manage Accounts");
 408            } else {
 409                com.mikepenz.materialdrawer.model.interfaces.NameableKt.setNameText(manageAccount, "Manage Account");
 410            }
 411            accountHeader.updateProfile(manageAccount);
 412
 413            final var fm = getFragmentManager();
 414            while (fm.getBackStackEntryCount() > 0) {
 415                try {
 416                    fm.popBackStackImmediate();
 417                } catch (IllegalStateException e) {
 418                    break;
 419                }
 420            }
 421
 422            refreshUi();
 423
 424            return false;
 425        });
 426
 427         accountHeader.setOnAccountHeaderProfileImageListener((v, profile, isCurrent) -> {
 428            if (isCurrent) {
 429                final Account account = (Account) accountHeader.getActiveProfile().getTag();
 430                if (account == null) {
 431                    AccountUtils.launchManageAccounts(this);
 432                } else {
 433                    switchToAccount(account);
 434                }
 435            }
 436            return false;
 437         });
 438    }
 439
 440    @Override
 441    public boolean colorCodeAccounts() {
 442        if (accountHeader != null) {
 443            final var active = accountHeader.getActiveProfile();
 444            if (active != null && active.getTag() != null) return false;
 445        }
 446        return super.colorCodeAccounts();
 447    }
 448
 449    @Override
 450    public void populateWithOrderedConversations(List<Conversation> list) {
 451        populateWithOrderedConversations(list, true);
 452    }
 453
 454    public void populateWithOrderedConversations(List<Conversation> list, final boolean tagFilter) {
 455        super.populateWithOrderedConversations(list);
 456        if (accountHeader == null || accountHeader.getActiveProfile() == null) return;
 457
 458        final var selectedAccount =
 459            accountHeader.getActiveProfile().getTag() != null ?
 460            ((Account) accountHeader.getActiveProfile().getTag()).getUuid() :
 461            null;
 462
 463        for (final var c : ImmutableList.copyOf(list)) {
 464            if (mainFilter == DRAWER_CHANNELS && c.getMode() != Conversation.MODE_MULTI) {
 465                list.remove(c);
 466            } else if (mainFilter == DRAWER_DIRECT_MESSAGES && c.getMode() == Conversation.MODE_MULTI) {
 467                list.remove(c);
 468            } else if (selectedAccount != null && !selectedAccount.equals(c.getAccount().getUuid())) {
 469                list.remove(c);
 470            } else if (selectedTag != null && tagFilter && !c.getTags(this).contains(selectedTag)) {
 471                list.remove(c);
 472            }
 473        }
 474    }
 475
 476    @Override
 477    public void launchStartConversation() {
 478        StartConversationActivity.launch(this, (Account) accountHeader.getActiveProfile().getTag(), selectedTag == null ? null : selectedTag.getName());
 479    }
 480
 481    private boolean performRedirectIfNecessary(boolean noAnimation) {
 482        return performRedirectIfNecessary(null, noAnimation);
 483    }
 484
 485    private boolean performRedirectIfNecessary(final Conversation ignore, final boolean noAnimation) {
 486        if (xmppConnectionService == null) {
 487            return false;
 488        }
 489
 490        boolean isConversationsListEmpty = xmppConnectionService.isConversationsListEmpty(ignore);
 491        if (isConversationsListEmpty && mRedirectInProcess.compareAndSet(false, true)) {
 492            final Intent intent = SignupUtils.getRedirectionIntent(this);
 493            if (noAnimation) {
 494                intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
 495            }
 496            runOnUiThread(() -> {
 497                startActivity(intent);
 498                if (noAnimation) {
 499                    overridePendingTransition(0, 0);
 500                }
 501            });
 502        }
 503        return mRedirectInProcess.get();
 504    }
 505
 506    private void showDialogsIfMainIsOverview() {
 507        Pair<Account, Account> incomplete = null;
 508        if (xmppConnectionService != null && (incomplete = xmppConnectionService.onboardingIncomplete()) != null) {
 509            FinishOnboarding.finish(xmppConnectionService, this, incomplete.first, incomplete.second);
 510        }
 511        if (xmppConnectionService == null || xmppConnectionService.isOnboarding()) {
 512            return;
 513        }
 514        final Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
 515        if (fragment instanceof ConversationsOverviewFragment) {
 516            if (ExceptionHelper.checkForCrash(this)) return;
 517            if (offerToSetupDiallerIntegration()) return;
 518            if (offerToDownloadStickers()) return;
 519            if (openBatteryOptimizationDialogIfNeeded()) return;
 520            requestNotificationPermissionIfNeeded();
 521            xmppConnectionService.rescanStickers();
 522        }
 523    }
 524
 525    private String getBatteryOptimizationPreferenceKey() {
 526        @SuppressLint("HardwareIds") String device = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
 527        return "show_battery_optimization" + (device == null ? "" : device);
 528    }
 529
 530    private void setNeverAskForBatteryOptimizationsAgain() {
 531        getPreferences().edit().putBoolean(getBatteryOptimizationPreferenceKey(), false).apply();
 532    }
 533
 534    private boolean openBatteryOptimizationDialogIfNeeded() {
 535        if (isOptimizingBattery() && getPreferences().getBoolean(getBatteryOptimizationPreferenceKey(), true)) {
 536            final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
 537            builder.setTitle(R.string.battery_optimizations_enabled);
 538            builder.setMessage(getString(R.string.battery_optimizations_enabled_dialog, getString(R.string.app_name)));
 539            builder.setPositiveButton(R.string.next, (dialog, which) -> {
 540                final Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
 541                final Uri uri = Uri.parse("package:" + getPackageName());
 542                intent.setData(uri);
 543                try {
 544                    startActivityForResult(intent, REQUEST_BATTERY_OP);
 545                } catch (final ActivityNotFoundException e) {
 546                    Toast.makeText(this, R.string.device_does_not_support_battery_op, Toast.LENGTH_SHORT).show();
 547                }
 548            });
 549            builder.setOnDismissListener(dialog -> setNeverAskForBatteryOptimizationsAgain());
 550            final AlertDialog dialog = builder.create();
 551            dialog.setCanceledOnTouchOutside(false);
 552            dialog.show();
 553            return true;
 554        }
 555        return false;
 556    }
 557
 558    private void requestNotificationPermissionIfNeeded() {
 559        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && ActivityCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
 560            requestPermissions(new String[]{Manifest.permission.POST_NOTIFICATIONS}, REQUEST_POST_NOTIFICATION);
 561        }
 562    }
 563
 564    private boolean offerToDownloadStickers() {
 565        int offered = getPreferences().getInt("default_stickers_offered", 0);
 566        if (offered > 0) return false;
 567        getPreferences().edit().putInt("default_stickers_offered", 1).apply();
 568
 569        AlertDialog.Builder builder = new AlertDialog.Builder(this);
 570        builder.setTitle("Download Stickers?");
 571        builder.setMessage("Would you like to download some default sticker packs?");
 572        builder.setPositiveButton(R.string.yes, (dialog, which) -> {
 573            if (hasStoragePermission(REQUEST_DOWNLOAD_STICKERS)) {
 574                downloadStickers();
 575            }
 576        });
 577        builder.setNegativeButton(R.string.no, (dialog, which) -> {
 578            showDialogsIfMainIsOverview();
 579        });
 580        final AlertDialog dialog = builder.create();
 581        dialog.setCanceledOnTouchOutside(false);
 582        dialog.show();
 583        return true;
 584    }
 585
 586    private boolean offerToSetupDiallerIntegration() {
 587        if (mRequestCode == DIALLER_INTEGRATION) {
 588            mRequestCode = -1;
 589            return true;
 590        }
 591        if (Build.VERSION.SDK_INT < 23) return false;
 592        if (Build.VERSION.SDK_INT >= 33) {
 593            if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELECOM) && !getPackageManager().hasSystemFeature(PackageManager.FEATURE_CONNECTION_SERVICE)) return false;
 594        } else {
 595            if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CONNECTION_SERVICE)) return false;
 596        }
 597
 598        Set<String> pstnGateways = new HashSet<>();
 599        for (Account account : xmppConnectionService.getAccounts()) {
 600            for (Contact contact : account.getRoster().getContacts()) {
 601                if (contact.getPresences().anyIdentity("gateway", "pstn")) {
 602                    pstnGateways.add(contact.getJid().asBareJid().toEscapedString());
 603                }
 604            }
 605        }
 606
 607        if (pstnGateways.size() < 1) return false;
 608        Set<String> fromPrefs = getPreferences().getStringSet("pstn_gateways", Set.of("UPGRADE"));
 609        getPreferences().edit().putStringSet("pstn_gateways", pstnGateways).apply();
 610        pstnGateways.removeAll(fromPrefs);
 611        if (pstnGateways.size() < 1) return false;
 612
 613        if (fromPrefs.contains("UPGRADE")) return false;
 614
 615        AlertDialog.Builder builder = new AlertDialog.Builder(this);
 616        builder.setTitle("Dialler Integration");
 617        builder.setMessage("Cheogram Android is able to integrate with your system's dialler app to allow dialling calls via your configured gateway " + String.join(", ", pstnGateways) + ".\n\nEnabling this integration will require granting microphone permission to the app.  Would you like to enable it now?");
 618        builder.setPositiveButton(R.string.yes, (dialog, which) -> {
 619            final String[] permissions;
 620            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
 621                permissions = new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.BLUETOOTH_CONNECT};
 622            } else {
 623                permissions = new String[]{Manifest.permission.RECORD_AUDIO};
 624            }
 625            requestPermissions(permissions, REQUEST_MICROPHONE);
 626        });
 627        builder.setNegativeButton(R.string.no, (dialog, which) -> {
 628            showDialogsIfMainIsOverview();
 629        });
 630        final AlertDialog dialog = builder.create();
 631        dialog.setCanceledOnTouchOutside(false);
 632        dialog.show();
 633        return true;
 634    }
 635
 636    private void notifyFragmentOfBackendConnected(@IdRes int id) {
 637        final Fragment fragment = getFragmentManager().findFragmentById(id);
 638        if (fragment instanceof OnBackendConnected callback) {
 639            callback.onBackendConnected();
 640        }
 641    }
 642
 643    private void refreshFragment(@IdRes int id) {
 644        final Fragment fragment = getFragmentManager().findFragmentById(id);
 645        if (fragment instanceof XmppFragment xmppFragment) {
 646            xmppFragment.refresh();
 647            if (refreshForNewCaps) xmppFragment.refreshForNewCaps(newCapsJids);
 648        }
 649    }
 650
 651    private boolean processViewIntent(Intent intent) {
 652        final String uuid = intent.getStringExtra(EXTRA_CONVERSATION);
 653        final Conversation conversation = uuid != null ? xmppConnectionService.findConversationByUuid(uuid) : null;
 654        if (conversation == null) {
 655            Log.d(Config.LOGTAG, "unable to view conversation with uuid:" + uuid);
 656            return false;
 657        }
 658        openConversation(conversation, intent.getExtras());
 659        return true;
 660    }
 661
 662    @Override
 663    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
 664        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
 665        UriHandlerActivity.onRequestPermissionResult(this, requestCode, grantResults);
 666        if (grantResults.length > 0) {
 667            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
 668                switch (requestCode) {
 669                    case REQUEST_OPEN_MESSAGE:
 670                        refreshUiReal();
 671                        ConversationFragment.openPendingMessage(this);
 672                        break;
 673                    case REQUEST_PLAY_PAUSE:
 674                        ConversationFragment.startStopPending(this);
 675                        break;
 676                    case REQUEST_MICROPHONE:
 677                        Intent intent = new Intent();
 678                        intent.setComponent(new ComponentName("com.android.server.telecom",
 679                            "com.android.server.telecom.settings.EnableAccountPreferenceActivity"));
 680                        try {
 681                            startActivityForResult(intent, DIALLER_INTEGRATION);
 682                        } catch (ActivityNotFoundException e) {
 683                            displayToast("Dialler integration not available on your OS");
 684                        }
 685                        break;
 686                    case REQUEST_DOWNLOAD_STICKERS:
 687                        downloadStickers();
 688                        break;
 689                }
 690            } else {
 691                showDialogsIfMainIsOverview();
 692            }
 693        } else {
 694            showDialogsIfMainIsOverview();
 695        }
 696    }
 697
 698    private void downloadStickers() {
 699        Intent intent = new Intent(this, DownloadDefaultStickers.class);
 700        intent.putExtra("tor", xmppConnectionService.useTorToConnect());
 701        ContextCompat.startForegroundService(this, intent);
 702        displayToast("Sticker download started");
 703        showDialogsIfMainIsOverview();
 704    }
 705
 706    @Override
 707    public void onActivityResult(int requestCode, int resultCode, final Intent data) {
 708        super.onActivityResult(requestCode, resultCode, data);
 709
 710        if (requestCode == DIALLER_INTEGRATION) {
 711            mRequestCode = requestCode;
 712            try {
 713                startActivity(new Intent(android.telecom.TelecomManager.ACTION_CHANGE_PHONE_ACCOUNTS));
 714            } catch (ActivityNotFoundException e) {
 715                displayToast("Dialler integration not available on your OS");
 716            }
 717            return;
 718        }
 719
 720        ActivityResult activityResult = ActivityResult.of(requestCode, resultCode, data);
 721        if (xmppConnectionService != null) {
 722            handleActivityResult(activityResult);
 723        } else {
 724            this.postponedActivityResult.push(activityResult);
 725        }
 726    }
 727
 728    private void handleActivityResult(final ActivityResult activityResult) {
 729        if (activityResult.resultCode == Activity.RESULT_OK) {
 730            handlePositiveActivityResult(activityResult.requestCode, activityResult.data);
 731        } else {
 732            handleNegativeActivityResult(activityResult.requestCode);
 733        }
 734        if (activityResult.requestCode == REQUEST_BATTERY_OP) {
 735            // the result code is always 0 even when battery permission were granted
 736            requestNotificationPermissionIfNeeded();
 737            XmppConnectionService.toggleForegroundService(xmppConnectionService);
 738        }
 739    }
 740
 741    private void handleNegativeActivityResult(int requestCode) {
 742        Conversation conversation = ConversationFragment.getConversationReliable(this);
 743        switch (requestCode) {
 744            case REQUEST_DECRYPT_PGP:
 745                if (conversation == null) {
 746                    break;
 747                }
 748                conversation.getAccount().getPgpDecryptionService().giveUpCurrentDecryption();
 749                break;
 750            case REQUEST_BATTERY_OP:
 751                setNeverAskForBatteryOptimizationsAgain();
 752                break;
 753        }
 754    }
 755
 756    private void handlePositiveActivityResult(int requestCode, final Intent data) {
 757        Conversation conversation = ConversationFragment.getConversationReliable(this);
 758        if (conversation == null) {
 759            Log.d(Config.LOGTAG, "conversation not found");
 760            return;
 761        }
 762        switch (requestCode) {
 763            case REQUEST_DECRYPT_PGP:
 764                conversation.getAccount().getPgpDecryptionService().continueDecryption(data);
 765                break;
 766            case REQUEST_CHOOSE_PGP_ID:
 767                long id = data.getLongExtra(OpenPgpApi.EXTRA_SIGN_KEY_ID, 0);
 768                if (id != 0) {
 769                    conversation.getAccount().setPgpSignId(id);
 770                    announcePgp(conversation.getAccount(), null, null, onOpenPGPKeyPublished);
 771                } else {
 772                    choosePgpSignId(conversation.getAccount());
 773                }
 774                break;
 775            case REQUEST_ANNOUNCE_PGP:
 776                announcePgp(conversation.getAccount(), conversation, data, onOpenPGPKeyPublished);
 777                break;
 778        }
 779    }
 780
 781    @Override
 782    protected void onCreate(final Bundle savedInstanceState) {
 783        super.onCreate(savedInstanceState);
 784        savedState = savedInstanceState;
 785        ConversationMenuConfigurator.reloadFeatures(this);
 786        OmemoSetting.load(this);
 787        this.binding = DataBindingUtil.setContentView(this, R.layout.activity_conversations);
 788        Activities.setStatusAndNavigationBarColors(this, binding.getRoot());
 789        setSupportActionBar(binding.toolbar);
 790        configureActionBar(getSupportActionBar());
 791        this.getFragmentManager().addOnBackStackChangedListener(this::invalidateActionBarTitle);
 792        this.getFragmentManager().addOnBackStackChangedListener(this::showDialogsIfMainIsOverview);
 793        this.initializeFragments();
 794        this.invalidateActionBarTitle();
 795        final Intent intent;
 796        if (savedInstanceState == null) {
 797            intent = getIntent();
 798        } else {
 799            intent = savedInstanceState.getParcelable("intent");
 800        }
 801        if (isViewOrShareIntent(intent)) {
 802            pendingViewIntent.push(intent);
 803            setIntent(createLauncherIntent(this));
 804        }
 805    }
 806
 807    @Override
 808    public boolean onCreateOptionsMenu(Menu menu) {
 809        getMenuInflater().inflate(R.menu.activity_conversations, menu);
 810        final MenuItem qrCodeScanMenuItem = menu.findItem(R.id.action_scan_qr_code);
 811        if (qrCodeScanMenuItem != null) {
 812            if (isCameraFeatureAvailable() && (xmppConnectionService == null || !xmppConnectionService.isOnboarding())) {
 813                Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
 814                boolean visible = getResources().getBoolean(R.bool.show_qr_code_scan)
 815                        && fragment instanceof ConversationsOverviewFragment;
 816                qrCodeScanMenuItem.setVisible(visible);
 817            } else {
 818                qrCodeScanMenuItem.setVisible(false);
 819            }
 820        }
 821        return super.onCreateOptionsMenu(menu);
 822    }
 823
 824    @Override
 825    public void onConversationSelected(Conversation conversation) {
 826        clearPendingViewIntent();
 827        if (ConversationFragment.getConversation(this) == conversation) {
 828            Log.d(Config.LOGTAG, "ignore onConversationSelected() because conversation is already open");
 829            return;
 830        }
 831        openConversation(conversation, null);
 832    }
 833
 834    public void clearPendingViewIntent() {
 835        if (pendingViewIntent.clear()) {
 836            Log.e(Config.LOGTAG, "cleared pending view intent");
 837        }
 838    }
 839
 840    private void displayToast(final String msg) {
 841        runOnUiThread(() -> Toast.makeText(ConversationsActivity.this, msg, Toast.LENGTH_SHORT).show());
 842    }
 843
 844    @Override
 845    public void onAffiliationChangedSuccessful(Jid jid) {
 846
 847    }
 848
 849    @Override
 850    public void onAffiliationChangeFailed(Jid jid, int resId) {
 851        displayToast(getString(resId, jid.asBareJid().toString()));
 852    }
 853
 854    private void openConversation(Conversation conversation, Bundle extras) {
 855        final FragmentManager fragmentManager = getFragmentManager();
 856        executePendingTransactions(fragmentManager);
 857        ConversationFragment conversationFragment = (ConversationFragment) fragmentManager.findFragmentById(R.id.secondary_fragment);
 858        final boolean mainNeedsRefresh;
 859        if (conversationFragment == null) {
 860            mainNeedsRefresh = false;
 861            final Fragment mainFragment = fragmentManager.findFragmentById(R.id.main_fragment);
 862            if (mainFragment instanceof ConversationFragment) {
 863                conversationFragment = (ConversationFragment) mainFragment;
 864            } else {
 865                conversationFragment = new ConversationFragment();
 866                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
 867                fragmentTransaction.replace(R.id.main_fragment, conversationFragment);
 868                fragmentTransaction.addToBackStack(null);
 869                try {
 870                    fragmentTransaction.commit();
 871                } catch (IllegalStateException e) {
 872                    Log.w(Config.LOGTAG, "sate loss while opening conversation", e);
 873                    //allowing state loss is probably fine since view intents et all are already stored and a click can probably be 'ignored'
 874                    return;
 875                }
 876            }
 877        } else {
 878            mainNeedsRefresh = true;
 879        }
 880        conversationFragment.reInit(conversation, extras == null ? new Bundle() : extras);
 881        if (mainNeedsRefresh) {
 882            refreshFragment(R.id.main_fragment);
 883        }
 884        invalidateActionBarTitle();
 885    }
 886
 887    private static void executePendingTransactions(final FragmentManager fragmentManager) {
 888        try {
 889            fragmentManager.executePendingTransactions();
 890        } catch (final Exception e) {
 891            Log.e(Config.LOGTAG,"unable to execute pending fragment transactions");
 892        }
 893    }
 894
 895    public boolean onXmppUriClicked(Uri uri) {
 896        XmppUri xmppUri = new XmppUri(uri);
 897        if (xmppUri.isValidJid() && !xmppUri.hasFingerprints()) {
 898            final Conversation conversation = xmppConnectionService.findUniqueConversationByJid(xmppUri);
 899            if (conversation != null) {
 900                if (xmppUri.getParameter("password") != null) {
 901                    xmppConnectionService.providePasswordForMuc(conversation, xmppUri.getParameter("password"));
 902                }
 903                if (xmppUri.isAction("command")) {
 904                    startCommand(conversation.getAccount(), xmppUri.getJid(), xmppUri.getParameter("node"));
 905                } else {
 906                    Bundle extras = new Bundle();
 907                    extras.putString(Intent.EXTRA_TEXT, xmppUri.getBody());
 908                    if (xmppUri.isAction("message")) extras.putString(EXTRA_POST_INIT_ACTION, "message");
 909                    openConversation(conversation, extras);
 910                }
 911                return true;
 912            }
 913        }
 914        return false;
 915    }
 916
 917    public boolean onTelUriClicked(Uri uri, Account acct) {
 918        final String tel;
 919        try {
 920            tel = PhoneNumberUtilWrapper.normalize(this, uri.getSchemeSpecificPart());
 921        } catch (final IllegalArgumentException | NumberParseException | NullPointerException e) {
 922            return false;
 923        }
 924
 925        Set<String> gateways = new HashSet<>();
 926        for (Account account : (acct == null ? xmppConnectionService.getAccounts() : List.of(acct))) {
 927            for (Contact contact : account.getRoster().getContacts()) {
 928                if (contact.getPresences().anyIdentity("gateway", "pstn") || contact.getPresences().anyIdentity("gateway", "sms")) {
 929                    if (acct == null) acct = account;
 930                    gateways.add(contact.getJid().asBareJid().toEscapedString());
 931                }
 932            }
 933        }
 934
 935        for (String gateway : gateways) {
 936            if (onXmppUriClicked(Uri.parse("xmpp:" + tel + "@" + gateway))) return true;
 937        }
 938
 939        if (gateways.size() == 1 && acct != null) {
 940            openConversation(xmppConnectionService.findOrCreateConversation(acct, Jid.ofLocalAndDomain(tel, gateways.iterator().next()), false, true), null);
 941            return true;
 942        }
 943
 944        return false;
 945    }
 946
 947    @Override
 948    public boolean onOptionsItemSelected(MenuItem item) {
 949        if (MenuDoubleTabUtil.shouldIgnoreTap()) {
 950            return false;
 951        }
 952        switch (item.getItemId()) {
 953            case android.R.id.home:
 954                FragmentManager fm = getFragmentManager();
 955                if (android.os.Build.VERSION.SDK_INT >= 26) {
 956                    Fragment f = fm.getFragments().get(fm.getFragments().size() - 1);
 957                    if (f != null && f instanceof ConversationFragment) {
 958                        if (((ConversationFragment) f).onBackPressed()) {
 959                            return true;
 960                        }
 961                    }
 962                }
 963                if (fm.getBackStackEntryCount() > 0) {
 964                    try {
 965                        fm.popBackStack();
 966                    } catch (IllegalStateException e) {
 967                        Log.w(Config.LOGTAG, "Unable to pop back stack after pressing home button");
 968                    }
 969                    return true;
 970                }
 971                break;
 972            case R.id.action_scan_qr_code:
 973                UriHandlerActivity.scan(this);
 974                return true;
 975            case R.id.action_search_all_conversations:
 976                startActivity(new Intent(this, SearchActivity.class));
 977                return true;
 978            case R.id.action_search_this_conversation:
 979                final Conversation conversation = ConversationFragment.getConversation(this);
 980                if (conversation == null) {
 981                    return true;
 982                }
 983                final Intent intent = new Intent(this, SearchActivity.class);
 984                intent.putExtra(SearchActivity.EXTRA_CONVERSATION_UUID, conversation.getUuid());
 985                startActivity(intent);
 986                return true;
 987        }
 988        return super.onOptionsItemSelected(item);
 989    }
 990
 991    @Override
 992    public boolean onKeyDown(final int keyCode, final KeyEvent keyEvent) {
 993        if (keyCode == KeyEvent.KEYCODE_DPAD_UP && keyEvent.isCtrlPressed()) {
 994            final ConversationFragment conversationFragment = ConversationFragment.get(this);
 995            if (conversationFragment != null && conversationFragment.onArrowUpCtrlPressed()) {
 996                return true;
 997            }
 998        }
 999        return super.onKeyDown(keyCode, keyEvent);
1000    }
1001
1002    @Override
1003    public void onSaveInstanceState(Bundle savedInstanceState) {
1004        final Intent pendingIntent = pendingViewIntent.peek();
1005        savedInstanceState.putParcelable("intent", pendingIntent != null ? pendingIntent : getIntent());
1006        savedInstanceState = binding.drawer.saveInstanceState(savedInstanceState);
1007        savedInstanceState = accountHeader.saveInstanceState(savedInstanceState);
1008        super.onSaveInstanceState(savedInstanceState);
1009    }
1010
1011    @Override
1012    public void onStart() {
1013        super.onStart();
1014        mRedirectInProcess.set(false);
1015    }
1016
1017    @Override
1018    protected void onNewIntent(final Intent intent) {
1019        super.onNewIntent(intent);
1020        if (isViewOrShareIntent(intent)) {
1021            if (xmppConnectionService != null) {
1022                clearPendingViewIntent();
1023                processViewIntent(intent);
1024            } else {
1025                pendingViewIntent.push(intent);
1026            }
1027        }
1028        setIntent(createLauncherIntent(this));
1029    }
1030
1031    @Override
1032    public void onPause() {
1033        this.mActivityPaused = true;
1034        super.onPause();
1035    }
1036
1037    @Override
1038    public void onResume() {
1039        super.onResume();
1040        this.mActivityPaused = false;
1041    }
1042
1043    private void initializeFragments() {
1044        final FragmentManager fragmentManager = getFragmentManager();
1045        FragmentTransaction transaction = fragmentManager.beginTransaction();
1046        final Fragment mainFragment = fragmentManager.findFragmentById(R.id.main_fragment);
1047        final Fragment secondaryFragment = fragmentManager.findFragmentById(R.id.secondary_fragment);
1048        if (mainFragment != null) {
1049            if (binding.secondaryFragment != null) {
1050                if (mainFragment instanceof ConversationFragment) {
1051                    getFragmentManager().popBackStack();
1052                    transaction.remove(mainFragment);
1053                    transaction.commit();
1054                    fragmentManager.executePendingTransactions();
1055                    transaction = fragmentManager.beginTransaction();
1056                    transaction.replace(R.id.secondary_fragment, mainFragment);
1057                    transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
1058                    transaction.commit();
1059                    return;
1060                }
1061            } else {
1062                if (secondaryFragment instanceof ConversationFragment) {
1063                    transaction.remove(secondaryFragment);
1064                    transaction.commit();
1065                    getFragmentManager().executePendingTransactions();
1066                    transaction = fragmentManager.beginTransaction();
1067                    transaction.replace(R.id.main_fragment, secondaryFragment);
1068                    transaction.addToBackStack(null);
1069                    transaction.commit();
1070                    return;
1071                }
1072            }
1073        } else {
1074            transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
1075        }
1076        if (binding.secondaryFragment != null && secondaryFragment == null) {
1077            transaction.replace(R.id.secondary_fragment, new ConversationFragment());
1078        }
1079        transaction.commit();
1080    }
1081
1082    private void invalidateActionBarTitle() {
1083        final ActionBar actionBar = getSupportActionBar();
1084        if (actionBar == null) {
1085            return;
1086        }
1087        final FragmentManager fragmentManager = getFragmentManager();
1088        final Fragment mainFragment = fragmentManager.findFragmentById(R.id.main_fragment);
1089        if (mainFragment instanceof ConversationFragment conversationFragment) {
1090            final Conversation conversation = conversationFragment.getConversation();
1091            if (conversation != null) {
1092                actionBar.setTitle(conversation.getName());
1093                actionBar.setDisplayHomeAsUpEnabled(!xmppConnectionService.isOnboarding() || !conversation.getJid().equals(Jid.of("cheogram.com")));
1094                ToolbarUtils.setActionBarOnClickListener(
1095                        binding.toolbar,
1096                        (v) -> { if(!xmppConnectionService.isOnboarding()) openConversationDetails(conversation); }
1097                );
1098                return;
1099            }
1100        }
1101        final Fragment secondaryFragment = fragmentManager.findFragmentById(R.id.secondary_fragment);
1102        if (secondaryFragment instanceof ConversationFragment conversationFragment) {
1103            final Conversation conversation = conversationFragment.getConversation();
1104            if (conversation != null) {
1105                actionBar.setTitle(conversation.getName());
1106            } else {
1107                actionBar.setTitle(R.string.app_name);
1108            }
1109        } else {
1110            actionBar.setTitle(R.string.app_name);
1111        }
1112        actionBar.setDisplayHomeAsUpEnabled(false);
1113        ToolbarUtils.resetActionBarOnClickListeners(binding.toolbar);
1114    }
1115
1116    private void openConversationDetails(final Conversation conversation) {
1117        if (conversation.getMode() == Conversational.MODE_MULTI) {
1118            ConferenceDetailsActivity.open(this, conversation);
1119        } else {
1120            final Contact contact = conversation.getContact();
1121            if (contact.isSelf()) {
1122                switchToAccount(conversation.getAccount());
1123            } else {
1124                switchToContactDetails(contact);
1125            }
1126        }
1127    }
1128
1129    @Override
1130    public void onConversationArchived(Conversation conversation) {
1131        if (performRedirectIfNecessary(conversation, false)) {
1132            return;
1133        }
1134        final FragmentManager fragmentManager = getFragmentManager();
1135        final Fragment mainFragment = fragmentManager.findFragmentById(R.id.main_fragment);
1136        if (mainFragment instanceof ConversationFragment) {
1137            try {
1138                fragmentManager.popBackStack();
1139            } catch (final IllegalStateException e) {
1140                Log.w(Config.LOGTAG, "state loss while popping back state after archiving conversation", e);
1141                //this usually means activity is no longer active; meaning on the next open we will run through this again
1142            }
1143            return;
1144        }
1145        final Fragment secondaryFragment = fragmentManager.findFragmentById(R.id.secondary_fragment);
1146        if (secondaryFragment instanceof ConversationFragment) {
1147            if (((ConversationFragment) secondaryFragment).getConversation() == conversation) {
1148                Conversation suggestion = ConversationsOverviewFragment.getSuggestion(this, conversation);
1149                if (suggestion != null) {
1150                    openConversation(suggestion, null);
1151                }
1152            }
1153        }
1154    }
1155
1156    @Override
1157    public void onConversationsListItemUpdated() {
1158        Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
1159        if (fragment instanceof ConversationsOverviewFragment) {
1160            ((ConversationsOverviewFragment) fragment).refresh();
1161        }
1162    }
1163
1164    @Override
1165    public void switchToConversation(Conversation conversation) {
1166        Log.d(Config.LOGTAG, "override");
1167        openConversation(conversation, null);
1168    }
1169
1170    @Override
1171    public void onConversationRead(Conversation conversation, String upToUuid) {
1172        if (!mActivityPaused && pendingViewIntent.peek() == null) {
1173            xmppConnectionService.sendReadMarker(conversation, upToUuid);
1174        } else {
1175            Log.d(Config.LOGTAG, "ignoring read callback. mActivityPaused=" + mActivityPaused);
1176        }
1177    }
1178
1179    @Override
1180    public void onAccountUpdate() {
1181        this.refreshUi();
1182    }
1183
1184    @Override
1185    public void onConversationUpdate(boolean newCaps) {
1186        if (performRedirectIfNecessary(false)) {
1187            return;
1188        }
1189        refreshForNewCaps = newCaps;
1190        this.refreshUi();
1191    }
1192
1193    @Override
1194    public void onRosterUpdate(final XmppConnectionService.UpdateRosterReason reason, final Contact contact) {
1195        if (reason != XmppConnectionService.UpdateRosterReason.AVATAR) {
1196            refreshForNewCaps = true;
1197            if (contact != null) newCapsJids.add(contact.getJid().asBareJid());
1198        }
1199        this.refreshUi();
1200    }
1201
1202    @Override
1203    public void OnUpdateBlocklist(OnUpdateBlocklist.Status status) {
1204        this.refreshUi();
1205    }
1206
1207    @Override
1208    public void onShowErrorToast(int resId) {
1209        runOnUiThread(() -> Toast.makeText(this, resId, Toast.LENGTH_SHORT).show());
1210    }
1211}