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