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