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