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