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