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.content.ActivityNotFoundException;
 38import android.content.Context;
 39import android.content.Intent;
 40import android.content.pm.PackageManager;
 41import android.net.Uri;
 42import android.os.Bundle;
 43import android.provider.Settings;
 44import android.util.Log;
 45import android.view.KeyEvent;
 46import android.view.Menu;
 47import android.view.MenuItem;
 48import android.widget.Toast;
 49
 50import androidx.annotation.IdRes;
 51import androidx.annotation.NonNull;
 52import androidx.appcompat.app.ActionBar;
 53import androidx.appcompat.app.AlertDialog;
 54import androidx.databinding.DataBindingUtil;
 55import androidx.fragment.app.Fragment;
 56import androidx.fragment.app.FragmentManager;
 57import androidx.fragment.app.FragmentTransaction;
 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(getSupportFragmentManager()) == null) {
169            Conversation conversation = ConversationsOverviewFragment.getSuggestion(getSupportFragmentManager());
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 = getSupportFragmentManager().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 = getSupportFragmentManager().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 = getSupportFragmentManager().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        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
285        UriHandlerActivity.onRequestPermissionResult(this, requestCode, grantResults);
286        if (grantResults.length > 0) {
287            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
288                switch (requestCode) {
289                    case REQUEST_OPEN_MESSAGE:
290                        refreshUiReal();
291                        ConversationFragment.openPendingMessage(getSupportFragmentManager());
292                        break;
293                    case REQUEST_PLAY_PAUSE:
294                        ConversationFragment.startStopPending(getSupportFragmentManager());
295                        break;
296                }
297            }
298        }
299    }
300
301    @Override
302    public void onActivityResult(int requestCode, int resultCode, final Intent data) {
303        super.onActivityResult(requestCode, resultCode, data);
304        ActivityResult activityResult = ActivityResult.of(requestCode, resultCode, data);
305        if (xmppConnectionService != null) {
306            handleActivityResult(activityResult);
307        } else {
308            this.postponedActivityResult.push(activityResult);
309        }
310    }
311
312    private void handleActivityResult(ActivityResult activityResult) {
313        if (activityResult.resultCode == Activity.RESULT_OK) {
314            handlePositiveActivityResult(activityResult.requestCode, activityResult.data);
315        } else {
316            handleNegativeActivityResult(activityResult.requestCode);
317        }
318    }
319
320    private void handleNegativeActivityResult(int requestCode) {
321        Conversation conversation = ConversationFragment.getConversationReliable(getSupportFragmentManager());
322        switch (requestCode) {
323            case REQUEST_DECRYPT_PGP:
324                if (conversation == null) {
325                    break;
326                }
327                conversation.getAccount().getPgpDecryptionService().giveUpCurrentDecryption();
328                break;
329            case REQUEST_BATTERY_OP:
330                setNeverAskForBatteryOptimizationsAgain();
331                break;
332        }
333    }
334
335    private void handlePositiveActivityResult(int requestCode, final Intent data) {
336        Conversation conversation = ConversationFragment.getConversationReliable(getSupportFragmentManager());
337        if (conversation == null) {
338            Log.d(Config.LOGTAG, "conversation not found");
339            return;
340        }
341        switch (requestCode) {
342            case REQUEST_DECRYPT_PGP:
343                conversation.getAccount().getPgpDecryptionService().continueDecryption(data);
344                break;
345            case REQUEST_CHOOSE_PGP_ID:
346                long id = data.getLongExtra(OpenPgpApi.EXTRA_SIGN_KEY_ID, 0);
347                if (id != 0) {
348                    conversation.getAccount().setPgpSignId(id);
349                    announcePgp(conversation.getAccount(), null, null, onOpenPGPKeyPublished);
350                } else {
351                    choosePgpSignId(conversation.getAccount());
352                }
353                break;
354            case REQUEST_ANNOUNCE_PGP:
355                announcePgp(conversation.getAccount(), conversation, data, onOpenPGPKeyPublished);
356                break;
357        }
358    }
359
360    @Override
361    protected void onCreate(final Bundle savedInstanceState) {
362        super.onCreate(savedInstanceState);
363        ConversationMenuConfigurator.reloadFeatures(this);
364        OmemoSetting.load(this);
365        this.binding = DataBindingUtil.setContentView(this, R.layout.activity_conversations);
366        setSupportActionBar(binding.toolbar);
367        configureActionBar(getSupportActionBar());
368        this.getSupportFragmentManager().addOnBackStackChangedListener(this::invalidateActionBarTitle);
369        this.getSupportFragmentManager().addOnBackStackChangedListener(this::showDialogsIfMainIsOverview);
370        this.initializeFragments();
371        this.invalidateActionBarTitle();
372        final Intent intent;
373        if (savedInstanceState == null) {
374            intent = getIntent();
375        } else {
376            intent = savedInstanceState.getParcelable("intent");
377        }
378        if (isViewOrShareIntent(intent)) {
379            pendingViewIntent.push(intent);
380            setIntent(createLauncherIntent(this));
381        }
382    }
383
384    @Override
385    public boolean onCreateOptionsMenu(Menu menu) {
386        getMenuInflater().inflate(R.menu.activity_conversations, menu);
387        final MenuItem qrCodeScanMenuItem = menu.findItem(R.id.action_scan_qr_code);
388        if (qrCodeScanMenuItem != null) {
389            if (isCameraFeatureAvailable()) {
390                Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.main_fragment);
391                boolean visible = getResources().getBoolean(R.bool.show_qr_code_scan)
392                        && fragment instanceof ConversationsOverviewFragment;
393                qrCodeScanMenuItem.setVisible(visible);
394            } else {
395                qrCodeScanMenuItem.setVisible(false);
396            }
397        }
398        return super.onCreateOptionsMenu(menu);
399    }
400
401    @Override
402    public void onConversationSelected(Conversation conversation) {
403        clearPendingViewIntent();
404        if (ConversationFragment.getConversation(getSupportFragmentManager()) == conversation) {
405            Log.d(Config.LOGTAG, "ignore onConversationSelected() because conversation is already open");
406            return;
407        }
408        openConversation(conversation, null);
409    }
410
411    public void clearPendingViewIntent() {
412        if (pendingViewIntent.clear()) {
413            Log.e(Config.LOGTAG, "cleared pending view intent");
414        }
415    }
416
417    private void displayToast(final String msg) {
418        runOnUiThread(() -> Toast.makeText(ConversationsActivity.this, msg, Toast.LENGTH_SHORT).show());
419    }
420
421    @Override
422    public void onAffiliationChangedSuccessful(Jid jid) {
423
424    }
425
426    @Override
427    public void onAffiliationChangeFailed(Jid jid, int resId) {
428        displayToast(getString(resId, jid.asBareJid().toString()));
429    }
430
431    private void openConversation(Conversation conversation, Bundle extras) {
432        final FragmentManager fragmentManager = getSupportFragmentManager();
433        fragmentManager.executePendingTransactions();
434        ConversationFragment conversationFragment = (ConversationFragment) fragmentManager.findFragmentById(R.id.secondary_fragment);
435        final boolean mainNeedsRefresh;
436        if (conversationFragment == null) {
437            mainNeedsRefresh = false;
438            final Fragment mainFragment = fragmentManager.findFragmentById(R.id.main_fragment);
439            if (mainFragment instanceof ConversationFragment) {
440                conversationFragment = (ConversationFragment) mainFragment;
441            } else {
442                conversationFragment = new ConversationFragment();
443                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
444                fragmentTransaction.replace(R.id.main_fragment, conversationFragment);
445                fragmentTransaction.addToBackStack(null);
446                try {
447                    fragmentTransaction.commit();
448                } catch (IllegalStateException e) {
449                    Log.w(Config.LOGTAG, "sate loss while opening conversation", e);
450                    //allowing state loss is probably fine since view intents et all are already stored and a click can probably be 'ignored'
451                    return;
452                }
453            }
454        } else {
455            mainNeedsRefresh = true;
456        }
457        conversationFragment.reInit(conversation, extras == null ? new Bundle() : extras);
458        if (mainNeedsRefresh) {
459            refreshFragment(R.id.main_fragment);
460        } else {
461            invalidateActionBarTitle();
462        }
463    }
464
465    public boolean onXmppUriClicked(Uri uri) {
466        XmppUri xmppUri = new XmppUri(uri);
467        if (xmppUri.isValidJid() && !xmppUri.hasFingerprints()) {
468            final Conversation conversation = xmppConnectionService.findUniqueConversationByJid(xmppUri);
469            if (conversation != null) {
470                openConversation(conversation, null);
471                return true;
472            }
473        }
474        return false;
475    }
476
477    @Override
478    public boolean onOptionsItemSelected(MenuItem item) {
479        if (MenuDoubleTabUtil.shouldIgnoreTap()) {
480            return false;
481        }
482        switch (item.getItemId()) {
483            case android.R.id.home:
484                FragmentManager fm = getSupportFragmentManager();
485                if (fm.getBackStackEntryCount() > 0) {
486                    try {
487                        fm.popBackStack();
488                    } catch (IllegalStateException e) {
489                        Log.w(Config.LOGTAG, "Unable to pop back stack after pressing home button");
490                    }
491                    return true;
492                }
493                break;
494            case R.id.action_scan_qr_code:
495                UriHandlerActivity.scan(this);
496                return true;
497            case R.id.action_search_all_conversations:
498                startActivity(new Intent(this, SearchActivity.class));
499                return true;
500            case R.id.action_search_this_conversation:
501                final Conversation conversation = ConversationFragment.getConversation(getSupportFragmentManager());
502                if (conversation == null) {
503                    return true;
504                }
505                final Intent intent = new Intent(this, SearchActivity.class);
506                intent.putExtra(SearchActivity.EXTRA_CONVERSATION_UUID, conversation.getUuid());
507                startActivity(intent);
508                return true;
509        }
510        return super.onOptionsItemSelected(item);
511    }
512
513    @Override
514    public boolean onKeyDown(final int keyCode, final KeyEvent keyEvent) {
515        if (keyCode == KeyEvent.KEYCODE_DPAD_UP && keyEvent.isCtrlPressed()) {
516            final ConversationFragment conversationFragment = ConversationFragment.get(getSupportFragmentManager());
517            if (conversationFragment != null && conversationFragment.onArrowUpCtrlPressed()) {
518                return true;
519            }
520        }
521        return super.onKeyDown(keyCode, keyEvent);
522    }
523
524    @Override
525    public void onSaveInstanceState(final Bundle savedInstanceState) {
526        final Intent pendingIntent = pendingViewIntent.peek();
527        savedInstanceState.putParcelable("intent", pendingIntent != null ? pendingIntent : getIntent());
528        super.onSaveInstanceState(savedInstanceState);
529    }
530
531    @Override
532    protected void onStart() {
533        final int theme = findTheme();
534        if (this.mTheme != theme) {
535            this.mSkipBackgroundBinding = true;
536            recreate();
537        } else {
538            this.mSkipBackgroundBinding = false;
539        }
540        mRedirectInProcess.set(false);
541        super.onStart();
542    }
543
544    @Override
545    protected void onNewIntent(final Intent intent) {
546        super.onNewIntent(intent);
547        if (isViewOrShareIntent(intent)) {
548            if (xmppConnectionService != null) {
549                clearPendingViewIntent();
550                processViewIntent(intent);
551            } else {
552                pendingViewIntent.push(intent);
553            }
554        }
555        setIntent(createLauncherIntent(this));
556    }
557
558    @Override
559    public void onPause() {
560        this.mActivityPaused = true;
561        super.onPause();
562    }
563
564    @Override
565    public void onResume() {
566        super.onResume();
567        this.mActivityPaused = false;
568    }
569
570    private void initializeFragments() {
571        final FragmentManager fragmentManager = getSupportFragmentManager();
572        FragmentTransaction transaction = fragmentManager.beginTransaction();
573        final Fragment mainFragment = fragmentManager.findFragmentById(R.id.main_fragment);
574        final Fragment secondaryFragment = fragmentManager.findFragmentById(R.id.secondary_fragment);
575        if (mainFragment != null) {
576            if (binding.secondaryFragment != null) {
577                if (mainFragment instanceof ConversationFragment) {
578                    getSupportFragmentManager().popBackStack();
579                    transaction.remove(mainFragment);
580                    transaction.commit();
581                    fragmentManager.executePendingTransactions();
582                    transaction = fragmentManager.beginTransaction();
583                    transaction.replace(R.id.secondary_fragment, mainFragment);
584                    transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
585                    transaction.commit();
586                    return;
587                }
588            } else {
589                if (secondaryFragment instanceof ConversationFragment) {
590                    transaction.remove(secondaryFragment);
591                    transaction.commit();
592                    getSupportFragmentManager().executePendingTransactions();
593                    transaction = fragmentManager.beginTransaction();
594                    transaction.replace(R.id.main_fragment, secondaryFragment);
595                    transaction.addToBackStack(null);
596                    transaction.commit();
597                    return;
598                }
599            }
600        } else {
601            transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
602        }
603        if (binding.secondaryFragment != null && secondaryFragment == null) {
604            transaction.replace(R.id.secondary_fragment, new ConversationFragment());
605        }
606        transaction.commit();
607    }
608
609    private void invalidateActionBarTitle() {
610        final ActionBar actionBar = getSupportActionBar();
611        if (actionBar == null) {
612            return;
613        }
614        final FragmentManager fragmentManager = getSupportFragmentManager();
615        final Fragment mainFragment = fragmentManager.findFragmentById(R.id.main_fragment);
616        if (mainFragment instanceof ConversationFragment) {
617            final Conversation conversation = ((ConversationFragment) mainFragment).getConversation();
618            if (conversation != null) {
619                actionBar.setTitle(EmojiWrapper.transform(conversation.getName()));
620                actionBar.setDisplayHomeAsUpEnabled(true);
621                ActionBarUtil.setActionBarOnClickListener(
622                        binding.toolbar,
623                        (v) -> openConversationDetails(conversation)
624                );
625                return;
626            }
627        }
628        actionBar.setTitle(R.string.app_name);
629        actionBar.setDisplayHomeAsUpEnabled(false);
630        ActionBarUtil.resetActionBarOnClickListeners(binding.toolbar);
631    }
632
633    private void openConversationDetails(final Conversation conversation) {
634        if (conversation.getMode() == Conversational.MODE_MULTI) {
635            ConferenceDetailsActivity.open(this, conversation);
636        } else {
637            final Contact contact = conversation.getContact();
638            if (contact.isSelf()) {
639                switchToAccount(conversation.getAccount());
640            } else {
641                switchToContactDetails(contact);
642            }
643        }
644    }
645
646    @Override
647    public void onConversationArchived(Conversation conversation) {
648        if (performRedirectIfNecessary(conversation, false)) {
649            return;
650        }
651        final FragmentManager fragmentManager = getSupportFragmentManager();
652        final Fragment mainFragment = fragmentManager.findFragmentById(R.id.main_fragment);
653        if (mainFragment instanceof ConversationFragment) {
654            try {
655                fragmentManager.popBackStack();
656            } catch (final IllegalStateException e) {
657                Log.w(Config.LOGTAG, "state loss while popping back state after archiving conversation", e);
658                //this usually means activity is no longer active; meaning on the next open we will run through this again
659            }
660            return;
661        }
662        final Fragment secondaryFragment = fragmentManager.findFragmentById(R.id.secondary_fragment);
663        if (secondaryFragment instanceof ConversationFragment) {
664            if (((ConversationFragment) secondaryFragment).getConversation() == conversation) {
665                Conversation suggestion = ConversationsOverviewFragment.getSuggestion(getSupportFragmentManager(), conversation);
666                if (suggestion != null) {
667                    openConversation(suggestion, null);
668                }
669            }
670        }
671    }
672
673    @Override
674    public void onConversationsListItemUpdated() {
675        Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.main_fragment);
676        if (fragment instanceof ConversationsOverviewFragment) {
677            ((ConversationsOverviewFragment) fragment).refresh();
678        }
679    }
680
681    @Override
682    public void switchToConversation(Conversation conversation) {
683        Log.d(Config.LOGTAG, "override");
684        openConversation(conversation, null);
685    }
686
687    @Override
688    public void onConversationRead(Conversation conversation, String upToUuid) {
689        if (!mActivityPaused && pendingViewIntent.peek() == null) {
690            xmppConnectionService.sendReadMarker(conversation, upToUuid);
691        } else {
692            Log.d(Config.LOGTAG, "ignoring read callback. mActivityPaused=" + mActivityPaused);
693        }
694    }
695
696    @Override
697    public void onAccountUpdate() {
698        this.refreshUi();
699    }
700
701    @Override
702    public void onConversationUpdate() {
703        if (performRedirectIfNecessary(false)) {
704            return;
705        }
706        this.refreshUi();
707    }
708
709    @Override
710    public void onRosterUpdate() {
711        this.refreshUi();
712    }
713
714    @Override
715    public void OnUpdateBlocklist(OnUpdateBlocklist.Status status) {
716        this.refreshUi();
717    }
718
719    @Override
720    public void onShowErrorToast(int resId) {
721        runOnUiThread(() -> Toast.makeText(this, resId, Toast.LENGTH_SHORT).show());
722    }
723}