ConversationsActivity.java

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