ConversationsActivity.java

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