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.content.res.TypedArray;
  22import android.graphics.Bitmap;
  23import android.graphics.Point;
  24import android.graphics.drawable.BitmapDrawable;
  25import android.graphics.drawable.Drawable;
  26import android.net.ConnectivityManager;
  27import android.net.Uri;
  28import android.os.AsyncTask;
  29import android.os.Build;
  30import android.os.Bundle;
  31import android.os.Handler;
  32import android.os.IBinder;
  33import android.os.PowerManager;
  34import android.os.SystemClock;
  35import android.preference.PreferenceManager;
  36import android.text.Html;
  37import android.text.InputType;
  38import android.util.DisplayMetrics;
  39import android.util.Log;
  40import android.view.Menu;
  41import android.view.MenuItem;
  42import android.view.View;
  43import android.widget.Button;
  44import android.widget.CheckBox;
  45import android.widget.ImageView;
  46import android.widget.Toast;
  47
  48import androidx.annotation.BoolRes;
  49import androidx.annotation.NonNull;
  50import androidx.annotation.StringRes;
  51import androidx.appcompat.app.AlertDialog;
  52import androidx.appcompat.app.AppCompatDelegate;
  53import androidx.databinding.DataBindingUtil;
  54
  55import com.google.android.material.color.MaterialColors;
  56import com.google.android.material.dialog.MaterialAlertDialogBuilder;
  57import com.google.common.base.Strings;
  58
  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    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, 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        ExceptionHelper.init(getApplicationContext());
 489        EmojiInitializationService.execute(this);
 490        this.isCameraFeatureAvailable = getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
 491    }
 492
 493    protected boolean isCameraFeatureAvailable() {
 494        return this.isCameraFeatureAvailable;
 495    }
 496
 497    protected boolean isOptimizingBattery() {
 498        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
 499            final PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
 500            return pm != null
 501                    && !pm.isIgnoringBatteryOptimizations(getPackageName());
 502        } else {
 503            return false;
 504        }
 505    }
 506
 507    protected boolean isAffectedByDataSaver() {
 508        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
 509            final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
 510            return cm != null
 511                    && cm.isActiveNetworkMetered()
 512                    && Compatibility.getRestrictBackgroundStatus(cm) == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
 513        } else {
 514            return false;
 515        }
 516    }
 517
 518    private boolean usingEnterKey() {
 519        return getBooleanPreference("display_enter_key", R.bool.display_enter_key);
 520    }
 521
 522    private boolean useTor() {
 523        return QuickConversationsService.isConversations() && getBooleanPreference("use_tor", R.bool.use_tor);
 524    }
 525
 526    protected SharedPreferences getPreferences() {
 527        return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
 528    }
 529
 530    protected boolean getBooleanPreference(String name, @BoolRes int res) {
 531        return getPreferences().getBoolean(name, getResources().getBoolean(res));
 532    }
 533
 534    public void switchToConversation(Conversation conversation) {
 535        switchToConversation(conversation, null);
 536    }
 537
 538    public void switchToConversationAndQuote(Conversation conversation, String text) {
 539        switchToConversation(conversation, text, true, null, false, false);
 540    }
 541
 542    public void switchToConversation(Conversation conversation, String text) {
 543        switchToConversation(conversation, text, false, null, false, false);
 544    }
 545
 546    public void switchToConversationDoNotAppend(Conversation conversation, String text) {
 547        switchToConversation(conversation, text, false, null, false, true);
 548    }
 549
 550    public void highlightInMuc(Conversation conversation, String nick) {
 551        switchToConversation(conversation, null, false, nick, false, false);
 552    }
 553
 554    public void privateMsgInMuc(Conversation conversation, String nick) {
 555        switchToConversation(conversation, null, false, nick, true, false);
 556    }
 557
 558    private void switchToConversation(Conversation conversation, String text, boolean asQuote, String nick, boolean pm, boolean doNotAppend) {
 559        Intent intent = new Intent(this, ConversationsActivity.class);
 560        intent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
 561        intent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversation.getUuid());
 562        if (text != null) {
 563            intent.putExtra(Intent.EXTRA_TEXT, text);
 564            if (asQuote) {
 565                intent.putExtra(ConversationsActivity.EXTRA_AS_QUOTE, true);
 566            }
 567        }
 568        if (nick != null) {
 569            intent.putExtra(ConversationsActivity.EXTRA_NICK, nick);
 570            intent.putExtra(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, pm);
 571        }
 572        if (doNotAppend) {
 573            intent.putExtra(ConversationsActivity.EXTRA_DO_NOT_APPEND, true);
 574        }
 575        intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_CLEAR_TOP);
 576        startActivity(intent);
 577        finish();
 578    }
 579
 580    public void switchToContactDetails(Contact contact) {
 581        switchToContactDetails(contact, null);
 582    }
 583
 584    public void switchToContactDetails(Contact contact, String messageFingerprint) {
 585        Intent intent = new Intent(this, ContactDetailsActivity.class);
 586        intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT);
 587        intent.putExtra(EXTRA_ACCOUNT, contact.getAccount().getJid().asBareJid().toEscapedString());
 588        intent.putExtra("contact", contact.getJid().toEscapedString());
 589        intent.putExtra("fingerprint", messageFingerprint);
 590        startActivity(intent);
 591    }
 592
 593    public void switchToAccount(Account account, String fingerprint) {
 594        switchToAccount(account, false, fingerprint);
 595    }
 596
 597    public void switchToAccount(Account account) {
 598        switchToAccount(account, false, null);
 599    }
 600
 601    public void switchToAccount(Account account, boolean init, String fingerprint) {
 602        Intent intent = new Intent(this, EditAccountActivity.class);
 603        intent.putExtra("jid", account.getJid().asBareJid().toEscapedString());
 604        intent.putExtra("init", init);
 605        if (init) {
 606            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
 607        }
 608        if (fingerprint != null) {
 609            intent.putExtra("fingerprint", fingerprint);
 610        }
 611        startActivity(intent);
 612        if (init) {
 613            overridePendingTransition(0, 0);
 614        }
 615    }
 616
 617    protected void delegateUriPermissionsToService(Uri uri) {
 618        Intent intent = new Intent(this, XmppConnectionService.class);
 619        intent.setAction(Intent.ACTION_SEND);
 620        intent.setData(uri);
 621        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
 622        try {
 623            startService(intent);
 624        } catch (Exception e) {
 625            Log.e(Config.LOGTAG, "unable to delegate uri permission", e);
 626        }
 627    }
 628
 629    protected void inviteToConversation(Conversation conversation) {
 630        startActivityForResult(ChooseContactActivity.create(this, conversation), REQUEST_INVITE_TO_CONVERSATION);
 631    }
 632
 633    protected void announcePgp(final Account account, final Conversation conversation, Intent intent, final Runnable onSuccess) {
 634        if (account.getPgpId() == 0) {
 635            choosePgpSignId(account);
 636        } else {
 637            final String status = Strings.nullToEmpty(account.getPresenceStatusMessage());
 638            xmppConnectionService.getPgpEngine().generateSignature(intent, account, status, new UiCallback<String>() {
 639
 640                @Override
 641                public void userInputRequired(final PendingIntent pi, final String signature) {
 642                    try {
 643                        startIntentSenderForResult(pi.getIntentSender(), REQUEST_ANNOUNCE_PGP, null, 0, 0, 0,Compatibility.pgpStartIntentSenderOptions());
 644                    } catch (final SendIntentException ignored) {
 645                    }
 646                }
 647
 648                @Override
 649                public void success(String signature) {
 650                    account.setPgpSignature(signature);
 651                    xmppConnectionService.databaseBackend.updateAccount(account);
 652                    xmppConnectionService.sendPresence(account);
 653                    if (conversation != null) {
 654                        conversation.setNextEncryption(Message.ENCRYPTION_PGP);
 655                        xmppConnectionService.updateConversation(conversation);
 656                        refreshUi();
 657                    }
 658                    if (onSuccess != null) {
 659                        runOnUiThread(onSuccess);
 660                    }
 661                }
 662
 663                @Override
 664                public void error(int error, String signature) {
 665                    if (error == 0) {
 666                        account.setPgpSignId(0);
 667                        account.unsetPgpSignature();
 668                        xmppConnectionService.databaseBackend.updateAccount(account);
 669                        choosePgpSignId(account);
 670                    } else {
 671                        displayErrorDialog(error);
 672                    }
 673                }
 674            });
 675        }
 676    }
 677
 678    protected void choosePgpSignId(final Account account) {
 679        xmppConnectionService.getPgpEngine().chooseKey(account, new UiCallback<>() {
 680            @Override
 681            public void success(final Account a) {
 682            }
 683
 684            @Override
 685            public void error(int errorCode, Account object) {
 686
 687            }
 688
 689            @Override
 690            public void userInputRequired(PendingIntent pi, Account object) {
 691                try {
 692                    startIntentSenderForResult(pi.getIntentSender(),
 693                            REQUEST_CHOOSE_PGP_ID, null, 0, 0, 0, Compatibility.pgpStartIntentSenderOptions());
 694                } catch (final SendIntentException ignored) {
 695                }
 696            }
 697        });
 698    }
 699
 700    protected void displayErrorDialog(final int errorCode) {
 701        runOnUiThread(() -> {
 702            final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(XmppActivity.this);
 703            builder.setTitle(getString(R.string.error));
 704            builder.setMessage(errorCode);
 705            builder.setNeutralButton(R.string.accept, null);
 706            builder.create().show();
 707        });
 708
 709    }
 710
 711    protected void showAddToRosterDialog(final Contact contact) {
 712        final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
 713        builder.setTitle(contact.getJid().toString());
 714        builder.setMessage(getString(R.string.not_in_roster));
 715        builder.setNegativeButton(getString(R.string.cancel), null);
 716        builder.setPositiveButton(getString(R.string.add_contact), (dialog, which) -> xmppConnectionService.createContact(contact, true));
 717        builder.create().show();
 718    }
 719
 720    private void showAskForPresenceDialog(final Contact contact) {
 721        final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
 722        builder.setTitle(contact.getJid().toString());
 723        builder.setMessage(R.string.request_presence_updates);
 724        builder.setNegativeButton(R.string.cancel, null);
 725        builder.setPositiveButton(R.string.request_now,
 726                (dialog, which) -> {
 727                    if (xmppConnectionServiceBound) {
 728                        xmppConnectionService.sendPresencePacket(contact
 729                                .getAccount(), xmppConnectionService
 730                                .getPresenceGenerator()
 731                                .requestPresenceUpdatesFrom(contact));
 732                    }
 733                });
 734        builder.create().show();
 735    }
 736
 737    protected void quickEdit(String previousValue, @StringRes int hint, OnValueEdited callback) {
 738        quickEdit(previousValue, callback, hint, false, false);
 739    }
 740
 741    protected void quickEdit(String previousValue, @StringRes int hint, OnValueEdited callback, boolean permitEmpty) {
 742        quickEdit(previousValue, callback, hint, false, permitEmpty);
 743    }
 744
 745    protected void quickPasswordEdit(String previousValue, OnValueEdited callback) {
 746        quickEdit(previousValue, callback, R.string.password, true, false);
 747    }
 748
 749    @SuppressLint("InflateParams")
 750    private void quickEdit(final String previousValue,
 751                           final OnValueEdited callback,
 752                           final @StringRes int hint,
 753                           boolean password,
 754                           boolean permitEmpty) {
 755        final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
 756        final DialogQuickeditBinding binding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.dialog_quickedit, null, false);
 757        if (password) {
 758            binding.inputEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
 759        }
 760        builder.setPositiveButton(R.string.accept, null);
 761        if (hint != 0) {
 762            binding.inputLayout.setHint(getString(hint));
 763        }
 764        binding.inputEditText.requestFocus();
 765        if (previousValue != null) {
 766            binding.inputEditText.getText().append(previousValue);
 767        }
 768        builder.setView(binding.getRoot());
 769        builder.setNegativeButton(R.string.cancel, null);
 770        final AlertDialog dialog = builder.create();
 771        dialog.setOnShowListener(d -> SoftKeyboardUtils.showKeyboard(binding.inputEditText));
 772        dialog.show();
 773        View.OnClickListener clickListener = v -> {
 774            String value = binding.inputEditText.getText().toString();
 775            if (!value.equals(previousValue) && (!value.trim().isEmpty() || permitEmpty)) {
 776                String error = callback.onValueEdited(value);
 777                if (error != null) {
 778                    binding.inputLayout.setError(error);
 779                    return;
 780                }
 781            }
 782            SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
 783            dialog.dismiss();
 784        };
 785        dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(clickListener);
 786        dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setOnClickListener((v -> {
 787            SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
 788            dialog.dismiss();
 789        }));
 790        dialog.setCanceledOnTouchOutside(false);
 791        dialog.setOnDismissListener(dialog1 -> {
 792            SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
 793        });
 794    }
 795
 796    protected boolean hasStoragePermission(int requestCode) {
 797        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
 798            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
 799                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
 800                return false;
 801            } else {
 802                return true;
 803            }
 804        } else {
 805            return true;
 806        }
 807    }
 808
 809    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
 810        super.onActivityResult(requestCode, resultCode, data);
 811        if (requestCode == REQUEST_INVITE_TO_CONVERSATION && resultCode == RESULT_OK) {
 812            mPendingConferenceInvite = ConferenceInvite.parse(data);
 813            if (xmppConnectionServiceBound && mPendingConferenceInvite != null) {
 814                if (mPendingConferenceInvite.execute(this)) {
 815                    mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
 816                    mToast.show();
 817                }
 818                mPendingConferenceInvite = null;
 819            }
 820        }
 821    }
 822
 823    public boolean copyTextToClipboard(String text, int labelResId) {
 824        ClipboardManager mClipBoardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
 825        String label = getResources().getString(labelResId);
 826        if (mClipBoardManager != null) {
 827            ClipData mClipData = ClipData.newPlainText(label, text);
 828            mClipBoardManager.setPrimaryClip(mClipData);
 829            return true;
 830        }
 831        return false;
 832    }
 833
 834    protected boolean manuallyChangePresence() {
 835        return getBooleanPreference(SettingsActivity.MANUALLY_CHANGE_PRESENCE, R.bool.manually_change_presence);
 836    }
 837
 838    protected String getShareableUri() {
 839        return getShareableUri(false);
 840    }
 841
 842    protected String getShareableUri(boolean http) {
 843        return null;
 844    }
 845
 846    protected void shareLink(boolean http) {
 847        String uri = getShareableUri(http);
 848        if (uri == null || uri.isEmpty()) {
 849            return;
 850        }
 851        Intent intent = new Intent(Intent.ACTION_SEND);
 852        intent.setType("text/plain");
 853        intent.putExtra(Intent.EXTRA_TEXT, getShareableUri(http));
 854        try {
 855            startActivity(Intent.createChooser(intent, getText(R.string.share_uri_with)));
 856        } catch (ActivityNotFoundException e) {
 857            Toast.makeText(this, R.string.no_application_to_share_uri, Toast.LENGTH_SHORT).show();
 858        }
 859    }
 860
 861    protected void launchOpenKeyChain(long keyId) {
 862        PgpEngine pgp = XmppActivity.this.xmppConnectionService.getPgpEngine();
 863        try {
 864            startIntentSenderForResult(
 865                    pgp.getIntentForKey(keyId).getIntentSender(), 0, null, 0,
 866                    0, 0, Compatibility.pgpStartIntentSenderOptions());
 867        } catch (final Throwable e) {
 868            Log.d(Config.LOGTAG,"could not launch OpenKeyChain", e);
 869            Toast.makeText(XmppActivity.this, R.string.openpgp_error, Toast.LENGTH_SHORT).show();
 870        }
 871    }
 872
 873    @Override
 874    protected void onResume(){
 875        super.onResume();
 876        SettingsUtils.applyScreenshotPreventionSetting(this);
 877    }
 878
 879    @Override
 880    public void onPause() {
 881        super.onPause();
 882    }
 883
 884    @Override
 885    public boolean onMenuOpened(int id, Menu menu) {
 886        if (id == AppCompatDelegate.FEATURE_SUPPORT_ACTION_BAR && menu != null) {
 887            MenuDoubleTabUtil.recordMenuOpen();
 888        }
 889        return super.onMenuOpened(id, menu);
 890    }
 891
 892    protected void showQrCode() {
 893        showQrCode(getShareableUri());
 894    }
 895
 896    protected void showQrCode(final String uri) {
 897        if (uri == null || uri.isEmpty()) {
 898            return;
 899        }
 900        final Point size = new Point();
 901        getWindowManager().getDefaultDisplay().getSize(size);
 902        final int width = Math.min(size.x, size.y);
 903        final boolean nightMode = (this.getResources().getConfiguration().uiMode
 904                & Configuration.UI_MODE_NIGHT_MASK)
 905                == Configuration.UI_MODE_NIGHT_YES;
 906        final int black;
 907        final int white;
 908        if (nightMode) {
 909            black = MaterialColors.getColor(this, com.google.android.material.R.attr.colorSurfaceContainerHighest,"No surface color configured");
 910            white = MaterialColors.getColor(this, com.google.android.material.R.attr.colorSurfaceInverse,"No inverse surface color configured");
 911        } else {
 912            black = MaterialColors.getColor(this, com.google.android.material.R.attr.colorSurfaceInverse,"No inverse surface color configured");
 913            white = MaterialColors.getColor(this, com.google.android.material.R.attr.colorSurfaceContainerHighest,"No surface color configured");
 914        }
 915        final var bitmap = BarcodeProvider.create2dBarcodeBitmap(uri, width, black, white);
 916        final ImageView view = new ImageView(this);
 917        view.setBackgroundColor(white);
 918        view.setImageBitmap(bitmap);
 919        MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
 920        builder.setView(view);
 921        builder.create().show();
 922    }
 923
 924    protected Account extractAccount(Intent intent) {
 925        final String jid = intent != null ? intent.getStringExtra(EXTRA_ACCOUNT) : null;
 926        try {
 927            return jid != null ? xmppConnectionService.findAccountByJid(Jid.ofEscaped(jid)) : null;
 928        } catch (IllegalArgumentException e) {
 929            return null;
 930        }
 931    }
 932
 933    public AvatarService avatarService() {
 934        return xmppConnectionService.getAvatarService();
 935    }
 936
 937    public void loadBitmap(Message message, ImageView imageView) {
 938        Bitmap bm;
 939        try {
 940            bm = xmppConnectionService.getFileBackend().getThumbnail(message, (int) (metrics.density * 288), true);
 941        } catch (IOException e) {
 942            bm = null;
 943        }
 944        if (bm != null) {
 945            cancelPotentialWork(message, imageView);
 946            imageView.setImageBitmap(bm);
 947            imageView.setBackgroundColor(0x00000000);
 948        } else {
 949            if (cancelPotentialWork(message, imageView)) {
 950                imageView.setBackgroundColor(0xff333333);
 951                imageView.setImageDrawable(null);
 952                final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
 953                final AsyncDrawable asyncDrawable = new AsyncDrawable(
 954                        getResources(), null, task);
 955                imageView.setImageDrawable(asyncDrawable);
 956                try {
 957                    task.execute(message);
 958                } catch (final RejectedExecutionException ignored) {
 959                    ignored.printStackTrace();
 960                }
 961            }
 962        }
 963    }
 964
 965    protected interface OnValueEdited {
 966        String onValueEdited(String value);
 967    }
 968
 969    public static class ConferenceInvite {
 970        private String uuid;
 971        private final List<Jid> jids = new ArrayList<>();
 972
 973        public static ConferenceInvite parse(Intent data) {
 974            ConferenceInvite invite = new ConferenceInvite();
 975            invite.uuid = data.getStringExtra(ChooseContactActivity.EXTRA_CONVERSATION);
 976            if (invite.uuid == null) {
 977                return null;
 978            }
 979            invite.jids.addAll(ChooseContactActivity.extractJabberIds(data));
 980            return invite;
 981        }
 982
 983        public boolean execute(XmppActivity activity) {
 984            XmppConnectionService service = activity.xmppConnectionService;
 985            Conversation conversation = service.findConversationByUuid(this.uuid);
 986            if (conversation == null) {
 987                return false;
 988            }
 989            if (conversation.getMode() == Conversation.MODE_MULTI) {
 990                for (Jid jid : jids) {
 991                    service.invite(conversation, jid);
 992                }
 993                return false;
 994            } else {
 995                jids.add(conversation.getJid().asBareJid());
 996                return service.createAdhocConference(conversation.getAccount(), null, jids, activity.adhocCallback);
 997            }
 998        }
 999    }
1000
1001    static class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
1002        private final WeakReference<ImageView> imageViewReference;
1003        private Message message = null;
1004
1005        private BitmapWorkerTask(ImageView imageView) {
1006            this.imageViewReference = new WeakReference<>(imageView);
1007        }
1008
1009        @Override
1010        protected Bitmap doInBackground(Message... params) {
1011            if (isCancelled()) {
1012                return null;
1013            }
1014            message = params[0];
1015            try {
1016                final XmppActivity activity = find(imageViewReference);
1017                if (activity != null && activity.xmppConnectionService != null) {
1018                    return activity.xmppConnectionService.getFileBackend().getThumbnail(message, (int) (activity.metrics.density * 288), false);
1019                } else {
1020                    return null;
1021                }
1022            } catch (IOException e) {
1023                return null;
1024            }
1025        }
1026
1027        @Override
1028        protected void onPostExecute(final Bitmap bitmap) {
1029            if (!isCancelled()) {
1030                final ImageView imageView = imageViewReference.get();
1031                if (imageView != null) {
1032                    imageView.setImageBitmap(bitmap);
1033                    imageView.setBackgroundColor(bitmap == null ? 0xff333333 : 0x00000000);
1034                }
1035            }
1036        }
1037    }
1038
1039    private static class AsyncDrawable extends BitmapDrawable {
1040        private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
1041
1042        private AsyncDrawable(Resources res, Bitmap bitmap, BitmapWorkerTask bitmapWorkerTask) {
1043            super(res, bitmap);
1044            bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
1045        }
1046
1047        private BitmapWorkerTask getBitmapWorkerTask() {
1048            return bitmapWorkerTaskReference.get();
1049        }
1050    }
1051
1052    public static XmppActivity find(@NonNull WeakReference<ImageView> viewWeakReference) {
1053        final View view = viewWeakReference.get();
1054        return view == null ? null : find(view);
1055    }
1056
1057    public static XmppActivity find(@NonNull final View view) {
1058        Context context = view.getContext();
1059        while (context instanceof ContextWrapper) {
1060            if (context instanceof XmppActivity) {
1061                return (XmppActivity) context;
1062            }
1063            context = ((ContextWrapper) context).getBaseContext();
1064        }
1065        return null;
1066    }
1067}