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            } else if (id >= 1000) {
 383                selectedTag = (Tag) drawerItem.getTag();
 384            }
 385            binding.drawer.getSelectExtension().selectByIdentifier(mainFilter, false, true);
 386            refreshUi();
 387            return false;
 388        });
 389
 390         accountHeader.setOnAccountHeaderListener((v, profile, isCurrent) -> {
 391            final var id = profile.getIdentifier();
 392            if (isCurrent) return false; // Ignore switching to already selected profile
 393
 394            if (id == DRAWER_MANAGE_ACCOUNT) {
 395                final Account account = (Account) accountHeader.getActiveProfile().getTag();
 396                if (account == null) {
 397                    AccountUtils.launchManageAccounts(this);
 398                } else {
 399                    switchToAccount(account);
 400                }
 401                return false;
 402            }
 403
 404            if (id == DRAWER_MANAGE_PHONE_ACCOUNTS) {
 405                final String[] permissions;
 406                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
 407                    permissions = new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.BLUETOOTH_CONNECT};
 408                } else {
 409                    permissions = new String[]{Manifest.permission.RECORD_AUDIO};
 410                }
 411                requestPermissions(permissions, REQUEST_MICROPHONE);
 412                return false;
 413            }
 414
 415            // Clicked on an actual profile
 416            if (profile.getTag() == null) {
 417                com.mikepenz.materialdrawer.model.interfaces.NameableKt.setNameText(manageAccount, "Manage Accounts");
 418            } else {
 419                com.mikepenz.materialdrawer.model.interfaces.NameableKt.setNameText(manageAccount, "Manage Account");
 420            }
 421            accountHeader.updateProfile(manageAccount);
 422
 423            final var fm = getFragmentManager();
 424            while (fm.getBackStackEntryCount() > 0) {
 425                try {
 426                    fm.popBackStackImmediate();
 427                } catch (IllegalStateException e) {
 428                    break;
 429                }
 430            }
 431
 432            refreshUi();
 433
 434            return false;
 435        });
 436
 437         accountHeader.setOnAccountHeaderProfileImageListener((v, profile, isCurrent) -> {
 438            if (isCurrent) {
 439                final Account account = (Account) accountHeader.getActiveProfile().getTag();
 440                if (account == null) {
 441                    AccountUtils.launchManageAccounts(this);
 442                } else {
 443                    switchToAccount(account);
 444                }
 445            }
 446            return false;
 447         });
 448    }
 449
 450    @Override
 451    public boolean colorCodeAccounts() {
 452        if (accountHeader != null) {
 453            final var active = accountHeader.getActiveProfile();
 454            if (active != null && active.getTag() != null) return false;
 455        }
 456        return super.colorCodeAccounts();
 457    }
 458
 459    @Override
 460    public void populateWithOrderedConversations(List<Conversation> list) {
 461        populateWithOrderedConversations(list, true);
 462    }
 463
 464    public void populateWithOrderedConversations(List<Conversation> list, final boolean tagFilter) {
 465        super.populateWithOrderedConversations(list);
 466        if (accountHeader == null || accountHeader.getActiveProfile() == null) return;
 467
 468        final var selectedAccount =
 469            accountHeader.getActiveProfile().getTag() != null ?
 470            ((Account) accountHeader.getActiveProfile().getTag()).getUuid() :
 471            null;
 472
 473        for (final var c : ImmutableList.copyOf(list)) {
 474            if (mainFilter == DRAWER_CHANNELS && c.getMode() != Conversation.MODE_MULTI) {
 475                list.remove(c);
 476            } else if (mainFilter == DRAWER_DIRECT_MESSAGES && c.getMode() == Conversation.MODE_MULTI) {
 477                list.remove(c);
 478            } else if (selectedAccount != null && !selectedAccount.equals(c.getAccount().getUuid())) {
 479                list.remove(c);
 480            } else if (selectedTag != null && tagFilter && !c.getTags(this).contains(selectedTag)) {
 481                list.remove(c);
 482            }
 483        }
 484    }
 485
 486    @Override
 487    public void launchStartConversation() {
 488        StartConversationActivity.launch(this, (Account) accountHeader.getActiveProfile().getTag(), selectedTag == null ? null : selectedTag.getName());
 489    }
 490
 491    private boolean performRedirectIfNecessary(boolean noAnimation) {
 492        return performRedirectIfNecessary(null, noAnimation);
 493    }
 494
 495    private boolean performRedirectIfNecessary(final Conversation ignore, final boolean noAnimation) {
 496        if (xmppConnectionService == null) {
 497            return false;
 498        }
 499
 500        boolean isConversationsListEmpty = xmppConnectionService.isConversationsListEmpty(ignore);
 501        if (isConversationsListEmpty && mRedirectInProcess.compareAndSet(false, true)) {
 502            final Intent intent = SignupUtils.getRedirectionIntent(this);
 503            if (noAnimation) {
 504                intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
 505            }
 506            runOnUiThread(() -> {
 507                startActivity(intent);
 508                if (noAnimation) {
 509                    overridePendingTransition(0, 0);
 510                }
 511            });
 512        }
 513        return mRedirectInProcess.get();
 514    }
 515
 516    private void showDialogsIfMainIsOverview() {
 517        Pair<Account, Account> incomplete = null;
 518        if (xmppConnectionService != null && (incomplete = xmppConnectionService.onboardingIncomplete()) != null) {
 519            FinishOnboarding.finish(xmppConnectionService, this, incomplete.first, incomplete.second);
 520        }
 521        if (xmppConnectionService == null || xmppConnectionService.isOnboarding()) {
 522            return;
 523        }
 524        final Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
 525        if (fragment instanceof ConversationsOverviewFragment) {
 526            if (ExceptionHelper.checkForCrash(this)) return;
 527            if (offerToSetupDiallerIntegration()) return;
 528            if (offerToDownloadStickers()) return;
 529            if (openBatteryOptimizationDialogIfNeeded()) return;
 530            requestNotificationPermissionIfNeeded();
 531            xmppConnectionService.rescanStickers();
 532        }
 533    }
 534
 535    private String getBatteryOptimizationPreferenceKey() {
 536        @SuppressLint("HardwareIds") String device = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
 537        return "show_battery_optimization" + (device == null ? "" : device);
 538    }
 539
 540    private void setNeverAskForBatteryOptimizationsAgain() {
 541        getPreferences().edit().putBoolean(getBatteryOptimizationPreferenceKey(), false).apply();
 542    }
 543
 544    private boolean openBatteryOptimizationDialogIfNeeded() {
 545        if (isOptimizingBattery() && getPreferences().getBoolean(getBatteryOptimizationPreferenceKey(), true)) {
 546            final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
 547            builder.setTitle(R.string.battery_optimizations_enabled);
 548            builder.setMessage(getString(R.string.battery_optimizations_enabled_dialog, getString(R.string.app_name)));
 549            builder.setPositiveButton(R.string.next, (dialog, which) -> {
 550                final Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
 551                final Uri uri = Uri.parse("package:" + getPackageName());
 552                intent.setData(uri);
 553                try {
 554                    startActivityForResult(intent, REQUEST_BATTERY_OP);
 555                } catch (final ActivityNotFoundException e) {
 556                    Toast.makeText(this, R.string.device_does_not_support_battery_op, Toast.LENGTH_SHORT).show();
 557                }
 558            });
 559            builder.setOnDismissListener(dialog -> setNeverAskForBatteryOptimizationsAgain());
 560            final AlertDialog dialog = builder.create();
 561            dialog.setCanceledOnTouchOutside(false);
 562            dialog.show();
 563            return true;
 564        }
 565        return false;
 566    }
 567
 568    private void requestNotificationPermissionIfNeeded() {
 569        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && ActivityCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
 570            requestPermissions(new String[]{Manifest.permission.POST_NOTIFICATIONS}, REQUEST_POST_NOTIFICATION);
 571        }
 572    }
 573
 574    private boolean offerToDownloadStickers() {
 575        int offered = getPreferences().getInt("default_stickers_offered", 0);
 576        if (offered > 0) return false;
 577        getPreferences().edit().putInt("default_stickers_offered", 1).apply();
 578
 579        AlertDialog.Builder builder = new AlertDialog.Builder(this);
 580        builder.setTitle("Download Stickers?");
 581        builder.setMessage("Would you like to download some default sticker packs?");
 582        builder.setPositiveButton(R.string.yes, (dialog, which) -> {
 583            if (hasStoragePermission(REQUEST_DOWNLOAD_STICKERS)) {
 584                downloadStickers();
 585            }
 586        });
 587        builder.setNegativeButton(R.string.no, (dialog, which) -> {
 588            showDialogsIfMainIsOverview();
 589        });
 590        final AlertDialog dialog = builder.create();
 591        dialog.setCanceledOnTouchOutside(false);
 592        dialog.show();
 593        return true;
 594    }
 595
 596    private boolean offerToSetupDiallerIntegration() {
 597        if (mRequestCode == DIALLER_INTEGRATION) {
 598            mRequestCode = -1;
 599            return true;
 600        }
 601        if (Build.VERSION.SDK_INT < 23) return false;
 602        if (Build.VERSION.SDK_INT >= 33) {
 603            if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELECOM) && !getPackageManager().hasSystemFeature(PackageManager.FEATURE_CONNECTION_SERVICE)) return false;
 604        } else {
 605            if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CONNECTION_SERVICE)) return false;
 606        }
 607
 608        Set<String> pstnGateways = new HashSet<>();
 609        for (Account account : xmppConnectionService.getAccounts()) {
 610            for (Contact contact : account.getRoster().getContacts()) {
 611                if (contact.getPresences().anyIdentity("gateway", "pstn")) {
 612                    pstnGateways.add(contact.getJid().asBareJid().toEscapedString());
 613                }
 614            }
 615        }
 616
 617        if (pstnGateways.size() < 1) return false;
 618        Set<String> fromPrefs = getPreferences().getStringSet("pstn_gateways", Set.of("UPGRADE"));
 619        getPreferences().edit().putStringSet("pstn_gateways", pstnGateways).apply();
 620        pstnGateways.removeAll(fromPrefs);
 621        if (pstnGateways.size() < 1) return false;
 622
 623        if (fromPrefs.contains("UPGRADE")) return false;
 624
 625        AlertDialog.Builder builder = new AlertDialog.Builder(this);
 626        builder.setTitle("Dialler Integration");
 627        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?");
 628        builder.setPositiveButton(R.string.yes, (dialog, which) -> {
 629            final String[] permissions;
 630            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
 631                permissions = new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.BLUETOOTH_CONNECT};
 632            } else {
 633                permissions = new String[]{Manifest.permission.RECORD_AUDIO};
 634            }
 635            requestPermissions(permissions, REQUEST_MICROPHONE);
 636        });
 637        builder.setNegativeButton(R.string.no, (dialog, which) -> {
 638            showDialogsIfMainIsOverview();
 639        });
 640        final AlertDialog dialog = builder.create();
 641        dialog.setCanceledOnTouchOutside(false);
 642        dialog.show();
 643        return true;
 644    }
 645
 646    private void notifyFragmentOfBackendConnected(@IdRes int id) {
 647        final Fragment fragment = getFragmentManager().findFragmentById(id);
 648        if (fragment instanceof OnBackendConnected callback) {
 649            callback.onBackendConnected();
 650        }
 651    }
 652
 653    private void refreshFragment(@IdRes int id) {
 654        final Fragment fragment = getFragmentManager().findFragmentById(id);
 655        if (fragment instanceof XmppFragment xmppFragment) {
 656            xmppFragment.refresh();
 657            if (refreshForNewCaps) xmppFragment.refreshForNewCaps(newCapsJids);
 658        }
 659    }
 660
 661    private boolean processViewIntent(Intent intent) {
 662        final String uuid = intent.getStringExtra(EXTRA_CONVERSATION);
 663        final Conversation conversation = uuid != null ? xmppConnectionService.findConversationByUuid(uuid) : null;
 664        if (conversation == null) {
 665            Log.d(Config.LOGTAG, "unable to view conversation with uuid:" + uuid);
 666            return false;
 667        }
 668        openConversation(conversation, intent.getExtras());
 669        return true;
 670    }
 671
 672    @Override
 673    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
 674        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
 675        UriHandlerActivity.onRequestPermissionResult(this, requestCode, grantResults);
 676        if (grantResults.length > 0) {
 677            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
 678                switch (requestCode) {
 679                    case REQUEST_OPEN_MESSAGE:
 680                        refreshUiReal();
 681                        ConversationFragment.openPendingMessage(this);
 682                        break;
 683                    case REQUEST_PLAY_PAUSE:
 684                        ConversationFragment.startStopPending(this);
 685                        break;
 686                    case REQUEST_MICROPHONE:
 687                        Intent intent = new Intent();
 688                        intent.setComponent(new ComponentName("com.android.server.telecom",
 689                            "com.android.server.telecom.settings.EnableAccountPreferenceActivity"));
 690                        try {
 691                            startActivityForResult(intent, DIALLER_INTEGRATION);
 692                        } catch (ActivityNotFoundException e) {
 693                            displayToast("Dialler integration not available on your OS");
 694                        }
 695                        break;
 696                    case REQUEST_DOWNLOAD_STICKERS:
 697                        downloadStickers();
 698                        break;
 699                }
 700            } else {
 701                showDialogsIfMainIsOverview();
 702            }
 703        } else {
 704            showDialogsIfMainIsOverview();
 705        }
 706    }
 707
 708    private void downloadStickers() {
 709        Intent intent = new Intent(this, DownloadDefaultStickers.class);
 710        intent.putExtra("tor", xmppConnectionService.useTorToConnect());
 711        ContextCompat.startForegroundService(this, intent);
 712        displayToast("Sticker download started");
 713        showDialogsIfMainIsOverview();
 714    }
 715
 716    @Override
 717    public void onActivityResult(int requestCode, int resultCode, final Intent data) {
 718        super.onActivityResult(requestCode, resultCode, data);
 719
 720        if (requestCode == DIALLER_INTEGRATION) {
 721            mRequestCode = requestCode;
 722            try {
 723                startActivity(new Intent(android.telecom.TelecomManager.ACTION_CHANGE_PHONE_ACCOUNTS));
 724            } catch (ActivityNotFoundException e) {
 725                displayToast("Dialler integration not available on your OS");
 726            }
 727            return;
 728        }
 729
 730        ActivityResult activityResult = ActivityResult.of(requestCode, resultCode, data);
 731        if (xmppConnectionService != null) {
 732            handleActivityResult(activityResult);
 733        } else {
 734            this.postponedActivityResult.push(activityResult);
 735        }
 736    }
 737
 738    private void handleActivityResult(final ActivityResult activityResult) {
 739        if (activityResult.resultCode == Activity.RESULT_OK) {
 740            handlePositiveActivityResult(activityResult.requestCode, activityResult.data);
 741        } else {
 742            handleNegativeActivityResult(activityResult.requestCode);
 743        }
 744        if (activityResult.requestCode == REQUEST_BATTERY_OP) {
 745            // the result code is always 0 even when battery permission were granted
 746            requestNotificationPermissionIfNeeded();
 747            XmppConnectionService.toggleForegroundService(xmppConnectionService);
 748        }
 749    }
 750
 751    private void handleNegativeActivityResult(int requestCode) {
 752        Conversation conversation = ConversationFragment.getConversationReliable(this);
 753        switch (requestCode) {
 754            case REQUEST_DECRYPT_PGP:
 755                if (conversation == null) {
 756                    break;
 757                }
 758                conversation.getAccount().getPgpDecryptionService().giveUpCurrentDecryption();
 759                break;
 760            case REQUEST_BATTERY_OP:
 761                setNeverAskForBatteryOptimizationsAgain();
 762                break;
 763        }
 764    }
 765
 766    private void handlePositiveActivityResult(int requestCode, final Intent data) {
 767        Conversation conversation = ConversationFragment.getConversationReliable(this);
 768        if (conversation == null) {
 769            Log.d(Config.LOGTAG, "conversation not found");
 770            return;
 771        }
 772        switch (requestCode) {
 773            case REQUEST_DECRYPT_PGP:
 774                conversation.getAccount().getPgpDecryptionService().continueDecryption(data);
 775                break;
 776            case REQUEST_CHOOSE_PGP_ID:
 777                long id = data.getLongExtra(OpenPgpApi.EXTRA_SIGN_KEY_ID, 0);
 778                if (id != 0) {
 779                    conversation.getAccount().setPgpSignId(id);
 780                    announcePgp(conversation.getAccount(), null, null, onOpenPGPKeyPublished);
 781                } else {
 782                    choosePgpSignId(conversation.getAccount());
 783                }
 784                break;
 785            case REQUEST_ANNOUNCE_PGP:
 786                announcePgp(conversation.getAccount(), conversation, data, onOpenPGPKeyPublished);
 787                break;
 788        }
 789    }
 790
 791    @Override
 792    protected void onCreate(final Bundle savedInstanceState) {
 793        super.onCreate(savedInstanceState);
 794        savedState = savedInstanceState;
 795        ConversationMenuConfigurator.reloadFeatures(this);
 796        OmemoSetting.load(this);
 797        this.binding = DataBindingUtil.setContentView(this, R.layout.activity_conversations);
 798        Activities.setStatusAndNavigationBarColors(this, binding.getRoot());
 799        setSupportActionBar(binding.toolbar);
 800        configureActionBar(getSupportActionBar());
 801        this.getFragmentManager().addOnBackStackChangedListener(this::invalidateActionBarTitle);
 802        this.getFragmentManager().addOnBackStackChangedListener(this::showDialogsIfMainIsOverview);
 803        this.initializeFragments();
 804        this.invalidateActionBarTitle();
 805        final Intent intent;
 806        if (savedInstanceState == null) {
 807            intent = getIntent();
 808        } else {
 809            intent = savedInstanceState.getParcelable("intent");
 810        }
 811        if (isViewOrShareIntent(intent)) {
 812            pendingViewIntent.push(intent);
 813            setIntent(createLauncherIntent(this));
 814        }
 815    }
 816
 817    @Override
 818    public boolean onCreateOptionsMenu(Menu menu) {
 819        getMenuInflater().inflate(R.menu.activity_conversations, menu);
 820        final MenuItem qrCodeScanMenuItem = menu.findItem(R.id.action_scan_qr_code);
 821        if (qrCodeScanMenuItem != null) {
 822            if (isCameraFeatureAvailable() && (xmppConnectionService == null || !xmppConnectionService.isOnboarding())) {
 823                Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
 824                boolean visible = getResources().getBoolean(R.bool.show_qr_code_scan)
 825                        && fragment instanceof ConversationsOverviewFragment;
 826                qrCodeScanMenuItem.setVisible(visible);
 827            } else {
 828                qrCodeScanMenuItem.setVisible(false);
 829            }
 830        }
 831        return super.onCreateOptionsMenu(menu);
 832    }
 833
 834    @Override
 835    public void onConversationSelected(Conversation conversation) {
 836        clearPendingViewIntent();
 837        if (ConversationFragment.getConversation(this) == conversation) {
 838            Log.d(Config.LOGTAG, "ignore onConversationSelected() because conversation is already open");
 839            return;
 840        }
 841        openConversation(conversation, null);
 842    }
 843
 844    public void clearPendingViewIntent() {
 845        if (pendingViewIntent.clear()) {
 846            Log.e(Config.LOGTAG, "cleared pending view intent");
 847        }
 848    }
 849
 850    private void displayToast(final String msg) {
 851        runOnUiThread(() -> Toast.makeText(ConversationsActivity.this, msg, Toast.LENGTH_SHORT).show());
 852    }
 853
 854    @Override
 855    public void onAffiliationChangedSuccessful(Jid jid) {
 856
 857    }
 858
 859    @Override
 860    public void onAffiliationChangeFailed(Jid jid, int resId) {
 861        displayToast(getString(resId, jid.asBareJid().toString()));
 862    }
 863
 864    private void openConversation(Conversation conversation, Bundle extras) {
 865        final FragmentManager fragmentManager = getFragmentManager();
 866        executePendingTransactions(fragmentManager);
 867        ConversationFragment conversationFragment = (ConversationFragment) fragmentManager.findFragmentById(R.id.secondary_fragment);
 868        final boolean mainNeedsRefresh;
 869        if (conversationFragment == null) {
 870            mainNeedsRefresh = false;
 871            final Fragment mainFragment = fragmentManager.findFragmentById(R.id.main_fragment);
 872            if (mainFragment instanceof ConversationFragment) {
 873                conversationFragment = (ConversationFragment) mainFragment;
 874            } else {
 875                conversationFragment = new ConversationFragment();
 876                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
 877                fragmentTransaction.replace(R.id.main_fragment, conversationFragment);
 878                fragmentTransaction.addToBackStack(null);
 879                try {
 880                    fragmentTransaction.commit();
 881                } catch (IllegalStateException e) {
 882                    Log.w(Config.LOGTAG, "sate loss while opening conversation", e);
 883                    //allowing state loss is probably fine since view intents et all are already stored and a click can probably be 'ignored'
 884                    return;
 885                }
 886            }
 887        } else {
 888            mainNeedsRefresh = true;
 889        }
 890        conversationFragment.reInit(conversation, extras == null ? new Bundle() : extras);
 891        if (mainNeedsRefresh) {
 892            refreshFragment(R.id.main_fragment);
 893        }
 894        invalidateActionBarTitle();
 895    }
 896
 897    private static void executePendingTransactions(final FragmentManager fragmentManager) {
 898        try {
 899            fragmentManager.executePendingTransactions();
 900        } catch (final Exception e) {
 901            Log.e(Config.LOGTAG,"unable to execute pending fragment transactions");
 902        }
 903    }
 904
 905    public boolean onXmppUriClicked(Uri uri) {
 906        XmppUri xmppUri = new XmppUri(uri);
 907        if (xmppUri.isValidJid() && !xmppUri.hasFingerprints()) {
 908            final Conversation conversation = xmppConnectionService.findUniqueConversationByJid(xmppUri);
 909            if (conversation != null) {
 910                if (xmppUri.getParameter("password") != null) {
 911                    xmppConnectionService.providePasswordForMuc(conversation, xmppUri.getParameter("password"));
 912                }
 913                if (xmppUri.isAction("command")) {
 914                    startCommand(conversation.getAccount(), xmppUri.getJid(), xmppUri.getParameter("node"));
 915                } else {
 916                    Bundle extras = new Bundle();
 917                    extras.putString(Intent.EXTRA_TEXT, xmppUri.getBody());
 918                    if (xmppUri.isAction("message")) extras.putString(EXTRA_POST_INIT_ACTION, "message");
 919                    openConversation(conversation, extras);
 920                }
 921                return true;
 922            }
 923        }
 924        return false;
 925    }
 926
 927    public boolean onTelUriClicked(Uri uri, Account acct) {
 928        final String tel;
 929        try {
 930            tel = PhoneNumberUtilWrapper.normalize(this, uri.getSchemeSpecificPart());
 931        } catch (final IllegalArgumentException | NumberParseException | NullPointerException e) {
 932            return false;
 933        }
 934
 935        Set<String> gateways = new HashSet<>();
 936        for (Account account : (acct == null ? xmppConnectionService.getAccounts() : List.of(acct))) {
 937            for (Contact contact : account.getRoster().getContacts()) {
 938                if (contact.getPresences().anyIdentity("gateway", "pstn") || contact.getPresences().anyIdentity("gateway", "sms")) {
 939                    if (acct == null) acct = account;
 940                    gateways.add(contact.getJid().asBareJid().toEscapedString());
 941                }
 942            }
 943        }
 944
 945        for (String gateway : gateways) {
 946            if (onXmppUriClicked(Uri.parse("xmpp:" + tel + "@" + gateway))) return true;
 947        }
 948
 949        if (gateways.size() == 1 && acct != null) {
 950            openConversation(xmppConnectionService.findOrCreateConversation(acct, Jid.ofLocalAndDomain(tel, gateways.iterator().next()), false, true), null);
 951            return true;
 952        }
 953
 954        return false;
 955    }
 956
 957    @Override
 958    public boolean onOptionsItemSelected(MenuItem item) {
 959        if (MenuDoubleTabUtil.shouldIgnoreTap()) {
 960            return false;
 961        }
 962        switch (item.getItemId()) {
 963            case android.R.id.home:
 964                FragmentManager fm = getFragmentManager();
 965                if (android.os.Build.VERSION.SDK_INT >= 26) {
 966                    Fragment f = fm.getFragments().get(fm.getFragments().size() - 1);
 967                    if (f != null && f instanceof ConversationFragment) {
 968                        if (((ConversationFragment) f).onBackPressed()) {
 969                            return true;
 970                        }
 971                    }
 972                }
 973                if (fm.getBackStackEntryCount() > 0) {
 974                    try {
 975                        fm.popBackStack();
 976                    } catch (IllegalStateException e) {
 977                        Log.w(Config.LOGTAG, "Unable to pop back stack after pressing home button");
 978                    }
 979                    return true;
 980                }
 981                break;
 982            case R.id.action_scan_qr_code:
 983                UriHandlerActivity.scan(this);
 984                return true;
 985            case R.id.action_search_all_conversations:
 986                startActivity(new Intent(this, SearchActivity.class));
 987                return true;
 988            case R.id.action_search_this_conversation:
 989                final Conversation conversation = ConversationFragment.getConversation(this);
 990                if (conversation == null) {
 991                    return true;
 992                }
 993                final Intent intent = new Intent(this, SearchActivity.class);
 994                intent.putExtra(SearchActivity.EXTRA_CONVERSATION_UUID, conversation.getUuid());
 995                startActivity(intent);
 996                return true;
 997        }
 998        return super.onOptionsItemSelected(item);
 999    }
1000
1001    @Override
1002    public boolean onKeyDown(final int keyCode, final KeyEvent keyEvent) {
1003        if (keyCode == KeyEvent.KEYCODE_DPAD_UP && keyEvent.isCtrlPressed()) {
1004            final ConversationFragment conversationFragment = ConversationFragment.get(this);
1005            if (conversationFragment != null && conversationFragment.onArrowUpCtrlPressed()) {
1006                return true;
1007            }
1008        }
1009        return super.onKeyDown(keyCode, keyEvent);
1010    }
1011
1012    @Override
1013    public void onSaveInstanceState(Bundle savedInstanceState) {
1014        final Intent pendingIntent = pendingViewIntent.peek();
1015        savedInstanceState.putParcelable("intent", pendingIntent != null ? pendingIntent : getIntent());
1016        savedInstanceState.putLong("mainFilter", mainFilter);
1017        savedInstanceState.putSerializable("selectedTag", selectedTag);
1018        savedInstanceState = binding.drawer.saveInstanceState(savedInstanceState);
1019        savedInstanceState = accountHeader.saveInstanceState(savedInstanceState);
1020        super.onSaveInstanceState(savedInstanceState);
1021    }
1022
1023    @Override
1024    public void onStart() {
1025        super.onStart();
1026        mRedirectInProcess.set(false);
1027    }
1028
1029    @Override
1030    protected void onNewIntent(final Intent intent) {
1031        super.onNewIntent(intent);
1032        if (isViewOrShareIntent(intent)) {
1033            if (xmppConnectionService != null) {
1034                clearPendingViewIntent();
1035                processViewIntent(intent);
1036            } else {
1037                pendingViewIntent.push(intent);
1038            }
1039        }
1040        setIntent(createLauncherIntent(this));
1041    }
1042
1043    @Override
1044    public void onPause() {
1045        this.mActivityPaused = true;
1046        super.onPause();
1047    }
1048
1049    @Override
1050    public void onResume() {
1051        super.onResume();
1052        this.mActivityPaused = false;
1053    }
1054
1055    private void initializeFragments() {
1056        final FragmentManager fragmentManager = getFragmentManager();
1057        FragmentTransaction transaction = fragmentManager.beginTransaction();
1058        final Fragment mainFragment = fragmentManager.findFragmentById(R.id.main_fragment);
1059        final Fragment secondaryFragment = fragmentManager.findFragmentById(R.id.secondary_fragment);
1060        if (mainFragment != null) {
1061            if (binding.secondaryFragment != null) {
1062                if (mainFragment instanceof ConversationFragment) {
1063                    getFragmentManager().popBackStack();
1064                    transaction.remove(mainFragment);
1065                    transaction.commit();
1066                    fragmentManager.executePendingTransactions();
1067                    transaction = fragmentManager.beginTransaction();
1068                    transaction.replace(R.id.secondary_fragment, mainFragment);
1069                    transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
1070                    transaction.commit();
1071                    return;
1072                }
1073            } else {
1074                if (secondaryFragment instanceof ConversationFragment) {
1075                    transaction.remove(secondaryFragment);
1076                    transaction.commit();
1077                    getFragmentManager().executePendingTransactions();
1078                    transaction = fragmentManager.beginTransaction();
1079                    transaction.replace(R.id.main_fragment, secondaryFragment);
1080                    transaction.addToBackStack(null);
1081                    transaction.commit();
1082                    return;
1083                }
1084            }
1085        } else {
1086            transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
1087        }
1088        if (binding.secondaryFragment != null && secondaryFragment == null) {
1089            transaction.replace(R.id.secondary_fragment, new ConversationFragment());
1090        }
1091        transaction.commit();
1092    }
1093
1094    private void invalidateActionBarTitle() {
1095        final ActionBar actionBar = getSupportActionBar();
1096        if (actionBar == null) {
1097            return;
1098        }
1099        final FragmentManager fragmentManager = getFragmentManager();
1100        final Fragment mainFragment = fragmentManager.findFragmentById(R.id.main_fragment);
1101        if (mainFragment instanceof ConversationFragment conversationFragment) {
1102            final Conversation conversation = conversationFragment.getConversation();
1103            if (conversation != null) {
1104                actionBar.setTitle(conversation.getName());
1105                actionBar.setDisplayHomeAsUpEnabled(!xmppConnectionService.isOnboarding() || !conversation.getJid().equals(Jid.of("cheogram.com")));
1106                ToolbarUtils.setActionBarOnClickListener(
1107                        binding.toolbar,
1108                        (v) -> { if(!xmppConnectionService.isOnboarding()) openConversationDetails(conversation); }
1109                );
1110                return;
1111            }
1112        }
1113        final Fragment secondaryFragment = fragmentManager.findFragmentById(R.id.secondary_fragment);
1114        if (secondaryFragment instanceof ConversationFragment conversationFragment) {
1115            final Conversation conversation = conversationFragment.getConversation();
1116            if (conversation != null) {
1117                actionBar.setTitle(conversation.getName());
1118            } else {
1119                actionBar.setTitle(R.string.app_name);
1120            }
1121        } else {
1122            actionBar.setTitle(R.string.app_name);
1123        }
1124        actionBar.setDisplayHomeAsUpEnabled(false);
1125        ToolbarUtils.resetActionBarOnClickListeners(binding.toolbar);
1126    }
1127
1128    private void openConversationDetails(final Conversation conversation) {
1129        if (conversation.getMode() == Conversational.MODE_MULTI) {
1130            ConferenceDetailsActivity.open(this, conversation);
1131        } else {
1132            final Contact contact = conversation.getContact();
1133            if (contact.isSelf()) {
1134                switchToAccount(conversation.getAccount());
1135            } else {
1136                switchToContactDetails(contact);
1137            }
1138        }
1139    }
1140
1141    @Override
1142    public void onConversationArchived(Conversation conversation) {
1143        if (performRedirectIfNecessary(conversation, false)) {
1144            return;
1145        }
1146        final FragmentManager fragmentManager = getFragmentManager();
1147        final Fragment mainFragment = fragmentManager.findFragmentById(R.id.main_fragment);
1148        if (mainFragment instanceof ConversationFragment) {
1149            try {
1150                fragmentManager.popBackStack();
1151            } catch (final IllegalStateException e) {
1152                Log.w(Config.LOGTAG, "state loss while popping back state after archiving conversation", e);
1153                //this usually means activity is no longer active; meaning on the next open we will run through this again
1154            }
1155            return;
1156        }
1157        final Fragment secondaryFragment = fragmentManager.findFragmentById(R.id.secondary_fragment);
1158        if (secondaryFragment instanceof ConversationFragment) {
1159            if (((ConversationFragment) secondaryFragment).getConversation() == conversation) {
1160                Conversation suggestion = ConversationsOverviewFragment.getSuggestion(this, conversation);
1161                if (suggestion != null) {
1162                    openConversation(suggestion, null);
1163                }
1164            }
1165        }
1166    }
1167
1168    @Override
1169    public void onConversationsListItemUpdated() {
1170        Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
1171        if (fragment instanceof ConversationsOverviewFragment) {
1172            ((ConversationsOverviewFragment) fragment).refresh();
1173        }
1174    }
1175
1176    @Override
1177    public void switchToConversation(Conversation conversation) {
1178        Log.d(Config.LOGTAG, "override");
1179        openConversation(conversation, null);
1180    }
1181
1182    @Override
1183    public void onConversationRead(Conversation conversation, String upToUuid) {
1184        if (!mActivityPaused && pendingViewIntent.peek() == null) {
1185            xmppConnectionService.sendReadMarker(conversation, upToUuid);
1186        } else {
1187            Log.d(Config.LOGTAG, "ignoring read callback. mActivityPaused=" + mActivityPaused);
1188        }
1189    }
1190
1191    @Override
1192    public void onAccountUpdate() {
1193        this.refreshUi();
1194    }
1195
1196    @Override
1197    public void onConversationUpdate(boolean newCaps) {
1198        if (performRedirectIfNecessary(false)) {
1199            return;
1200        }
1201        refreshForNewCaps = newCaps;
1202        this.refreshUi();
1203    }
1204
1205    @Override
1206    public void onRosterUpdate(final XmppConnectionService.UpdateRosterReason reason, final Contact contact) {
1207        if (reason != XmppConnectionService.UpdateRosterReason.AVATAR) {
1208            refreshForNewCaps = true;
1209            if (contact != null) newCapsJids.add(contact.getJid().asBareJid());
1210        }
1211        this.refreshUi();
1212    }
1213
1214    @Override
1215    public void OnUpdateBlocklist(OnUpdateBlocklist.Status status) {
1216        this.refreshUi();
1217    }
1218
1219    @Override
1220    public void onShowErrorToast(int resId) {
1221        runOnUiThread(() -> Toast.makeText(this, resId, Toast.LENGTH_SHORT).show());
1222    }
1223}