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
 32
 33import static eu.siacs.conversations.ui.ConversationFragment.REQUEST_DECRYPT_PGP;
 34
 35import android.Manifest;
 36import android.annotation.SuppressLint;
 37import android.app.Activity;
 38import android.app.Fragment;
 39import android.app.FragmentManager;
 40import android.app.FragmentTransaction;
 41import android.content.ActivityNotFoundException;
 42import android.content.ComponentName;
 43import android.content.Context;
 44import android.content.Intent;
 45import android.content.pm.PackageManager;
 46import android.net.Uri;
 47import android.os.Build;
 48import android.os.Bundle;
 49import android.provider.Settings;
 50import android.util.Log;
 51import android.view.KeyEvent;
 52import android.view.Menu;
 53import android.view.MenuItem;
 54import android.widget.Toast;
 55
 56import androidx.annotation.IdRes;
 57import androidx.annotation.NonNull;
 58import androidx.appcompat.app.ActionBar;
 59import androidx.appcompat.app.AlertDialog;
 60import androidx.core.content.ContextCompat;
 61import androidx.databinding.DataBindingUtil;
 62
 63import com.cheogram.android.DownloadDefaultStickers;
 64
 65import org.openintents.openpgp.util.OpenPgpApi;
 66
 67import java.util.Arrays;
 68import java.util.List;
 69import java.util.HashSet;
 70import java.util.Set;
 71import java.util.concurrent.atomic.AtomicBoolean;
 72
 73import eu.siacs.conversations.Config;
 74import eu.siacs.conversations.R;
 75import eu.siacs.conversations.crypto.OmemoSetting;
 76import eu.siacs.conversations.databinding.ActivityConversationsBinding;
 77import eu.siacs.conversations.entities.Account;
 78import eu.siacs.conversations.entities.Contact;
 79import eu.siacs.conversations.entities.Conversation;
 80import eu.siacs.conversations.entities.Conversational;
 81import eu.siacs.conversations.services.XmppConnectionService;
 82import eu.siacs.conversations.ui.interfaces.OnBackendConnected;
 83import eu.siacs.conversations.ui.interfaces.OnConversationArchived;
 84import eu.siacs.conversations.ui.interfaces.OnConversationRead;
 85import eu.siacs.conversations.ui.interfaces.OnConversationSelected;
 86import eu.siacs.conversations.ui.interfaces.OnConversationsListItemUpdated;
 87import eu.siacs.conversations.ui.util.ActionBarUtil;
 88import eu.siacs.conversations.ui.util.ActivityResult;
 89import eu.siacs.conversations.ui.util.ConversationMenuConfigurator;
 90import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
 91import eu.siacs.conversations.ui.util.PendingItem;
 92import eu.siacs.conversations.utils.ExceptionHelper;
 93import eu.siacs.conversations.utils.SignupUtils;
 94import eu.siacs.conversations.utils.ThemeHelper;
 95import eu.siacs.conversations.utils.XmppUri;
 96import eu.siacs.conversations.xmpp.Jid;
 97import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
 98
 99public class ConversationsActivity extends XmppActivity implements OnConversationSelected, OnConversationArchived, OnConversationsListItemUpdated, OnConversationRead, XmppConnectionService.OnAccountUpdate, XmppConnectionService.OnConversationUpdate, XmppConnectionService.OnRosterUpdate, OnUpdateBlocklist, XmppConnectionService.OnShowErrorToast, XmppConnectionService.OnAffiliationChanged {
100
101    public static final String ACTION_VIEW_CONVERSATION = "eu.siacs.conversations.action.VIEW";
102    public static final String EXTRA_CONVERSATION = "conversationUuid";
103    public static final String EXTRA_DOWNLOAD_UUID = "eu.siacs.conversations.download_uuid";
104    public static final String EXTRA_AS_QUOTE = "eu.siacs.conversations.as_quote";
105    public static final String EXTRA_NICK = "nick";
106    public static final String EXTRA_IS_PRIVATE_MESSAGE = "pm";
107    public static final String EXTRA_DO_NOT_APPEND = "do_not_append";
108    public static final String EXTRA_POST_INIT_ACTION = "post_init_action";
109    public static final String POST_ACTION_RECORD_VOICE = "record_voice";
110    public static final String EXTRA_TYPE = "type";
111    public static final String EXTRA_NODE = "node";
112    public static final String EXTRA_JID = "jid";
113
114    private static final List<String> VIEW_AND_SHARE_ACTIONS = Arrays.asList(
115            ACTION_VIEW_CONVERSATION,
116            Intent.ACTION_SEND,
117            Intent.ACTION_SEND_MULTIPLE
118    );
119
120    public static final int REQUEST_OPEN_MESSAGE = 0x9876;
121    public static final int REQUEST_PLAY_PAUSE = 0x5432;
122    public static final int REQUEST_MICROPHONE = 0x5432f;
123    public static final int DIALLER_INTEGRATION = 0x5432ff;
124    public static final int REQUEST_DOWNLOAD_STICKERS = 0xbf8702;
125
126
127    //secondary fragment (when holding the conversation, must be initialized before refreshing the overview fragment
128    private static final @IdRes
129    int[] FRAGMENT_ID_NOTIFICATION_ORDER = {R.id.secondary_fragment, R.id.main_fragment};
130    private final PendingItem<Intent> pendingViewIntent = new PendingItem<>();
131    private final PendingItem<ActivityResult> postponedActivityResult = new PendingItem<>();
132    private ActivityConversationsBinding binding;
133    private boolean mActivityPaused = true;
134    private final AtomicBoolean mRedirectInProcess = new AtomicBoolean(false);
135    private boolean refreshForNewCaps = false;
136    private int mRequestCode = -1;
137
138    private static boolean isViewOrShareIntent(Intent i) {
139        Log.d(Config.LOGTAG, "action: " + (i == null ? null : i.getAction()));
140        return i != null && VIEW_AND_SHARE_ACTIONS.contains(i.getAction()) && i.hasExtra(EXTRA_CONVERSATION);
141    }
142
143    private static Intent createLauncherIntent(Context context) {
144        final Intent intent = new Intent(context, ConversationsActivity.class);
145        intent.setAction(Intent.ACTION_MAIN);
146        intent.addCategory(Intent.CATEGORY_LAUNCHER);
147        return intent;
148    }
149
150    @Override
151    protected void refreshUiReal() {
152        invalidateOptionsMenu();
153        for (@IdRes int id : FRAGMENT_ID_NOTIFICATION_ORDER) {
154            refreshFragment(id);
155        }
156        refreshForNewCaps = false;
157    }
158
159    @Override
160    void onBackendConnected() {
161        if (performRedirectIfNecessary(true)) {
162            return;
163        }
164        xmppConnectionService.getNotificationService().setIsInForeground(true);
165        final Intent intent = pendingViewIntent.pop();
166        if (intent != null) {
167            if (processViewIntent(intent)) {
168                if (binding.secondaryFragment != null) {
169                    notifyFragmentOfBackendConnected(R.id.main_fragment);
170                }
171                invalidateActionBarTitle();
172                return;
173            }
174        }
175        for (@IdRes int id : FRAGMENT_ID_NOTIFICATION_ORDER) {
176            notifyFragmentOfBackendConnected(id);
177        }
178
179        final ActivityResult activityResult = postponedActivityResult.pop();
180        if (activityResult != null) {
181            handleActivityResult(activityResult);
182        }
183
184        invalidateActionBarTitle();
185        if (binding.secondaryFragment != null && ConversationFragment.getConversation(this) == null) {
186            Conversation conversation = ConversationsOverviewFragment.getSuggestion(this);
187            if (conversation != null) {
188                openConversation(conversation, null);
189            }
190        }
191        showDialogsIfMainIsOverview();
192    }
193
194    private boolean performRedirectIfNecessary(boolean noAnimation) {
195        return performRedirectIfNecessary(null, noAnimation);
196    }
197
198    private boolean performRedirectIfNecessary(final Conversation ignore, final boolean noAnimation) {
199        if (xmppConnectionService == null) {
200            return false;
201        }
202        boolean isConversationsListEmpty = xmppConnectionService.isConversationsListEmpty(ignore);
203        if (isConversationsListEmpty && mRedirectInProcess.compareAndSet(false, true)) {
204            final Intent intent = SignupUtils.getRedirectionIntent(this);
205            if (noAnimation) {
206                intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
207            }
208            runOnUiThread(() -> {
209                startActivity(intent);
210                if (noAnimation) {
211                    overridePendingTransition(0, 0);
212                }
213            });
214        }
215        return mRedirectInProcess.get();
216    }
217
218    private void showDialogsIfMainIsOverview() {
219        if (xmppConnectionService == null) {
220            return;
221        }
222        final Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
223        if (fragment instanceof ConversationsOverviewFragment) {
224            if (ExceptionHelper.checkForCrash(this)) return;
225            if (offerToSetupDiallerIntegration()) return;
226            if (offerToDownloadStickers()) return;
227            openBatteryOptimizationDialogIfNeeded();
228        }
229    }
230
231    private String getBatteryOptimizationPreferenceKey() {
232        @SuppressLint("HardwareIds") String device = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
233        return "show_battery_optimization" + (device == null ? "" : device);
234    }
235
236    private void setNeverAskForBatteryOptimizationsAgain() {
237        getPreferences().edit().putBoolean(getBatteryOptimizationPreferenceKey(), false).apply();
238    }
239
240    private void openBatteryOptimizationDialogIfNeeded() {
241        if (isOptimizingBattery()
242                && android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M
243                && getPreferences().getBoolean(getBatteryOptimizationPreferenceKey(), true)) {
244            AlertDialog.Builder builder = new AlertDialog.Builder(this);
245            builder.setTitle(R.string.battery_optimizations_enabled);
246            builder.setMessage(getString(R.string.battery_optimizations_enabled_dialog, getString(R.string.app_name)));
247            builder.setPositiveButton(R.string.next, (dialog, which) -> {
248                Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
249                Uri uri = Uri.parse("package:" + getPackageName());
250                intent.setData(uri);
251                try {
252                    startActivityForResult(intent, REQUEST_BATTERY_OP);
253                } catch (ActivityNotFoundException e) {
254                    Toast.makeText(this, R.string.device_does_not_support_battery_op, Toast.LENGTH_SHORT).show();
255                }
256            });
257            builder.setOnDismissListener(dialog -> setNeverAskForBatteryOptimizationsAgain());
258            final AlertDialog dialog = builder.create();
259            dialog.setCanceledOnTouchOutside(false);
260            dialog.show();
261        }
262    }
263
264    private boolean offerToDownloadStickers() {
265        int offered = getPreferences().getInt("default_stickers_offered", 0);
266        if (offered > 0) return false;
267        getPreferences().edit().putInt("default_stickers_offered", 1).apply();
268
269        AlertDialog.Builder builder = new AlertDialog.Builder(this);
270        builder.setTitle("Download Stickers?");
271        builder.setMessage("Would you like to download some default sticker packs?");
272        builder.setPositiveButton(R.string.yes, (dialog, which) -> {
273            if (hasStoragePermission(REQUEST_DOWNLOAD_STICKERS)) {
274                downloadStickers();
275            }
276        });
277        builder.setNegativeButton(R.string.no, (dialog, which) -> { });
278        final AlertDialog dialog = builder.create();
279        dialog.setCanceledOnTouchOutside(false);
280        dialog.show();
281        return true;
282    }
283
284    private boolean offerToSetupDiallerIntegration() {
285        if (mRequestCode == DIALLER_INTEGRATION) {
286            mRequestCode = -1;
287            return true;
288        }
289        if (Build.VERSION.SDK_INT < 23) return false;
290        if (Build.VERSION.SDK_INT >= 33) {
291            if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELECOM)) return false;
292        } else {
293            if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CONNECTION_SERVICE)) return false;
294        }
295
296        Set<String> pstnGateways = new HashSet<>();
297        for (Account account : xmppConnectionService.getAccounts()) {
298            for (Contact contact : account.getRoster().getContacts()) {
299                if (contact.getPresences().anyIdentity("gateway", "pstn")) {
300                    pstnGateways.add(contact.getJid().asBareJid().toEscapedString());
301                }
302            }
303        }
304
305        if (pstnGateways.size() < 1) return false;
306        Set<String> fromPrefs = getPreferences().getStringSet("pstn_gateways", Set.of("UPGRADE"));
307        getPreferences().edit().putStringSet("pstn_gateways", pstnGateways).apply();
308        pstnGateways.removeAll(fromPrefs);
309        if (pstnGateways.size() < 1) return false;
310
311        if (fromPrefs.contains("UPGRADE")) return false;
312
313        AlertDialog.Builder builder = new AlertDialog.Builder(this);
314        builder.setTitle("Dialler Integration");
315        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?");
316        builder.setPositiveButton(R.string.yes, (dialog, which) -> {
317            final String[] permissions;
318            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
319                permissions = new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.BLUETOOTH_CONNECT};
320            } else {
321                permissions = new String[]{Manifest.permission.RECORD_AUDIO};
322            }
323            requestPermissions(permissions, REQUEST_MICROPHONE);
324        });
325        builder.setNegativeButton(R.string.no, (dialog, which) -> { });
326        final AlertDialog dialog = builder.create();
327        dialog.setCanceledOnTouchOutside(false);
328        dialog.show();
329        return true;
330    }
331
332    private void notifyFragmentOfBackendConnected(@IdRes int id) {
333        final Fragment fragment = getFragmentManager().findFragmentById(id);
334        if (fragment instanceof OnBackendConnected) {
335            ((OnBackendConnected) fragment).onBackendConnected();
336        }
337    }
338
339    private void refreshFragment(@IdRes int id) {
340        final Fragment fragment = getFragmentManager().findFragmentById(id);
341        if (fragment instanceof XmppFragment) {
342            ((XmppFragment) fragment).refresh();
343            if (refreshForNewCaps) ((XmppFragment) fragment).refreshForNewCaps();
344        }
345    }
346
347    private boolean processViewIntent(Intent intent) {
348        final String uuid = intent.getStringExtra(EXTRA_CONVERSATION);
349        final Conversation conversation = uuid != null ? xmppConnectionService.findConversationByUuid(uuid) : null;
350        if (conversation == null) {
351            Log.d(Config.LOGTAG, "unable to view conversation with uuid:" + uuid);
352            return false;
353        }
354        openConversation(conversation, intent.getExtras());
355        return true;
356    }
357
358    @Override
359    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
360        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
361        UriHandlerActivity.onRequestPermissionResult(this, requestCode, grantResults);
362        if (grantResults.length > 0) {
363            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
364                switch (requestCode) {
365                    case REQUEST_OPEN_MESSAGE:
366                        refreshUiReal();
367                        ConversationFragment.openPendingMessage(this);
368                        break;
369                    case REQUEST_PLAY_PAUSE:
370                        ConversationFragment.startStopPending(this);
371                        break;
372                    case REQUEST_MICROPHONE:
373                        Intent intent = new Intent();
374                        intent.setComponent(new ComponentName("com.android.server.telecom",
375                            "com.android.server.telecom.settings.EnableAccountPreferenceActivity"));
376                        startActivityForResult(intent, DIALLER_INTEGRATION);
377                        break;
378                    case REQUEST_DOWNLOAD_STICKERS:
379                        downloadStickers();
380                        break;
381                }
382            }
383        }
384    }
385
386    private void downloadStickers() {
387        Intent intent = new Intent(this, DownloadDefaultStickers.class);
388        intent.putExtra("tor", xmppConnectionService.useTorToConnect());
389        ContextCompat.startForegroundService(this, intent);
390        displayToast("Sticker download started");
391        showDialogsIfMainIsOverview();
392    }
393
394    @Override
395    public void onActivityResult(int requestCode, int resultCode, final Intent data) {
396        super.onActivityResult(requestCode, resultCode, data);
397
398        if (requestCode == DIALLER_INTEGRATION) {
399            mRequestCode = requestCode;
400            startActivity(new Intent(android.telecom.TelecomManager.ACTION_CHANGE_PHONE_ACCOUNTS));
401            return;
402        }
403
404        ActivityResult activityResult = ActivityResult.of(requestCode, resultCode, data);
405        if (xmppConnectionService != null) {
406            handleActivityResult(activityResult);
407        } else {
408            this.postponedActivityResult.push(activityResult);
409        }
410    }
411
412    private void handleActivityResult(ActivityResult activityResult) {
413        if (activityResult.resultCode == Activity.RESULT_OK) {
414            handlePositiveActivityResult(activityResult.requestCode, activityResult.data);
415        } else {
416            handleNegativeActivityResult(activityResult.requestCode);
417        }
418    }
419
420    private void handleNegativeActivityResult(int requestCode) {
421        Conversation conversation = ConversationFragment.getConversationReliable(this);
422        switch (requestCode) {
423            case REQUEST_DECRYPT_PGP:
424                if (conversation == null) {
425                    break;
426                }
427                conversation.getAccount().getPgpDecryptionService().giveUpCurrentDecryption();
428                break;
429            case REQUEST_BATTERY_OP:
430                setNeverAskForBatteryOptimizationsAgain();
431                break;
432        }
433    }
434
435    private void handlePositiveActivityResult(int requestCode, final Intent data) {
436        Conversation conversation = ConversationFragment.getConversationReliable(this);
437        if (conversation == null) {
438            Log.d(Config.LOGTAG, "conversation not found");
439            return;
440        }
441        switch (requestCode) {
442            case REQUEST_DECRYPT_PGP:
443                conversation.getAccount().getPgpDecryptionService().continueDecryption(data);
444                break;
445            case REQUEST_CHOOSE_PGP_ID:
446                long id = data.getLongExtra(OpenPgpApi.EXTRA_SIGN_KEY_ID, 0);
447                if (id != 0) {
448                    conversation.getAccount().setPgpSignId(id);
449                    announcePgp(conversation.getAccount(), null, null, onOpenPGPKeyPublished);
450                } else {
451                    choosePgpSignId(conversation.getAccount());
452                }
453                break;
454            case REQUEST_ANNOUNCE_PGP:
455                announcePgp(conversation.getAccount(), conversation, data, onOpenPGPKeyPublished);
456                break;
457        }
458    }
459
460    @Override
461    protected void onCreate(final Bundle savedInstanceState) {
462        super.onCreate(savedInstanceState);
463        ConversationMenuConfigurator.reloadFeatures(this);
464        OmemoSetting.load(this);
465        this.binding = DataBindingUtil.setContentView(this, R.layout.activity_conversations);
466        setSupportActionBar(binding.toolbar);
467        configureActionBar(getSupportActionBar());
468        this.getFragmentManager().addOnBackStackChangedListener(this::invalidateActionBarTitle);
469        this.getFragmentManager().addOnBackStackChangedListener(this::showDialogsIfMainIsOverview);
470        this.initializeFragments();
471        this.invalidateActionBarTitle();
472        final Intent intent;
473        if (savedInstanceState == null) {
474            intent = getIntent();
475        } else {
476            intent = savedInstanceState.getParcelable("intent");
477        }
478        if (isViewOrShareIntent(intent)) {
479            pendingViewIntent.push(intent);
480            setIntent(createLauncherIntent(this));
481        }
482    }
483
484    @Override
485    public boolean onCreateOptionsMenu(Menu menu) {
486        getMenuInflater().inflate(R.menu.activity_conversations, menu);
487        final MenuItem qrCodeScanMenuItem = menu.findItem(R.id.action_scan_qr_code);
488        if (qrCodeScanMenuItem != null) {
489            if (isCameraFeatureAvailable()) {
490                Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
491                boolean visible = getResources().getBoolean(R.bool.show_qr_code_scan)
492                        && fragment instanceof ConversationsOverviewFragment;
493                qrCodeScanMenuItem.setVisible(visible);
494            } else {
495                qrCodeScanMenuItem.setVisible(false);
496            }
497        }
498        return super.onCreateOptionsMenu(menu);
499    }
500
501    @Override
502    public void onConversationSelected(Conversation conversation) {
503        clearPendingViewIntent();
504        if (ConversationFragment.getConversation(this) == conversation) {
505            Log.d(Config.LOGTAG, "ignore onConversationSelected() because conversation is already open");
506            return;
507        }
508        openConversation(conversation, null);
509    }
510
511    public void clearPendingViewIntent() {
512        if (pendingViewIntent.clear()) {
513            Log.e(Config.LOGTAG, "cleared pending view intent");
514        }
515    }
516
517    private void displayToast(final String msg) {
518        runOnUiThread(() -> Toast.makeText(ConversationsActivity.this, msg, Toast.LENGTH_SHORT).show());
519    }
520
521    @Override
522    public void onAffiliationChangedSuccessful(Jid jid) {
523
524    }
525
526    @Override
527    public void onAffiliationChangeFailed(Jid jid, int resId) {
528        displayToast(getString(resId, jid.asBareJid().toString()));
529    }
530
531    private void openConversation(Conversation conversation, Bundle extras) {
532        final FragmentManager fragmentManager = getFragmentManager();
533        executePendingTransactions(fragmentManager);
534        ConversationFragment conversationFragment = (ConversationFragment) fragmentManager.findFragmentById(R.id.secondary_fragment);
535        final boolean mainNeedsRefresh;
536        if (conversationFragment == null) {
537            mainNeedsRefresh = false;
538            final Fragment mainFragment = fragmentManager.findFragmentById(R.id.main_fragment);
539            if (mainFragment instanceof ConversationFragment) {
540                conversationFragment = (ConversationFragment) mainFragment;
541            } else {
542                conversationFragment = new ConversationFragment();
543                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
544                fragmentTransaction.replace(R.id.main_fragment, conversationFragment);
545                fragmentTransaction.addToBackStack(null);
546                try {
547                    fragmentTransaction.commit();
548                } catch (IllegalStateException e) {
549                    Log.w(Config.LOGTAG, "sate loss while opening conversation", e);
550                    //allowing state loss is probably fine since view intents et all are already stored and a click can probably be 'ignored'
551                    return;
552                }
553            }
554        } else {
555            mainNeedsRefresh = true;
556        }
557        conversationFragment.reInit(conversation, extras == null ? new Bundle() : extras);
558        if (mainNeedsRefresh) {
559            refreshFragment(R.id.main_fragment);
560        } else {
561            invalidateActionBarTitle();
562        }
563    }
564
565    private static void executePendingTransactions(final FragmentManager fragmentManager) {
566        try {
567            fragmentManager.executePendingTransactions();
568        } catch (final Exception e) {
569            Log.e(Config.LOGTAG,"unable to execute pending fragment transactions");
570        }
571    }
572
573    public boolean onXmppUriClicked(Uri uri) {
574        XmppUri xmppUri = new XmppUri(uri);
575        if (xmppUri.isValidJid() && !xmppUri.hasFingerprints()) {
576            final Conversation conversation = xmppConnectionService.findUniqueConversationByJid(xmppUri);
577            if (conversation != null) {
578                if (xmppUri.isAction("command")) {
579                    startCommand(conversation.getAccount(), conversation.getJid(), xmppUri.getParameter("node"));
580                } else {
581                    Bundle extras = new Bundle();
582                    extras.putString(Intent.EXTRA_TEXT, xmppUri.getBody());
583                    if (xmppUri.isAction("message")) extras.putString(EXTRA_POST_INIT_ACTION, "message");
584                    openConversation(conversation, extras);
585                }
586                return true;
587            }
588        }
589        return false;
590    }
591
592    @Override
593    public boolean onOptionsItemSelected(MenuItem item) {
594        if (MenuDoubleTabUtil.shouldIgnoreTap()) {
595            return false;
596        }
597        switch (item.getItemId()) {
598            case android.R.id.home:
599                FragmentManager fm = getFragmentManager();
600                if (android.os.Build.VERSION.SDK_INT >= 26) {
601                    Fragment f = fm.getFragments().get(fm.getFragments().size() - 1);
602                    if (f != null && f instanceof ConversationFragment) {
603                        if (((ConversationFragment) f).onBackPressed()) {
604                            return true;
605                        }
606                    }
607                }
608                if (fm.getBackStackEntryCount() > 0) {
609                    try {
610                        fm.popBackStack();
611                    } catch (IllegalStateException e) {
612                        Log.w(Config.LOGTAG, "Unable to pop back stack after pressing home button");
613                    }
614                    return true;
615                }
616                break;
617            case R.id.action_scan_qr_code:
618                UriHandlerActivity.scan(this);
619                return true;
620            case R.id.action_search_all_conversations:
621                startActivity(new Intent(this, SearchActivity.class));
622                return true;
623            case R.id.action_search_this_conversation:
624                final Conversation conversation = ConversationFragment.getConversation(this);
625                if (conversation == null) {
626                    return true;
627                }
628                final Intent intent = new Intent(this, SearchActivity.class);
629                intent.putExtra(SearchActivity.EXTRA_CONVERSATION_UUID, conversation.getUuid());
630                startActivity(intent);
631                return true;
632        }
633        return super.onOptionsItemSelected(item);
634    }
635
636    @Override
637    public boolean onKeyDown(final int keyCode, final KeyEvent keyEvent) {
638        if (keyCode == KeyEvent.KEYCODE_DPAD_UP && keyEvent.isCtrlPressed()) {
639            final ConversationFragment conversationFragment = ConversationFragment.get(this);
640            if (conversationFragment != null && conversationFragment.onArrowUpCtrlPressed()) {
641                return true;
642            }
643        }
644        return super.onKeyDown(keyCode, keyEvent);
645    }
646
647    @Override
648    public void onSaveInstanceState(final Bundle savedInstanceState) {
649        final Intent pendingIntent = pendingViewIntent.peek();
650        savedInstanceState.putParcelable("intent", pendingIntent != null ? pendingIntent : getIntent());
651        super.onSaveInstanceState(savedInstanceState);
652    }
653
654    @Override
655    protected void onStart() {
656        super.onStart();
657        final int theme = findTheme();
658        if (this.mTheme != theme || !this.mCustomColors.equals(ThemeHelper.applyCustomColors(this))) {
659            this.mSkipBackgroundBinding = true;
660            recreate();
661        } else {
662            this.mSkipBackgroundBinding = false;
663        }
664        mRedirectInProcess.set(false);
665    }
666
667    @Override
668    protected void onNewIntent(final Intent intent) {
669        super.onNewIntent(intent);
670        if (isViewOrShareIntent(intent)) {
671            if (xmppConnectionService != null) {
672                clearPendingViewIntent();
673                processViewIntent(intent);
674            } else {
675                pendingViewIntent.push(intent);
676            }
677        }
678        setIntent(createLauncherIntent(this));
679    }
680
681    @Override
682    public void onPause() {
683        this.mActivityPaused = true;
684        super.onPause();
685    }
686
687    @Override
688    public void onResume() {
689        super.onResume();
690        this.mActivityPaused = false;
691    }
692
693    private void initializeFragments() {
694        final FragmentManager fragmentManager = getFragmentManager();
695        FragmentTransaction transaction = fragmentManager.beginTransaction();
696        final Fragment mainFragment = fragmentManager.findFragmentById(R.id.main_fragment);
697        final Fragment secondaryFragment = fragmentManager.findFragmentById(R.id.secondary_fragment);
698        if (mainFragment != null) {
699            if (binding.secondaryFragment != null) {
700                if (mainFragment instanceof ConversationFragment) {
701                    getFragmentManager().popBackStack();
702                    transaction.remove(mainFragment);
703                    transaction.commit();
704                    fragmentManager.executePendingTransactions();
705                    transaction = fragmentManager.beginTransaction();
706                    transaction.replace(R.id.secondary_fragment, mainFragment);
707                    transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
708                    transaction.commit();
709                    return;
710                }
711            } else {
712                if (secondaryFragment instanceof ConversationFragment) {
713                    transaction.remove(secondaryFragment);
714                    transaction.commit();
715                    getFragmentManager().executePendingTransactions();
716                    transaction = fragmentManager.beginTransaction();
717                    transaction.replace(R.id.main_fragment, secondaryFragment);
718                    transaction.addToBackStack(null);
719                    transaction.commit();
720                    return;
721                }
722            }
723        } else {
724            transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
725        }
726        if (binding.secondaryFragment != null && secondaryFragment == null) {
727            transaction.replace(R.id.secondary_fragment, new ConversationFragment());
728        }
729        transaction.commit();
730    }
731
732    private void invalidateActionBarTitle() {
733        final ActionBar actionBar = getSupportActionBar();
734        if (actionBar == null) {
735            return;
736        }
737        final FragmentManager fragmentManager = getFragmentManager();
738        final Fragment mainFragment = fragmentManager.findFragmentById(R.id.main_fragment);
739        if (mainFragment instanceof ConversationFragment) {
740            final Conversation conversation = ((ConversationFragment) mainFragment).getConversation();
741            if (conversation != null) {
742                actionBar.setTitle(conversation.getName());
743                actionBar.setDisplayHomeAsUpEnabled(true);
744                ActionBarUtil.setActionBarOnClickListener(
745                        binding.toolbar,
746                        (v) -> openConversationDetails(conversation)
747                );
748                return;
749            }
750        }
751        actionBar.setTitle(R.string.app_name);
752        actionBar.setDisplayHomeAsUpEnabled(false);
753        ActionBarUtil.resetActionBarOnClickListeners(binding.toolbar);
754    }
755
756    private void openConversationDetails(final Conversation conversation) {
757        if (conversation.getMode() == Conversational.MODE_MULTI) {
758            ConferenceDetailsActivity.open(this, conversation);
759        } else {
760            final Contact contact = conversation.getContact();
761            if (contact.isSelf()) {
762                switchToAccount(conversation.getAccount());
763            } else {
764                switchToContactDetails(contact);
765            }
766        }
767    }
768
769    @Override
770    public void onConversationArchived(Conversation conversation) {
771        if (performRedirectIfNecessary(conversation, false)) {
772            return;
773        }
774        final FragmentManager fragmentManager = getFragmentManager();
775        final Fragment mainFragment = fragmentManager.findFragmentById(R.id.main_fragment);
776        if (mainFragment instanceof ConversationFragment) {
777            try {
778                fragmentManager.popBackStack();
779            } catch (final IllegalStateException e) {
780                Log.w(Config.LOGTAG, "state loss while popping back state after archiving conversation", e);
781                //this usually means activity is no longer active; meaning on the next open we will run through this again
782            }
783            return;
784        }
785        final Fragment secondaryFragment = fragmentManager.findFragmentById(R.id.secondary_fragment);
786        if (secondaryFragment instanceof ConversationFragment) {
787            if (((ConversationFragment) secondaryFragment).getConversation() == conversation) {
788                Conversation suggestion = ConversationsOverviewFragment.getSuggestion(this, conversation);
789                if (suggestion != null) {
790                    openConversation(suggestion, null);
791                }
792            }
793        }
794    }
795
796    @Override
797    public void onConversationsListItemUpdated() {
798        Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
799        if (fragment instanceof ConversationsOverviewFragment) {
800            ((ConversationsOverviewFragment) fragment).refresh();
801        }
802    }
803
804    @Override
805    public void switchToConversation(Conversation conversation) {
806        Log.d(Config.LOGTAG, "override");
807        openConversation(conversation, null);
808    }
809
810    @Override
811    public void onConversationRead(Conversation conversation, String upToUuid) {
812        if (!mActivityPaused && pendingViewIntent.peek() == null) {
813            xmppConnectionService.sendReadMarker(conversation, upToUuid);
814        } else {
815            Log.d(Config.LOGTAG, "ignoring read callback. mActivityPaused=" + mActivityPaused);
816        }
817    }
818
819    @Override
820    public void onAccountUpdate() {
821        this.refreshUi();
822    }
823
824    @Override
825    public void onConversationUpdate(boolean newCaps) {
826        if (performRedirectIfNecessary(false)) {
827            return;
828        }
829        refreshForNewCaps = newCaps;
830        this.refreshUi();
831    }
832
833    @Override
834    public void onRosterUpdate() {
835        refreshForNewCaps = true;
836        this.refreshUi();
837    }
838
839    @Override
840    public void OnUpdateBlocklist(OnUpdateBlocklist.Status status) {
841        this.refreshUi();
842    }
843
844    @Override
845    public void onShowErrorToast(int resId) {
846        runOnUiThread(() -> Toast.makeText(this, resId, Toast.LENGTH_SHORT).show());
847    }
848}