XmppActivity.java

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