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 org.openintents.openpgp.util.OpenPgpApi;
 63
 64import java.util.Arrays;
 65import java.util.List;
 66import java.util.Objects;
 67import java.util.concurrent.atomic.AtomicBoolean;
 68
 69import eu.siacs.conversations.Config;
 70import eu.siacs.conversations.R;
 71import eu.siacs.conversations.crypto.OmemoSetting;
 72import eu.siacs.conversations.databinding.ActivityConversationsBinding;
 73import eu.siacs.conversations.entities.Account;
 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.ActionBarUtil;
 84import eu.siacs.conversations.ui.util.ActivityResult;
 85import eu.siacs.conversations.ui.util.ConversationMenuConfigurator;
 86import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
 87import eu.siacs.conversations.ui.util.PendingItem;
 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    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        }
218    }
219
220    private String getBatteryOptimizationPreferenceKey() {
221        @SuppressLint("HardwareIds") String device = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
222        return "show_battery_optimization" + (device == null ? "" : device);
223    }
224
225    private void setNeverAskForBatteryOptimizationsAgain() {
226        getPreferences().edit().putBoolean(getBatteryOptimizationPreferenceKey(), false).apply();
227    }
228
229    private boolean openBatteryOptimizationDialogIfNeeded() {
230        if (isOptimizingBattery()
231                && android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M
232                && getPreferences().getBoolean(getBatteryOptimizationPreferenceKey(), true)) {
233            final AlertDialog.Builder builder = new AlertDialog.Builder(this);
234            builder.setTitle(R.string.battery_optimizations_enabled);
235            builder.setMessage(getString(R.string.battery_optimizations_enabled_dialog, getString(R.string.app_name)));
236            builder.setPositiveButton(R.string.next, (dialog, which) -> {
237                final Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
238                final Uri uri = Uri.parse("package:" + getPackageName());
239                intent.setData(uri);
240                try {
241                    startActivityForResult(intent, REQUEST_BATTERY_OP);
242                } catch (ActivityNotFoundException e) {
243                    Toast.makeText(this, R.string.device_does_not_support_battery_op, Toast.LENGTH_SHORT).show();
244                }
245            });
246            builder.setOnDismissListener(dialog -> setNeverAskForBatteryOptimizationsAgain());
247            final AlertDialog dialog = builder.create();
248            dialog.setCanceledOnTouchOutside(false);
249            dialog.show();
250            return true;
251        }
252        return false;
253    }
254
255    private void requestNotificationPermissionIfNeeded() {
256        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && ActivityCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
257            requestPermissions(new String[]{Manifest.permission.POST_NOTIFICATIONS}, REQUEST_POST_NOTIFICATION);
258        }
259    }
260
261    private void notifyFragmentOfBackendConnected(@IdRes int id) {
262        final Fragment fragment = getFragmentManager().findFragmentById(id);
263        if (fragment instanceof OnBackendConnected) {
264            ((OnBackendConnected) fragment).onBackendConnected();
265        }
266    }
267
268    private void refreshFragment(@IdRes int id) {
269        final Fragment fragment = getFragmentManager().findFragmentById(id);
270        if (fragment instanceof XmppFragment) {
271            ((XmppFragment) fragment).refresh();
272        }
273    }
274
275    private boolean processViewIntent(Intent intent) {
276        final String uuid = intent.getStringExtra(EXTRA_CONVERSATION);
277        final Conversation conversation = uuid != null ? xmppConnectionService.findConversationByUuid(uuid) : null;
278        if (conversation == null) {
279            Log.d(Config.LOGTAG, "unable to view conversation with uuid:" + uuid);
280            return false;
281        }
282        openConversation(conversation, intent.getExtras());
283        return true;
284    }
285
286    @Override
287    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
288        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
289        UriHandlerActivity.onRequestPermissionResult(this, requestCode, grantResults);
290        if (grantResults.length > 0) {
291            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
292                switch (requestCode) {
293                    case REQUEST_OPEN_MESSAGE:
294                        refreshUiReal();
295                        ConversationFragment.openPendingMessage(this);
296                        break;
297                    case REQUEST_PLAY_PAUSE:
298                        ConversationFragment.startStopPending(this);
299                        break;
300                }
301            }
302        }
303    }
304
305    @Override
306    public void onActivityResult(int requestCode, int resultCode, final Intent data) {
307        super.onActivityResult(requestCode, resultCode, data);
308        ActivityResult activityResult = ActivityResult.of(requestCode, resultCode, data);
309        if (xmppConnectionService != null) {
310            handleActivityResult(activityResult);
311        } else {
312            this.postponedActivityResult.push(activityResult);
313        }
314    }
315
316    private void handleActivityResult(final ActivityResult activityResult) {
317        if (activityResult.resultCode == Activity.RESULT_OK) {
318            handlePositiveActivityResult(activityResult.requestCode, activityResult.data);
319        } else {
320            handleNegativeActivityResult(activityResult.requestCode);
321        }
322        if (activityResult.requestCode == REQUEST_BATTERY_OP) {
323            // the result code is always 0 even when battery permission were granted
324            requestNotificationPermissionIfNeeded();
325            XmppConnectionService.toggleForegroundService(xmppConnectionService);
326        }
327    }
328
329    private void handleNegativeActivityResult(int requestCode) {
330        Conversation conversation = ConversationFragment.getConversationReliable(this);
331        switch (requestCode) {
332            case REQUEST_DECRYPT_PGP:
333                if (conversation == null) {
334                    break;
335                }
336                conversation.getAccount().getPgpDecryptionService().giveUpCurrentDecryption();
337                break;
338            case REQUEST_BATTERY_OP:
339                setNeverAskForBatteryOptimizationsAgain();
340                break;
341        }
342    }
343
344    private void handlePositiveActivityResult(int requestCode, final Intent data) {
345        Conversation conversation = ConversationFragment.getConversationReliable(this);
346        if (conversation == null) {
347            Log.d(Config.LOGTAG, "conversation not found");
348            return;
349        }
350        switch (requestCode) {
351            case REQUEST_DECRYPT_PGP:
352                conversation.getAccount().getPgpDecryptionService().continueDecryption(data);
353                break;
354            case REQUEST_CHOOSE_PGP_ID:
355                long id = data.getLongExtra(OpenPgpApi.EXTRA_SIGN_KEY_ID, 0);
356                if (id != 0) {
357                    conversation.getAccount().setPgpSignId(id);
358                    announcePgp(conversation.getAccount(), null, null, onOpenPGPKeyPublished);
359                } else {
360                    choosePgpSignId(conversation.getAccount());
361                }
362                break;
363            case REQUEST_ANNOUNCE_PGP:
364                announcePgp(conversation.getAccount(), conversation, data, onOpenPGPKeyPublished);
365                break;
366        }
367    }
368
369    @Override
370    protected void onCreate(final Bundle savedInstanceState) {
371        super.onCreate(savedInstanceState);
372        ConversationMenuConfigurator.reloadFeatures(this);
373        OmemoSetting.load(this);
374        this.binding = DataBindingUtil.setContentView(this, R.layout.activity_conversations);
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        } else {
470            invalidateActionBarTitle();
471        }
472    }
473
474    private static void executePendingTransactions(final FragmentManager fragmentManager) {
475        try {
476            fragmentManager.executePendingTransactions();
477        } catch (final Exception e) {
478            Log.e(Config.LOGTAG,"unable to execute pending fragment transactions");
479        }
480    }
481
482    public boolean onXmppUriClicked(Uri uri) {
483        XmppUri xmppUri = new XmppUri(uri);
484        if (xmppUri.isValidJid() && !xmppUri.hasFingerprints()) {
485            final Conversation conversation = xmppConnectionService.findUniqueConversationByJid(xmppUri);
486            if (conversation != null) {
487                openConversation(conversation, null);
488                return true;
489            }
490        }
491        return false;
492    }
493
494    @Override
495    public boolean onOptionsItemSelected(MenuItem item) {
496        if (MenuDoubleTabUtil.shouldIgnoreTap()) {
497            return false;
498        }
499        switch (item.getItemId()) {
500            case android.R.id.home:
501                FragmentManager fm = getFragmentManager();
502                if (fm.getBackStackEntryCount() > 0) {
503                    try {
504                        fm.popBackStack();
505                    } catch (IllegalStateException e) {
506                        Log.w(Config.LOGTAG, "Unable to pop back stack after pressing home button");
507                    }
508                    return true;
509                }
510                break;
511            case R.id.action_scan_qr_code:
512                UriHandlerActivity.scan(this);
513                return true;
514            case R.id.action_search_all_conversations:
515                startActivity(new Intent(this, SearchActivity.class));
516                return true;
517            case R.id.action_search_this_conversation:
518                final Conversation conversation = ConversationFragment.getConversation(this);
519                if (conversation == null) {
520                    return true;
521                }
522                final Intent intent = new Intent(this, SearchActivity.class);
523                intent.putExtra(SearchActivity.EXTRA_CONVERSATION_UUID, conversation.getUuid());
524                startActivity(intent);
525                return true;
526        }
527        return super.onOptionsItemSelected(item);
528    }
529
530    @Override
531    public boolean onKeyDown(final int keyCode, final KeyEvent keyEvent) {
532        if (keyCode == KeyEvent.KEYCODE_DPAD_UP && keyEvent.isCtrlPressed()) {
533            final ConversationFragment conversationFragment = ConversationFragment.get(this);
534            if (conversationFragment != null && conversationFragment.onArrowUpCtrlPressed()) {
535                return true;
536            }
537        }
538        return super.onKeyDown(keyCode, keyEvent);
539    }
540
541    @Override
542    public void onSaveInstanceState(final Bundle savedInstanceState) {
543        final Intent pendingIntent = pendingViewIntent.peek();
544        savedInstanceState.putParcelable("intent", pendingIntent != null ? pendingIntent : getIntent());
545        super.onSaveInstanceState(savedInstanceState);
546    }
547
548    @Override
549    protected void onStart() {
550        super.onStart();
551        final int theme = findTheme();
552        if (this.mTheme != theme) {
553            this.mSkipBackgroundBinding = true;
554            recreate();
555        } else {
556            this.mSkipBackgroundBinding = false;
557        }
558        mRedirectInProcess.set(false);
559    }
560
561    @Override
562    protected void onNewIntent(final Intent intent) {
563        super.onNewIntent(intent);
564        if (isViewOrShareIntent(intent)) {
565            if (xmppConnectionService != null) {
566                clearPendingViewIntent();
567                processViewIntent(intent);
568            } else {
569                pendingViewIntent.push(intent);
570            }
571        }
572        setIntent(createLauncherIntent(this));
573    }
574
575    @Override
576    public void onPause() {
577        this.mActivityPaused = true;
578        super.onPause();
579    }
580
581    @Override
582    public void onResume() {
583        super.onResume();
584        this.mActivityPaused = false;
585    }
586
587    private void initializeFragments() {
588        final FragmentManager fragmentManager = getFragmentManager();
589        FragmentTransaction transaction = fragmentManager.beginTransaction();
590        final Fragment mainFragment = fragmentManager.findFragmentById(R.id.main_fragment);
591        final Fragment secondaryFragment = fragmentManager.findFragmentById(R.id.secondary_fragment);
592        if (mainFragment != null) {
593            if (binding.secondaryFragment != null) {
594                if (mainFragment instanceof ConversationFragment) {
595                    getFragmentManager().popBackStack();
596                    transaction.remove(mainFragment);
597                    transaction.commit();
598                    fragmentManager.executePendingTransactions();
599                    transaction = fragmentManager.beginTransaction();
600                    transaction.replace(R.id.secondary_fragment, mainFragment);
601                    transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
602                    transaction.commit();
603                    return;
604                }
605            } else {
606                if (secondaryFragment instanceof ConversationFragment) {
607                    transaction.remove(secondaryFragment);
608                    transaction.commit();
609                    getFragmentManager().executePendingTransactions();
610                    transaction = fragmentManager.beginTransaction();
611                    transaction.replace(R.id.main_fragment, secondaryFragment);
612                    transaction.addToBackStack(null);
613                    transaction.commit();
614                    return;
615                }
616            }
617        } else {
618            transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
619        }
620        if (binding.secondaryFragment != null && secondaryFragment == null) {
621            transaction.replace(R.id.secondary_fragment, new ConversationFragment());
622        }
623        transaction.commit();
624    }
625
626    private void invalidateActionBarTitle() {
627        final ActionBar actionBar = getSupportActionBar();
628        if (actionBar == null) {
629            return;
630        }
631        final FragmentManager fragmentManager = getFragmentManager();
632        final Fragment mainFragment = fragmentManager.findFragmentById(R.id.main_fragment);
633        if (mainFragment instanceof ConversationFragment) {
634            final Conversation conversation = ((ConversationFragment) mainFragment).getConversation();
635            if (conversation != null) {
636                actionBar.setTitle(conversation.getName());
637                actionBar.setDisplayHomeAsUpEnabled(true);
638                ActionBarUtil.setActionBarOnClickListener(
639                        binding.toolbar,
640                        (v) -> openConversationDetails(conversation)
641                );
642                return;
643            }
644        }
645        actionBar.setTitle(R.string.app_name);
646        actionBar.setDisplayHomeAsUpEnabled(false);
647        ActionBarUtil.resetActionBarOnClickListeners(binding.toolbar);
648    }
649
650    private void openConversationDetails(final Conversation conversation) {
651        if (conversation.getMode() == Conversational.MODE_MULTI) {
652            ConferenceDetailsActivity.open(this, conversation);
653        } else {
654            final Contact contact = conversation.getContact();
655            if (contact.isSelf()) {
656                switchToAccount(conversation.getAccount());
657            } else {
658                switchToContactDetails(contact);
659            }
660        }
661    }
662
663    @Override
664    public void onConversationArchived(Conversation conversation) {
665        if (performRedirectIfNecessary(conversation, false)) {
666            return;
667        }
668        final FragmentManager fragmentManager = getFragmentManager();
669        final Fragment mainFragment = fragmentManager.findFragmentById(R.id.main_fragment);
670        if (mainFragment instanceof ConversationFragment) {
671            try {
672                fragmentManager.popBackStack();
673            } catch (final IllegalStateException e) {
674                Log.w(Config.LOGTAG, "state loss while popping back state after archiving conversation", e);
675                //this usually means activity is no longer active; meaning on the next open we will run through this again
676            }
677            return;
678        }
679        final Fragment secondaryFragment = fragmentManager.findFragmentById(R.id.secondary_fragment);
680        if (secondaryFragment instanceof ConversationFragment) {
681            if (((ConversationFragment) secondaryFragment).getConversation() == conversation) {
682                Conversation suggestion = ConversationsOverviewFragment.getSuggestion(this, conversation);
683                if (suggestion != null) {
684                    openConversation(suggestion, null);
685                }
686            }
687        }
688    }
689
690    @Override
691    public void onConversationsListItemUpdated() {
692        Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
693        if (fragment instanceof ConversationsOverviewFragment) {
694            ((ConversationsOverviewFragment) fragment).refresh();
695        }
696    }
697
698    @Override
699    public void switchToConversation(Conversation conversation) {
700        Log.d(Config.LOGTAG, "override");
701        openConversation(conversation, null);
702    }
703
704    @Override
705    public void onConversationRead(Conversation conversation, String upToUuid) {
706        if (!mActivityPaused && pendingViewIntent.peek() == null) {
707            xmppConnectionService.sendReadMarker(conversation, upToUuid);
708        } else {
709            Log.d(Config.LOGTAG, "ignoring read callback. mActivityPaused=" + mActivityPaused);
710        }
711    }
712
713    @Override
714    public void onAccountUpdate() {
715        this.refreshUi();
716    }
717
718    @Override
719    public void onConversationUpdate() {
720        if (performRedirectIfNecessary(false)) {
721            return;
722        }
723        this.refreshUi();
724    }
725
726    @Override
727    public void onRosterUpdate() {
728        this.refreshUi();
729    }
730
731    @Override
732    public void OnUpdateBlocklist(OnUpdateBlocklist.Status status) {
733        this.refreshUi();
734    }
735
736    @Override
737    public void onShowErrorToast(int resId) {
738        runOnUiThread(() -> Toast.makeText(this, resId, Toast.LENGTH_SHORT).show());
739    }
740}