XmppActivity.java

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