XmppActivity.java

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