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