XmppActivity.java

   1package eu.siacs.conversations.ui;
   2
   3import android.telephony.TelephonyManager;
   4
   5import android.Manifest;
   6import android.annotation.SuppressLint;
   7import android.annotation.TargetApi;
   8import android.app.PendingIntent;
   9import android.content.ActivityNotFoundException;
  10import android.content.ClipData;
  11import android.content.ClipboardManager;
  12import android.content.ComponentName;
  13import android.content.Context;
  14import android.content.ContextWrapper;
  15import android.content.DialogInterface;
  16import android.content.Intent;
  17import android.content.IntentSender.SendIntentException;
  18import android.content.ServiceConnection;
  19import android.content.SharedPreferences;
  20import android.content.pm.PackageManager;
  21import android.content.pm.ResolveInfo;
  22import android.content.res.Resources;
  23import android.content.res.TypedArray;
  24import android.graphics.Bitmap;
  25import android.graphics.Color;
  26import android.graphics.Point;
  27import android.graphics.drawable.AnimatedImageDrawable;
  28import android.graphics.drawable.BitmapDrawable;
  29import android.graphics.drawable.Drawable;
  30import android.net.ConnectivityManager;
  31import android.net.Uri;
  32import android.os.AsyncTask;
  33import android.os.Build;
  34import android.os.Bundle;
  35import android.os.Handler;
  36import android.os.IBinder;
  37import android.os.PowerManager;
  38import android.os.SystemClock;
  39import android.preference.PreferenceManager;
  40import android.text.Html;
  41import android.text.InputType;
  42import android.util.DisplayMetrics;
  43import android.util.Log;
  44import android.util.Pair;
  45import android.view.Menu;
  46import android.view.MenuItem;
  47import android.view.View;
  48import android.webkit.ValueCallback;
  49import android.widget.Button;
  50import android.widget.CheckBox;
  51import android.widget.ImageView;
  52import android.widget.Toast;
  53
  54import androidx.annotation.BoolRes;
  55import androidx.annotation.NonNull;
  56import androidx.annotation.StringRes;
  57import androidx.appcompat.app.AlertDialog;
  58import androidx.appcompat.app.AlertDialog.Builder;
  59import androidx.appcompat.app.AppCompatDelegate;
  60import androidx.databinding.DataBindingUtil;
  61
  62import com.google.common.base.Strings;
  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.RejectedExecutionException;
  71
  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    public boolean mSkipBackgroundBinding = false;
 174
 175    public static boolean cancelPotentialWork(Message message, ImageView imageView) {
 176        final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
 177
 178        if (bitmapWorkerTask != null) {
 179            final Message oldMessage = bitmapWorkerTask.message;
 180            if (oldMessage == null || message != oldMessage) {
 181                bitmapWorkerTask.cancel(true);
 182            } else {
 183                return false;
 184            }
 185        }
 186        return true;
 187    }
 188
 189    private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
 190        if (imageView != null) {
 191            final Drawable drawable = imageView.getDrawable();
 192            if (drawable instanceof AsyncDrawable) {
 193                final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
 194                return asyncDrawable.getBitmapWorkerTask();
 195            }
 196        }
 197        return null;
 198    }
 199
 200    protected void hideToast() {
 201        if (mToast != null) {
 202            mToast.cancel();
 203        }
 204    }
 205
 206    protected void replaceToast(String msg) {
 207        replaceToast(msg, true);
 208    }
 209
 210    protected void replaceToast(String msg, boolean showlong) {
 211        hideToast();
 212        mToast = Toast.makeText(this, msg, showlong ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT);
 213        mToast.show();
 214    }
 215
 216    protected final void refreshUi() {
 217        final long diff = SystemClock.elapsedRealtime() - mLastUiRefresh;
 218        if (diff > Config.REFRESH_UI_INTERVAL) {
 219            mRefreshUiHandler.removeCallbacks(mRefreshUiRunnable);
 220            runOnUiThread(mRefreshUiRunnable);
 221        } else {
 222            final long next = Config.REFRESH_UI_INTERVAL - diff;
 223            mRefreshUiHandler.removeCallbacks(mRefreshUiRunnable);
 224            mRefreshUiHandler.postDelayed(mRefreshUiRunnable, next);
 225        }
 226    }
 227
 228    abstract protected void refreshUiReal();
 229
 230    @Override
 231    protected void onStart() {
 232        super.onStart();
 233        if (!xmppConnectionServiceBound) {
 234            if (this.mSkipBackgroundBinding) {
 235                Log.d(Config.LOGTAG, "skipping background binding");
 236            } else {
 237                connectToBackend();
 238            }
 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        Builder builder = new AlertDialog.Builder(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 AlertDialog.Builder builder = new AlertDialog.Builder(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    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, 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        ExceptionHelper.init(getApplicationContext());
 512        EmojiInitializationService.execute(this);
 513        this.isCameraFeatureAvailable = getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
 514        this.mTheme = findTheme();
 515        setTheme(this.mTheme);
 516        this.mCustomColors = ThemeHelper.applyCustomColors(this);
 517    }
 518
 519    protected boolean isCameraFeatureAvailable() {
 520        return this.isCameraFeatureAvailable;
 521    }
 522
 523    public boolean isDarkTheme() {
 524        return ThemeHelper.isDark(mTheme);
 525    }
 526
 527    public int getThemeResource(int r_attr_name, int r_drawable_def) {
 528        int[] attrs = {r_attr_name};
 529        TypedArray ta = this.getTheme().obtainStyledAttributes(attrs);
 530
 531        int res = ta.getResourceId(0, r_drawable_def);
 532        ta.recycle();
 533
 534        return res;
 535    }
 536
 537    protected boolean isOptimizingBattery() {
 538        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
 539            final PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
 540            return pm != null
 541                    && !pm.isIgnoringBatteryOptimizations(getPackageName());
 542        } else {
 543            return false;
 544        }
 545    }
 546
 547    protected boolean isAffectedByDataSaver() {
 548        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
 549            final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
 550            return cm != null
 551                    && cm.isActiveNetworkMetered()
 552                    && Compatibility.getRestrictBackgroundStatus(cm) == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
 553        } else {
 554            return false;
 555        }
 556    }
 557
 558    private boolean usingEnterKey() {
 559        return getBooleanPreference("display_enter_key", R.bool.display_enter_key);
 560    }
 561
 562    private boolean useTor() {
 563        return getBooleanPreference("use_tor", R.bool.use_tor);
 564    }
 565
 566    protected SharedPreferences getPreferences() {
 567        return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
 568    }
 569
 570    protected boolean getBooleanPreference(String name, @BoolRes int res) {
 571        return getPreferences().getBoolean(name, getResources().getBoolean(res));
 572    }
 573
 574    public void startCommand(final Account account, final Jid jid, final String node) {
 575        Intent intent = new Intent(this, ConversationsActivity.class);
 576        intent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
 577        intent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, xmppConnectionService.findOrCreateConversation(account, jid, false, false).getUuid());
 578        intent.putExtra(ConversationsActivity.EXTRA_POST_INIT_ACTION, "command");
 579        intent.putExtra(ConversationsActivity.EXTRA_NODE, node);
 580        intent.putExtra(ConversationsActivity.EXTRA_JID, (CharSequence) jid);
 581        intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_CLEAR_TOP);
 582        startActivity(intent);
 583    }
 584
 585    public void switchToConversation(Conversation conversation) {
 586        switchToConversation(conversation, null);
 587    }
 588
 589    public void switchToConversationAndQuote(Conversation conversation, String text) {
 590        switchToConversation(conversation, text, true, null, false, false);
 591    }
 592
 593    public void switchToConversation(Conversation conversation, String text) {
 594        switchToConversation(conversation, text, false, null, false, false);
 595    }
 596
 597    public void switchToConversationDoNotAppend(Conversation conversation, String text) {
 598        switchToConversation(conversation, text, false, null, false, true);
 599    }
 600
 601    public void highlightInMuc(Conversation conversation, String nick) {
 602        switchToConversation(conversation, null, false, nick, false, false);
 603    }
 604
 605    public void privateMsgInMuc(Conversation conversation, String nick) {
 606        switchToConversation(conversation, null, false, nick, true, false);
 607    }
 608
 609    public void switchToConversation(Conversation conversation, String text, boolean asQuote, String nick, boolean pm, boolean doNotAppend) {
 610        switchToConversation(conversation, text, asQuote, nick, pm, doNotAppend, null);
 611    }
 612
 613    public void switchToConversation(Conversation conversation, String text, boolean asQuote, String nick, boolean pm, boolean doNotAppend, String postInit) {
 614        switchToConversation(conversation, text, asQuote, nick, pm, doNotAppend, postInit, null);
 615    }
 616
 617    public void switchToConversation(Conversation conversation, String text, boolean asQuote, String nick, boolean pm, boolean doNotAppend, String postInit, String thread) {
 618        if (conversation == null) return;
 619
 620        Intent intent = new Intent(this, ConversationsActivity.class);
 621        intent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
 622        intent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversation.getUuid());
 623        intent.putExtra(ConversationsActivity.EXTRA_THREAD, thread);
 624        if (text != null) {
 625            intent.putExtra(Intent.EXTRA_TEXT, text);
 626            if (asQuote) {
 627                intent.putExtra(ConversationsActivity.EXTRA_AS_QUOTE, true);
 628            }
 629        }
 630        if (nick != null) {
 631            intent.putExtra(ConversationsActivity.EXTRA_NICK, nick);
 632            intent.putExtra(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, pm);
 633        }
 634        if (doNotAppend) {
 635            intent.putExtra(ConversationsActivity.EXTRA_DO_NOT_APPEND, true);
 636        }
 637        intent.putExtra(ConversationsActivity.EXTRA_POST_INIT_ACTION, postInit);
 638        intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_CLEAR_TOP);
 639        startActivity(intent);
 640        finish();
 641    }
 642
 643    public void switchToContactDetails(Contact contact) {
 644        switchToContactDetails(contact, null);
 645    }
 646
 647    public void switchToContactDetails(Contact contact, String messageFingerprint) {
 648        Intent intent = new Intent(this, ContactDetailsActivity.class);
 649        intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT);
 650        intent.putExtra(EXTRA_ACCOUNT, contact.getAccount().getJid().asBareJid().toEscapedString());
 651        intent.putExtra("contact", contact.getJid().toEscapedString());
 652        intent.putExtra("fingerprint", messageFingerprint);
 653        startActivity(intent);
 654    }
 655
 656    public void switchToAccount(Account account, String fingerprint) {
 657        switchToAccount(account, false, fingerprint);
 658    }
 659
 660    public void switchToAccount(Account account) {
 661        switchToAccount(account, false, null);
 662    }
 663
 664    public void switchToAccount(Account account, boolean init, String fingerprint) {
 665        Intent intent = new Intent(this, EditAccountActivity.class);
 666        intent.putExtra("jid", account.getJid().asBareJid().toEscapedString());
 667        intent.putExtra("init", init);
 668        if (init) {
 669            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
 670        }
 671        if (fingerprint != null) {
 672            intent.putExtra("fingerprint", fingerprint);
 673        }
 674        startActivity(intent);
 675        if (init) {
 676            overridePendingTransition(0, 0);
 677        }
 678    }
 679
 680    protected void delegateUriPermissionsToService(Uri uri) {
 681        Intent intent = new Intent(this, XmppConnectionService.class);
 682        intent.setAction(Intent.ACTION_SEND);
 683        intent.setData(uri);
 684        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
 685        try {
 686            startService(intent);
 687        } catch (Exception e) {
 688            Log.e(Config.LOGTAG, "unable to delegate uri permission", e);
 689        }
 690    }
 691
 692    protected void inviteToConversation(Conversation conversation) {
 693        startActivityForResult(ChooseContactActivity.create(this, conversation), REQUEST_INVITE_TO_CONVERSATION);
 694    }
 695
 696    protected void announcePgp(final Account account, final Conversation conversation, Intent intent, final Runnable onSuccess) {
 697        if (account.getPgpId() == 0) {
 698            choosePgpSignId(account);
 699        } else {
 700            final String status = Strings.nullToEmpty(account.getPresenceStatusMessage());
 701            xmppConnectionService.getPgpEngine().generateSignature(intent, account, status, new UiCallback<String>() {
 702
 703                @Override
 704                public void userInputRequired(final PendingIntent pi, final String signature) {
 705                    try {
 706                        startIntentSenderForResult(pi.getIntentSender(), REQUEST_ANNOUNCE_PGP, null, 0, 0, 0,Compatibility.pgpStartIntentSenderOptions());
 707                    } catch (final SendIntentException ignored) {
 708                    }
 709                }
 710
 711                @Override
 712                public void success(String signature) {
 713                    account.setPgpSignature(signature);
 714                    xmppConnectionService.databaseBackend.updateAccount(account);
 715                    xmppConnectionService.sendPresence(account);
 716                    if (conversation != null) {
 717                        conversation.setNextEncryption(Message.ENCRYPTION_PGP);
 718                        xmppConnectionService.updateConversation(conversation);
 719                        refreshUi();
 720                    }
 721                    if (onSuccess != null) {
 722                        runOnUiThread(onSuccess);
 723                    }
 724                }
 725
 726                @Override
 727                public void error(int error, String signature) {
 728                    if (error == 0) {
 729                        account.setPgpSignId(0);
 730                        account.unsetPgpSignature();
 731                        xmppConnectionService.databaseBackend.updateAccount(account);
 732                        choosePgpSignId(account);
 733                    } else {
 734                        displayErrorDialog(error);
 735                    }
 736                }
 737            });
 738        }
 739    }
 740
 741    @SuppressWarnings("deprecation")
 742    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
 743    protected void setListItemBackgroundOnView(View view) {
 744        int sdk = android.os.Build.VERSION.SDK_INT;
 745        if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
 746            view.setBackgroundDrawable(getResources().getDrawable(R.drawable.greybackground));
 747        } else {
 748            view.setBackground(getResources().getDrawable(R.drawable.greybackground));
 749        }
 750    }
 751
 752    protected void choosePgpSignId(Account account) {
 753        xmppConnectionService.getPgpEngine().chooseKey(account, new UiCallback<Account>() {
 754            @Override
 755            public void success(Account account1) {
 756            }
 757
 758            @Override
 759            public void error(int errorCode, Account object) {
 760
 761            }
 762
 763            @Override
 764            public void userInputRequired(PendingIntent pi, Account object) {
 765                try {
 766                    startIntentSenderForResult(pi.getIntentSender(),
 767                            REQUEST_CHOOSE_PGP_ID, null, 0, 0, 0, Compatibility.pgpStartIntentSenderOptions());
 768                } catch (final SendIntentException ignored) {
 769                }
 770            }
 771        });
 772    }
 773
 774    protected void displayErrorDialog(final int errorCode) {
 775        runOnUiThread(() -> {
 776            Builder builder = new Builder(XmppActivity.this);
 777            builder.setIconAttribute(android.R.attr.alertDialogIcon);
 778            builder.setTitle(getString(R.string.error));
 779            builder.setMessage(errorCode);
 780            builder.setNeutralButton(R.string.accept, null);
 781            builder.create().show();
 782        });
 783
 784    }
 785
 786    protected void showAddToRosterDialog(final Contact contact) {
 787        AlertDialog.Builder builder = new AlertDialog.Builder(this);
 788        builder.setTitle(contact.getJid().toString());
 789        builder.setMessage(getString(R.string.not_in_roster));
 790        builder.setNegativeButton(getString(R.string.cancel), null);
 791        builder.setPositiveButton(getString(R.string.add_contact), (dialog, which) -> {
 792            contact.copySystemTagsToGroups();
 793            xmppConnectionService.createContact(contact, true);
 794        });
 795        builder.create().show();
 796    }
 797
 798    private void showAskForPresenceDialog(final Contact contact) {
 799        AlertDialog.Builder builder = new AlertDialog.Builder(this);
 800        builder.setTitle(contact.getJid().toString());
 801        builder.setMessage(R.string.request_presence_updates);
 802        builder.setNegativeButton(R.string.cancel, null);
 803        builder.setPositiveButton(R.string.request_now,
 804                (dialog, which) -> {
 805                    if (xmppConnectionServiceBound) {
 806                        xmppConnectionService.sendPresencePacket(contact
 807                                .getAccount(), xmppConnectionService
 808                                .getPresenceGenerator()
 809                                .requestPresenceUpdatesFrom(contact));
 810                    }
 811                });
 812        builder.create().show();
 813    }
 814
 815    protected void quickEdit(String previousValue, @StringRes int hint, OnValueEdited callback) {
 816        quickEdit(previousValue, callback, hint, false, false);
 817    }
 818
 819    protected void quickEdit(String previousValue, @StringRes int hint, OnValueEdited callback, boolean permitEmpty) {
 820        quickEdit(previousValue, callback, hint, false, permitEmpty);
 821    }
 822
 823    protected void quickPasswordEdit(String previousValue, OnValueEdited callback) {
 824        quickEdit(previousValue, callback, R.string.password, true, false);
 825    }
 826
 827    protected void quickEdit(final String previousValue, final OnValueEdited callback, final @StringRes int hint, boolean password, boolean permitEmpty) {
 828        quickEdit(previousValue, callback, hint, password, permitEmpty, false);
 829    }
 830
 831    @SuppressLint("InflateParams")
 832    protected void quickEdit(final String previousValue,
 833                           final OnValueEdited callback,
 834                           final @StringRes int hint,
 835                           boolean password,
 836                           boolean permitEmpty,
 837                           boolean alwaysCallback) {
 838        AlertDialog.Builder builder = new AlertDialog.Builder(this);
 839        DialogQuickeditBinding binding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.dialog_quickedit, null, false);
 840        if (password) {
 841            binding.inputEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
 842        }
 843        builder.setPositiveButton(R.string.accept, null);
 844        if (hint != 0) {
 845            binding.inputLayout.setHint(getString(hint));
 846        }
 847        binding.inputEditText.requestFocus();
 848        if (previousValue != null) {
 849            binding.inputEditText.getText().append(previousValue);
 850        }
 851        builder.setView(binding.getRoot());
 852        builder.setNegativeButton(R.string.cancel, null);
 853        final AlertDialog dialog = builder.create();
 854        dialog.setOnShowListener(d -> SoftKeyboardUtils.showKeyboard(binding.inputEditText));
 855        dialog.show();
 856        View.OnClickListener clickListener = v -> {
 857            String value = binding.inputEditText.getText().toString();
 858            if ((alwaysCallback || !value.equals(previousValue)) && (!value.trim().isEmpty() || permitEmpty)) {
 859                String error = callback.onValueEdited(value);
 860                if (error != null) {
 861                    binding.inputLayout.setError(error);
 862                    return;
 863                }
 864            }
 865            SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
 866            dialog.dismiss();
 867        };
 868        dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(clickListener);
 869        dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setOnClickListener((v -> {
 870            SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
 871            dialog.dismiss();
 872        }));
 873        dialog.setCanceledOnTouchOutside(false);
 874        dialog.setOnDismissListener(dialog1 -> {
 875            SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
 876        });
 877    }
 878
 879    protected boolean hasStoragePermission(int requestCode) {
 880        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
 881            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
 882                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
 883                return false;
 884            } else {
 885                return true;
 886            }
 887        } else {
 888            return true;
 889        }
 890    }
 891
 892    public synchronized void startActivityWithCallback(Intent intent, ValueCallback<Uri[]> cb) {
 893        Pair<Integer, ValueCallback<Uri[]>> peek = activityCallbacks.peek();
 894        int index = peek == null ? 1 : peek.first + 1;
 895        activityCallbacks.add(new Pair<>(index, cb));
 896        startActivityForResult(intent, index);
 897    }
 898
 899    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
 900        super.onActivityResult(requestCode, resultCode, data);
 901        if (requestCode == REQUEST_INVITE_TO_CONVERSATION && resultCode == RESULT_OK) {
 902            mPendingConferenceInvite = ConferenceInvite.parse(data);
 903            if (xmppConnectionServiceBound && mPendingConferenceInvite != null) {
 904                if (mPendingConferenceInvite.execute(this)) {
 905                    mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
 906                    mToast.show();
 907                }
 908                mPendingConferenceInvite = null;
 909            }
 910        } else if (resultCode == RESULT_OK) {
 911            for (Pair<Integer, ValueCallback<Uri[]>> cb : new ArrayList<>(activityCallbacks)) {
 912                if (cb.first == requestCode) {
 913                    activityCallbacks.remove(cb);
 914                    ArrayList<Uri> dataUris = new ArrayList<>();
 915                    if (data.getDataString() != null) {
 916                        dataUris.add(Uri.parse(data.getDataString()));
 917                    } else if (data.getClipData() != null) {
 918                        for (int i = 0; i < data.getClipData().getItemCount(); i++) {
 919                            dataUris.add(data.getClipData().getItemAt(i).getUri());
 920                        }
 921                    }
 922                    cb.second.onReceiveValue(dataUris.toArray(new Uri[0]));
 923                }
 924            }
 925        }
 926    }
 927
 928    public boolean copyTextToClipboard(String text, int labelResId) {
 929        ClipboardManager mClipBoardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
 930        String label = getResources().getString(labelResId);
 931        if (mClipBoardManager != null) {
 932            ClipData mClipData = ClipData.newPlainText(label, text);
 933            mClipBoardManager.setPrimaryClip(mClipData);
 934            return true;
 935        }
 936        return false;
 937    }
 938
 939    protected boolean manuallyChangePresence() {
 940        return getBooleanPreference(SettingsActivity.MANUALLY_CHANGE_PRESENCE, R.bool.manually_change_presence);
 941    }
 942
 943    protected String getShareableUri() {
 944        return getShareableUri(false);
 945    }
 946
 947    protected String getShareableUri(boolean http) {
 948        return null;
 949    }
 950
 951    protected void shareLink(boolean http) {
 952        String uri = getShareableUri(http);
 953        if (uri == null || uri.isEmpty()) {
 954            return;
 955        }
 956        Intent intent = new Intent(Intent.ACTION_SEND);
 957        intent.setType("text/plain");
 958        intent.putExtra(Intent.EXTRA_TEXT, getShareableUri(http));
 959        try {
 960            startActivity(Intent.createChooser(intent, getText(R.string.share_uri_with)));
 961        } catch (ActivityNotFoundException e) {
 962            Toast.makeText(this, R.string.no_application_to_share_uri, Toast.LENGTH_SHORT).show();
 963        }
 964    }
 965
 966    protected void launchOpenKeyChain(long keyId) {
 967        PgpEngine pgp = XmppActivity.this.xmppConnectionService.getPgpEngine();
 968        try {
 969            startIntentSenderForResult(
 970                    pgp.getIntentForKey(keyId).getIntentSender(), 0, null, 0,
 971                    0, 0, Compatibility.pgpStartIntentSenderOptions());
 972        } catch (final Throwable e) {
 973            Log.d(Config.LOGTAG,"could not launch OpenKeyChain", e);
 974            Toast.makeText(XmppActivity.this, R.string.openpgp_error, Toast.LENGTH_SHORT).show();
 975        }
 976    }
 977
 978    @Override
 979    protected void onResume(){
 980        super.onResume();
 981        SettingsUtils.applyScreenshotPreventionSetting(this);
 982    }
 983
 984    protected int findTheme() {
 985        return ThemeHelper.find(this);
 986    }
 987
 988    @Override
 989    public void onPause() {
 990        super.onPause();
 991    }
 992
 993    @Override
 994    public boolean onMenuOpened(int id, Menu menu) {
 995        if (id == AppCompatDelegate.FEATURE_SUPPORT_ACTION_BAR && menu != null) {
 996            MenuDoubleTabUtil.recordMenuOpen();
 997        }
 998        return super.onMenuOpened(id, menu);
 999    }
1000
1001    protected void showQrCode() {
1002        showQrCode(getShareableUri());
1003    }
1004
1005    protected void showQrCode(final String uri) {
1006        if (uri == null || uri.isEmpty()) {
1007            return;
1008        }
1009        Point size = new Point();
1010        getWindowManager().getDefaultDisplay().getSize(size);
1011        final int width = (size.x < size.y ? size.x : size.y);
1012        Bitmap bitmap = BarcodeProvider.create2dBarcodeBitmap(uri, width);
1013        ImageView view = new ImageView(this);
1014        view.setBackgroundColor(Color.WHITE);
1015        view.setImageBitmap(bitmap);
1016        AlertDialog.Builder builder = new AlertDialog.Builder(this);
1017        builder.setView(view);
1018        builder.create().show();
1019    }
1020
1021    protected Account extractAccount(Intent intent) {
1022        final String jid = intent != null ? intent.getStringExtra(EXTRA_ACCOUNT) : null;
1023        try {
1024            return jid != null ? xmppConnectionService.findAccountByJid(Jid.ofEscaped(jid)) : null;
1025        } catch (IllegalArgumentException e) {
1026            return null;
1027        }
1028    }
1029
1030    public AvatarService avatarService() {
1031        return xmppConnectionService.getAvatarService();
1032    }
1033
1034    public void loadBitmap(Message message, ImageView imageView) {
1035        Drawable bm;
1036        try {
1037            bm = xmppConnectionService.getFileBackend().getThumbnail(message, getResources(), (int) (metrics.density * 288), true);
1038        } catch (IOException e) {
1039            bm = null;
1040        }
1041        if (bm != null) {
1042            cancelPotentialWork(message, imageView);
1043            imageView.setImageDrawable(bm);
1044            imageView.setBackgroundColor(0x00000000);
1045            if (Build.VERSION.SDK_INT >= 28 && bm instanceof AnimatedImageDrawable) {
1046                ((AnimatedImageDrawable) bm).start();
1047            }
1048        } else {
1049            if (cancelPotentialWork(message, imageView)) {
1050                final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
1051                final BitmapDrawable fallbackThumb = xmppConnectionService.getFileBackend().getFallbackThumbnail(message, (int) (metrics.density * 288), true);
1052                imageView.setBackgroundColor(fallbackThumb == null ? 0xff333333 : 0x00000000);
1053                final AsyncDrawable asyncDrawable = new AsyncDrawable(
1054                        getResources(), fallbackThumb != null ? fallbackThumb.getBitmap() : null, task);
1055                imageView.setImageDrawable(asyncDrawable);
1056                try {
1057                    task.execute(message);
1058                } catch (final RejectedExecutionException ignored) {
1059                    ignored.printStackTrace();
1060                }
1061            }
1062        }
1063    }
1064
1065    protected interface OnValueEdited {
1066        String onValueEdited(String value);
1067    }
1068
1069    public static class ConferenceInvite {
1070        private String uuid;
1071        private final List<Jid> jids = new ArrayList<>();
1072
1073        public static ConferenceInvite parse(Intent data) {
1074            ConferenceInvite invite = new ConferenceInvite();
1075            invite.uuid = data.getStringExtra(ChooseContactActivity.EXTRA_CONVERSATION);
1076            if (invite.uuid == null) {
1077                return null;
1078            }
1079            invite.jids.addAll(ChooseContactActivity.extractJabberIds(data));
1080            return invite;
1081        }
1082
1083        public boolean execute(XmppActivity activity) {
1084            XmppConnectionService service = activity.xmppConnectionService;
1085            Conversation conversation = service.findConversationByUuid(this.uuid);
1086            if (conversation == null) {
1087                return false;
1088            }
1089            if (conversation.getMode() == Conversation.MODE_MULTI) {
1090                for (Jid jid : jids) {
1091                    service.invite(conversation, jid);
1092                }
1093                return false;
1094            } else {
1095                jids.add(conversation.getJid().asBareJid());
1096                return service.createAdhocConference(conversation.getAccount(), null, jids, activity.adhocCallback);
1097            }
1098        }
1099    }
1100
1101    static class BitmapWorkerTask extends AsyncTask<Message, Void, Drawable> {
1102        private final WeakReference<ImageView> imageViewReference;
1103        private Message message = null;
1104
1105        private BitmapWorkerTask(ImageView imageView) {
1106            this.imageViewReference = new WeakReference<>(imageView);
1107        }
1108
1109        @Override
1110        protected Drawable doInBackground(Message... params) {
1111            if (isCancelled()) {
1112                return null;
1113            }
1114            final XmppActivity activity = find(imageViewReference);
1115            Drawable d = null;
1116            message = params[0];
1117            try {
1118                if (activity != null && activity.xmppConnectionService != null) {
1119                    d = activity.xmppConnectionService.getFileBackend().getThumbnail(message, imageViewReference.get().getContext().getResources(), (int) (activity.metrics.density * 288), false);
1120                }
1121            } catch (IOException e) { e.printStackTrace(); }
1122            final ImageView imageView = imageViewReference.get();
1123            if (d == null && activity != null && activity.xmppConnectionService != null && imageView != null && imageView.getDrawable() instanceof AsyncDrawable && ((AsyncDrawable) imageView.getDrawable()).getBitmap() == null) {
1124                d = activity.xmppConnectionService.getFileBackend().getFallbackThumbnail(message, (int) (activity.metrics.density * 288), false);
1125            }
1126            return d;
1127        }
1128
1129        @Override
1130        protected void onPostExecute(final Drawable drawable) {
1131            if (!isCancelled()) {
1132                final ImageView imageView = imageViewReference.get();
1133                if (imageView != null) {
1134                    Drawable old = imageView.getDrawable();
1135                    if (old instanceof AsyncDrawable) {
1136                        ((AsyncDrawable) old).clearTask();
1137                    }
1138                    if (drawable != null) {
1139                        imageView.setImageDrawable(drawable);
1140                    }
1141                    imageView.setBackgroundColor(drawable == null ? 0xff333333 : 0x00000000);
1142                    if (Build.VERSION.SDK_INT >= 28 && drawable instanceof AnimatedImageDrawable) {
1143                        ((AnimatedImageDrawable) drawable).start();
1144                    }
1145                }
1146            }
1147        }
1148    }
1149
1150    private static class AsyncDrawable extends BitmapDrawable {
1151        private WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
1152
1153        private AsyncDrawable(Resources res, Bitmap bitmap, BitmapWorkerTask bitmapWorkerTask) {
1154            super(res, bitmap);
1155            bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
1156        }
1157
1158        private synchronized BitmapWorkerTask getBitmapWorkerTask() {
1159            if (bitmapWorkerTaskReference == null) return null;
1160
1161            return bitmapWorkerTaskReference.get();
1162        }
1163
1164        public synchronized void clearTask() {
1165            bitmapWorkerTaskReference = null;
1166        }
1167    }
1168
1169    public static XmppActivity find(@NonNull WeakReference<ImageView> viewWeakReference) {
1170        final View view = viewWeakReference.get();
1171        return view == null ? null : find(view);
1172    }
1173
1174    public static XmppActivity find(@NonNull final View view) {
1175        Context context = view.getContext();
1176        while (context instanceof ContextWrapper) {
1177            if (context instanceof XmppActivity) {
1178                return (XmppActivity) context;
1179            }
1180            context = ((ContextWrapper) context).getBaseContext();
1181        }
1182        return null;
1183    }
1184}