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