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