XmppActivity.java

   1package eu.siacs.conversations.ui;
   2
   3import android.telephony.TelephonyManager;
   4
   5import android.Manifest;
   6import android.annotation.SuppressLint;
   7import android.app.NotificationManager;
   8import android.app.PendingIntent;
   9import android.content.ActivityNotFoundException;
  10import android.content.ClipData;
  11import android.content.ClipboardManager;
  12import android.content.ComponentName;
  13import android.content.Context;
  14import android.content.ContextWrapper;
  15import android.content.DialogInterface;
  16import android.content.Intent;
  17import android.content.IntentSender.SendIntentException;
  18import android.content.ServiceConnection;
  19import android.content.SharedPreferences;
  20import android.content.pm.PackageManager;
  21import android.content.pm.ResolveInfo;
  22import android.content.res.Configuration;
  23import android.content.res.Resources;
  24import android.graphics.Bitmap;
  25import android.graphics.Point;
  26import android.graphics.drawable.AnimatedImageDrawable;
  27import android.graphics.drawable.BitmapDrawable;
  28import android.graphics.drawable.Drawable;
  29import android.net.ConnectivityManager;
  30import android.net.Uri;
  31import android.os.AsyncTask;
  32import android.os.Build;
  33import android.os.Bundle;
  34import android.os.Handler;
  35import android.os.IBinder;
  36import android.os.Looper;
  37import android.os.PowerManager;
  38import android.os.SystemClock;
  39import android.preference.PreferenceManager;
  40import android.provider.Settings;
  41import android.text.Editable;
  42import android.text.Html;
  43import android.text.InputType;
  44import android.text.Spannable;
  45import android.util.DisplayMetrics;
  46import android.util.Log;
  47import android.util.Pair;
  48import android.view.Menu;
  49import android.view.MenuItem;
  50import android.view.View;
  51import android.webkit.ValueCallback;
  52import android.widget.Button;
  53import android.widget.CheckBox;
  54import android.widget.ImageView;
  55import android.widget.Toast;
  56import androidx.annotation.BoolRes;
  57import androidx.annotation.NonNull;
  58import androidx.annotation.RequiresApi;
  59import androidx.annotation.StringRes;
  60import androidx.appcompat.app.AlertDialog;
  61import androidx.appcompat.app.AppCompatDelegate;
  62import androidx.core.content.pm.ShortcutInfoCompat;
  63import androidx.core.content.pm.ShortcutManagerCompat;
  64import androidx.databinding.DataBindingUtil;
  65import androidx.recyclerview.widget.RecyclerView.Adapter;
  66import com.google.android.material.color.MaterialColors;
  67import com.google.android.material.dialog.MaterialAlertDialogBuilder;
  68import com.google.common.base.Strings;
  69import com.google.common.collect.Collections2;
  70import com.google.common.collect.ImmutableSet;
  71
  72import com.cheogram.android.EmojiSearch;
  73
  74import com.otaliastudios.autocomplete.Autocomplete;
  75import com.otaliastudios.autocomplete.AutocompleteCallback;
  76import com.otaliastudios.autocomplete.AutocompletePolicy;
  77import com.otaliastudios.autocomplete.AutocompletePresenter;
  78import com.otaliastudios.autocomplete.RecyclerViewPresenter;
  79
  80import java.io.IOException;
  81import java.lang.ref.WeakReference;
  82import java.util.ArrayList;
  83import java.util.HashMap;
  84import java.util.List;
  85import java.util.PriorityQueue;
  86import java.util.concurrent.atomic.AtomicReference;
  87import java.util.concurrent.RejectedExecutionException;
  88
  89import eu.siacs.conversations.AppSettings;
  90import eu.siacs.conversations.BuildConfig;
  91import eu.siacs.conversations.Config;
  92import eu.siacs.conversations.R;
  93import eu.siacs.conversations.crypto.PgpEngine;
  94import eu.siacs.conversations.databinding.DialogAddReactionBinding;
  95import eu.siacs.conversations.databinding.DialogQuickeditBinding;
  96import eu.siacs.conversations.entities.Account;
  97import eu.siacs.conversations.entities.Contact;
  98import eu.siacs.conversations.entities.Conversation;
  99import eu.siacs.conversations.entities.Message;
 100import eu.siacs.conversations.entities.Presences;
 101import eu.siacs.conversations.entities.Reaction;
 102import eu.siacs.conversations.services.AvatarService;
 103import eu.siacs.conversations.services.BarcodeProvider;
 104import eu.siacs.conversations.services.NotificationService;
 105import eu.siacs.conversations.services.QuickConversationsService;
 106import eu.siacs.conversations.services.XmppConnectionService;
 107import eu.siacs.conversations.services.XmppConnectionService.XmppConnectionBinder;
 108import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
 109import eu.siacs.conversations.ui.util.PresenceSelector;
 110import eu.siacs.conversations.ui.util.SettingsUtils;
 111import eu.siacs.conversations.ui.util.SoftKeyboardUtils;
 112import eu.siacs.conversations.utils.AccountUtils;
 113import eu.siacs.conversations.utils.Compatibility;
 114import eu.siacs.conversations.utils.SignupUtils;
 115import eu.siacs.conversations.utils.ThemeHelper;
 116import eu.siacs.conversations.xmpp.Jid;
 117import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
 118import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
 119import java.io.IOException;
 120import java.lang.ref.WeakReference;
 121import java.util.ArrayList;
 122import java.util.Collection;
 123import java.util.List;
 124import java.util.concurrent.RejectedExecutionException;
 125import java.util.function.Consumer;
 126
 127public abstract class XmppActivity extends ActionBarActivity {
 128
 129    public static final String EXTRA_ACCOUNT = "account";
 130    protected static final int REQUEST_ANNOUNCE_PGP = 0x0101;
 131    protected static final int REQUEST_INVITE_TO_CONVERSATION = 0x0102;
 132    protected static final int REQUEST_CHOOSE_PGP_ID = 0x0103;
 133    protected static final int REQUEST_BATTERY_OP = 0x49ff;
 134    protected static final int REQUEST_POST_NOTIFICATION = 0x50ff;
 135    public XmppConnectionService xmppConnectionService;
 136    public boolean xmppConnectionServiceBound = false;
 137
 138    protected static final String FRAGMENT_TAG_DIALOG = "dialog";
 139
 140    private boolean isCameraFeatureAvailable = false;
 141
 142    protected int mTheme;
 143    protected HashMap<Integer,Integer> mCustomColors;
 144    protected boolean mUsingEnterKey = false;
 145    protected boolean mUseTor = false;
 146    protected Toast mToast;
 147    public Runnable onOpenPGPKeyPublished =
 148            () ->
 149                    Toast.makeText(
 150                                    XmppActivity.this,
 151                                    R.string.openpgp_has_been_published,
 152                                    Toast.LENGTH_SHORT)
 153                            .show();
 154    protected ConferenceInvite mPendingConferenceInvite = null;
 155    protected PriorityQueue<Pair<Integer, ValueCallback<Uri[]>>> activityCallbacks =
 156        Build.VERSION.SDK_INT >= 24 ? new PriorityQueue<>((x, y) -> y.first.compareTo(x.first)) : new PriorityQueue<>();
 157    protected ServiceConnection mConnection =
 158            new ServiceConnection() {
 159
 160                @Override
 161                public void onServiceConnected(ComponentName className, IBinder service) {
 162                    XmppConnectionBinder binder = (XmppConnectionBinder) service;
 163                    xmppConnectionService = binder.getService();
 164                    xmppConnectionServiceBound = true;
 165                    registerListeners();
 166                    onBackendConnected();
 167                }
 168
 169                @Override
 170                public void onServiceDisconnected(ComponentName arg0) {
 171                    xmppConnectionServiceBound = false;
 172                }
 173            };
 174    private DisplayMetrics metrics;
 175    private long mLastUiRefresh = 0;
 176    private final Handler mRefreshUiHandler = new Handler();
 177    private final Runnable mRefreshUiRunnable =
 178            () -> {
 179                mLastUiRefresh = SystemClock.elapsedRealtime();
 180                refreshUiReal();
 181            };
 182    private final UiCallback<Conversation> adhocCallback =
 183            new UiCallback<Conversation>() {
 184                @Override
 185                public void success(final Conversation conversation) {
 186                    runOnUiThread(
 187                            () -> {
 188                                switchToConversation(conversation);
 189                                hideToast();
 190                            });
 191                }
 192
 193                @Override
 194                public void error(final int errorCode, Conversation object) {
 195                    runOnUiThread(() -> replaceToast(getString(errorCode)));
 196                }
 197
 198                @Override
 199                public void userInputRequired(PendingIntent pi, Conversation object) {}
 200            };
 201
 202    public static boolean cancelPotentialWork(Message message, ImageView imageView) {
 203        final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
 204
 205        if (bitmapWorkerTask != null) {
 206            final Message oldMessage = bitmapWorkerTask.message;
 207            if (oldMessage == null || message != oldMessage) {
 208                bitmapWorkerTask.cancel(true);
 209            } else {
 210                return false;
 211            }
 212        }
 213        return true;
 214    }
 215
 216    private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
 217        if (imageView != null) {
 218            final Drawable drawable = imageView.getDrawable();
 219            if (drawable instanceof AsyncDrawable) {
 220                final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
 221                return asyncDrawable.getBitmapWorkerTask();
 222            }
 223        }
 224        return null;
 225    }
 226
 227    protected void hideToast() {
 228        final var toast = this.mToast;
 229        if (toast == null) {
 230            return;
 231        }
 232        toast.cancel();
 233    }
 234
 235    protected void replaceToast(String msg) {
 236        replaceToast(msg, true);
 237    }
 238
 239    protected void replaceToast(String msg, boolean showlong) {
 240        hideToast();
 241        mToast = Toast.makeText(this, msg, showlong ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT);
 242        mToast.show();
 243    }
 244
 245    public final void refreshUi() {
 246        final long diff = SystemClock.elapsedRealtime() - mLastUiRefresh;
 247        if (diff > Config.REFRESH_UI_INTERVAL) {
 248            mRefreshUiHandler.removeCallbacks(mRefreshUiRunnable);
 249            mRefreshUiHandler.postDelayed(mRefreshUiRunnable, 1);
 250        } else {
 251            final long next = Config.REFRESH_UI_INTERVAL - diff;
 252            mRefreshUiHandler.removeCallbacks(mRefreshUiRunnable);
 253            mRefreshUiHandler.postDelayed(mRefreshUiRunnable, next);
 254        }
 255    }
 256
 257    protected abstract void refreshUiReal();
 258
 259    @Override
 260    public void onStart() {
 261        super.onStart();
 262        if (!this.mCustomColors.equals(ThemeHelper.applyCustomColors(this))) {
 263            recreate();
 264        }
 265        if (!xmppConnectionServiceBound) {
 266            connectToBackend();
 267        } else {
 268            this.registerListeners();
 269            this.onBackendConnected();
 270        }
 271        this.mUsingEnterKey = usingEnterKey();
 272        this.mUseTor = useTor();
 273    }
 274
 275    public void connectToBackend() {
 276        Intent intent = new Intent(this, XmppConnectionService.class);
 277        intent.setAction("ui");
 278        try {
 279            startService(intent);
 280        } catch (IllegalStateException e) {
 281            Log.w(Config.LOGTAG, "unable to start service from " + getClass().getSimpleName());
 282        }
 283        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
 284    }
 285
 286    @Override
 287    protected void onStop() {
 288        super.onStop();
 289        if (xmppConnectionServiceBound) {
 290            this.unregisterListeners();
 291            unbindService(mConnection);
 292            xmppConnectionServiceBound = false;
 293        }
 294    }
 295
 296    @RequiresApi(api = Build.VERSION_CODES.R)
 297    protected void configureCustomNotification(final ShortcutInfoCompat shortcut) {
 298        final var notificationManager = getSystemService(NotificationManager.class);
 299        final var channel =
 300                notificationManager.getNotificationChannel(
 301                        NotificationService.MESSAGES_NOTIFICATION_CHANNEL, shortcut.getId());
 302        if (channel != null && channel.getConversationId() != null) {
 303            ShortcutManagerCompat.pushDynamicShortcut(this, shortcut);
 304            openNotificationSettings(shortcut);
 305        } else {
 306            NotificationService.createConversationChannel(this, shortcut);
 307            ShortcutManagerCompat.pushDynamicShortcut(this, shortcut);
 308            openNotificationSettings(shortcut);
 309        }
 310    }
 311
 312    @RequiresApi(api = Build.VERSION_CODES.R)
 313    protected void openNotificationSettings(final ShortcutInfoCompat shortcut) {
 314        final var intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);
 315        intent.putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName());
 316        intent.putExtra(
 317                Settings.EXTRA_CHANNEL_ID, NotificationService.MESSAGES_NOTIFICATION_CHANNEL);
 318        intent.putExtra(Settings.EXTRA_CONVERSATION_ID, shortcut.getId());
 319        startActivity(intent);
 320    }
 321
 322    public boolean hasPgp() {
 323        return xmppConnectionService.getPgpEngine() != null;
 324    }
 325
 326    public void showInstallPgpDialog() {
 327        final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
 328        builder.setTitle(getString(R.string.openkeychain_required));
 329        builder.setIconAttribute(android.R.attr.alertDialogIcon);
 330        builder.setMessage(
 331                Html.fromHtml(
 332                        getString(
 333                                R.string.openkeychain_required_long,
 334                                getString(R.string.app_name))));
 335        builder.setNegativeButton(getString(R.string.cancel), null);
 336        builder.setNeutralButton(
 337                getString(R.string.restart),
 338                (dialog, which) -> {
 339                    if (xmppConnectionServiceBound) {
 340                        unbindService(mConnection);
 341                        xmppConnectionServiceBound = false;
 342                    }
 343                    stopService(new Intent(XmppActivity.this, XmppConnectionService.class));
 344                    finish();
 345                });
 346        builder.setPositiveButton(
 347                getString(R.string.install),
 348                (dialog, which) -> {
 349                    final Uri uri =
 350                            Uri.parse("market://details?id=org.sufficientlysecure.keychain");
 351                    Intent marketIntent = new Intent(Intent.ACTION_VIEW, uri);
 352                    PackageManager manager = getApplicationContext().getPackageManager();
 353                    final var infos = manager.queryIntentActivities(marketIntent, 0);
 354                    if (infos.isEmpty()) {
 355                        final var website = Uri.parse("http://www.openkeychain.org/");
 356                        final Intent browserIntent = new Intent(Intent.ACTION_VIEW, website);
 357                        try {
 358                            startActivity(browserIntent);
 359                        } catch (final ActivityNotFoundException e) {
 360                            Toast.makeText(
 361                                            this,
 362                                            R.string.application_found_to_open_website,
 363                                            Toast.LENGTH_LONG)
 364                                    .show();
 365                        }
 366                    } else {
 367                        startActivity(marketIntent);
 368                    }
 369                    finish();
 370                });
 371        builder.create().show();
 372    }
 373
 374    public void addReaction(Consumer<EmojiSearch.Emoji> callback) {
 375        final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
 376        final var layoutInflater = this.getLayoutInflater();
 377        final DialogAddReactionBinding viewBinding =
 378                DataBindingUtil.inflate(layoutInflater, R.layout.dialog_add_reaction, null, false);
 379        builder.setView(viewBinding.getRoot());
 380        final var dialog = builder.create();
 381        for (final String emoji : Reaction.SUGGESTIONS) {
 382            final Button button =
 383                    (Button)
 384                            layoutInflater.inflate(
 385                                    R.layout.item_emoji_button, viewBinding.emojis, false);
 386            viewBinding.emojis.addView(button);
 387            button.setText(emoji);
 388            button.setOnClickListener(
 389                    v -> {
 390                        callback.accept(new EmojiSearch.Emoji(emoji, 0));
 391                        dialog.dismiss();
 392                    });
 393        }
 394
 395        final var emojiDebounce = new Handler(Looper.getMainLooper());
 396        final var emojiSearch = xmppConnectionService.emojiSearch();
 397        final var autocomplete = Autocomplete.<EmojiSearch.Emoji>on(viewBinding.search)
 398            .with(getDrawable(R.drawable.background_message_bubble))
 399            .with(new AutocompletePolicy() {
 400                @Override
 401                public boolean shouldShowPopup(@NonNull Spannable text, int cursorPos) { return true; }
 402
 403                @Override
 404                public boolean shouldDismissPopup(@NonNull Spannable text, int cursorPos) { return false; }
 405
 406                @Override
 407                public CharSequence getQuery(@NonNull Spannable text) { return text; }
 408
 409                @Override
 410                public void onDismiss(@NonNull Spannable text) { }
 411            })
 412            .with(new RecyclerViewPresenter<EmojiSearch.Emoji>(this) {
 413                protected EmojiSearch.EmojiSearchAdapter adapter;
 414
 415                @Override
 416                protected Adapter instantiateAdapter() {
 417                    adapter = emojiSearch.makeAdapter(item -> dispatchClick(item));
 418                    return adapter;
 419                }
 420
 421                @Override
 422                protected void onViewHidden() {
 423                    if (getRecyclerView() == null) return;
 424                    super.onViewHidden();
 425                }
 426
 427                @Override
 428                protected void onQuery(CharSequence query) {
 429                    emojiDebounce.removeCallbacksAndMessages(null);
 430                    emojiDebounce.postDelayed(() -> {
 431                        if (getRecyclerView() == null) return;
 432                        getRecyclerView().setItemAnimator(null);
 433                        adapter.search(XmppActivity.this, getRecyclerView(), query.toString());
 434                    }, 100L);
 435                }
 436            })
 437            .with(new AutocompleteCallback<EmojiSearch.Emoji>() {
 438                @Override
 439                public boolean onPopupItemClicked(Editable editable, EmojiSearch.Emoji emoji) {
 440                    callback.accept(emoji);
 441                    dialog.dismiss();
 442                    return true;
 443                }
 444
 445                @Override
 446                public void onPopupVisibilityChanged(boolean shown) {}
 447            }).build();
 448
 449        dialog.show();
 450        dialog.getWindow().getDecorView().post(() -> {
 451            autocomplete.showPopup("");
 452        });
 453    }
 454
 455    protected void deleteAccount(final Account account) {
 456        this.deleteAccount(account, null);
 457    }
 458
 459    protected void deleteAccount(final Account account, final Runnable postDelete) {
 460        final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
 461        final View dialogView = getLayoutInflater().inflate(R.layout.dialog_delete_account, null);
 462        final CheckBox deleteFromServer = dialogView.findViewById(R.id.delete_from_server);
 463        builder.setView(dialogView);
 464        builder.setTitle(R.string.mgmt_account_delete);
 465        builder.setPositiveButton(getString(R.string.delete), null);
 466        builder.setNegativeButton(getString(R.string.cancel), null);
 467        final AlertDialog dialog = builder.create();
 468        dialog.setOnShowListener(
 469                dialogInterface -> {
 470                    final Button button = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
 471                    button.setOnClickListener(
 472                            v -> {
 473                                final boolean unregister = deleteFromServer.isChecked();
 474                                if (unregister) {
 475                                    if (account.isOnlineAndConnected()) {
 476                                        deleteFromServer.setEnabled(false);
 477                                        button.setText(R.string.please_wait);
 478                                        button.setEnabled(false);
 479                                        xmppConnectionService.unregisterAccount(
 480                                                account,
 481                                                result -> {
 482                                                    runOnUiThread(
 483                                                            () -> {
 484                                                                if (result) {
 485                                                                    dialog.dismiss();
 486                                                                    if (postDelete != null) {
 487                                                                        postDelete.run();
 488                                                                    }
 489                                                                    if (xmppConnectionService
 490                                                                                            .getAccounts()
 491                                                                                            .size()
 492                                                                                    == 0
 493                                                                            && Config
 494                                                                                            .MAGIC_CREATE_DOMAIN
 495                                                                                    != null) {
 496                                                                        final Intent intent =
 497                                                                                SignupUtils
 498                                                                                        .getSignUpIntent(
 499                                                                                                this);
 500                                                                        intent.setFlags(
 501                                                                                Intent
 502                                                                                                .FLAG_ACTIVITY_NEW_TASK
 503                                                                                        | Intent
 504                                                                                                .FLAG_ACTIVITY_CLEAR_TASK);
 505                                                                        startActivity(intent);
 506                                                                    }
 507                                                                } else {
 508                                                                    deleteFromServer.setEnabled(
 509                                                                            true);
 510                                                                    button.setText(R.string.delete);
 511                                                                    button.setEnabled(true);
 512                                                                    Toast.makeText(
 513                                                                                    this,
 514                                                                                    R.string
 515                                                                                            .could_not_delete_account_from_server,
 516                                                                                    Toast
 517                                                                                            .LENGTH_LONG)
 518                                                                            .show();
 519                                                                }
 520                                                            });
 521                                                });
 522                                    } else {
 523                                        Toast.makeText(
 524                                                        this,
 525                                                        R.string.not_connected_try_again,
 526                                                        Toast.LENGTH_LONG)
 527                                                .show();
 528                                    }
 529                                } else {
 530                                    xmppConnectionService.deleteAccount(account);
 531                                    dialog.dismiss();
 532                                    if (xmppConnectionService.getAccounts().size() == 0
 533                                            && Config.MAGIC_CREATE_DOMAIN != null) {
 534                                        final Intent intent = SignupUtils.getSignUpIntent(this);
 535                                        intent.setFlags(
 536                                                Intent.FLAG_ACTIVITY_NEW_TASK
 537                                                        | Intent.FLAG_ACTIVITY_CLEAR_TASK);
 538                                        startActivity(intent);
 539                                    } else if (postDelete != null) {
 540                                        postDelete.run();
 541                                    }
 542                                }
 543                            });
 544                });
 545        dialog.show();
 546    }
 547
 548    protected abstract void onBackendConnected();
 549
 550    protected void registerListeners() {
 551        if (this instanceof XmppConnectionService.OnConversationUpdate) {
 552            this.xmppConnectionService.setOnConversationListChangedListener(
 553                    (XmppConnectionService.OnConversationUpdate) this);
 554        }
 555        if (this instanceof XmppConnectionService.OnAccountUpdate) {
 556            this.xmppConnectionService.setOnAccountListChangedListener(
 557                    (XmppConnectionService.OnAccountUpdate) this);
 558        }
 559        if (this instanceof XmppConnectionService.OnCaptchaRequested) {
 560            this.xmppConnectionService.setOnCaptchaRequestedListener(
 561                    (XmppConnectionService.OnCaptchaRequested) this);
 562        }
 563        if (this instanceof XmppConnectionService.OnRosterUpdate) {
 564            this.xmppConnectionService.setOnRosterUpdateListener(
 565                    (XmppConnectionService.OnRosterUpdate) this);
 566        }
 567        if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
 568            this.xmppConnectionService.setOnMucRosterUpdateListener(
 569                    (XmppConnectionService.OnMucRosterUpdate) this);
 570        }
 571        if (this instanceof OnUpdateBlocklist) {
 572            this.xmppConnectionService.setOnUpdateBlocklistListener((OnUpdateBlocklist) this);
 573        }
 574        if (this instanceof XmppConnectionService.OnShowErrorToast) {
 575            this.xmppConnectionService.setOnShowErrorToastListener(
 576                    (XmppConnectionService.OnShowErrorToast) this);
 577        }
 578        if (this instanceof OnKeyStatusUpdated) {
 579            this.xmppConnectionService.setOnKeyStatusUpdatedListener((OnKeyStatusUpdated) this);
 580        }
 581        if (this instanceof XmppConnectionService.OnJingleRtpConnectionUpdate) {
 582            this.xmppConnectionService.setOnRtpConnectionUpdateListener(
 583                    (XmppConnectionService.OnJingleRtpConnectionUpdate) this);
 584        }
 585    }
 586
 587    protected void unregisterListeners() {
 588        if (this instanceof XmppConnectionService.OnConversationUpdate) {
 589            this.xmppConnectionService.removeOnConversationListChangedListener(
 590                    (XmppConnectionService.OnConversationUpdate) this);
 591        }
 592        if (this instanceof XmppConnectionService.OnAccountUpdate) {
 593            this.xmppConnectionService.removeOnAccountListChangedListener(
 594                    (XmppConnectionService.OnAccountUpdate) this);
 595        }
 596        if (this instanceof XmppConnectionService.OnCaptchaRequested) {
 597            this.xmppConnectionService.removeOnCaptchaRequestedListener(
 598                    (XmppConnectionService.OnCaptchaRequested) this);
 599        }
 600        if (this instanceof XmppConnectionService.OnRosterUpdate) {
 601            this.xmppConnectionService.removeOnRosterUpdateListener(
 602                    (XmppConnectionService.OnRosterUpdate) this);
 603        }
 604        if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
 605            this.xmppConnectionService.removeOnMucRosterUpdateListener(
 606                    (XmppConnectionService.OnMucRosterUpdate) this);
 607        }
 608        if (this instanceof OnUpdateBlocklist) {
 609            this.xmppConnectionService.removeOnUpdateBlocklistListener((OnUpdateBlocklist) this);
 610        }
 611        if (this instanceof XmppConnectionService.OnShowErrorToast) {
 612            this.xmppConnectionService.removeOnShowErrorToastListener(
 613                    (XmppConnectionService.OnShowErrorToast) this);
 614        }
 615        if (this instanceof OnKeyStatusUpdated) {
 616            this.xmppConnectionService.removeOnNewKeysAvailableListener((OnKeyStatusUpdated) this);
 617        }
 618        if (this instanceof XmppConnectionService.OnJingleRtpConnectionUpdate) {
 619            this.xmppConnectionService.removeRtpConnectionUpdateListener(
 620                    (XmppConnectionService.OnJingleRtpConnectionUpdate) this);
 621        }
 622    }
 623
 624    @Override
 625    public boolean onOptionsItemSelected(final MenuItem item) {
 626        switch (item.getItemId()) {
 627            case R.id.action_settings:
 628                startActivity(
 629                        new Intent(
 630                                this, eu.siacs.conversations.ui.activity.SettingsActivity.class));
 631                break;
 632            case R.id.action_privacy_policy:
 633                openPrivacyPolicy();
 634                break;
 635            case R.id.action_accounts:
 636                AccountUtils.launchManageAccounts(this);
 637                break;
 638            case R.id.action_account:
 639                AccountUtils.launchManageAccount(this);
 640                break;
 641            case android.R.id.home:
 642                finish();
 643                break;
 644            case R.id.action_show_qr_code:
 645                showQrCode();
 646                break;
 647        }
 648        return super.onOptionsItemSelected(item);
 649    }
 650
 651    private void openPrivacyPolicy() {
 652        if (BuildConfig.PRIVACY_POLICY == null) {
 653            return;
 654        }
 655        final var viewPolicyIntent = new Intent(Intent.ACTION_VIEW);
 656        viewPolicyIntent.setData(Uri.parse(BuildConfig.PRIVACY_POLICY));
 657        try {
 658            startActivity(viewPolicyIntent);
 659        } catch (final ActivityNotFoundException e) {
 660            Toast.makeText(this, R.string.no_application_found_to_open_link, Toast.LENGTH_SHORT)
 661                    .show();
 662        }
 663    }
 664
 665    public void selectPresence(
 666            final Conversation conversation, final PresenceSelector.OnPresenceSelected listener) {
 667        final Contact contact = conversation.getContact();
 668        if (contact.showInRoster() || contact.isSelf()) {
 669            final Presences presences = contact.getPresences();
 670            if (presences.size() == 0) {
 671                if (contact.isSelf()) {
 672                    conversation.setNextCounterpart(null);
 673                    listener.onPresenceSelected();
 674                } else if (!contact.getOption(Contact.Options.TO)
 675                        && !contact.getOption(Contact.Options.ASKING)
 676                        && contact.getAccount().getStatus() == Account.State.ONLINE) {
 677                    showAskForPresenceDialog(contact);
 678                } else if (!contact.getOption(Contact.Options.TO)
 679                        || !contact.getOption(Contact.Options.FROM)) {
 680                    PresenceSelector.warnMutualPresenceSubscription(this, conversation, listener);
 681                } else {
 682                    conversation.setNextCounterpart(null);
 683                    listener.onPresenceSelected();
 684                }
 685            } else if (presences.size() == 1) {
 686                final String presence = presences.toResourceArray()[0];
 687                conversation.setNextCounterpart(
 688                        PresenceSelector.getNextCounterpart(contact, presence));
 689                listener.onPresenceSelected();
 690            } else {
 691                PresenceSelector.showPresenceSelectionDialog(this, conversation, listener);
 692            }
 693        } else {
 694            showAddToRosterDialog(conversation.getContact());
 695        }
 696    }
 697
 698    @SuppressLint("UnsupportedChromeOsCameraSystemFeature")
 699    @Override
 700    protected void onCreate(Bundle savedInstanceState) {
 701        super.onCreate(savedInstanceState);
 702        metrics = getResources().getDisplayMetrics();
 703        this.isCameraFeatureAvailable =
 704                getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
 705        this.mCustomColors = ThemeHelper.applyCustomColors(this);
 706    }
 707
 708    protected boolean isCameraFeatureAvailable() {
 709        return this.isCameraFeatureAvailable;
 710    }
 711
 712    protected boolean isOptimizingBattery() {
 713        final PowerManager pm = getSystemService(PowerManager.class);
 714        return !pm.isIgnoringBatteryOptimizations(getPackageName());
 715    }
 716
 717    protected boolean isAffectedByDataSaver() {
 718        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
 719            final ConnectivityManager cm =
 720                    (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
 721            return cm != null
 722                    && cm.isActiveNetworkMetered()
 723                    && Compatibility.getRestrictBackgroundStatus(cm)
 724                            == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
 725        } else {
 726            return false;
 727        }
 728    }
 729
 730    private boolean usingEnterKey() {
 731        return getBooleanPreference("display_enter_key", R.bool.display_enter_key);
 732    }
 733
 734    private boolean useTor() {
 735        return getBooleanPreference("use_tor", R.bool.use_tor);
 736    }
 737
 738    protected SharedPreferences getPreferences() {
 739        return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
 740    }
 741
 742    protected boolean getBooleanPreference(String name, @BoolRes int res) {
 743        return getPreferences().getBoolean(name, getResources().getBoolean(res));
 744    }
 745
 746    public void startCommand(final Account account, final Jid jid, final String node) {
 747        Intent intent = new Intent(this, ConversationsActivity.class);
 748        intent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
 749        intent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, xmppConnectionService.findOrCreateConversation(account, jid, false, false).getUuid());
 750        intent.putExtra(ConversationsActivity.EXTRA_POST_INIT_ACTION, "command");
 751        intent.putExtra(ConversationsActivity.EXTRA_NODE, node);
 752        intent.putExtra(ConversationsActivity.EXTRA_JID, (CharSequence) jid);
 753        intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_CLEAR_TOP);
 754        startActivity(intent);
 755    }
 756
 757    public boolean colorCodeAccounts() {
 758        return xmppConnectionService.getAccounts().size() > 1;
 759    }
 760
 761    public void populateWithOrderedConversations(List<Conversation> list) {
 762        xmppConnectionService.populateWithOrderedConversations(list);
 763    }
 764
 765    public void launchStartConversation() {
 766        StartConversationActivity.launch(this);
 767    }
 768
 769    public void switchToConversation(Conversation conversation) {
 770        switchToConversation(conversation, null);
 771    }
 772
 773    public void switchToConversationAndQuote(Conversation conversation, String text) {
 774        switchToConversation(conversation, text, true, null, false, false);
 775    }
 776
 777    public void switchToConversation(Conversation conversation, String text) {
 778        switchToConversation(conversation, text, false, null, false, false);
 779    }
 780
 781    public void switchToConversationDoNotAppend(Conversation conversation, String text) {
 782        switchToConversation(conversation, text, false, null, false, true);
 783    }
 784
 785    public void highlightInMuc(Conversation conversation, String nick) {
 786        switchToConversation(conversation, null, false, nick, false, false);
 787    }
 788
 789    public void privateMsgInMuc(Conversation conversation, String nick) {
 790        switchToConversation(conversation, null, false, nick, true, false);
 791    }
 792
 793    public void switchToConversation(Conversation conversation, String text, boolean asQuote, String nick, boolean pm, boolean doNotAppend) {
 794        switchToConversation(conversation, text, asQuote, nick, pm, doNotAppend, null);
 795    }
 796
 797    public void switchToConversation(Conversation conversation, String text, boolean asQuote, String nick, boolean pm, boolean doNotAppend, String postInit) {
 798        switchToConversation(conversation, text, asQuote, nick, pm, doNotAppend, postInit, null);
 799    }
 800
 801    public void switchToConversation(
 802            Conversation conversation,
 803            String text,
 804            boolean asQuote,
 805            String nick,
 806            boolean pm,
 807            boolean doNotAppend,
 808            String postInit,
 809            String thread) {
 810        if (conversation == null) return;
 811        Intent intent = new Intent(this, ConversationsActivity.class);
 812        intent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
 813        intent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversation.getUuid());
 814        intent.putExtra(ConversationsActivity.EXTRA_THREAD, thread);
 815        if (text != null) {
 816            intent.putExtra(Intent.EXTRA_TEXT, text);
 817            if (asQuote) {
 818                intent.putExtra(ConversationsActivity.EXTRA_AS_QUOTE, true);
 819            }
 820        }
 821        if (nick != null) {
 822            intent.putExtra(ConversationsActivity.EXTRA_NICK, nick);
 823            intent.putExtra(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, pm);
 824        }
 825        if (doNotAppend) {
 826            intent.putExtra(ConversationsActivity.EXTRA_DO_NOT_APPEND, true);
 827        }
 828        intent.putExtra(ConversationsActivity.EXTRA_POST_INIT_ACTION, postInit);
 829        intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_CLEAR_TOP);
 830        startActivity(intent);
 831        finish();
 832    }
 833
 834    public void switchToContactDetails(Contact contact) {
 835        switchToContactDetails(contact, null);
 836    }
 837
 838    public void switchToContactDetails(Contact contact, String messageFingerprint) {
 839        Intent intent = new Intent(this, ContactDetailsActivity.class);
 840        intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT);
 841        intent.putExtra(EXTRA_ACCOUNT, contact.getAccount().getJid().asBareJid().toEscapedString());
 842        intent.putExtra("contact", contact.getJid().toEscapedString());
 843        intent.putExtra("fingerprint", messageFingerprint);
 844        startActivity(intent);
 845    }
 846
 847    public void switchToAccount(Account account, String fingerprint) {
 848        switchToAccount(account, false, fingerprint);
 849    }
 850
 851    public void switchToAccount(Account account) {
 852        switchToAccount(account, false, null);
 853    }
 854
 855    public void switchToAccount(Account account, boolean init, String fingerprint) {
 856        Intent intent = new Intent(this, EditAccountActivity.class);
 857        intent.putExtra("jid", account.getJid().asBareJid().toEscapedString());
 858        intent.putExtra("init", init);
 859        if (init) {
 860            intent.setFlags(
 861                    Intent.FLAG_ACTIVITY_NEW_TASK
 862                            | Intent.FLAG_ACTIVITY_CLEAR_TASK
 863                            | Intent.FLAG_ACTIVITY_NO_ANIMATION);
 864        }
 865        if (fingerprint != null) {
 866            intent.putExtra("fingerprint", fingerprint);
 867        }
 868        startActivity(intent);
 869        if (init) {
 870            overridePendingTransition(0, 0);
 871        }
 872    }
 873
 874    protected void delegateUriPermissionsToService(Uri uri) {
 875        Intent intent = new Intent(this, XmppConnectionService.class);
 876        intent.setAction(Intent.ACTION_SEND);
 877        intent.setData(uri);
 878        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
 879        try {
 880            startService(intent);
 881        } catch (Exception e) {
 882            Log.e(Config.LOGTAG, "unable to delegate uri permission", e);
 883        }
 884    }
 885
 886    protected void inviteToConversation(Conversation conversation) {
 887        startActivityForResult(
 888                ChooseContactActivity.create(this, conversation), REQUEST_INVITE_TO_CONVERSATION);
 889    }
 890
 891    protected void announcePgp(
 892            final Account account,
 893            final Conversation conversation,
 894            Intent intent,
 895            final Runnable onSuccess) {
 896        if (account.getPgpId() == 0) {
 897            choosePgpSignId(account);
 898        } else {
 899            final String status = Strings.nullToEmpty(account.getPresenceStatusMessage());
 900            xmppConnectionService
 901                    .getPgpEngine()
 902                    .generateSignature(
 903                            intent,
 904                            account,
 905                            status,
 906                            new UiCallback<String>() {
 907
 908                                @Override
 909                                public void userInputRequired(
 910                                        final PendingIntent pi, final String signature) {
 911                                    try {
 912                                        startIntentSenderForResult(
 913                                                pi.getIntentSender(),
 914                                                REQUEST_ANNOUNCE_PGP,
 915                                                null,
 916                                                0,
 917                                                0,
 918                                                0,
 919                                                Compatibility.pgpStartIntentSenderOptions());
 920                                    } catch (final SendIntentException ignored) {
 921                                    }
 922                                }
 923
 924                                @Override
 925                                public void success(String signature) {
 926                                    account.setPgpSignature(signature);
 927                                    xmppConnectionService.databaseBackend.updateAccount(account);
 928                                    xmppConnectionService.sendPresence(account);
 929                                    if (conversation != null) {
 930                                        conversation.setNextEncryption(Message.ENCRYPTION_PGP);
 931                                        xmppConnectionService.updateConversation(conversation);
 932                                        refreshUi();
 933                                    }
 934                                    if (onSuccess != null) {
 935                                        runOnUiThread(onSuccess);
 936                                    }
 937                                }
 938
 939                                @Override
 940                                public void error(int error, String signature) {
 941                                    if (error == 0) {
 942                                        account.setPgpSignId(0);
 943                                        account.unsetPgpSignature();
 944                                        xmppConnectionService.databaseBackend.updateAccount(
 945                                                account);
 946                                        choosePgpSignId(account);
 947                                    } else {
 948                                        displayErrorDialog(error);
 949                                    }
 950                                }
 951                            });
 952        }
 953    }
 954
 955    protected void choosePgpSignId(final Account account) {
 956        xmppConnectionService
 957                .getPgpEngine()
 958                .chooseKey(
 959                        account,
 960                        new UiCallback<>() {
 961                            @Override
 962                            public void success(final Account a) {}
 963
 964                            @Override
 965                            public void error(int errorCode, Account object) {}
 966
 967                            @Override
 968                            public void userInputRequired(PendingIntent pi, Account object) {
 969                                try {
 970                                    startIntentSenderForResult(
 971                                            pi.getIntentSender(),
 972                                            REQUEST_CHOOSE_PGP_ID,
 973                                            null,
 974                                            0,
 975                                            0,
 976                                            0,
 977                                            Compatibility.pgpStartIntentSenderOptions());
 978                                } catch (final SendIntentException ignored) {
 979                                }
 980                            }
 981                        });
 982    }
 983
 984    protected void displayErrorDialog(final int errorCode) {
 985        runOnUiThread(
 986                () -> {
 987                    final MaterialAlertDialogBuilder builder =
 988                            new MaterialAlertDialogBuilder(XmppActivity.this);
 989                    builder.setTitle(getString(R.string.error));
 990                    builder.setMessage(errorCode);
 991                    builder.setNeutralButton(R.string.accept, null);
 992                    builder.create().show();
 993                });
 994    }
 995
 996    protected void showAddToRosterDialog(final Contact contact) {
 997        final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
 998        builder.setTitle(contact.getJid().toString());
 999        builder.setMessage(getString(R.string.not_in_roster));
1000        builder.setNegativeButton(getString(R.string.cancel), null);
1001        builder.setPositiveButton(getString(R.string.add_contact), (dialog, which) -> {
1002            contact.copySystemTagsToGroups();
1003            xmppConnectionService.createContact(contact, true);
1004        });
1005        builder.create().show();
1006    }
1007
1008    private void showAskForPresenceDialog(final Contact contact) {
1009        final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
1010        builder.setTitle(contact.getJid().toString());
1011        builder.setMessage(R.string.request_presence_updates);
1012        builder.setNegativeButton(R.string.cancel, null);
1013        builder.setPositiveButton(
1014                R.string.request_now,
1015                (dialog, which) -> {
1016                    if (xmppConnectionServiceBound) {
1017                        xmppConnectionService.sendPresencePacket(
1018                                contact.getAccount(),
1019                                xmppConnectionService
1020                                        .getPresenceGenerator()
1021                                        .requestPresenceUpdatesFrom(contact));
1022                    }
1023                });
1024        builder.create().show();
1025    }
1026
1027    protected void quickEdit(String previousValue, @StringRes int hint, OnValueEdited callback) {
1028        quickEdit(previousValue, callback, hint, false, false);
1029    }
1030
1031    protected void quickEdit(
1032            String previousValue,
1033            @StringRes int hint,
1034            OnValueEdited callback,
1035            boolean permitEmpty) {
1036        quickEdit(previousValue, callback, hint, false, permitEmpty);
1037    }
1038
1039    protected void quickPasswordEdit(String previousValue, OnValueEdited callback) {
1040        quickEdit(previousValue, callback, R.string.password, true, false);
1041    }
1042
1043    protected void quickEdit(final String previousValue, final OnValueEdited callback, final @StringRes int hint, boolean password, boolean permitEmpty) {
1044        quickEdit(previousValue, callback, hint, password, permitEmpty, false);
1045    }
1046
1047    protected void quickEdit(final String previousValue, final OnValueEdited callback, final @StringRes int hint, boolean password, boolean permitEmpty, boolean alwaysCallback) {
1048        quickEdit(previousValue, callback, hint, password, permitEmpty, alwaysCallback, false);
1049    }
1050
1051    @SuppressLint("InflateParams")
1052    protected void quickEdit(final String previousValue,
1053                           final OnValueEdited callback,
1054                           final @StringRes int hint,
1055                           boolean password,
1056                           boolean permitEmpty,
1057                           boolean alwaysCallback,
1058                           boolean startSelected) {
1059        final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
1060        final DialogQuickeditBinding binding =
1061                DataBindingUtil.inflate(
1062                        getLayoutInflater(), R.layout.dialog_quickedit, null, false);
1063        if (password) {
1064            binding.inputEditText.setInputType(
1065                    InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
1066        }
1067        builder.setPositiveButton(R.string.accept, null);
1068        if (hint != 0) {
1069            binding.inputLayout.setHint(getString(hint));
1070        }
1071        binding.inputEditText.requestFocus();
1072        if (previousValue != null) {
1073            binding.inputEditText.getText().append(previousValue);
1074        }
1075        builder.setView(binding.getRoot());
1076        builder.setNegativeButton(R.string.cancel, null);
1077        final AlertDialog dialog = builder.create();
1078        dialog.setOnShowListener(d -> SoftKeyboardUtils.showKeyboard(binding.inputEditText));
1079        dialog.show();
1080        if (startSelected) {
1081            binding.inputEditText.selectAll();
1082        }
1083        View.OnClickListener clickListener =
1084                v -> {
1085                    String value = binding.inputEditText.getText().toString();
1086                    if ((alwaysCallback || !value.equals(previousValue)) && (!value.trim().isEmpty() || permitEmpty)) {
1087                        String error = callback.onValueEdited(value);
1088                        if (error != null) {
1089                            binding.inputLayout.setError(error);
1090                            return;
1091                        }
1092                    }
1093                    SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
1094                    dialog.dismiss();
1095                };
1096        dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(clickListener);
1097        dialog.getButton(DialogInterface.BUTTON_NEGATIVE)
1098                .setOnClickListener(
1099                        (v -> {
1100                            SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
1101                            dialog.dismiss();
1102                        }));
1103        dialog.setCanceledOnTouchOutside(false);
1104        dialog.setOnDismissListener(
1105                dialog1 -> {
1106                    SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
1107                });
1108    }
1109
1110    protected boolean hasStoragePermission(int requestCode) {
1111        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
1112            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
1113                    != PackageManager.PERMISSION_GRANTED) {
1114                requestPermissions(
1115                        new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
1116                return false;
1117            } else {
1118                return true;
1119            }
1120        } else {
1121            return true;
1122        }
1123    }
1124
1125    public synchronized void startActivityWithCallback(Intent intent, ValueCallback<Uri[]> cb) {
1126        Pair<Integer, ValueCallback<Uri[]>> peek = activityCallbacks.peek();
1127        int index = peek == null ? 1 : peek.first + 1;
1128        activityCallbacks.add(new Pair<>(index, cb));
1129        startActivityForResult(intent, index);
1130    }
1131
1132    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
1133        super.onActivityResult(requestCode, resultCode, data);
1134        if (requestCode == REQUEST_INVITE_TO_CONVERSATION && resultCode == RESULT_OK) {
1135            mPendingConferenceInvite = ConferenceInvite.parse(data);
1136            if (xmppConnectionServiceBound && mPendingConferenceInvite != null) {
1137                if (mPendingConferenceInvite.execute(this)) {
1138                    mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
1139                    mToast.show();
1140                }
1141                mPendingConferenceInvite = null;
1142            }
1143        } else if (resultCode == RESULT_OK) {
1144            for (Pair<Integer, ValueCallback<Uri[]>> cb : new ArrayList<>(activityCallbacks)) {
1145                if (cb.first == requestCode) {
1146                    activityCallbacks.remove(cb);
1147                    ArrayList<Uri> dataUris = new ArrayList<>();
1148                    if (data.getDataString() != null) {
1149                        dataUris.add(Uri.parse(data.getDataString()));
1150                    } else if (data.getClipData() != null) {
1151                        for (int i = 0; i < data.getClipData().getItemCount(); i++) {
1152                            dataUris.add(data.getClipData().getItemAt(i).getUri());
1153                        }
1154                    }
1155                    cb.second.onReceiveValue(dataUris.toArray(new Uri[0]));
1156                }
1157            }
1158        }
1159    }
1160
1161    public boolean copyTextToClipboard(String text, int labelResId) {
1162        ClipboardManager mClipBoardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
1163        String label = getResources().getString(labelResId);
1164        if (mClipBoardManager != null) {
1165            ClipData mClipData = ClipData.newPlainText(label, text);
1166            mClipBoardManager.setPrimaryClip(mClipData);
1167            return true;
1168        }
1169        return false;
1170    }
1171
1172    protected boolean manuallyChangePresence() {
1173        return getBooleanPreference(
1174                AppSettings.MANUALLY_CHANGE_PRESENCE, R.bool.manually_change_presence);
1175    }
1176
1177    protected String getShareableUri() {
1178        return getShareableUri(false);
1179    }
1180
1181    protected String getShareableUri(boolean http) {
1182        return null;
1183    }
1184
1185    protected void shareLink(boolean http) {
1186        String uri = getShareableUri(http);
1187        if (uri == null || uri.isEmpty()) {
1188            return;
1189        }
1190        Intent intent = new Intent(Intent.ACTION_SEND);
1191        intent.setType("text/plain");
1192        intent.putExtra(Intent.EXTRA_TEXT, getShareableUri(http));
1193        try {
1194            startActivity(Intent.createChooser(intent, getText(R.string.share_uri_with)));
1195        } catch (ActivityNotFoundException e) {
1196            Toast.makeText(this, R.string.no_application_to_share_uri, Toast.LENGTH_SHORT).show();
1197        }
1198    }
1199
1200    protected void launchOpenKeyChain(long keyId) {
1201        PgpEngine pgp = XmppActivity.this.xmppConnectionService.getPgpEngine();
1202        try {
1203            startIntentSenderForResult(
1204                    pgp.getIntentForKey(keyId).getIntentSender(),
1205                    0,
1206                    null,
1207                    0,
1208                    0,
1209                    0,
1210                    Compatibility.pgpStartIntentSenderOptions());
1211        } catch (final Throwable e) {
1212            Log.d(Config.LOGTAG, "could not launch OpenKeyChain", e);
1213            Toast.makeText(XmppActivity.this, R.string.openpgp_error, Toast.LENGTH_SHORT).show();
1214        }
1215    }
1216
1217    @Override
1218    protected void onResume() {
1219        super.onResume();
1220        SettingsUtils.applyScreenshotSetting(this);
1221    }
1222
1223    @Override
1224    public void onPause() {
1225        super.onPause();
1226    }
1227
1228    @Override
1229    public boolean onMenuOpened(int id, Menu menu) {
1230        if (id == AppCompatDelegate.FEATURE_SUPPORT_ACTION_BAR && menu != null) {
1231            MenuDoubleTabUtil.recordMenuOpen();
1232        }
1233        return super.onMenuOpened(id, menu);
1234    }
1235
1236    protected void showQrCode() {
1237        final var uri = getShareableUri();
1238        if (uri != null) {
1239            showQrCode(uri);
1240            return;
1241        }
1242
1243        final var accounts = xmppConnectionService.getAccounts();
1244        if (accounts.size() < 1) return;
1245
1246        if (accounts.size() == 1) {
1247            showQrCode(accounts.get(0).getShareableUri());
1248            return;
1249        }
1250
1251        final AtomicReference<Account> selectedAccount = new AtomicReference<>(accounts.get(0));
1252        final MaterialAlertDialogBuilder alertDialogBuilder = new MaterialAlertDialogBuilder(this);
1253        alertDialogBuilder.setTitle(R.string.choose_account);
1254        final String[] asStrings = Collections2.transform(accounts, a -> a.getJid().asBareJid().toEscapedString()).toArray(new String[0]);
1255        alertDialogBuilder.setSingleChoiceItems(asStrings, 0, (dialog, which) -> selectedAccount.set(accounts.get(which)));
1256        alertDialogBuilder.setNegativeButton(R.string.cancel, null);
1257        alertDialogBuilder.setPositiveButton(R.string.ok, (dialog, which) -> showQrCode(selectedAccount.get().getShareableUri()));
1258        alertDialogBuilder.create().show();
1259    }
1260
1261    protected void showQrCode(final String uri) {
1262        if (uri == null || uri.isEmpty()) {
1263            return;
1264        }
1265        final Point size = new Point();
1266        getWindowManager().getDefaultDisplay().getSize(size);
1267        final int width = Math.min(size.x, size.y);
1268        final int black;
1269        final int white;
1270        if (Activities.isNightMode(this)) {
1271            black =
1272                    MaterialColors.getColor(
1273                            this,
1274                            com.google.android.material.R.attr.colorSurfaceContainerHighest,
1275                            "No surface color configured");
1276            white =
1277                    MaterialColors.getColor(
1278                            this,
1279                            com.google.android.material.R.attr.colorSurfaceInverse,
1280                            "No inverse surface color configured");
1281        } else {
1282            black =
1283                    MaterialColors.getColor(
1284                            this,
1285                            com.google.android.material.R.attr.colorSurfaceInverse,
1286                            "No inverse surface color configured");
1287            white =
1288                    MaterialColors.getColor(
1289                            this,
1290                            com.google.android.material.R.attr.colorSurfaceContainerHighest,
1291                            "No surface color configured");
1292        }
1293        final var bitmap = BarcodeProvider.create2dBarcodeBitmap(uri, width, black, white);
1294        final ImageView view = new ImageView(this);
1295        view.setBackgroundColor(white);
1296        view.setImageBitmap(bitmap);
1297        MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
1298        builder.setView(view);
1299        builder.create().show();
1300    }
1301
1302    protected Account extractAccount(Intent intent) {
1303        final String jid = intent != null ? intent.getStringExtra(EXTRA_ACCOUNT) : null;
1304        try {
1305            return jid != null ? xmppConnectionService.findAccountByJid(Jid.ofEscaped(jid)) : null;
1306        } catch (IllegalArgumentException e) {
1307            return null;
1308        }
1309    }
1310
1311    public AvatarService avatarService() {
1312        return xmppConnectionService.getAvatarService();
1313    }
1314
1315    public void loadBitmap(Message message, ImageView imageView) {
1316        Drawable bm;
1317        try {
1318            bm =
1319                    xmppConnectionService
1320                            .getFileBackend()
1321                            .getThumbnail(message, getResources(), (int) (metrics.density * 288), true);
1322        } catch (IOException e) {
1323            bm = null;
1324        }
1325        if (bm != null) {
1326            cancelPotentialWork(message, imageView);
1327            imageView.setImageDrawable(bm);
1328            imageView.setBackgroundColor(0x00000000);
1329            if (Build.VERSION.SDK_INT >= 28 && bm instanceof AnimatedImageDrawable) {
1330                ((AnimatedImageDrawable) bm).start();
1331            }
1332        } else {
1333            if (cancelPotentialWork(message, imageView)) {
1334                final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
1335                final BitmapDrawable fallbackThumb = xmppConnectionService.getFileBackend().getFallbackThumbnail(message, (int) (metrics.density * 288), true);
1336                imageView.setBackgroundColor(fallbackThumb == null ? 0xff333333 : 0x00000000);
1337                final AsyncDrawable asyncDrawable = new AsyncDrawable(
1338                        getResources(), fallbackThumb != null ? fallbackThumb.getBitmap() : null, task);
1339                imageView.setImageDrawable(asyncDrawable);
1340                try {
1341                    task.execute(message);
1342                } catch (final RejectedExecutionException ignored) {
1343                    ignored.printStackTrace();
1344                }
1345            }
1346        }
1347    }
1348
1349    protected interface OnValueEdited {
1350        String onValueEdited(String value);
1351    }
1352
1353    public static class ConferenceInvite {
1354        private String uuid;
1355        private final List<Jid> jids = new ArrayList<>();
1356
1357        public static ConferenceInvite parse(Intent data) {
1358            ConferenceInvite invite = new ConferenceInvite();
1359            invite.uuid = data.getStringExtra(ChooseContactActivity.EXTRA_CONVERSATION);
1360            if (invite.uuid == null) {
1361                return null;
1362            }
1363            invite.jids.addAll(ChooseContactActivity.extractJabberIds(data));
1364            return invite;
1365        }
1366
1367        public boolean execute(XmppActivity activity) {
1368            XmppConnectionService service = activity.xmppConnectionService;
1369            Conversation conversation = service.findConversationByUuid(this.uuid);
1370            if (conversation == null) {
1371                return false;
1372            }
1373            if (conversation.getMode() == Conversation.MODE_MULTI) {
1374                for (Jid jid : jids) {
1375                    service.invite(conversation, jid);
1376                }
1377                return false;
1378            } else {
1379                jids.add(conversation.getJid().asBareJid());
1380                return service.createAdhocConference(
1381                        conversation.getAccount(), null, jids, activity.adhocCallback);
1382            }
1383        }
1384    }
1385
1386    static class BitmapWorkerTask extends AsyncTask<Message, Void, Drawable> {
1387        private final WeakReference<ImageView> imageViewReference;
1388        private Message message = null;
1389
1390        private BitmapWorkerTask(ImageView imageView) {
1391            this.imageViewReference = new WeakReference<>(imageView);
1392        }
1393
1394        @Override
1395        protected Drawable doInBackground(Message... params) {
1396            if (isCancelled()) {
1397                return null;
1398            }
1399            final XmppActivity activity = find(imageViewReference);
1400            Drawable d = null;
1401            message = params[0];
1402            try {
1403                if (activity != null && activity.xmppConnectionService != null) {
1404                    d = activity.xmppConnectionService.getFileBackend().getThumbnail(message, imageViewReference.get().getContext().getResources(), (int) (activity.metrics.density * 288), false);
1405                }
1406            } catch (IOException e) { e.printStackTrace(); }
1407            final ImageView imageView = imageViewReference.get();
1408            if (d == null && activity != null && activity.xmppConnectionService != null && imageView != null && imageView.getDrawable() instanceof AsyncDrawable && ((AsyncDrawable) imageView.getDrawable()).getBitmap() == null) {
1409                d = activity.xmppConnectionService.getFileBackend().getFallbackThumbnail(message, (int) (activity.metrics.density * 288), false);
1410            }
1411            return d;
1412        }
1413
1414        @Override
1415        protected void onPostExecute(final Drawable drawable) {
1416            if (!isCancelled()) {
1417                final ImageView imageView = imageViewReference.get();
1418                if (imageView != null) {
1419                    Drawable old = imageView.getDrawable();
1420                    if (old instanceof AsyncDrawable) {
1421                        ((AsyncDrawable) old).clearTask();
1422                    }
1423                    if (drawable != null) {
1424                        imageView.setImageDrawable(drawable);
1425                    }
1426                    imageView.setBackgroundColor(drawable == null ? 0xff333333 : 0x00000000);
1427                    if (Build.VERSION.SDK_INT >= 28 && drawable instanceof AnimatedImageDrawable) {
1428                        ((AnimatedImageDrawable) drawable).start();
1429                    }
1430                }
1431            }
1432        }
1433    }
1434
1435    private static class AsyncDrawable extends BitmapDrawable {
1436        private WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
1437
1438        private AsyncDrawable(Resources res, Bitmap bitmap, BitmapWorkerTask bitmapWorkerTask) {
1439            super(res, bitmap);
1440            bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
1441        }
1442
1443        private synchronized BitmapWorkerTask getBitmapWorkerTask() {
1444            if (bitmapWorkerTaskReference == null) return null;
1445
1446            return bitmapWorkerTaskReference.get();
1447        }
1448
1449        public synchronized void clearTask() {
1450            bitmapWorkerTaskReference = null;
1451        }
1452    }
1453
1454    public static XmppActivity find(@NonNull WeakReference<ImageView> viewWeakReference) {
1455        final View view = viewWeakReference.get();
1456        return view == null ? null : find(view);
1457    }
1458
1459    public static XmppActivity find(@NonNull final View view) {
1460        Context context = view.getContext();
1461        while (context instanceof ContextWrapper) {
1462            if (context instanceof XmppActivity) {
1463                return (XmppActivity) context;
1464            }
1465            context = ((ContextWrapper) context).getBaseContext();
1466        }
1467        return null;
1468    }
1469
1470    public boolean isDark() {
1471        int nightModeFlags = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
1472        return nightModeFlags == Configuration.UI_MODE_NIGHT_YES;
1473    }
1474}