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