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