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        final PowerManager pm = getSystemService(PowerManager.class);
 520        return !pm.isIgnoringBatteryOptimizations(getPackageName());
 521}
 522
 523    protected boolean isAffectedByDataSaver() {
 524        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
 525            final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
 526            return cm != null
 527                    && cm.isActiveNetworkMetered()
 528                    && Compatibility.getRestrictBackgroundStatus(cm) == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
 529        } else {
 530            return false;
 531        }
 532    }
 533
 534    private boolean usingEnterKey() {
 535        return getBooleanPreference("display_enter_key", R.bool.display_enter_key);
 536    }
 537
 538    private boolean useTor() {
 539        return getBooleanPreference("use_tor", R.bool.use_tor);
 540    }
 541
 542    protected SharedPreferences getPreferences() {
 543        return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
 544    }
 545
 546    protected boolean getBooleanPreference(String name, @BoolRes int res) {
 547        return getPreferences().getBoolean(name, getResources().getBoolean(res));
 548    }
 549
 550    public void startCommand(final Account account, final Jid jid, final String node) {
 551        Intent intent = new Intent(this, ConversationsActivity.class);
 552        intent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
 553        intent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, xmppConnectionService.findOrCreateConversation(account, jid, false, false).getUuid());
 554        intent.putExtra(ConversationsActivity.EXTRA_POST_INIT_ACTION, "command");
 555        intent.putExtra(ConversationsActivity.EXTRA_NODE, node);
 556        intent.putExtra(ConversationsActivity.EXTRA_JID, (CharSequence) jid);
 557        intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_CLEAR_TOP);
 558        startActivity(intent);
 559    }
 560
 561    public void switchToConversation(Conversation conversation) {
 562        switchToConversation(conversation, null);
 563    }
 564
 565    public void switchToConversationAndQuote(Conversation conversation, String text) {
 566        switchToConversation(conversation, text, true, null, false, false);
 567    }
 568
 569    public void switchToConversation(Conversation conversation, String text) {
 570        switchToConversation(conversation, text, false, null, false, false);
 571    }
 572
 573    public void switchToConversationDoNotAppend(Conversation conversation, String text) {
 574        switchToConversation(conversation, text, false, null, false, true);
 575    }
 576
 577    public void highlightInMuc(Conversation conversation, String nick) {
 578        switchToConversation(conversation, null, false, nick, false, false);
 579    }
 580
 581    public void privateMsgInMuc(Conversation conversation, String nick) {
 582        switchToConversation(conversation, null, false, nick, true, false);
 583    }
 584
 585    public void switchToConversation(Conversation conversation, String text, boolean asQuote, String nick, boolean pm, boolean doNotAppend) {
 586        switchToConversation(conversation, text, asQuote, nick, pm, doNotAppend, null);
 587    }
 588
 589    public void switchToConversation(Conversation conversation, String text, boolean asQuote, String nick, boolean pm, boolean doNotAppend, String postInit) {
 590        switchToConversation(conversation, text, asQuote, nick, pm, doNotAppend, postInit, null);
 591    }
 592
 593    public void switchToConversation(Conversation conversation, String text, boolean asQuote, String nick, boolean pm, boolean doNotAppend, String postInit, String thread) {
 594        if (conversation == null) return;
 595
 596        Intent intent = new Intent(this, ConversationsActivity.class);
 597        intent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
 598        intent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversation.getUuid());
 599        intent.putExtra(ConversationsActivity.EXTRA_THREAD, thread);
 600        if (text != null) {
 601            intent.putExtra(Intent.EXTRA_TEXT, text);
 602            if (asQuote) {
 603                intent.putExtra(ConversationsActivity.EXTRA_AS_QUOTE, true);
 604            }
 605        }
 606        if (nick != null) {
 607            intent.putExtra(ConversationsActivity.EXTRA_NICK, nick);
 608            intent.putExtra(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, pm);
 609        }
 610        if (doNotAppend) {
 611            intent.putExtra(ConversationsActivity.EXTRA_DO_NOT_APPEND, true);
 612        }
 613        intent.putExtra(ConversationsActivity.EXTRA_POST_INIT_ACTION, postInit);
 614        intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_CLEAR_TOP);
 615        startActivity(intent);
 616        finish();
 617    }
 618
 619    public void switchToContactDetails(Contact contact) {
 620        switchToContactDetails(contact, null);
 621    }
 622
 623    public void switchToContactDetails(Contact contact, String messageFingerprint) {
 624        Intent intent = new Intent(this, ContactDetailsActivity.class);
 625        intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT);
 626        intent.putExtra(EXTRA_ACCOUNT, contact.getAccount().getJid().asBareJid().toEscapedString());
 627        intent.putExtra("contact", contact.getJid().toEscapedString());
 628        intent.putExtra("fingerprint", messageFingerprint);
 629        startActivity(intent);
 630    }
 631
 632    public void switchToAccount(Account account, String fingerprint) {
 633        switchToAccount(account, false, fingerprint);
 634    }
 635
 636    public void switchToAccount(Account account) {
 637        switchToAccount(account, false, null);
 638    }
 639
 640    public void switchToAccount(Account account, boolean init, String fingerprint) {
 641        Intent intent = new Intent(this, EditAccountActivity.class);
 642        intent.putExtra("jid", account.getJid().asBareJid().toEscapedString());
 643        intent.putExtra("init", init);
 644        if (init) {
 645            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
 646        }
 647        if (fingerprint != null) {
 648            intent.putExtra("fingerprint", fingerprint);
 649        }
 650        startActivity(intent);
 651        if (init) {
 652            overridePendingTransition(0, 0);
 653        }
 654    }
 655
 656    protected void delegateUriPermissionsToService(Uri uri) {
 657        Intent intent = new Intent(this, XmppConnectionService.class);
 658        intent.setAction(Intent.ACTION_SEND);
 659        intent.setData(uri);
 660        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
 661        try {
 662            startService(intent);
 663        } catch (Exception e) {
 664            Log.e(Config.LOGTAG, "unable to delegate uri permission", e);
 665        }
 666    }
 667
 668    protected void inviteToConversation(Conversation conversation) {
 669        startActivityForResult(ChooseContactActivity.create(this, conversation), REQUEST_INVITE_TO_CONVERSATION);
 670    }
 671
 672    protected void announcePgp(final Account account, final Conversation conversation, Intent intent, final Runnable onSuccess) {
 673        if (account.getPgpId() == 0) {
 674            choosePgpSignId(account);
 675        } else {
 676            final String status = Strings.nullToEmpty(account.getPresenceStatusMessage());
 677            xmppConnectionService.getPgpEngine().generateSignature(intent, account, status, new UiCallback<String>() {
 678
 679                @Override
 680                public void userInputRequired(final PendingIntent pi, final String signature) {
 681                    try {
 682                        startIntentSenderForResult(pi.getIntentSender(), REQUEST_ANNOUNCE_PGP, null, 0, 0, 0,Compatibility.pgpStartIntentSenderOptions());
 683                    } catch (final SendIntentException ignored) {
 684                    }
 685                }
 686
 687                @Override
 688                public void success(String signature) {
 689                    account.setPgpSignature(signature);
 690                    xmppConnectionService.databaseBackend.updateAccount(account);
 691                    xmppConnectionService.sendPresence(account);
 692                    if (conversation != null) {
 693                        conversation.setNextEncryption(Message.ENCRYPTION_PGP);
 694                        xmppConnectionService.updateConversation(conversation);
 695                        refreshUi();
 696                    }
 697                    if (onSuccess != null) {
 698                        runOnUiThread(onSuccess);
 699                    }
 700                }
 701
 702                @Override
 703                public void error(int error, String signature) {
 704                    if (error == 0) {
 705                        account.setPgpSignId(0);
 706                        account.unsetPgpSignature();
 707                        xmppConnectionService.databaseBackend.updateAccount(account);
 708                        choosePgpSignId(account);
 709                    } else {
 710                        displayErrorDialog(error);
 711                    }
 712                }
 713            });
 714        }
 715    }
 716
 717    protected void choosePgpSignId(final Account account) {
 718        xmppConnectionService.getPgpEngine().chooseKey(account, new UiCallback<>() {
 719            @Override
 720            public void success(final Account a) {
 721            }
 722
 723            @Override
 724            public void error(int errorCode, Account object) {
 725
 726            }
 727
 728            @Override
 729            public void userInputRequired(PendingIntent pi, Account object) {
 730                try {
 731                    startIntentSenderForResult(pi.getIntentSender(),
 732                            REQUEST_CHOOSE_PGP_ID, null, 0, 0, 0, Compatibility.pgpStartIntentSenderOptions());
 733                } catch (final SendIntentException ignored) {
 734                }
 735            }
 736        });
 737    }
 738
 739    protected void displayErrorDialog(final int errorCode) {
 740        runOnUiThread(() -> {
 741            final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(XmppActivity.this);
 742            builder.setTitle(getString(R.string.error));
 743            builder.setMessage(errorCode);
 744            builder.setNeutralButton(R.string.accept, null);
 745            builder.create().show();
 746        });
 747
 748    }
 749
 750    protected void showAddToRosterDialog(final Contact contact) {
 751        final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
 752        builder.setTitle(contact.getJid().toString());
 753        builder.setMessage(getString(R.string.not_in_roster));
 754        builder.setNegativeButton(getString(R.string.cancel), null);
 755        builder.setPositiveButton(getString(R.string.add_contact), (dialog, which) -> {
 756            contact.copySystemTagsToGroups();
 757            xmppConnectionService.createContact(contact, true);
 758        });
 759        builder.create().show();
 760    }
 761
 762    private void showAskForPresenceDialog(final Contact contact) {
 763        final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
 764        builder.setTitle(contact.getJid().toString());
 765        builder.setMessage(R.string.request_presence_updates);
 766        builder.setNegativeButton(R.string.cancel, null);
 767        builder.setPositiveButton(R.string.request_now,
 768                (dialog, which) -> {
 769                    if (xmppConnectionServiceBound) {
 770                        xmppConnectionService.sendPresencePacket(contact
 771                                .getAccount(), xmppConnectionService
 772                                .getPresenceGenerator()
 773                                .requestPresenceUpdatesFrom(contact));
 774                    }
 775                });
 776        builder.create().show();
 777    }
 778
 779    protected void quickEdit(String previousValue, @StringRes int hint, OnValueEdited callback) {
 780        quickEdit(previousValue, callback, hint, false, false);
 781    }
 782
 783    protected void quickEdit(String previousValue, @StringRes int hint, OnValueEdited callback, boolean permitEmpty) {
 784        quickEdit(previousValue, callback, hint, false, permitEmpty);
 785    }
 786
 787    protected void quickPasswordEdit(String previousValue, OnValueEdited callback) {
 788        quickEdit(previousValue, callback, R.string.password, true, false);
 789    }
 790
 791    protected void quickEdit(final String previousValue, final OnValueEdited callback, final @StringRes int hint, boolean password, boolean permitEmpty) {
 792        quickEdit(previousValue, callback, hint, password, permitEmpty, false);
 793    }
 794
 795    protected void quickEdit(final String previousValue, final OnValueEdited callback, final @StringRes int hint, boolean password, boolean permitEmpty, boolean alwaysCallback) {
 796        quickEdit(previousValue, callback, hint, password, permitEmpty, alwaysCallback, false);
 797    }
 798
 799    @SuppressLint("InflateParams")
 800    protected void quickEdit(final String previousValue,
 801                           final OnValueEdited callback,
 802                           final @StringRes int hint,
 803                           boolean password,
 804                           boolean permitEmpty,
 805                           boolean alwaysCallback,
 806                           boolean startSelected) {
 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        if (startSelected) {
 826            binding.inputEditText.selectAll();
 827        }
 828        View.OnClickListener clickListener = v -> {
 829            String value = binding.inputEditText.getText().toString();
 830            if ((alwaysCallback || !value.equals(previousValue)) && (!value.trim().isEmpty() || permitEmpty)) {
 831                String error = callback.onValueEdited(value);
 832                if (error != null) {
 833                    binding.inputLayout.setError(error);
 834                    return;
 835                }
 836            }
 837            SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
 838            dialog.dismiss();
 839        };
 840        dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(clickListener);
 841        dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setOnClickListener((v -> {
 842            SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
 843            dialog.dismiss();
 844        }));
 845        dialog.setCanceledOnTouchOutside(false);
 846        dialog.setOnDismissListener(dialog1 -> {
 847            SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
 848        });
 849    }
 850
 851    protected boolean hasStoragePermission(int requestCode) {
 852        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
 853            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
 854                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
 855                return false;
 856            } else {
 857                return true;
 858            }
 859        } else {
 860            return true;
 861        }
 862    }
 863
 864    public synchronized void startActivityWithCallback(Intent intent, ValueCallback<Uri[]> cb) {
 865        Pair<Integer, ValueCallback<Uri[]>> peek = activityCallbacks.peek();
 866        int index = peek == null ? 1 : peek.first + 1;
 867        activityCallbacks.add(new Pair<>(index, cb));
 868        startActivityForResult(intent, index);
 869    }
 870
 871    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
 872        super.onActivityResult(requestCode, resultCode, data);
 873        if (requestCode == REQUEST_INVITE_TO_CONVERSATION && resultCode == RESULT_OK) {
 874            mPendingConferenceInvite = ConferenceInvite.parse(data);
 875            if (xmppConnectionServiceBound && mPendingConferenceInvite != null) {
 876                if (mPendingConferenceInvite.execute(this)) {
 877                    mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
 878                    mToast.show();
 879                }
 880                mPendingConferenceInvite = null;
 881            }
 882        } else if (resultCode == RESULT_OK) {
 883            for (Pair<Integer, ValueCallback<Uri[]>> cb : new ArrayList<>(activityCallbacks)) {
 884                if (cb.first == requestCode) {
 885                    activityCallbacks.remove(cb);
 886                    ArrayList<Uri> dataUris = new ArrayList<>();
 887                    if (data.getDataString() != null) {
 888                        dataUris.add(Uri.parse(data.getDataString()));
 889                    } else if (data.getClipData() != null) {
 890                        for (int i = 0; i < data.getClipData().getItemCount(); i++) {
 891                            dataUris.add(data.getClipData().getItemAt(i).getUri());
 892                        }
 893                    }
 894                    cb.second.onReceiveValue(dataUris.toArray(new Uri[0]));
 895                }
 896            }
 897        }
 898    }
 899
 900    public boolean copyTextToClipboard(String text, int labelResId) {
 901        ClipboardManager mClipBoardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
 902        String label = getResources().getString(labelResId);
 903        if (mClipBoardManager != null) {
 904            ClipData mClipData = ClipData.newPlainText(label, text);
 905            mClipBoardManager.setPrimaryClip(mClipData);
 906            return true;
 907        }
 908        return false;
 909    }
 910
 911    protected boolean manuallyChangePresence() {
 912        return getBooleanPreference(AppSettings.MANUALLY_CHANGE_PRESENCE, R.bool.manually_change_presence);
 913    }
 914
 915    protected String getShareableUri() {
 916        return getShareableUri(false);
 917    }
 918
 919    protected String getShareableUri(boolean http) {
 920        return null;
 921    }
 922
 923    protected void shareLink(boolean http) {
 924        String uri = getShareableUri(http);
 925        if (uri == null || uri.isEmpty()) {
 926            return;
 927        }
 928        Intent intent = new Intent(Intent.ACTION_SEND);
 929        intent.setType("text/plain");
 930        intent.putExtra(Intent.EXTRA_TEXT, getShareableUri(http));
 931        try {
 932            startActivity(Intent.createChooser(intent, getText(R.string.share_uri_with)));
 933        } catch (ActivityNotFoundException e) {
 934            Toast.makeText(this, R.string.no_application_to_share_uri, Toast.LENGTH_SHORT).show();
 935        }
 936    }
 937
 938    protected void launchOpenKeyChain(long keyId) {
 939        PgpEngine pgp = XmppActivity.this.xmppConnectionService.getPgpEngine();
 940        try {
 941            startIntentSenderForResult(
 942                    pgp.getIntentForKey(keyId).getIntentSender(), 0, null, 0,
 943                    0, 0, Compatibility.pgpStartIntentSenderOptions());
 944        } catch (final Throwable e) {
 945            Log.d(Config.LOGTAG,"could not launch OpenKeyChain", e);
 946            Toast.makeText(XmppActivity.this, R.string.openpgp_error, Toast.LENGTH_SHORT).show();
 947        }
 948    }
 949
 950    @Override
 951    protected void onResume(){
 952        super.onResume();
 953        SettingsUtils.applyScreenshotSetting(this);
 954    }
 955
 956    @Override
 957    public void onPause() {
 958        super.onPause();
 959    }
 960
 961    @Override
 962    public boolean onMenuOpened(int id, Menu menu) {
 963        if (id == AppCompatDelegate.FEATURE_SUPPORT_ACTION_BAR && menu != null) {
 964            MenuDoubleTabUtil.recordMenuOpen();
 965        }
 966        return super.onMenuOpened(id, menu);
 967    }
 968
 969    protected void showQrCode() {
 970        showQrCode(getShareableUri());
 971    }
 972
 973    protected void showQrCode(final String uri) {
 974        if (uri == null || uri.isEmpty()) {
 975            return;
 976        }
 977        final Point size = new Point();
 978        getWindowManager().getDefaultDisplay().getSize(size);
 979        final int width = Math.min(size.x, size.y);
 980        final int black;
 981        final int white;
 982        if (Activities.isNightMode(this)) {
 983            black = MaterialColors.getColor(this, com.google.android.material.R.attr.colorSurfaceContainerHighest,"No surface color configured");
 984            white = MaterialColors.getColor(this, com.google.android.material.R.attr.colorSurfaceInverse,"No inverse surface color configured");
 985        } else {
 986            black = MaterialColors.getColor(this, com.google.android.material.R.attr.colorSurfaceInverse,"No inverse surface color configured");
 987            white = MaterialColors.getColor(this, com.google.android.material.R.attr.colorSurfaceContainerHighest,"No surface color configured");
 988        }
 989        final var bitmap = BarcodeProvider.create2dBarcodeBitmap(uri, width, black, white);
 990        final ImageView view = new ImageView(this);
 991        view.setBackgroundColor(white);
 992        view.setImageBitmap(bitmap);
 993        MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
 994        builder.setView(view);
 995        builder.create().show();
 996    }
 997
 998    protected Account extractAccount(Intent intent) {
 999        final String jid = intent != null ? intent.getStringExtra(EXTRA_ACCOUNT) : null;
1000        try {
1001            return jid != null ? xmppConnectionService.findAccountByJid(Jid.ofEscaped(jid)) : null;
1002        } catch (IllegalArgumentException e) {
1003            return null;
1004        }
1005    }
1006
1007    public AvatarService avatarService() {
1008        return xmppConnectionService.getAvatarService();
1009    }
1010
1011    public void loadBitmap(Message message, ImageView imageView) {
1012        Drawable bm;
1013        try {
1014            bm = xmppConnectionService.getFileBackend().getThumbnail(message, getResources(), (int) (metrics.density * 288), true);
1015        } catch (IOException e) {
1016            bm = null;
1017        }
1018        if (bm != null) {
1019            cancelPotentialWork(message, imageView);
1020            imageView.setImageDrawable(bm);
1021            imageView.setBackgroundColor(0x00000000);
1022            if (Build.VERSION.SDK_INT >= 28 && bm instanceof AnimatedImageDrawable) {
1023                ((AnimatedImageDrawable) bm).start();
1024            }
1025        } else {
1026            if (cancelPotentialWork(message, imageView)) {
1027                final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
1028                final BitmapDrawable fallbackThumb = xmppConnectionService.getFileBackend().getFallbackThumbnail(message, (int) (metrics.density * 288), true);
1029                imageView.setBackgroundColor(fallbackThumb == null ? 0xff333333 : 0x00000000);
1030                final AsyncDrawable asyncDrawable = new AsyncDrawable(
1031                        getResources(), fallbackThumb != null ? fallbackThumb.getBitmap() : null, task);
1032                imageView.setImageDrawable(asyncDrawable);
1033                try {
1034                    task.execute(message);
1035                } catch (final RejectedExecutionException ignored) {
1036                    ignored.printStackTrace();
1037                }
1038            }
1039        }
1040    }
1041
1042    protected interface OnValueEdited {
1043        String onValueEdited(String value);
1044    }
1045
1046    public static class ConferenceInvite {
1047        private String uuid;
1048        private final List<Jid> jids = new ArrayList<>();
1049
1050        public static ConferenceInvite parse(Intent data) {
1051            ConferenceInvite invite = new ConferenceInvite();
1052            invite.uuid = data.getStringExtra(ChooseContactActivity.EXTRA_CONVERSATION);
1053            if (invite.uuid == null) {
1054                return null;
1055            }
1056            invite.jids.addAll(ChooseContactActivity.extractJabberIds(data));
1057            return invite;
1058        }
1059
1060        public boolean execute(XmppActivity activity) {
1061            XmppConnectionService service = activity.xmppConnectionService;
1062            Conversation conversation = service.findConversationByUuid(this.uuid);
1063            if (conversation == null) {
1064                return false;
1065            }
1066            if (conversation.getMode() == Conversation.MODE_MULTI) {
1067                for (Jid jid : jids) {
1068                    service.invite(conversation, jid);
1069                }
1070                return false;
1071            } else {
1072                jids.add(conversation.getJid().asBareJid());
1073                return service.createAdhocConference(conversation.getAccount(), null, jids, activity.adhocCallback);
1074            }
1075        }
1076    }
1077
1078    static class BitmapWorkerTask extends AsyncTask<Message, Void, Drawable> {
1079        private final WeakReference<ImageView> imageViewReference;
1080        private Message message = null;
1081
1082        private BitmapWorkerTask(ImageView imageView) {
1083            this.imageViewReference = new WeakReference<>(imageView);
1084        }
1085
1086        @Override
1087        protected Drawable doInBackground(Message... params) {
1088            if (isCancelled()) {
1089                return null;
1090            }
1091            final XmppActivity activity = find(imageViewReference);
1092            Drawable d = null;
1093            message = params[0];
1094            try {
1095                if (activity != null && activity.xmppConnectionService != null) {
1096                    d = activity.xmppConnectionService.getFileBackend().getThumbnail(message, imageViewReference.get().getContext().getResources(), (int) (activity.metrics.density * 288), false);
1097                }
1098            } catch (IOException e) { e.printStackTrace(); }
1099            final ImageView imageView = imageViewReference.get();
1100            if (d == null && activity != null && activity.xmppConnectionService != null && imageView != null && imageView.getDrawable() instanceof AsyncDrawable && ((AsyncDrawable) imageView.getDrawable()).getBitmap() == null) {
1101                d = activity.xmppConnectionService.getFileBackend().getFallbackThumbnail(message, (int) (activity.metrics.density * 288), false);
1102            }
1103            return d;
1104        }
1105
1106        @Override
1107        protected void onPostExecute(final Drawable drawable) {
1108            if (!isCancelled()) {
1109                final ImageView imageView = imageViewReference.get();
1110                if (imageView != null) {
1111                    Drawable old = imageView.getDrawable();
1112                    if (old instanceof AsyncDrawable) {
1113                        ((AsyncDrawable) old).clearTask();
1114                    }
1115                    if (drawable != null) {
1116                        imageView.setImageDrawable(drawable);
1117                    }
1118                    imageView.setBackgroundColor(drawable == null ? 0xff333333 : 0x00000000);
1119                    if (Build.VERSION.SDK_INT >= 28 && drawable instanceof AnimatedImageDrawable) {
1120                        ((AnimatedImageDrawable) drawable).start();
1121                    }
1122                }
1123            }
1124        }
1125    }
1126
1127    private static class AsyncDrawable extends BitmapDrawable {
1128        private WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
1129
1130        private AsyncDrawable(Resources res, Bitmap bitmap, BitmapWorkerTask bitmapWorkerTask) {
1131            super(res, bitmap);
1132            bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
1133        }
1134
1135        private synchronized BitmapWorkerTask getBitmapWorkerTask() {
1136            if (bitmapWorkerTaskReference == null) return null;
1137
1138            return bitmapWorkerTaskReference.get();
1139        }
1140
1141        public synchronized void clearTask() {
1142            bitmapWorkerTaskReference = null;
1143        }
1144    }
1145
1146    public static XmppActivity find(@NonNull WeakReference<ImageView> viewWeakReference) {
1147        final View view = viewWeakReference.get();
1148        return view == null ? null : find(view);
1149    }
1150
1151    public static XmppActivity find(@NonNull final View view) {
1152        Context context = view.getContext();
1153        while (context instanceof ContextWrapper) {
1154            if (context instanceof XmppActivity) {
1155                return (XmppActivity) context;
1156            }
1157            context = ((ContextWrapper) context).getBaseContext();
1158        }
1159        return null;
1160    }
1161
1162    public boolean isDark() {
1163        int nightModeFlags = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
1164        return nightModeFlags == Configuration.UI_MODE_NIGHT_YES;
1165    }
1166}