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