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 (hasAccountWithoutPush()
222                && isOptimizingBattery()
223                && android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M
224                && getPreferences().getBoolean(getBatteryOptimizationPreferenceKey(), true)) {
225            AlertDialog.Builder builder = new AlertDialog.Builder(this);
226            builder.setTitle(R.string.battery_optimizations_enabled);
227            builder.setMessage(getString(R.string.battery_optimizations_enabled_dialog, getString(R.string.app_name)));
228            builder.setPositiveButton(R.string.next, (dialog, which) -> {
229                Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
230                Uri uri = Uri.parse("package:" + getPackageName());
231                intent.setData(uri);
232                try {
233                    startActivityForResult(intent, REQUEST_BATTERY_OP);
234                } catch (ActivityNotFoundException e) {
235                    Toast.makeText(this, R.string.device_does_not_support_battery_op, Toast.LENGTH_SHORT).show();
236                }
237            });
238            builder.setOnDismissListener(dialog -> setNeverAskForBatteryOptimizationsAgain());
239            final AlertDialog dialog = builder.create();
240            dialog.setCanceledOnTouchOutside(false);
241            dialog.show();
242        }
243    }
244
245    private boolean hasAccountWithoutPush() {
246        for (Account account : xmppConnectionService.getAccounts()) {
247            if (account.getStatus() == Account.State.ONLINE && !xmppConnectionService.getPushManagementService().available(account)) {
248                return true;
249            }
250        }
251        return false;
252    }
253
254    private void notifyFragmentOfBackendConnected(@IdRes int id) {
255        final Fragment fragment = getFragmentManager().findFragmentById(id);
256        if (fragment instanceof OnBackendConnected) {
257            ((OnBackendConnected) fragment).onBackendConnected();
258        }
259    }
260
261    private void refreshFragment(@IdRes int id) {
262        final Fragment fragment = getFragmentManager().findFragmentById(id);
263        if (fragment instanceof XmppFragment) {
264            ((XmppFragment) fragment).refresh();
265        }
266    }
267
268    private boolean processViewIntent(Intent intent) {
269        final String uuid = intent.getStringExtra(EXTRA_CONVERSATION);
270        final Conversation conversation = uuid != null ? xmppConnectionService.findConversationByUuid(uuid) : null;
271        if (conversation == null) {
272            Log.d(Config.LOGTAG, "unable to view conversation with uuid:" + uuid);
273            return false;
274        }
275        openConversation(conversation, intent.getExtras());
276        return true;
277    }
278
279    @Override
280    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
281        UriHandlerActivity.onRequestPermissionResult(this, requestCode, grantResults);
282        if (grantResults.length > 0) {
283            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
284                switch (requestCode) {
285                    case REQUEST_OPEN_MESSAGE:
286                        refreshUiReal();
287                        ConversationFragment.openPendingMessage(this);
288                        break;
289                    case REQUEST_PLAY_PAUSE:
290                        ConversationFragment.startStopPending(this);
291                        break;
292                }
293            }
294        }
295    }
296
297    @Override
298    public void onActivityResult(int requestCode, int resultCode, final Intent data) {
299        super.onActivityResult(requestCode, resultCode, data);
300        ActivityResult activityResult = ActivityResult.of(requestCode, resultCode, data);
301        if (xmppConnectionService != null) {
302            handleActivityResult(activityResult);
303        } else {
304            this.postponedActivityResult.push(activityResult);
305        }
306    }
307
308    private void handleActivityResult(ActivityResult activityResult) {
309        if (activityResult.resultCode == Activity.RESULT_OK) {
310            handlePositiveActivityResult(activityResult.requestCode, activityResult.data);
311        } else {
312            handleNegativeActivityResult(activityResult.requestCode);
313        }
314    }
315
316    private void handleNegativeActivityResult(int requestCode) {
317        Conversation conversation = ConversationFragment.getConversationReliable(this);
318        switch (requestCode) {
319            case REQUEST_DECRYPT_PGP:
320                if (conversation == null) {
321                    break;
322                }
323                conversation.getAccount().getPgpDecryptionService().giveUpCurrentDecryption();
324                break;
325            case REQUEST_BATTERY_OP:
326                setNeverAskForBatteryOptimizationsAgain();
327                break;
328        }
329    }
330
331    private void handlePositiveActivityResult(int requestCode, final Intent data) {
332        Conversation conversation = ConversationFragment.getConversationReliable(this);
333        if (conversation == null) {
334            Log.d(Config.LOGTAG, "conversation not found");
335            return;
336        }
337        switch (requestCode) {
338            case REQUEST_DECRYPT_PGP:
339                conversation.getAccount().getPgpDecryptionService().continueDecryption(data);
340                break;
341            case REQUEST_CHOOSE_PGP_ID:
342                long id = data.getLongExtra(OpenPgpApi.EXTRA_SIGN_KEY_ID, 0);
343                if (id != 0) {
344                    conversation.getAccount().setPgpSignId(id);
345                    announcePgp(conversation.getAccount(), null, null, onOpenPGPKeyPublished);
346                } else {
347                    choosePgpSignId(conversation.getAccount());
348                }
349                break;
350            case REQUEST_ANNOUNCE_PGP:
351                announcePgp(conversation.getAccount(), conversation, data, onOpenPGPKeyPublished);
352                break;
353        }
354    }
355
356    @Override
357    protected void onCreate(final Bundle savedInstanceState) {
358        super.onCreate(savedInstanceState);
359        ConversationMenuConfigurator.reloadFeatures(this);
360        OmemoSetting.load(this);
361        this.binding = DataBindingUtil.setContentView(this, R.layout.activity_conversations);
362        setSupportActionBar(binding.toolbar);
363        configureActionBar(getSupportActionBar());
364        this.getFragmentManager().addOnBackStackChangedListener(this::invalidateActionBarTitle);
365        this.getFragmentManager().addOnBackStackChangedListener(this::showDialogsIfMainIsOverview);
366        this.initializeFragments();
367        this.invalidateActionBarTitle();
368        final Intent intent;
369        if (savedInstanceState == null) {
370            intent = getIntent();
371        } else {
372            intent = savedInstanceState.getParcelable("intent");
373        }
374        if (isViewOrShareIntent(intent)) {
375            pendingViewIntent.push(intent);
376            setIntent(createLauncherIntent(this));
377        }
378    }
379
380    @Override
381    public boolean onCreateOptionsMenu(Menu menu) {
382        getMenuInflater().inflate(R.menu.activity_conversations, menu);
383        final MenuItem qrCodeScanMenuItem = menu.findItem(R.id.action_scan_qr_code);
384        if (qrCodeScanMenuItem != null) {
385            if (isCameraFeatureAvailable()) {
386                Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
387                boolean visible = getResources().getBoolean(R.bool.show_qr_code_scan)
388                        && fragment instanceof ConversationsOverviewFragment;
389                qrCodeScanMenuItem.setVisible(visible);
390            } else {
391                qrCodeScanMenuItem.setVisible(false);
392            }
393        }
394        return super.onCreateOptionsMenu(menu);
395    }
396
397    @Override
398    public void onConversationSelected(Conversation conversation) {
399        clearPendingViewIntent();
400        if (ConversationFragment.getConversation(this) == conversation) {
401            Log.d(Config.LOGTAG, "ignore onConversationSelected() because conversation is already open");
402            return;
403        }
404        openConversation(conversation, null);
405    }
406
407    public void clearPendingViewIntent() {
408        if (pendingViewIntent.clear()) {
409            Log.e(Config.LOGTAG, "cleared pending view intent");
410        }
411    }
412
413    private void displayToast(final String msg) {
414        runOnUiThread(() -> Toast.makeText(ConversationsActivity.this, msg, Toast.LENGTH_SHORT).show());
415    }
416
417    @Override
418    public void onAffiliationChangedSuccessful(Jid jid) {
419
420    }
421
422    @Override
423    public void onAffiliationChangeFailed(Jid jid, int resId) {
424        displayToast(getString(resId, jid.asBareJid().toString()));
425    }
426
427    private void openConversation(Conversation conversation, Bundle extras) {
428        ConversationFragment conversationFragment = (ConversationFragment) getFragmentManager().findFragmentById(R.id.secondary_fragment);
429        final boolean mainNeedsRefresh;
430        if (conversationFragment == null) {
431            mainNeedsRefresh = false;
432            Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
433            if (mainFragment instanceof ConversationFragment) {
434                conversationFragment = (ConversationFragment) mainFragment;
435            } else {
436                conversationFragment = new ConversationFragment();
437                FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
438                fragmentTransaction.replace(R.id.main_fragment, conversationFragment);
439                fragmentTransaction.addToBackStack(null);
440                try {
441                    fragmentTransaction.commit();
442                } catch (IllegalStateException e) {
443                    Log.w(Config.LOGTAG, "sate loss while opening conversation", e);
444                    //allowing state loss is probably fine since view intents et all are already stored and a click can probably be 'ignored'
445                    return;
446                }
447            }
448        } else {
449            mainNeedsRefresh = true;
450        }
451        conversationFragment.reInit(conversation, extras == null ? new Bundle() : extras);
452        if (mainNeedsRefresh) {
453            refreshFragment(R.id.main_fragment);
454        } else {
455            invalidateActionBarTitle();
456        }
457    }
458
459    public boolean onXmppUriClicked(Uri uri) {
460        XmppUri xmppUri = new XmppUri(uri);
461        if (xmppUri.isValidJid() && !xmppUri.hasFingerprints()) {
462            final Conversation conversation = xmppConnectionService.findUniqueConversationByJid(xmppUri);
463            if (conversation != null) {
464                openConversation(conversation, null);
465                return true;
466            }
467        }
468        return false;
469    }
470
471    @Override
472    public boolean onOptionsItemSelected(MenuItem item) {
473        if (MenuDoubleTabUtil.shouldIgnoreTap()) {
474            return false;
475        }
476        switch (item.getItemId()) {
477            case android.R.id.home:
478                FragmentManager fm = getFragmentManager();
479                if (fm.getBackStackEntryCount() > 0) {
480                    try {
481                        fm.popBackStack();
482                    } catch (IllegalStateException e) {
483                        Log.w(Config.LOGTAG, "Unable to pop back stack after pressing home button");
484                    }
485                    return true;
486                }
487                break;
488            case R.id.action_scan_qr_code:
489                UriHandlerActivity.scan(this);
490                return true;
491            case R.id.action_search_all_conversations:
492                startActivity(new Intent(this, SearchActivity.class));
493                return true;
494            case R.id.action_search_this_conversation:
495                final Conversation conversation = ConversationFragment.getConversation(this);
496                if (conversation == null) {
497                    return true;
498                }
499                final Intent intent = new Intent(this, SearchActivity.class);
500                intent.putExtra(SearchActivity.EXTRA_CONVERSATION_UUID, conversation.getUuid());
501                startActivity(intent);
502                return true;
503        }
504        return super.onOptionsItemSelected(item);
505    }
506
507    @Override
508    public boolean onKeyDown(final int keyCode, final KeyEvent keyEvent) {
509        if (keyCode == KeyEvent.KEYCODE_DPAD_UP && keyEvent.isCtrlPressed()) {
510            final ConversationFragment conversationFragment = ConversationFragment.get(this);
511            if (conversationFragment != null && conversationFragment.onArrowUpCtrlPressed()) {
512                return true;
513            }
514        }
515        return super.onKeyDown(keyCode, keyEvent);
516    }
517
518    @Override
519    public void onSaveInstanceState(final Bundle savedInstanceState) {
520        final Intent pendingIntent = pendingViewIntent.peek();
521        savedInstanceState.putParcelable("intent", pendingIntent != null ? pendingIntent : getIntent());
522        super.onSaveInstanceState(savedInstanceState);
523    }
524
525    @Override
526    protected void onStart() {
527        final int theme = findTheme();
528        if (this.mTheme != theme) {
529            this.mSkipBackgroundBinding = true;
530            recreate();
531        } else {
532            this.mSkipBackgroundBinding = false;
533        }
534        mRedirectInProcess.set(false);
535        super.onStart();
536    }
537
538    @Override
539    protected void onNewIntent(final Intent intent) {
540        super.onNewIntent(intent);
541        if (isViewOrShareIntent(intent)) {
542            if (xmppConnectionService != null) {
543                clearPendingViewIntent();
544                processViewIntent(intent);
545            } else {
546                pendingViewIntent.push(intent);
547            }
548        }
549        setIntent(createLauncherIntent(this));
550    }
551
552    @Override
553    public void onPause() {
554        this.mActivityPaused = true;
555        super.onPause();
556    }
557
558    @Override
559    public void onResume() {
560        super.onResume();
561        this.mActivityPaused = false;
562    }
563
564    private void initializeFragments() {
565        FragmentTransaction transaction = getFragmentManager().beginTransaction();
566        Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
567        Fragment secondaryFragment = getFragmentManager().findFragmentById(R.id.secondary_fragment);
568        if (mainFragment != null) {
569            if (binding.secondaryFragment != null) {
570                if (mainFragment instanceof ConversationFragment) {
571                    getFragmentManager().popBackStack();
572                    transaction.remove(mainFragment);
573                    transaction.commit();
574                    getFragmentManager().executePendingTransactions();
575                    transaction = getFragmentManager().beginTransaction();
576                    transaction.replace(R.id.secondary_fragment, mainFragment);
577                    transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
578                    transaction.commit();
579                    return;
580                }
581            } else {
582                if (secondaryFragment instanceof ConversationFragment) {
583                    transaction.remove(secondaryFragment);
584                    transaction.commit();
585                    getFragmentManager().executePendingTransactions();
586                    transaction = getFragmentManager().beginTransaction();
587                    transaction.replace(R.id.main_fragment, secondaryFragment);
588                    transaction.addToBackStack(null);
589                    transaction.commit();
590                    return;
591                }
592            }
593        } else {
594            transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
595        }
596        if (binding.secondaryFragment != null && secondaryFragment == null) {
597            transaction.replace(R.id.secondary_fragment, new ConversationFragment());
598        }
599        transaction.commit();
600    }
601
602    private void invalidateActionBarTitle() {
603        final ActionBar actionBar = getSupportActionBar();
604        if (actionBar != null) {
605            Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
606            if (mainFragment instanceof ConversationFragment) {
607                final Conversation conversation = ((ConversationFragment) mainFragment).getConversation();
608                if (conversation != null) {
609                    actionBar.setTitle(EmojiWrapper.transform(conversation.getName()));
610                    actionBar.setDisplayHomeAsUpEnabled(true);
611                    return;
612                }
613            }
614            actionBar.setTitle(R.string.app_name);
615            actionBar.setDisplayHomeAsUpEnabled(false);
616        }
617    }
618
619    @Override
620    public void onConversationArchived(Conversation conversation) {
621        if (performRedirectIfNecessary(conversation, false)) {
622            return;
623        }
624        Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
625        if (mainFragment instanceof ConversationFragment) {
626            try {
627                getFragmentManager().popBackStack();
628            } catch (IllegalStateException e) {
629                Log.w(Config.LOGTAG, "state loss while popping back state after archiving conversation", e);
630                //this usually means activity is no longer active; meaning on the next open we will run through this again
631            }
632            return;
633        }
634        Fragment secondaryFragment = getFragmentManager().findFragmentById(R.id.secondary_fragment);
635        if (secondaryFragment instanceof ConversationFragment) {
636            if (((ConversationFragment) secondaryFragment).getConversation() == conversation) {
637                Conversation suggestion = ConversationsOverviewFragment.getSuggestion(this, conversation);
638                if (suggestion != null) {
639                    openConversation(suggestion, null);
640                }
641            }
642        }
643    }
644
645    @Override
646    public void onConversationsListItemUpdated() {
647        Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
648        if (fragment instanceof ConversationsOverviewFragment) {
649            ((ConversationsOverviewFragment) fragment).refresh();
650        }
651    }
652
653    @Override
654    public void switchToConversation(Conversation conversation) {
655        Log.d(Config.LOGTAG, "override");
656        openConversation(conversation, null);
657    }
658
659    @Override
660    public void onConversationRead(Conversation conversation, String upToUuid) {
661        if (!mActivityPaused && pendingViewIntent.peek() == null) {
662            xmppConnectionService.sendReadMarker(conversation, upToUuid);
663        } else {
664            Log.d(Config.LOGTAG, "ignoring read callback. mActivityPaused=" + mActivityPaused);
665        }
666    }
667
668    @Override
669    public void onAccountUpdate() {
670        this.refreshUi();
671    }
672
673    @Override
674    public void onConversationUpdate() {
675        if (performRedirectIfNecessary(false)) {
676            return;
677        }
678        this.refreshUi();
679    }
680
681    @Override
682    public void onRosterUpdate() {
683        this.refreshUi();
684    }
685
686    @Override
687    public void OnUpdateBlocklist(OnUpdateBlocklist.Status status) {
688        this.refreshUi();
689    }
690
691    @Override
692    public void onShowErrorToast(int resId) {
693        runOnUiThread(() -> Toast.makeText(this, resId, Toast.LENGTH_SHORT).show());
694    }
695}