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