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.util.ActivityResult;
 75import eu.siacs.conversations.ui.util.ConversationMenuConfigurator;
 76import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
 77import eu.siacs.conversations.ui.util.PendingItem;
 78import eu.siacs.conversations.utils.AccountUtils;
 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 {
 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
 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                && android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M
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        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        AccountUtils.showHideMenuItems(menu);
381        MenuItem qrCodeScanMenuItem = menu.findItem(R.id.action_scan_qr_code);
382        if (qrCodeScanMenuItem != null) {
383            if (isCameraFeatureAvailable()) {
384                Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
385                boolean visible = getResources().getBoolean(R.bool.show_qr_code_scan)
386                        && fragment != null
387                        && fragment instanceof ConversationsOverviewFragment;
388                qrCodeScanMenuItem.setVisible(visible);
389            } else {
390                qrCodeScanMenuItem.setVisible(false);
391            }
392        }
393        return super.onCreateOptionsMenu(menu);
394    }
395
396    @Override
397    public void onConversationSelected(Conversation conversation) {
398        clearPendingViewIntent();
399        if (ConversationFragment.getConversation(this) == conversation) {
400            Log.d(Config.LOGTAG, "ignore onConversationSelected() because conversation is already open");
401            return;
402        }
403        openConversation(conversation, null);
404    }
405
406    public void clearPendingViewIntent() {
407        if (pendingViewIntent.clear()) {
408            Log.e(Config.LOGTAG, "cleared pending view intent");
409        }
410    }
411
412    private void displayToast(final String msg) {
413        runOnUiThread(() -> Toast.makeText(ConversationsActivity.this, msg, Toast.LENGTH_SHORT).show());
414    }
415
416    @Override
417    public void onAffiliationChangedSuccessful(Jid jid) {
418
419    }
420
421    @Override
422    public void onAffiliationChangeFailed(Jid jid, int resId) {
423        displayToast(getString(resId, jid.asBareJid().toString()));
424    }
425
426    private void openConversation(Conversation conversation, Bundle extras) {
427        ConversationFragment conversationFragment = (ConversationFragment) getFragmentManager().findFragmentById(R.id.secondary_fragment);
428        final boolean mainNeedsRefresh;
429        if (conversationFragment == null) {
430            mainNeedsRefresh = false;
431            Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
432            if (mainFragment instanceof ConversationFragment) {
433                conversationFragment = (ConversationFragment) mainFragment;
434            } else {
435                conversationFragment = new ConversationFragment();
436                FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
437                fragmentTransaction.replace(R.id.main_fragment, conversationFragment);
438                fragmentTransaction.addToBackStack(null);
439                try {
440                    fragmentTransaction.commit();
441                } catch (IllegalStateException e) {
442                    Log.w(Config.LOGTAG, "sate loss while opening conversation", e);
443                    //allowing state loss is probably fine since view intents et all are already stored and a click can probably be 'ignored'
444                    return;
445                }
446            }
447        } else {
448            mainNeedsRefresh = true;
449        }
450        conversationFragment.reInit(conversation, extras == null ? new Bundle() : extras);
451        if (mainNeedsRefresh) {
452            refreshFragment(R.id.main_fragment);
453        } else {
454            invalidateActionBarTitle();
455        }
456    }
457
458    public boolean onXmppUriClicked(Uri uri) {
459        XmppUri xmppUri = new XmppUri(uri);
460        if (xmppUri.isValidJid() && !xmppUri.hasFingerprints()) {
461            final Conversation conversation = xmppConnectionService.findUniqueConversationByJid(xmppUri);
462            if (conversation != null) {
463                openConversation(conversation, null);
464                return true;
465            }
466        }
467        return false;
468    }
469
470    @Override
471    public boolean onOptionsItemSelected(MenuItem item) {
472        if (MenuDoubleTabUtil.shouldIgnoreTap()) {
473            return false;
474        }
475        switch (item.getItemId()) {
476            case android.R.id.home:
477                FragmentManager fm = getFragmentManager();
478                if (fm.getBackStackEntryCount() > 0) {
479                    try {
480                        fm.popBackStack();
481                    } catch (IllegalStateException e) {
482                        Log.w(Config.LOGTAG, "Unable to pop back stack after pressing home button");
483                    }
484                    return true;
485                }
486                break;
487            case R.id.action_scan_qr_code:
488                UriHandlerActivity.scan(this);
489                return true;
490        }
491        return super.onOptionsItemSelected(item);
492    }
493
494    @Override
495    public void onSaveInstanceState(Bundle savedInstanceState) {
496        Intent pendingIntent = pendingViewIntent.peek();
497        savedInstanceState.putParcelable("intent", pendingIntent != null ? pendingIntent : getIntent());
498        super.onSaveInstanceState(savedInstanceState);
499    }
500
501    @Override
502    protected void onStart() {
503        final int theme = findTheme();
504        if (this.mTheme != theme) {
505            this.mSkipBackgroundBinding = true;
506            recreate();
507        } else {
508            this.mSkipBackgroundBinding = false;
509        }
510        mRedirectInProcess.set(false);
511        super.onStart();
512    }
513
514    @Override
515    protected void onNewIntent(final Intent intent) {
516        if (isViewOrShareIntent(intent)) {
517            if (xmppConnectionService != null) {
518                clearPendingViewIntent();
519                processViewIntent(intent);
520            } else {
521                pendingViewIntent.push(intent);
522            }
523        }
524        setIntent(createLauncherIntent(this));
525    }
526
527    @Override
528    public void onPause() {
529        this.mActivityPaused = true;
530        super.onPause();
531    }
532
533    @Override
534    public void onResume() {
535        super.onResume();
536        this.mActivityPaused = false;
537    }
538
539    private void initializeFragments() {
540        FragmentTransaction transaction = getFragmentManager().beginTransaction();
541        Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
542        Fragment secondaryFragment = getFragmentManager().findFragmentById(R.id.secondary_fragment);
543        if (mainFragment != null) {
544            if (binding.secondaryFragment != null) {
545                if (mainFragment instanceof ConversationFragment) {
546                    getFragmentManager().popBackStack();
547                    transaction.remove(mainFragment);
548                    transaction.commit();
549                    getFragmentManager().executePendingTransactions();
550                    transaction = getFragmentManager().beginTransaction();
551                    transaction.replace(R.id.secondary_fragment, mainFragment);
552                    transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
553                    transaction.commit();
554                    return;
555                }
556            } else {
557                if (secondaryFragment instanceof ConversationFragment) {
558                    transaction.remove(secondaryFragment);
559                    transaction.commit();
560                    getFragmentManager().executePendingTransactions();
561                    transaction = getFragmentManager().beginTransaction();
562                    transaction.replace(R.id.main_fragment, secondaryFragment);
563                    transaction.addToBackStack(null);
564                    transaction.commit();
565                    return;
566                }
567            }
568        } else {
569            transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
570        }
571        if (binding.secondaryFragment != null && secondaryFragment == null) {
572            transaction.replace(R.id.secondary_fragment, new ConversationFragment());
573        }
574        transaction.commit();
575    }
576
577    private void invalidateActionBarTitle() {
578        final ActionBar actionBar = getSupportActionBar();
579        if (actionBar != null) {
580            Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
581            if (mainFragment instanceof ConversationFragment) {
582                final Conversation conversation = ((ConversationFragment) mainFragment).getConversation();
583                if (conversation != null) {
584                    actionBar.setTitle(EmojiWrapper.transform(conversation.getName()));
585                    actionBar.setDisplayHomeAsUpEnabled(true);
586                    return;
587                }
588            }
589            actionBar.setTitle(R.string.app_name);
590            actionBar.setDisplayHomeAsUpEnabled(false);
591        }
592    }
593
594    @Override
595    public void onConversationArchived(Conversation conversation) {
596        if (performRedirectIfNecessary(conversation, false)) {
597            return;
598        }
599        Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
600        if (mainFragment instanceof ConversationFragment) {
601            try {
602                getFragmentManager().popBackStack();
603            } catch (IllegalStateException e) {
604                Log.w(Config.LOGTAG, "state loss while popping back state after archiving conversation", e);
605                //this usually means activity is no longer active; meaning on the next open we will run through this again
606            }
607            return;
608        }
609        Fragment secondaryFragment = getFragmentManager().findFragmentById(R.id.secondary_fragment);
610        if (secondaryFragment instanceof ConversationFragment) {
611            if (((ConversationFragment) secondaryFragment).getConversation() == conversation) {
612                Conversation suggestion = ConversationsOverviewFragment.getSuggestion(this, conversation);
613                if (suggestion != null) {
614                    openConversation(suggestion, null);
615                }
616            }
617        }
618    }
619
620    @Override
621    public void onConversationsListItemUpdated() {
622        Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
623        if (fragment instanceof ConversationsOverviewFragment) {
624            ((ConversationsOverviewFragment) fragment).refresh();
625        }
626    }
627
628    @Override
629    public void switchToConversation(Conversation conversation) {
630        Log.d(Config.LOGTAG, "override");
631        openConversation(conversation, null);
632    }
633
634    @Override
635    public void onConversationRead(Conversation conversation, String upToUuid) {
636        if (!mActivityPaused && pendingViewIntent.peek() == null) {
637            xmppConnectionService.sendReadMarker(conversation, upToUuid);
638        } else {
639            Log.d(Config.LOGTAG, "ignoring read callback. mActivityPaused=" + Boolean.toString(mActivityPaused));
640        }
641    }
642
643    @Override
644    public void onAccountUpdate() {
645        this.refreshUi();
646    }
647
648    @Override
649    public void onConversationUpdate() {
650        if (performRedirectIfNecessary(false)) {
651            return;
652        }
653        this.refreshUi();
654    }
655
656    @Override
657    public void onRosterUpdate() {
658        this.refreshUi();
659    }
660
661    @Override
662    public void OnUpdateBlocklist(OnUpdateBlocklist.Status status) {
663        this.refreshUi();
664    }
665
666    @Override
667    public void onShowErrorToast(int resId) {
668        runOnUiThread(() -> Toast.makeText(this, resId, Toast.LENGTH_SHORT).show());
669    }
670}