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                        try {
405                            startActivityForResult(intent, DIALLER_INTEGRATION);
406                        } catch (ActivityNotFoundException e) {
407                            displayToast("Dialler integration not available on your OS");
408                        }
409                        break;
410                    case REQUEST_DOWNLOAD_STICKERS:
411                        downloadStickers();
412                        break;
413                }
414            } else {
415                showDialogsIfMainIsOverview();
416            }
417        } else {
418            showDialogsIfMainIsOverview();
419        }
420    }
421
422    private void downloadStickers() {
423        Intent intent = new Intent(this, DownloadDefaultStickers.class);
424        intent.putExtra("tor", xmppConnectionService.useTorToConnect());
425        ContextCompat.startForegroundService(this, intent);
426        displayToast("Sticker download started");
427        showDialogsIfMainIsOverview();
428    }
429
430    @Override
431    public void onActivityResult(int requestCode, int resultCode, final Intent data) {
432        super.onActivityResult(requestCode, resultCode, data);
433
434        if (requestCode == DIALLER_INTEGRATION) {
435            mRequestCode = requestCode;
436            startActivity(new Intent(android.telecom.TelecomManager.ACTION_CHANGE_PHONE_ACCOUNTS));
437            return;
438        }
439
440        ActivityResult activityResult = ActivityResult.of(requestCode, resultCode, data);
441        if (xmppConnectionService != null) {
442            handleActivityResult(activityResult);
443        } else {
444            this.postponedActivityResult.push(activityResult);
445        }
446    }
447
448    private void handleActivityResult(final ActivityResult activityResult) {
449        if (activityResult.resultCode == Activity.RESULT_OK) {
450            handlePositiveActivityResult(activityResult.requestCode, activityResult.data);
451        } else {
452            handleNegativeActivityResult(activityResult.requestCode);
453        }
454        if (activityResult.requestCode == REQUEST_BATTERY_OP) {
455            // the result code is always 0 even when battery permission were granted
456            requestNotificationPermissionIfNeeded();
457            XmppConnectionService.toggleForegroundService(xmppConnectionService);
458        }
459    }
460
461    private void handleNegativeActivityResult(int requestCode) {
462        Conversation conversation = ConversationFragment.getConversationReliable(this);
463        switch (requestCode) {
464            case REQUEST_DECRYPT_PGP:
465                if (conversation == null) {
466                    break;
467                }
468                conversation.getAccount().getPgpDecryptionService().giveUpCurrentDecryption();
469                break;
470            case REQUEST_BATTERY_OP:
471                setNeverAskForBatteryOptimizationsAgain();
472                break;
473        }
474    }
475
476    private void handlePositiveActivityResult(int requestCode, final Intent data) {
477        Conversation conversation = ConversationFragment.getConversationReliable(this);
478        if (conversation == null) {
479            Log.d(Config.LOGTAG, "conversation not found");
480            return;
481        }
482        switch (requestCode) {
483            case REQUEST_DECRYPT_PGP:
484                conversation.getAccount().getPgpDecryptionService().continueDecryption(data);
485                break;
486            case REQUEST_CHOOSE_PGP_ID:
487                long id = data.getLongExtra(OpenPgpApi.EXTRA_SIGN_KEY_ID, 0);
488                if (id != 0) {
489                    conversation.getAccount().setPgpSignId(id);
490                    announcePgp(conversation.getAccount(), null, null, onOpenPGPKeyPublished);
491                } else {
492                    choosePgpSignId(conversation.getAccount());
493                }
494                break;
495            case REQUEST_ANNOUNCE_PGP:
496                announcePgp(conversation.getAccount(), conversation, data, onOpenPGPKeyPublished);
497                break;
498        }
499    }
500
501    @Override
502    protected void onCreate(final Bundle savedInstanceState) {
503        super.onCreate(savedInstanceState);
504        ConversationMenuConfigurator.reloadFeatures(this);
505        OmemoSetting.load(this);
506        this.binding = DataBindingUtil.setContentView(this, R.layout.activity_conversations);
507        setSupportActionBar(binding.toolbar);
508        configureActionBar(getSupportActionBar());
509        this.getFragmentManager().addOnBackStackChangedListener(this::invalidateActionBarTitle);
510        this.getFragmentManager().addOnBackStackChangedListener(this::showDialogsIfMainIsOverview);
511        this.initializeFragments();
512        this.invalidateActionBarTitle();
513        final Intent intent;
514        if (savedInstanceState == null) {
515            intent = getIntent();
516        } else {
517            intent = savedInstanceState.getParcelable("intent");
518        }
519        if (isViewOrShareIntent(intent)) {
520            pendingViewIntent.push(intent);
521            setIntent(createLauncherIntent(this));
522        }
523    }
524
525    @Override
526    public boolean onCreateOptionsMenu(Menu menu) {
527        getMenuInflater().inflate(R.menu.activity_conversations, menu);
528        final MenuItem qrCodeScanMenuItem = menu.findItem(R.id.action_scan_qr_code);
529        if (qrCodeScanMenuItem != null) {
530            if (isCameraFeatureAvailable() && (xmppConnectionService == null || !xmppConnectionService.isOnboarding())) {
531                Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
532                boolean visible = getResources().getBoolean(R.bool.show_qr_code_scan)
533                        && fragment instanceof ConversationsOverviewFragment;
534                qrCodeScanMenuItem.setVisible(visible);
535            } else {
536                qrCodeScanMenuItem.setVisible(false);
537            }
538        }
539        return super.onCreateOptionsMenu(menu);
540    }
541
542    @Override
543    public void onConversationSelected(Conversation conversation) {
544        clearPendingViewIntent();
545        if (ConversationFragment.getConversation(this) == conversation) {
546            Log.d(Config.LOGTAG, "ignore onConversationSelected() because conversation is already open");
547            return;
548        }
549        openConversation(conversation, null);
550    }
551
552    public void clearPendingViewIntent() {
553        if (pendingViewIntent.clear()) {
554            Log.e(Config.LOGTAG, "cleared pending view intent");
555        }
556    }
557
558    private void displayToast(final String msg) {
559        runOnUiThread(() -> Toast.makeText(ConversationsActivity.this, msg, Toast.LENGTH_SHORT).show());
560    }
561
562    @Override
563    public void onAffiliationChangedSuccessful(Jid jid) {
564
565    }
566
567    @Override
568    public void onAffiliationChangeFailed(Jid jid, int resId) {
569        displayToast(getString(resId, jid.asBareJid().toString()));
570    }
571
572    private void openConversation(Conversation conversation, Bundle extras) {
573        final FragmentManager fragmentManager = getFragmentManager();
574        executePendingTransactions(fragmentManager);
575        ConversationFragment conversationFragment = (ConversationFragment) fragmentManager.findFragmentById(R.id.secondary_fragment);
576        final boolean mainNeedsRefresh;
577        if (conversationFragment == null) {
578            mainNeedsRefresh = false;
579            final Fragment mainFragment = fragmentManager.findFragmentById(R.id.main_fragment);
580            if (mainFragment instanceof ConversationFragment) {
581                conversationFragment = (ConversationFragment) mainFragment;
582            } else {
583                conversationFragment = new ConversationFragment();
584                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
585                fragmentTransaction.replace(R.id.main_fragment, conversationFragment);
586                fragmentTransaction.addToBackStack(null);
587                try {
588                    fragmentTransaction.commit();
589                } catch (IllegalStateException e) {
590                    Log.w(Config.LOGTAG, "sate loss while opening conversation", e);
591                    //allowing state loss is probably fine since view intents et all are already stored and a click can probably be 'ignored'
592                    return;
593                }
594            }
595        } else {
596            mainNeedsRefresh = true;
597        }
598        conversationFragment.reInit(conversation, extras == null ? new Bundle() : extras);
599        if (mainNeedsRefresh) {
600            refreshFragment(R.id.main_fragment);
601        } else {
602            invalidateActionBarTitle();
603        }
604    }
605
606    private static void executePendingTransactions(final FragmentManager fragmentManager) {
607        try {
608            fragmentManager.executePendingTransactions();
609        } catch (final Exception e) {
610            Log.e(Config.LOGTAG,"unable to execute pending fragment transactions");
611        }
612    }
613
614    public boolean onXmppUriClicked(Uri uri) {
615        XmppUri xmppUri = new XmppUri(uri);
616        if (xmppUri.isValidJid() && !xmppUri.hasFingerprints()) {
617            final Conversation conversation = xmppConnectionService.findUniqueConversationByJid(xmppUri);
618            if (conversation != null) {
619                if (xmppUri.getParameter("password") != null) {
620                    xmppConnectionService.providePasswordForMuc(conversation, xmppUri.getParameter("password"));
621                }
622                if (xmppUri.isAction("command")) {
623                    startCommand(conversation.getAccount(), xmppUri.getJid(), xmppUri.getParameter("node"));
624                } else {
625                    Bundle extras = new Bundle();
626                    extras.putString(Intent.EXTRA_TEXT, xmppUri.getBody());
627                    if (xmppUri.isAction("message")) extras.putString(EXTRA_POST_INIT_ACTION, "message");
628                    openConversation(conversation, extras);
629                }
630                return true;
631            }
632        }
633        return false;
634    }
635
636    public boolean onTelUriClicked(Uri uri, Account acct) {
637        final String tel;
638        try {
639            tel = PhoneNumberUtilWrapper.normalize(this, uri.getSchemeSpecificPart());
640        } catch (final IllegalArgumentException | NumberParseException | NullPointerException e) {
641            return false;
642        }
643
644        Set<String> gateways = new HashSet<>();
645        for (Account account : (acct == null ? xmppConnectionService.getAccounts() : List.of(acct))) {
646            for (Contact contact : account.getRoster().getContacts()) {
647                if (contact.getPresences().anyIdentity("gateway", "pstn") || contact.getPresences().anyIdentity("gateway", "sms")) {
648                    if (acct == null) acct = account;
649                    gateways.add(contact.getJid().asBareJid().toEscapedString());
650                }
651            }
652        }
653
654        for (String gateway : gateways) {
655            if (onXmppUriClicked(Uri.parse("xmpp:" + tel + "@" + gateway))) return true;
656        }
657
658        if (gateways.size() == 1 && acct != null) {
659            openConversation(xmppConnectionService.findOrCreateConversation(acct, Jid.ofLocalAndDomain(tel, gateways.iterator().next()), false, true), null);
660            return true;
661        }
662
663        return false;
664    }
665
666    @Override
667    public boolean onOptionsItemSelected(MenuItem item) {
668        if (MenuDoubleTabUtil.shouldIgnoreTap()) {
669            return false;
670        }
671        switch (item.getItemId()) {
672            case android.R.id.home:
673                FragmentManager fm = getFragmentManager();
674                if (android.os.Build.VERSION.SDK_INT >= 26) {
675                    Fragment f = fm.getFragments().get(fm.getFragments().size() - 1);
676                    if (f != null && f instanceof ConversationFragment) {
677                        if (((ConversationFragment) f).onBackPressed()) {
678                            return true;
679                        }
680                    }
681                }
682                if (fm.getBackStackEntryCount() > 0) {
683                    try {
684                        fm.popBackStack();
685                    } catch (IllegalStateException e) {
686                        Log.w(Config.LOGTAG, "Unable to pop back stack after pressing home button");
687                    }
688                    return true;
689                }
690                break;
691            case R.id.action_scan_qr_code:
692                UriHandlerActivity.scan(this);
693                return true;
694            case R.id.action_search_all_conversations:
695                startActivity(new Intent(this, SearchActivity.class));
696                return true;
697            case R.id.action_search_this_conversation:
698                final Conversation conversation = ConversationFragment.getConversation(this);
699                if (conversation == null) {
700                    return true;
701                }
702                final Intent intent = new Intent(this, SearchActivity.class);
703                intent.putExtra(SearchActivity.EXTRA_CONVERSATION_UUID, conversation.getUuid());
704                startActivity(intent);
705                return true;
706        }
707        return super.onOptionsItemSelected(item);
708    }
709
710    @Override
711    public boolean onKeyDown(final int keyCode, final KeyEvent keyEvent) {
712        if (keyCode == KeyEvent.KEYCODE_DPAD_UP && keyEvent.isCtrlPressed()) {
713            final ConversationFragment conversationFragment = ConversationFragment.get(this);
714            if (conversationFragment != null && conversationFragment.onArrowUpCtrlPressed()) {
715                return true;
716            }
717        }
718        return super.onKeyDown(keyCode, keyEvent);
719    }
720
721    @Override
722    public void onSaveInstanceState(final Bundle savedInstanceState) {
723        final Intent pendingIntent = pendingViewIntent.peek();
724        savedInstanceState.putParcelable("intent", pendingIntent != null ? pendingIntent : getIntent());
725        super.onSaveInstanceState(savedInstanceState);
726    }
727
728    @Override
729    protected void onStart() {
730        super.onStart();
731        final int theme = findTheme();
732        if (this.mTheme != theme || !this.mCustomColors.equals(ThemeHelper.applyCustomColors(this))) {
733            this.mSkipBackgroundBinding = true;
734            recreate();
735        } else {
736            this.mSkipBackgroundBinding = false;
737        }
738        mRedirectInProcess.set(false);
739    }
740
741    @Override
742    protected void onNewIntent(final Intent intent) {
743        super.onNewIntent(intent);
744        if (isViewOrShareIntent(intent)) {
745            if (xmppConnectionService != null) {
746                clearPendingViewIntent();
747                processViewIntent(intent);
748            } else {
749                pendingViewIntent.push(intent);
750            }
751        }
752        setIntent(createLauncherIntent(this));
753    }
754
755    @Override
756    public void onPause() {
757        this.mActivityPaused = true;
758        super.onPause();
759    }
760
761    @Override
762    public void onResume() {
763        super.onResume();
764        this.mActivityPaused = false;
765    }
766
767    private void initializeFragments() {
768        final FragmentManager fragmentManager = getFragmentManager();
769        FragmentTransaction transaction = fragmentManager.beginTransaction();
770        final Fragment mainFragment = fragmentManager.findFragmentById(R.id.main_fragment);
771        final Fragment secondaryFragment = fragmentManager.findFragmentById(R.id.secondary_fragment);
772        if (mainFragment != null) {
773            if (binding.secondaryFragment != null) {
774                if (mainFragment instanceof ConversationFragment) {
775                    getFragmentManager().popBackStack();
776                    transaction.remove(mainFragment);
777                    transaction.commit();
778                    fragmentManager.executePendingTransactions();
779                    transaction = fragmentManager.beginTransaction();
780                    transaction.replace(R.id.secondary_fragment, mainFragment);
781                    transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
782                    transaction.commit();
783                    return;
784                }
785            } else {
786                if (secondaryFragment instanceof ConversationFragment) {
787                    transaction.remove(secondaryFragment);
788                    transaction.commit();
789                    getFragmentManager().executePendingTransactions();
790                    transaction = fragmentManager.beginTransaction();
791                    transaction.replace(R.id.main_fragment, secondaryFragment);
792                    transaction.addToBackStack(null);
793                    transaction.commit();
794                    return;
795                }
796            }
797        } else {
798            transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
799        }
800        if (binding.secondaryFragment != null && secondaryFragment == null) {
801            transaction.replace(R.id.secondary_fragment, new ConversationFragment());
802        }
803        transaction.commit();
804    }
805
806    private void invalidateActionBarTitle() {
807        final ActionBar actionBar = getSupportActionBar();
808        if (actionBar == null) {
809            return;
810        }
811        final FragmentManager fragmentManager = getFragmentManager();
812        final Fragment mainFragment = fragmentManager.findFragmentById(R.id.main_fragment);
813        if (mainFragment instanceof ConversationFragment) {
814            final Conversation conversation = ((ConversationFragment) mainFragment).getConversation();
815            if (conversation != null) {
816                actionBar.setTitle(conversation.getName());
817                actionBar.setDisplayHomeAsUpEnabled(!xmppConnectionService.isOnboarding() || !conversation.getJid().equals(Jid.of("cheogram.com")));
818                ActionBarUtil.setActionBarOnClickListener(
819                        binding.toolbar,
820                        (v) -> { if(!xmppConnectionService.isOnboarding()) openConversationDetails(conversation); }
821                );
822                return;
823            }
824        }
825        actionBar.setTitle(R.string.app_name);
826        actionBar.setDisplayHomeAsUpEnabled(false);
827        ActionBarUtil.resetActionBarOnClickListeners(binding.toolbar);
828    }
829
830    private void openConversationDetails(final Conversation conversation) {
831        if (conversation.getMode() == Conversational.MODE_MULTI) {
832            ConferenceDetailsActivity.open(this, conversation);
833        } else {
834            final Contact contact = conversation.getContact();
835            if (contact.isSelf()) {
836                switchToAccount(conversation.getAccount());
837            } else {
838                switchToContactDetails(contact);
839            }
840        }
841    }
842
843    @Override
844    public void onConversationArchived(Conversation conversation) {
845        if (performRedirectIfNecessary(conversation, false)) {
846            return;
847        }
848        final FragmentManager fragmentManager = getFragmentManager();
849        final Fragment mainFragment = fragmentManager.findFragmentById(R.id.main_fragment);
850        if (mainFragment instanceof ConversationFragment) {
851            try {
852                fragmentManager.popBackStack();
853            } catch (final IllegalStateException e) {
854                Log.w(Config.LOGTAG, "state loss while popping back state after archiving conversation", e);
855                //this usually means activity is no longer active; meaning on the next open we will run through this again
856            }
857            return;
858        }
859        final Fragment secondaryFragment = fragmentManager.findFragmentById(R.id.secondary_fragment);
860        if (secondaryFragment instanceof ConversationFragment) {
861            if (((ConversationFragment) secondaryFragment).getConversation() == conversation) {
862                Conversation suggestion = ConversationsOverviewFragment.getSuggestion(this, conversation);
863                if (suggestion != null) {
864                    openConversation(suggestion, null);
865                }
866            }
867        }
868    }
869
870    @Override
871    public void onConversationsListItemUpdated() {
872        Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
873        if (fragment instanceof ConversationsOverviewFragment) {
874            ((ConversationsOverviewFragment) fragment).refresh();
875        }
876    }
877
878    @Override
879    public void switchToConversation(Conversation conversation) {
880        Log.d(Config.LOGTAG, "override");
881        openConversation(conversation, null);
882    }
883
884    @Override
885    public void onConversationRead(Conversation conversation, String upToUuid) {
886        if (!mActivityPaused && pendingViewIntent.peek() == null) {
887            xmppConnectionService.sendReadMarker(conversation, upToUuid);
888        } else {
889            Log.d(Config.LOGTAG, "ignoring read callback. mActivityPaused=" + mActivityPaused);
890        }
891    }
892
893    @Override
894    public void onAccountUpdate() {
895        this.refreshUi();
896    }
897
898    @Override
899    public void onConversationUpdate(boolean newCaps) {
900        if (performRedirectIfNecessary(false)) {
901            return;
902        }
903        refreshForNewCaps = newCaps;
904        this.refreshUi();
905    }
906
907    @Override
908    public void onRosterUpdate() {
909        refreshForNewCaps = true;
910        this.refreshUi();
911    }
912
913    @Override
914    public void OnUpdateBlocklist(OnUpdateBlocklist.Status status) {
915        this.refreshUi();
916    }
917
918    @Override
919    public void onShowErrorToast(int resId) {
920        runOnUiThread(() -> Toast.makeText(this, resId, Toast.LENGTH_SHORT).show());
921    }
922}