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