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