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.getParameter("password") != null) {
616                    xmppConnectionService.providePasswordForMuc(conversation, xmppUri.getParameter("password"));
617                }
618                if (xmppUri.isAction("command")) {
619                    startCommand(conversation.getAccount(), xmppUri.getJid(), xmppUri.getParameter("node"));
620                } else {
621                    Bundle extras = new Bundle();
622                    extras.putString(Intent.EXTRA_TEXT, xmppUri.getBody());
623                    if (xmppUri.isAction("message")) extras.putString(EXTRA_POST_INIT_ACTION, "message");
624                    openConversation(conversation, extras);
625                }
626                return true;
627            }
628        }
629        return false;
630    }
631
632    public boolean onTelUriClicked(Uri uri, Account acct) {
633        final String tel;
634        try {
635            tel = PhoneNumberUtilWrapper.normalize(this, uri.getSchemeSpecificPart());
636        } catch (final IllegalArgumentException | NumberParseException | NullPointerException e) {
637            return false;
638        }
639
640        Set<String> gateways = new HashSet<>();
641        for (Account account : (acct == null ? xmppConnectionService.getAccounts() : List.of(acct))) {
642            for (Contact contact : account.getRoster().getContacts()) {
643                if (contact.getPresences().anyIdentity("gateway", "pstn") || contact.getPresences().anyIdentity("gateway", "sms")) {
644                    if (acct == null) acct = account;
645                    gateways.add(contact.getJid().asBareJid().toEscapedString());
646                }
647            }
648        }
649
650        for (String gateway : gateways) {
651            if (onXmppUriClicked(Uri.parse("xmpp:" + tel + "@" + gateway))) return true;
652        }
653
654        if (gateways.size() == 1 && acct != null) {
655            openConversation(xmppConnectionService.findOrCreateConversation(acct, Jid.ofLocalAndDomain(tel, gateways.iterator().next()), false, true), null);
656            return true;
657        }
658
659        return false;
660    }
661
662    @Override
663    public boolean onOptionsItemSelected(MenuItem item) {
664        if (MenuDoubleTabUtil.shouldIgnoreTap()) {
665            return false;
666        }
667        switch (item.getItemId()) {
668            case android.R.id.home:
669                FragmentManager fm = getFragmentManager();
670                if (android.os.Build.VERSION.SDK_INT >= 26) {
671                    Fragment f = fm.getFragments().get(fm.getFragments().size() - 1);
672                    if (f != null && f instanceof ConversationFragment) {
673                        if (((ConversationFragment) f).onBackPressed()) {
674                            return true;
675                        }
676                    }
677                }
678                if (fm.getBackStackEntryCount() > 0) {
679                    try {
680                        fm.popBackStack();
681                    } catch (IllegalStateException e) {
682                        Log.w(Config.LOGTAG, "Unable to pop back stack after pressing home button");
683                    }
684                    return true;
685                }
686                break;
687            case R.id.action_scan_qr_code:
688                UriHandlerActivity.scan(this);
689                return true;
690            case R.id.action_search_all_conversations:
691                startActivity(new Intent(this, SearchActivity.class));
692                return true;
693            case R.id.action_search_this_conversation:
694                final Conversation conversation = ConversationFragment.getConversation(this);
695                if (conversation == null) {
696                    return true;
697                }
698                final Intent intent = new Intent(this, SearchActivity.class);
699                intent.putExtra(SearchActivity.EXTRA_CONVERSATION_UUID, conversation.getUuid());
700                startActivity(intent);
701                return true;
702        }
703        return super.onOptionsItemSelected(item);
704    }
705
706    @Override
707    public boolean onKeyDown(final int keyCode, final KeyEvent keyEvent) {
708        if (keyCode == KeyEvent.KEYCODE_DPAD_UP && keyEvent.isCtrlPressed()) {
709            final ConversationFragment conversationFragment = ConversationFragment.get(this);
710            if (conversationFragment != null && conversationFragment.onArrowUpCtrlPressed()) {
711                return true;
712            }
713        }
714        return super.onKeyDown(keyCode, keyEvent);
715    }
716
717    @Override
718    public void onSaveInstanceState(final Bundle savedInstanceState) {
719        final Intent pendingIntent = pendingViewIntent.peek();
720        savedInstanceState.putParcelable("intent", pendingIntent != null ? pendingIntent : getIntent());
721        super.onSaveInstanceState(savedInstanceState);
722    }
723
724    @Override
725    protected void onStart() {
726        super.onStart();
727        final int theme = findTheme();
728        if (this.mTheme != theme || !this.mCustomColors.equals(ThemeHelper.applyCustomColors(this))) {
729            this.mSkipBackgroundBinding = true;
730            recreate();
731        } else {
732            this.mSkipBackgroundBinding = false;
733        }
734        mRedirectInProcess.set(false);
735    }
736
737    @Override
738    protected void onNewIntent(final Intent intent) {
739        super.onNewIntent(intent);
740        if (isViewOrShareIntent(intent)) {
741            if (xmppConnectionService != null) {
742                clearPendingViewIntent();
743                processViewIntent(intent);
744            } else {
745                pendingViewIntent.push(intent);
746            }
747        }
748        setIntent(createLauncherIntent(this));
749    }
750
751    @Override
752    public void onPause() {
753        this.mActivityPaused = true;
754        super.onPause();
755    }
756
757    @Override
758    public void onResume() {
759        super.onResume();
760        this.mActivityPaused = false;
761    }
762
763    private void initializeFragments() {
764        final FragmentManager fragmentManager = getFragmentManager();
765        FragmentTransaction transaction = fragmentManager.beginTransaction();
766        final Fragment mainFragment = fragmentManager.findFragmentById(R.id.main_fragment);
767        final Fragment secondaryFragment = fragmentManager.findFragmentById(R.id.secondary_fragment);
768        if (mainFragment != null) {
769            if (binding.secondaryFragment != null) {
770                if (mainFragment instanceof ConversationFragment) {
771                    getFragmentManager().popBackStack();
772                    transaction.remove(mainFragment);
773                    transaction.commit();
774                    fragmentManager.executePendingTransactions();
775                    transaction = fragmentManager.beginTransaction();
776                    transaction.replace(R.id.secondary_fragment, mainFragment);
777                    transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
778                    transaction.commit();
779                    return;
780                }
781            } else {
782                if (secondaryFragment instanceof ConversationFragment) {
783                    transaction.remove(secondaryFragment);
784                    transaction.commit();
785                    getFragmentManager().executePendingTransactions();
786                    transaction = fragmentManager.beginTransaction();
787                    transaction.replace(R.id.main_fragment, secondaryFragment);
788                    transaction.addToBackStack(null);
789                    transaction.commit();
790                    return;
791                }
792            }
793        } else {
794            transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
795        }
796        if (binding.secondaryFragment != null && secondaryFragment == null) {
797            transaction.replace(R.id.secondary_fragment, new ConversationFragment());
798        }
799        transaction.commit();
800    }
801
802    private void invalidateActionBarTitle() {
803        final ActionBar actionBar = getSupportActionBar();
804        if (actionBar == null) {
805            return;
806        }
807        final FragmentManager fragmentManager = getFragmentManager();
808        final Fragment mainFragment = fragmentManager.findFragmentById(R.id.main_fragment);
809        if (mainFragment instanceof ConversationFragment) {
810            final Conversation conversation = ((ConversationFragment) mainFragment).getConversation();
811            if (conversation != null) {
812                actionBar.setTitle(conversation.getName());
813                actionBar.setDisplayHomeAsUpEnabled(!xmppConnectionService.isOnboarding() || !conversation.getJid().equals(Jid.of("cheogram.com")));
814                ActionBarUtil.setActionBarOnClickListener(
815                        binding.toolbar,
816                        (v) -> { if(!xmppConnectionService.isOnboarding()) openConversationDetails(conversation); }
817                );
818                return;
819            }
820        }
821        actionBar.setTitle(R.string.app_name);
822        actionBar.setDisplayHomeAsUpEnabled(false);
823        ActionBarUtil.resetActionBarOnClickListeners(binding.toolbar);
824    }
825
826    private void openConversationDetails(final Conversation conversation) {
827        if (conversation.getMode() == Conversational.MODE_MULTI) {
828            ConferenceDetailsActivity.open(this, conversation);
829        } else {
830            final Contact contact = conversation.getContact();
831            if (contact.isSelf()) {
832                switchToAccount(conversation.getAccount());
833            } else {
834                switchToContactDetails(contact);
835            }
836        }
837    }
838
839    @Override
840    public void onConversationArchived(Conversation conversation) {
841        if (performRedirectIfNecessary(conversation, false)) {
842            return;
843        }
844        final FragmentManager fragmentManager = getFragmentManager();
845        final Fragment mainFragment = fragmentManager.findFragmentById(R.id.main_fragment);
846        if (mainFragment instanceof ConversationFragment) {
847            try {
848                fragmentManager.popBackStack();
849            } catch (final IllegalStateException e) {
850                Log.w(Config.LOGTAG, "state loss while popping back state after archiving conversation", e);
851                //this usually means activity is no longer active; meaning on the next open we will run through this again
852            }
853            return;
854        }
855        final Fragment secondaryFragment = fragmentManager.findFragmentById(R.id.secondary_fragment);
856        if (secondaryFragment instanceof ConversationFragment) {
857            if (((ConversationFragment) secondaryFragment).getConversation() == conversation) {
858                Conversation suggestion = ConversationsOverviewFragment.getSuggestion(this, conversation);
859                if (suggestion != null) {
860                    openConversation(suggestion, null);
861                }
862            }
863        }
864    }
865
866    @Override
867    public void onConversationsListItemUpdated() {
868        Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
869        if (fragment instanceof ConversationsOverviewFragment) {
870            ((ConversationsOverviewFragment) fragment).refresh();
871        }
872    }
873
874    @Override
875    public void switchToConversation(Conversation conversation) {
876        Log.d(Config.LOGTAG, "override");
877        openConversation(conversation, null);
878    }
879
880    @Override
881    public void onConversationRead(Conversation conversation, String upToUuid) {
882        if (!mActivityPaused && pendingViewIntent.peek() == null) {
883            xmppConnectionService.sendReadMarker(conversation, upToUuid);
884        } else {
885            Log.d(Config.LOGTAG, "ignoring read callback. mActivityPaused=" + mActivityPaused);
886        }
887    }
888
889    @Override
890    public void onAccountUpdate() {
891        this.refreshUi();
892    }
893
894    @Override
895    public void onConversationUpdate(boolean newCaps) {
896        if (performRedirectIfNecessary(false)) {
897            return;
898        }
899        refreshForNewCaps = newCaps;
900        this.refreshUi();
901    }
902
903    @Override
904    public void onRosterUpdate() {
905        refreshForNewCaps = true;
906        this.refreshUi();
907    }
908
909    @Override
910    public void OnUpdateBlocklist(OnUpdateBlocklist.Status status) {
911        this.refreshUi();
912    }
913
914    @Override
915    public void onShowErrorToast(int resId) {
916        runOnUiThread(() -> Toast.makeText(this, resId, Toast.LENGTH_SHORT).show());
917    }
918}