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