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