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