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