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        final FragmentManager fragmentManager = getFragmentManager();
429        fragmentManager.executePendingTransactions();
430        ConversationFragment conversationFragment = (ConversationFragment) fragmentManager.findFragmentById(R.id.secondary_fragment);
431        final boolean mainNeedsRefresh;
432        if (conversationFragment == null) {
433            mainNeedsRefresh = false;
434            final Fragment mainFragment = fragmentManager.findFragmentById(R.id.main_fragment);
435            if (mainFragment instanceof ConversationFragment) {
436                conversationFragment = (ConversationFragment) mainFragment;
437            } else {
438                conversationFragment = new ConversationFragment();
439                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
440                fragmentTransaction.replace(R.id.main_fragment, conversationFragment);
441                fragmentTransaction.addToBackStack(null);
442                try {
443                    fragmentTransaction.commit();
444                } catch (IllegalStateException e) {
445                    Log.w(Config.LOGTAG, "sate loss while opening conversation", e);
446                    //allowing state loss is probably fine since view intents et all are already stored and a click can probably be 'ignored'
447                    return;
448                }
449            }
450        } else {
451            mainNeedsRefresh = true;
452        }
453        conversationFragment.reInit(conversation, extras == null ? new Bundle() : extras);
454        if (mainNeedsRefresh) {
455            refreshFragment(R.id.main_fragment);
456        } else {
457            invalidateActionBarTitle();
458        }
459    }
460
461    public boolean onXmppUriClicked(Uri uri) {
462        XmppUri xmppUri = new XmppUri(uri);
463        if (xmppUri.isValidJid() && !xmppUri.hasFingerprints()) {
464            final Conversation conversation = xmppConnectionService.findUniqueConversationByJid(xmppUri);
465            if (conversation != null) {
466                openConversation(conversation, null);
467                return true;
468            }
469        }
470        return false;
471    }
472
473    @Override
474    public boolean onOptionsItemSelected(MenuItem item) {
475        if (MenuDoubleTabUtil.shouldIgnoreTap()) {
476            return false;
477        }
478        switch (item.getItemId()) {
479            case android.R.id.home:
480                FragmentManager fm = getFragmentManager();
481                if (fm.getBackStackEntryCount() > 0) {
482                    try {
483                        fm.popBackStack();
484                    } catch (IllegalStateException e) {
485                        Log.w(Config.LOGTAG, "Unable to pop back stack after pressing home button");
486                    }
487                    return true;
488                }
489                break;
490            case R.id.action_scan_qr_code:
491                UriHandlerActivity.scan(this);
492                return true;
493            case R.id.action_search_all_conversations:
494                startActivity(new Intent(this, SearchActivity.class));
495                return true;
496            case R.id.action_search_this_conversation:
497                final Conversation conversation = ConversationFragment.getConversation(this);
498                if (conversation == null) {
499                    return true;
500                }
501                final Intent intent = new Intent(this, SearchActivity.class);
502                intent.putExtra(SearchActivity.EXTRA_CONVERSATION_UUID, conversation.getUuid());
503                startActivity(intent);
504                return true;
505        }
506        return super.onOptionsItemSelected(item);
507    }
508
509    @Override
510    public boolean onKeyDown(final int keyCode, final KeyEvent keyEvent) {
511        if (keyCode == KeyEvent.KEYCODE_DPAD_UP && keyEvent.isCtrlPressed()) {
512            final ConversationFragment conversationFragment = ConversationFragment.get(this);
513            if (conversationFragment != null && conversationFragment.onArrowUpCtrlPressed()) {
514                return true;
515            }
516        }
517        return super.onKeyDown(keyCode, keyEvent);
518    }
519
520    @Override
521    public void onSaveInstanceState(final Bundle savedInstanceState) {
522        final Intent pendingIntent = pendingViewIntent.peek();
523        savedInstanceState.putParcelable("intent", pendingIntent != null ? pendingIntent : getIntent());
524        super.onSaveInstanceState(savedInstanceState);
525    }
526
527    @Override
528    protected void onStart() {
529        final int theme = findTheme();
530        if (this.mTheme != theme) {
531            this.mSkipBackgroundBinding = true;
532            recreate();
533        } else {
534            this.mSkipBackgroundBinding = false;
535        }
536        mRedirectInProcess.set(false);
537        super.onStart();
538    }
539
540    @Override
541    protected void onNewIntent(final Intent intent) {
542        super.onNewIntent(intent);
543        if (isViewOrShareIntent(intent)) {
544            if (xmppConnectionService != null) {
545                clearPendingViewIntent();
546                processViewIntent(intent);
547            } else {
548                pendingViewIntent.push(intent);
549            }
550        }
551        setIntent(createLauncherIntent(this));
552    }
553
554    @Override
555    public void onPause() {
556        this.mActivityPaused = true;
557        super.onPause();
558    }
559
560    @Override
561    public void onResume() {
562        super.onResume();
563        this.mActivityPaused = false;
564    }
565
566    private void initializeFragments() {
567        final FragmentManager fragmentManager = getFragmentManager();
568        FragmentTransaction transaction = fragmentManager.beginTransaction();
569        final Fragment mainFragment = fragmentManager.findFragmentById(R.id.main_fragment);
570        final Fragment secondaryFragment = fragmentManager.findFragmentById(R.id.secondary_fragment);
571        if (mainFragment != null) {
572            if (binding.secondaryFragment != null) {
573                if (mainFragment instanceof ConversationFragment) {
574                    getFragmentManager().popBackStack();
575                    transaction.remove(mainFragment);
576                    transaction.commit();
577                    fragmentManager.executePendingTransactions();
578                    transaction = fragmentManager.beginTransaction();
579                    transaction.replace(R.id.secondary_fragment, mainFragment);
580                    transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
581                    transaction.commit();
582                    return;
583                }
584            } else {
585                if (secondaryFragment instanceof ConversationFragment) {
586                    transaction.remove(secondaryFragment);
587                    transaction.commit();
588                    getFragmentManager().executePendingTransactions();
589                    transaction = fragmentManager.beginTransaction();
590                    transaction.replace(R.id.main_fragment, secondaryFragment);
591                    transaction.addToBackStack(null);
592                    transaction.commit();
593                    return;
594                }
595            }
596        } else {
597            transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
598        }
599        if (binding.secondaryFragment != null && secondaryFragment == null) {
600            transaction.replace(R.id.secondary_fragment, new ConversationFragment());
601        }
602        transaction.commit();
603    }
604
605    private void invalidateActionBarTitle() {
606        final ActionBar actionBar = getSupportActionBar();
607        if (actionBar != null) {
608            Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
609            if (mainFragment instanceof ConversationFragment) {
610                final Conversation conversation = ((ConversationFragment) mainFragment).getConversation();
611                if (conversation != null) {
612                    actionBar.setTitle(EmojiWrapper.transform(conversation.getName()));
613                    actionBar.setDisplayHomeAsUpEnabled(true);
614                    return;
615                }
616            }
617            actionBar.setTitle(R.string.app_name);
618            actionBar.setDisplayHomeAsUpEnabled(false);
619        }
620    }
621
622    @Override
623    public void onConversationArchived(Conversation conversation) {
624        if (performRedirectIfNecessary(conversation, false)) {
625            return;
626        }
627        Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
628        if (mainFragment instanceof ConversationFragment) {
629            try {
630                getFragmentManager().popBackStack();
631            } catch (IllegalStateException e) {
632                Log.w(Config.LOGTAG, "state loss while popping back state after archiving conversation", e);
633                //this usually means activity is no longer active; meaning on the next open we will run through this again
634            }
635            return;
636        }
637        Fragment secondaryFragment = getFragmentManager().findFragmentById(R.id.secondary_fragment);
638        if (secondaryFragment instanceof ConversationFragment) {
639            if (((ConversationFragment) secondaryFragment).getConversation() == conversation) {
640                Conversation suggestion = ConversationsOverviewFragment.getSuggestion(this, conversation);
641                if (suggestion != null) {
642                    openConversation(suggestion, null);
643                }
644            }
645        }
646    }
647
648    @Override
649    public void onConversationsListItemUpdated() {
650        Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
651        if (fragment instanceof ConversationsOverviewFragment) {
652            ((ConversationsOverviewFragment) fragment).refresh();
653        }
654    }
655
656    @Override
657    public void switchToConversation(Conversation conversation) {
658        Log.d(Config.LOGTAG, "override");
659        openConversation(conversation, null);
660    }
661
662    @Override
663    public void onConversationRead(Conversation conversation, String upToUuid) {
664        if (!mActivityPaused && pendingViewIntent.peek() == null) {
665            xmppConnectionService.sendReadMarker(conversation, upToUuid);
666        } else {
667            Log.d(Config.LOGTAG, "ignoring read callback. mActivityPaused=" + mActivityPaused);
668        }
669    }
670
671    @Override
672    public void onAccountUpdate() {
673        this.refreshUi();
674    }
675
676    @Override
677    public void onConversationUpdate() {
678        if (performRedirectIfNecessary(false)) {
679            return;
680        }
681        this.refreshUi();
682    }
683
684    @Override
685    public void onRosterUpdate() {
686        this.refreshUi();
687    }
688
689    @Override
690    public void OnUpdateBlocklist(OnUpdateBlocklist.Status status) {
691        this.refreshUi();
692    }
693
694    @Override
695    public void onShowErrorToast(int resId) {
696        runOnUiThread(() -> Toast.makeText(this, resId, Toast.LENGTH_SHORT).show());
697    }
698}