ConversationsActivity.java

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