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