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