XmppActivity.java

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