XmppActivity.java

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