ConversationsActivity.java

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