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