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