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