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