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