XmppActivity.java

   1package eu.siacs.conversations.ui;
   2
   3import android.telephony.TelephonyManager;
   4
   5import android.Manifest;
   6import android.annotation.SuppressLint;
   7import android.annotation.TargetApi;
   8import android.app.PendingIntent;
   9import android.content.ActivityNotFoundException;
  10import android.content.ClipData;
  11import android.content.ClipboardManager;
  12import android.content.ComponentName;
  13import android.content.Context;
  14import android.content.ContextWrapper;
  15import android.content.DialogInterface;
  16import android.content.Intent;
  17import android.content.IntentSender.SendIntentException;
  18import android.content.ServiceConnection;
  19import android.content.SharedPreferences;
  20import android.content.pm.PackageManager;
  21import android.content.pm.ResolveInfo;
  22import android.content.res.Resources;
  23import android.content.res.TypedArray;
  24import android.graphics.Bitmap;
  25import android.graphics.Color;
  26import android.graphics.Point;
  27import android.graphics.drawable.AnimatedImageDrawable;
  28import android.graphics.drawable.BitmapDrawable;
  29import android.graphics.drawable.Drawable;
  30import android.net.ConnectivityManager;
  31import android.net.Uri;
  32import android.os.AsyncTask;
  33import android.os.Build;
  34import android.os.Bundle;
  35import android.os.Handler;
  36import android.os.IBinder;
  37import android.os.PowerManager;
  38import android.os.SystemClock;
  39import android.preference.PreferenceManager;
  40import android.text.Html;
  41import android.text.InputType;
  42import android.util.DisplayMetrics;
  43import android.util.Log;
  44import android.view.Menu;
  45import android.view.MenuItem;
  46import android.view.View;
  47import android.widget.ImageView;
  48import android.widget.Toast;
  49
  50import androidx.annotation.BoolRes;
  51import androidx.annotation.NonNull;
  52import androidx.annotation.RequiresApi;
  53import androidx.annotation.StringRes;
  54import androidx.appcompat.app.AlertDialog;
  55import androidx.appcompat.app.AlertDialog.Builder;
  56import androidx.appcompat.app.AppCompatDelegate;
  57import androidx.databinding.DataBindingUtil;
  58
  59import com.google.common.base.Strings;
  60
  61import java.io.IOException;
  62import java.lang.ref.WeakReference;
  63import java.util.ArrayList;
  64import java.util.List;
  65import java.util.concurrent.RejectedExecutionException;
  66
  67import eu.siacs.conversations.Config;
  68import eu.siacs.conversations.R;
  69import eu.siacs.conversations.crypto.PgpEngine;
  70import eu.siacs.conversations.databinding.DialogQuickeditBinding;
  71import eu.siacs.conversations.entities.Account;
  72import eu.siacs.conversations.entities.Contact;
  73import eu.siacs.conversations.entities.Conversation;
  74import eu.siacs.conversations.entities.Message;
  75import eu.siacs.conversations.entities.Presences;
  76import eu.siacs.conversations.services.AvatarService;
  77import eu.siacs.conversations.services.BarcodeProvider;
  78import eu.siacs.conversations.services.EmojiInitializationService;
  79import eu.siacs.conversations.services.QuickConversationsService;
  80import eu.siacs.conversations.services.XmppConnectionService;
  81import eu.siacs.conversations.services.XmppConnectionService.XmppConnectionBinder;
  82import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
  83import eu.siacs.conversations.ui.util.PresenceSelector;
  84import eu.siacs.conversations.ui.util.SoftKeyboardUtils;
  85import eu.siacs.conversations.utils.AccountUtils;
  86import eu.siacs.conversations.utils.Compatibility;
  87import eu.siacs.conversations.utils.ExceptionHelper;
  88import eu.siacs.conversations.ui.util.SettingsUtils;
  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    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    abstract void onBackendConnected();
 296
 297    protected void registerListeners() {
 298        if (this instanceof XmppConnectionService.OnConversationUpdate) {
 299            this.xmppConnectionService.setOnConversationListChangedListener((XmppConnectionService.OnConversationUpdate) this);
 300        }
 301        if (this instanceof XmppConnectionService.OnAccountUpdate) {
 302            this.xmppConnectionService.setOnAccountListChangedListener((XmppConnectionService.OnAccountUpdate) this);
 303        }
 304        if (this instanceof XmppConnectionService.OnCaptchaRequested) {
 305            this.xmppConnectionService.setOnCaptchaRequestedListener((XmppConnectionService.OnCaptchaRequested) this);
 306        }
 307        if (this instanceof XmppConnectionService.OnRosterUpdate) {
 308            this.xmppConnectionService.setOnRosterUpdateListener((XmppConnectionService.OnRosterUpdate) this);
 309        }
 310        if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
 311            this.xmppConnectionService.setOnMucRosterUpdateListener((XmppConnectionService.OnMucRosterUpdate) this);
 312        }
 313        if (this instanceof OnUpdateBlocklist) {
 314            this.xmppConnectionService.setOnUpdateBlocklistListener((OnUpdateBlocklist) this);
 315        }
 316        if (this instanceof XmppConnectionService.OnShowErrorToast) {
 317            this.xmppConnectionService.setOnShowErrorToastListener((XmppConnectionService.OnShowErrorToast) this);
 318        }
 319        if (this instanceof OnKeyStatusUpdated) {
 320            this.xmppConnectionService.setOnKeyStatusUpdatedListener((OnKeyStatusUpdated) this);
 321        }
 322        if (this instanceof XmppConnectionService.OnJingleRtpConnectionUpdate) {
 323            this.xmppConnectionService.setOnRtpConnectionUpdateListener((XmppConnectionService.OnJingleRtpConnectionUpdate) this);
 324        }
 325    }
 326
 327    protected void unregisterListeners() {
 328        if (this instanceof XmppConnectionService.OnConversationUpdate) {
 329            this.xmppConnectionService.removeOnConversationListChangedListener((XmppConnectionService.OnConversationUpdate) this);
 330        }
 331        if (this instanceof XmppConnectionService.OnAccountUpdate) {
 332            this.xmppConnectionService.removeOnAccountListChangedListener((XmppConnectionService.OnAccountUpdate) this);
 333        }
 334        if (this instanceof XmppConnectionService.OnCaptchaRequested) {
 335            this.xmppConnectionService.removeOnCaptchaRequestedListener((XmppConnectionService.OnCaptchaRequested) this);
 336        }
 337        if (this instanceof XmppConnectionService.OnRosterUpdate) {
 338            this.xmppConnectionService.removeOnRosterUpdateListener((XmppConnectionService.OnRosterUpdate) this);
 339        }
 340        if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
 341            this.xmppConnectionService.removeOnMucRosterUpdateListener((XmppConnectionService.OnMucRosterUpdate) this);
 342        }
 343        if (this instanceof OnUpdateBlocklist) {
 344            this.xmppConnectionService.removeOnUpdateBlocklistListener((OnUpdateBlocklist) this);
 345        }
 346        if (this instanceof XmppConnectionService.OnShowErrorToast) {
 347            this.xmppConnectionService.removeOnShowErrorToastListener((XmppConnectionService.OnShowErrorToast) this);
 348        }
 349        if (this instanceof OnKeyStatusUpdated) {
 350            this.xmppConnectionService.removeOnNewKeysAvailableListener((OnKeyStatusUpdated) this);
 351        }
 352        if (this instanceof XmppConnectionService.OnJingleRtpConnectionUpdate) {
 353            this.xmppConnectionService.removeRtpConnectionUpdateListener((XmppConnectionService.OnJingleRtpConnectionUpdate) this);
 354        }
 355    }
 356
 357    @Override
 358    public boolean onOptionsItemSelected(final MenuItem item) {
 359        switch (item.getItemId()) {
 360            case R.id.action_settings:
 361                startActivity(new Intent(this, SettingsActivity.class));
 362                break;
 363            case R.id.action_accounts:
 364                AccountUtils.launchManageAccounts(this);
 365                break;
 366            case R.id.action_account:
 367                AccountUtils.launchManageAccount(this);
 368                break;
 369            case android.R.id.home:
 370                finish();
 371                break;
 372            case R.id.action_show_qr_code:
 373                showQrCode();
 374                break;
 375        }
 376        return super.onOptionsItemSelected(item);
 377    }
 378
 379    public void selectPresence(final Conversation conversation, final PresenceSelector.OnPresenceSelected listener) {
 380        final Contact contact = conversation.getContact();
 381        if (contact.showInRoster() || contact.isSelf()) {
 382            final Presences presences = contact.getPresences();
 383            if (presences.size() == 0) {
 384                if (contact.isSelf()) {
 385                    conversation.setNextCounterpart(null);
 386                    listener.onPresenceSelected();
 387                } else if (!contact.getOption(Contact.Options.TO)
 388                        && !contact.getOption(Contact.Options.ASKING)
 389                        && contact.getAccount().getStatus() == Account.State.ONLINE) {
 390                    showAskForPresenceDialog(contact);
 391                } else if (!contact.getOption(Contact.Options.TO)
 392                        || !contact.getOption(Contact.Options.FROM)) {
 393                    PresenceSelector.warnMutualPresenceSubscription(this, conversation, listener);
 394                } else {
 395                    conversation.setNextCounterpart(null);
 396                    listener.onPresenceSelected();
 397                }
 398            } else if (presences.size() == 1) {
 399                final String presence = presences.toResourceArray()[0];
 400                conversation.setNextCounterpart(PresenceSelector.getNextCounterpart(contact, presence));
 401                listener.onPresenceSelected();
 402            } else {
 403                PresenceSelector.showPresenceSelectionDialog(this, conversation, listener);
 404            }
 405        } else {
 406            showAddToRosterDialog(conversation.getContact());
 407        }
 408    }
 409
 410    @SuppressLint("UnsupportedChromeOsCameraSystemFeature")
 411    @Override
 412    protected void onCreate(Bundle savedInstanceState) {
 413        super.onCreate(savedInstanceState);
 414        metrics = getResources().getDisplayMetrics();
 415        ExceptionHelper.init(getApplicationContext());
 416        EmojiInitializationService.execute(this);
 417        this.isCameraFeatureAvailable = getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
 418        this.mTheme = findTheme();
 419        setTheme(this.mTheme);
 420    }
 421
 422    protected boolean isCameraFeatureAvailable() {
 423        return this.isCameraFeatureAvailable;
 424    }
 425
 426    public boolean isDarkTheme() {
 427        return ThemeHelper.isDark(mTheme);
 428    }
 429
 430    public int getThemeResource(int r_attr_name, int r_drawable_def) {
 431        int[] attrs = {r_attr_name};
 432        TypedArray ta = this.getTheme().obtainStyledAttributes(attrs);
 433
 434        int res = ta.getResourceId(0, r_drawable_def);
 435        ta.recycle();
 436
 437        return res;
 438    }
 439
 440    protected boolean isOptimizingBattery() {
 441        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
 442            final PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
 443            return pm != null
 444                    && !pm.isIgnoringBatteryOptimizations(getPackageName());
 445        } else {
 446            return false;
 447        }
 448    }
 449
 450    protected boolean isAffectedByDataSaver() {
 451        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
 452            final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
 453            return cm != null
 454                    && cm.isActiveNetworkMetered()
 455                    && Compatibility.getRestrictBackgroundStatus(cm) == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
 456        } else {
 457            return false;
 458        }
 459    }
 460
 461    private boolean usingEnterKey() {
 462        return getBooleanPreference("display_enter_key", R.bool.display_enter_key);
 463    }
 464
 465    private boolean useTor() {
 466        return getBooleanPreference("use_tor", R.bool.use_tor);
 467    }
 468
 469    protected SharedPreferences getPreferences() {
 470        return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
 471    }
 472
 473    protected boolean getBooleanPreference(String name, @BoolRes int res) {
 474        return getPreferences().getBoolean(name, getResources().getBoolean(res));
 475    }
 476
 477    public void switchToConversation(Conversation conversation) {
 478        switchToConversation(conversation, null);
 479    }
 480
 481    public void switchToConversationAndQuote(Conversation conversation, String text) {
 482        switchToConversation(conversation, text, true, null, false, false);
 483    }
 484
 485    public void switchToConversation(Conversation conversation, String text) {
 486        switchToConversation(conversation, text, false, null, false, false);
 487    }
 488
 489    public void switchToConversationDoNotAppend(Conversation conversation, String text) {
 490        switchToConversation(conversation, text, false, null, false, true);
 491    }
 492
 493    public void highlightInMuc(Conversation conversation, String nick) {
 494        switchToConversation(conversation, null, false, nick, false, false);
 495    }
 496
 497    public void privateMsgInMuc(Conversation conversation, String nick) {
 498        switchToConversation(conversation, null, false, nick, true, false);
 499    }
 500
 501    private void switchToConversation(Conversation conversation, String text, boolean asQuote, String nick, boolean pm, boolean doNotAppend) {
 502        Intent intent = new Intent(this, ConversationsActivity.class);
 503        intent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
 504        intent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversation.getUuid());
 505        if (text != null) {
 506            intent.putExtra(Intent.EXTRA_TEXT, text);
 507            if (asQuote) {
 508                intent.putExtra(ConversationsActivity.EXTRA_AS_QUOTE, true);
 509            }
 510        }
 511        if (nick != null) {
 512            intent.putExtra(ConversationsActivity.EXTRA_NICK, nick);
 513            intent.putExtra(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, pm);
 514        }
 515        if (doNotAppend) {
 516            intent.putExtra(ConversationsActivity.EXTRA_DO_NOT_APPEND, true);
 517        }
 518        intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_CLEAR_TOP);
 519        startActivity(intent);
 520        finish();
 521    }
 522
 523    public void switchToContactDetails(Contact contact) {
 524        switchToContactDetails(contact, null);
 525    }
 526
 527    public void switchToContactDetails(Contact contact, String messageFingerprint) {
 528        Intent intent = new Intent(this, ContactDetailsActivity.class);
 529        intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT);
 530        intent.putExtra(EXTRA_ACCOUNT, contact.getAccount().getJid().asBareJid().toEscapedString());
 531        intent.putExtra("contact", contact.getJid().toEscapedString());
 532        intent.putExtra("fingerprint", messageFingerprint);
 533        startActivity(intent);
 534    }
 535
 536    public void switchToAccount(Account account, String fingerprint) {
 537        switchToAccount(account, false, fingerprint);
 538    }
 539
 540    public void switchToAccount(Account account) {
 541        switchToAccount(account, false, null);
 542    }
 543
 544    public void switchToAccount(Account account, boolean init, String fingerprint) {
 545        Intent intent = new Intent(this, EditAccountActivity.class);
 546        intent.putExtra("jid", account.getJid().asBareJid().toEscapedString());
 547        intent.putExtra("init", init);
 548        if (init) {
 549            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
 550        }
 551        if (fingerprint != null) {
 552            intent.putExtra("fingerprint", fingerprint);
 553        }
 554        startActivity(intent);
 555        if (init) {
 556            overridePendingTransition(0, 0);
 557        }
 558    }
 559
 560    protected void delegateUriPermissionsToService(Uri uri) {
 561        Intent intent = new Intent(this, XmppConnectionService.class);
 562        intent.setAction(Intent.ACTION_SEND);
 563        intent.setData(uri);
 564        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
 565        try {
 566            startService(intent);
 567        } catch (Exception e) {
 568            Log.e(Config.LOGTAG, "unable to delegate uri permission", e);
 569        }
 570    }
 571
 572    protected void inviteToConversation(Conversation conversation) {
 573        startActivityForResult(ChooseContactActivity.create(this, conversation), REQUEST_INVITE_TO_CONVERSATION);
 574    }
 575
 576    protected void announcePgp(final Account account, final Conversation conversation, Intent intent, final Runnable onSuccess) {
 577        if (account.getPgpId() == 0) {
 578            choosePgpSignId(account);
 579        } else {
 580            final String status = Strings.nullToEmpty(account.getPresenceStatusMessage());
 581            xmppConnectionService.getPgpEngine().generateSignature(intent, account, status, new UiCallback<String>() {
 582
 583                @Override
 584                public void userInputRequired(PendingIntent pi, String signature) {
 585                    try {
 586                        startIntentSenderForResult(pi.getIntentSender(), REQUEST_ANNOUNCE_PGP, null, 0, 0, 0);
 587                    } catch (final SendIntentException ignored) {
 588                    }
 589                }
 590
 591                @Override
 592                public void success(String signature) {
 593                    account.setPgpSignature(signature);
 594                    xmppConnectionService.databaseBackend.updateAccount(account);
 595                    xmppConnectionService.sendPresence(account);
 596                    if (conversation != null) {
 597                        conversation.setNextEncryption(Message.ENCRYPTION_PGP);
 598                        xmppConnectionService.updateConversation(conversation);
 599                        refreshUi();
 600                    }
 601                    if (onSuccess != null) {
 602                        runOnUiThread(onSuccess);
 603                    }
 604                }
 605
 606                @Override
 607                public void error(int error, String signature) {
 608                    if (error == 0) {
 609                        account.setPgpSignId(0);
 610                        account.unsetPgpSignature();
 611                        xmppConnectionService.databaseBackend.updateAccount(account);
 612                        choosePgpSignId(account);
 613                    } else {
 614                        displayErrorDialog(error);
 615                    }
 616                }
 617            });
 618        }
 619    }
 620
 621    @SuppressWarnings("deprecation")
 622    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
 623    protected void setListItemBackgroundOnView(View view) {
 624        int sdk = android.os.Build.VERSION.SDK_INT;
 625        if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
 626            view.setBackgroundDrawable(getResources().getDrawable(R.drawable.greybackground));
 627        } else {
 628            view.setBackground(getResources().getDrawable(R.drawable.greybackground));
 629        }
 630    }
 631
 632    protected void choosePgpSignId(Account account) {
 633        xmppConnectionService.getPgpEngine().chooseKey(account, new UiCallback<Account>() {
 634            @Override
 635            public void success(Account account1) {
 636            }
 637
 638            @Override
 639            public void error(int errorCode, Account object) {
 640
 641            }
 642
 643            @Override
 644            public void userInputRequired(PendingIntent pi, Account object) {
 645                try {
 646                    startIntentSenderForResult(pi.getIntentSender(),
 647                            REQUEST_CHOOSE_PGP_ID, null, 0, 0, 0);
 648                } catch (final SendIntentException ignored) {
 649                }
 650            }
 651        });
 652    }
 653
 654    protected void displayErrorDialog(final int errorCode) {
 655        runOnUiThread(() -> {
 656            Builder builder = new Builder(XmppActivity.this);
 657            builder.setIconAttribute(android.R.attr.alertDialogIcon);
 658            builder.setTitle(getString(R.string.error));
 659            builder.setMessage(errorCode);
 660            builder.setNeutralButton(R.string.accept, null);
 661            builder.create().show();
 662        });
 663
 664    }
 665
 666    protected void showAddToRosterDialog(final Contact contact) {
 667        AlertDialog.Builder builder = new AlertDialog.Builder(this);
 668        builder.setTitle(contact.getJid().toString());
 669        builder.setMessage(getString(R.string.not_in_roster));
 670        builder.setNegativeButton(getString(R.string.cancel), null);
 671        builder.setPositiveButton(getString(R.string.add_contact), (dialog, which) -> xmppConnectionService.createContact(contact, true));
 672        builder.create().show();
 673    }
 674
 675    private void showAskForPresenceDialog(final Contact contact) {
 676        AlertDialog.Builder builder = new AlertDialog.Builder(this);
 677        builder.setTitle(contact.getJid().toString());
 678        builder.setMessage(R.string.request_presence_updates);
 679        builder.setNegativeButton(R.string.cancel, null);
 680        builder.setPositiveButton(R.string.request_now,
 681                (dialog, which) -> {
 682                    if (xmppConnectionServiceBound) {
 683                        xmppConnectionService.sendPresencePacket(contact
 684                                .getAccount(), xmppConnectionService
 685                                .getPresenceGenerator()
 686                                .requestPresenceUpdatesFrom(contact));
 687                    }
 688                });
 689        builder.create().show();
 690    }
 691
 692    protected void quickEdit(String previousValue, @StringRes int hint, OnValueEdited callback) {
 693        quickEdit(previousValue, callback, hint, false, false);
 694    }
 695
 696    protected void quickEdit(String previousValue, @StringRes int hint, OnValueEdited callback, boolean permitEmpty) {
 697        quickEdit(previousValue, callback, hint, false, permitEmpty);
 698    }
 699
 700    protected void quickPasswordEdit(String previousValue, OnValueEdited callback) {
 701        quickEdit(previousValue, callback, R.string.password, true, false);
 702    }
 703
 704    @SuppressLint("InflateParams")
 705    private void quickEdit(final String previousValue,
 706                           final OnValueEdited callback,
 707                           final @StringRes int hint,
 708                           boolean password,
 709                           boolean permitEmpty) {
 710        AlertDialog.Builder builder = new AlertDialog.Builder(this);
 711        DialogQuickeditBinding binding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.dialog_quickedit, null, false);
 712        if (password) {
 713            binding.inputEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
 714        }
 715        builder.setPositiveButton(R.string.accept, null);
 716        if (hint != 0) {
 717            binding.inputLayout.setHint(getString(hint));
 718        }
 719        binding.inputEditText.requestFocus();
 720        if (previousValue != null) {
 721            binding.inputEditText.getText().append(previousValue);
 722        }
 723        builder.setView(binding.getRoot());
 724        builder.setNegativeButton(R.string.cancel, null);
 725        final AlertDialog dialog = builder.create();
 726        dialog.setOnShowListener(d -> SoftKeyboardUtils.showKeyboard(binding.inputEditText));
 727        dialog.show();
 728        View.OnClickListener clickListener = v -> {
 729            String value = binding.inputEditText.getText().toString();
 730            if (!value.equals(previousValue) && (!value.trim().isEmpty() || permitEmpty)) {
 731                String error = callback.onValueEdited(value);
 732                if (error != null) {
 733                    binding.inputLayout.setError(error);
 734                    return;
 735                }
 736            }
 737            SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
 738            dialog.dismiss();
 739        };
 740        dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(clickListener);
 741        dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setOnClickListener((v -> {
 742            SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
 743            dialog.dismiss();
 744        }));
 745        dialog.setCanceledOnTouchOutside(false);
 746        dialog.setOnDismissListener(dialog1 -> {
 747            SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
 748        });
 749    }
 750
 751    protected boolean hasStoragePermission(int requestCode) {
 752        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
 753            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
 754                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
 755                return false;
 756            } else {
 757                return true;
 758            }
 759        } else {
 760            return true;
 761        }
 762    }
 763
 764    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
 765        super.onActivityResult(requestCode, resultCode, data);
 766        if (requestCode == REQUEST_INVITE_TO_CONVERSATION && resultCode == RESULT_OK) {
 767            mPendingConferenceInvite = ConferenceInvite.parse(data);
 768            if (xmppConnectionServiceBound && mPendingConferenceInvite != null) {
 769                if (mPendingConferenceInvite.execute(this)) {
 770                    mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
 771                    mToast.show();
 772                }
 773                mPendingConferenceInvite = null;
 774            }
 775        }
 776    }
 777
 778    public boolean copyTextToClipboard(String text, int labelResId) {
 779        ClipboardManager mClipBoardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
 780        String label = getResources().getString(labelResId);
 781        if (mClipBoardManager != null) {
 782            ClipData mClipData = ClipData.newPlainText(label, text);
 783            mClipBoardManager.setPrimaryClip(mClipData);
 784            return true;
 785        }
 786        return false;
 787    }
 788
 789    protected boolean manuallyChangePresence() {
 790        return getBooleanPreference(SettingsActivity.MANUALLY_CHANGE_PRESENCE, R.bool.manually_change_presence);
 791    }
 792
 793    protected String getShareableUri() {
 794        return getShareableUri(false);
 795    }
 796
 797    protected String getShareableUri(boolean http) {
 798        return null;
 799    }
 800
 801    protected void shareLink(boolean http) {
 802        String uri = getShareableUri(http);
 803        if (uri == null || uri.isEmpty()) {
 804            return;
 805        }
 806        Intent intent = new Intent(Intent.ACTION_SEND);
 807        intent.setType("text/plain");
 808        intent.putExtra(Intent.EXTRA_TEXT, getShareableUri(http));
 809        try {
 810            startActivity(Intent.createChooser(intent, getText(R.string.share_uri_with)));
 811        } catch (ActivityNotFoundException e) {
 812            Toast.makeText(this, R.string.no_application_to_share_uri, Toast.LENGTH_SHORT).show();
 813        }
 814    }
 815
 816    protected void launchOpenKeyChain(long keyId) {
 817        PgpEngine pgp = XmppActivity.this.xmppConnectionService.getPgpEngine();
 818        try {
 819            startIntentSenderForResult(
 820                    pgp.getIntentForKey(keyId).getIntentSender(), 0, null, 0,
 821                    0, 0);
 822        } catch (Throwable e) {
 823            Toast.makeText(XmppActivity.this, R.string.openpgp_error, Toast.LENGTH_SHORT).show();
 824        }
 825    }
 826
 827    @Override
 828    protected void onResume(){
 829        super.onResume();
 830        SettingsUtils.applyScreenshotPreventionSetting(this);
 831    }
 832
 833    protected int findTheme() {
 834        return ThemeHelper.find(this);
 835    }
 836
 837    @Override
 838    public void onPause() {
 839        super.onPause();
 840    }
 841
 842    @Override
 843    public boolean onMenuOpened(int id, Menu menu) {
 844        if (id == AppCompatDelegate.FEATURE_SUPPORT_ACTION_BAR && menu != null) {
 845            MenuDoubleTabUtil.recordMenuOpen();
 846        }
 847        return super.onMenuOpened(id, menu);
 848    }
 849
 850    protected void showQrCode() {
 851        showQrCode(getShareableUri());
 852    }
 853
 854    protected void showQrCode(final String uri) {
 855        if (uri == null || uri.isEmpty()) {
 856            return;
 857        }
 858        Point size = new Point();
 859        getWindowManager().getDefaultDisplay().getSize(size);
 860        final int width = (size.x < size.y ? size.x : size.y);
 861        Bitmap bitmap = BarcodeProvider.create2dBarcodeBitmap(uri, width);
 862        ImageView view = new ImageView(this);
 863        view.setBackgroundColor(Color.WHITE);
 864        view.setImageBitmap(bitmap);
 865        AlertDialog.Builder builder = new AlertDialog.Builder(this);
 866        builder.setView(view);
 867        builder.create().show();
 868    }
 869
 870    protected Account extractAccount(Intent intent) {
 871        final String jid = intent != null ? intent.getStringExtra(EXTRA_ACCOUNT) : null;
 872        try {
 873            return jid != null ? xmppConnectionService.findAccountByJid(Jid.ofEscaped(jid)) : null;
 874        } catch (IllegalArgumentException e) {
 875            return null;
 876        }
 877    }
 878
 879    public AvatarService avatarService() {
 880        return xmppConnectionService.getAvatarService();
 881    }
 882
 883    public void loadBitmap(Message message, ImageView imageView) {
 884        Drawable bm;
 885        try {
 886            bm = xmppConnectionService.getFileBackend().getThumbnail(message, getResources(), (int) (metrics.density * 288), true);
 887        } catch (IOException e) {
 888            bm = null;
 889        }
 890        if (bm != null) {
 891            cancelPotentialWork(message, imageView);
 892            imageView.setImageDrawable(bm);
 893            imageView.setBackgroundColor(0x00000000);
 894            if (Build.VERSION.SDK_INT >= 28 && bm instanceof AnimatedImageDrawable) {
 895                ((AnimatedImageDrawable) bm).start();
 896            }
 897        } else {
 898            if (cancelPotentialWork(message, imageView)) {
 899                imageView.setBackgroundColor(0xff333333);
 900                imageView.setImageDrawable(null);
 901                final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
 902                final AsyncDrawable asyncDrawable = new AsyncDrawable(
 903                        getResources(), null, task);
 904                imageView.setImageDrawable(asyncDrawable);
 905                try {
 906                    task.execute(message);
 907                } catch (final RejectedExecutionException ignored) {
 908                    ignored.printStackTrace();
 909                }
 910            }
 911        }
 912    }
 913
 914    protected interface OnValueEdited {
 915        String onValueEdited(String value);
 916    }
 917
 918    public static class ConferenceInvite {
 919        private String uuid;
 920        private final List<Jid> jids = new ArrayList<>();
 921
 922        public static ConferenceInvite parse(Intent data) {
 923            ConferenceInvite invite = new ConferenceInvite();
 924            invite.uuid = data.getStringExtra(ChooseContactActivity.EXTRA_CONVERSATION);
 925            if (invite.uuid == null) {
 926                return null;
 927            }
 928            invite.jids.addAll(ChooseContactActivity.extractJabberIds(data));
 929            return invite;
 930        }
 931
 932        public boolean execute(XmppActivity activity) {
 933            XmppConnectionService service = activity.xmppConnectionService;
 934            Conversation conversation = service.findConversationByUuid(this.uuid);
 935            if (conversation == null) {
 936                return false;
 937            }
 938            if (conversation.getMode() == Conversation.MODE_MULTI) {
 939                for (Jid jid : jids) {
 940                    service.invite(conversation, jid);
 941                }
 942                return false;
 943            } else {
 944                jids.add(conversation.getJid().asBareJid());
 945                return service.createAdhocConference(conversation.getAccount(), null, jids, activity.adhocCallback);
 946            }
 947        }
 948    }
 949
 950    static class BitmapWorkerTask extends AsyncTask<Message, Void, Drawable> {
 951        private final WeakReference<ImageView> imageViewReference;
 952        private Message message = null;
 953
 954        private BitmapWorkerTask(ImageView imageView) {
 955            this.imageViewReference = new WeakReference<>(imageView);
 956        }
 957
 958        @Override
 959        protected Drawable doInBackground(Message... params) {
 960            if (isCancelled()) {
 961                return null;
 962            }
 963            message = params[0];
 964            try {
 965                final XmppActivity activity = find(imageViewReference);
 966                if (activity != null && activity.xmppConnectionService != null) {
 967                    return activity.xmppConnectionService.getFileBackend().getThumbnail(message, imageViewReference.get().getContext().getResources(), (int) (activity.metrics.density * 288), false);
 968                } else {
 969                    return null;
 970                }
 971            } catch (IOException e) {
 972                return null;
 973            }
 974        }
 975
 976        @Override
 977        protected void onPostExecute(final Drawable drawable) {
 978            if (!isCancelled()) {
 979                final ImageView imageView = imageViewReference.get();
 980                if (imageView != null) {
 981                    imageView.setImageDrawable(drawable);
 982                    imageView.setBackgroundColor(drawable == null ? 0xff333333 : 0x00000000);
 983                    if (Build.VERSION.SDK_INT >= 28 && drawable instanceof AnimatedImageDrawable) {
 984                        ((AnimatedImageDrawable) drawable).start();
 985                    }
 986                }
 987            }
 988        }
 989    }
 990
 991    private static class AsyncDrawable extends BitmapDrawable {
 992        private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
 993
 994        private AsyncDrawable(Resources res, Bitmap bitmap, BitmapWorkerTask bitmapWorkerTask) {
 995            super(res, bitmap);
 996            bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
 997        }
 998
 999        private BitmapWorkerTask getBitmapWorkerTask() {
1000            return bitmapWorkerTaskReference.get();
1001        }
1002    }
1003
1004    public static XmppActivity find(@NonNull WeakReference<ImageView> viewWeakReference) {
1005        final View view = viewWeakReference.get();
1006        return view == null ? null : find(view);
1007    }
1008
1009    public static XmppActivity find(@NonNull final View view) {
1010        Context context = view.getContext();
1011        while (context instanceof ContextWrapper) {
1012            if (context instanceof XmppActivity) {
1013                return (XmppActivity) context;
1014            }
1015            context = ((ContextWrapper) context).getBaseContext();
1016        }
1017        return null;
1018    }
1019}