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.databinding.DataBindingUtil;
  23import android.graphics.Bitmap;
  24import android.graphics.Color;
  25import android.graphics.Point;
  26import android.graphics.drawable.BitmapDrawable;
  27import android.graphics.drawable.Drawable;
  28import android.net.ConnectivityManager;
  29import android.net.Uri;
  30import android.os.AsyncTask;
  31import android.os.Build;
  32import android.os.Bundle;
  33import android.os.Handler;
  34import android.os.IBinder;
  35import android.os.PowerManager;
  36import android.os.SystemClock;
  37import android.preference.PreferenceManager;
  38import android.support.annotation.BoolRes;
  39import android.support.annotation.NonNull;
  40import android.support.annotation.StringRes;
  41import android.support.v7.app.AlertDialog;
  42import android.support.v7.app.AlertDialog.Builder;
  43import android.support.v7.app.AppCompatDelegate;
  44import android.text.InputType;
  45import android.util.DisplayMetrics;
  46import android.util.Log;
  47import android.view.Menu;
  48import android.view.MenuItem;
  49import android.view.View;
  50import android.widget.ImageView;
  51import android.widget.Toast;
  52
  53import java.io.IOException;
  54import java.lang.ref.WeakReference;
  55import java.util.ArrayList;
  56import java.util.List;
  57import java.util.concurrent.RejectedExecutionException;
  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.QuickConversationsService;
  71import eu.siacs.conversations.services.XmppConnectionService;
  72import eu.siacs.conversations.services.XmppConnectionService.XmppConnectionBinder;
  73import eu.siacs.conversations.ui.service.EmojiService;
  74import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
  75import eu.siacs.conversations.ui.util.PresenceSelector;
  76import eu.siacs.conversations.ui.util.SoftKeyboardUtils;
  77import eu.siacs.conversations.utils.AccountUtils;
  78import eu.siacs.conversations.utils.ExceptionHelper;
  79import eu.siacs.conversations.utils.ThemeHelper;
  80import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
  81import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
  82import eu.siacs.conversations.xmpp.Jid;
  83
  84public abstract class XmppActivity extends ActionBarActivity {
  85
  86    public static final String EXTRA_ACCOUNT = "account";
  87    protected static final int REQUEST_ANNOUNCE_PGP = 0x0101;
  88    protected static final int REQUEST_INVITE_TO_CONVERSATION = 0x0102;
  89    protected static final int REQUEST_CHOOSE_PGP_ID = 0x0103;
  90    protected static final int REQUEST_BATTERY_OP = 0x49ff;
  91    public XmppConnectionService xmppConnectionService;
  92    public boolean xmppConnectionServiceBound = false;
  93
  94    protected static final String FRAGMENT_TAG_DIALOG = "dialog";
  95
  96    private boolean isCameraFeatureAvailable = false;
  97
  98    protected int mTheme;
  99    protected boolean mUsingEnterKey = false;
 100    protected boolean mUseTor = false;
 101    protected Toast mToast;
 102    public Runnable onOpenPGPKeyPublished = () -> Toast.makeText(XmppActivity.this, R.string.openpgp_has_been_published, Toast.LENGTH_SHORT).show();
 103    protected ConferenceInvite mPendingConferenceInvite = null;
 104    protected ServiceConnection mConnection = new ServiceConnection() {
 105
 106        @Override
 107        public void onServiceConnected(ComponentName className, IBinder service) {
 108            XmppConnectionBinder binder = (XmppConnectionBinder) service;
 109            xmppConnectionService = binder.getService();
 110            xmppConnectionServiceBound = true;
 111            registerListeners();
 112            onBackendConnected();
 113        }
 114
 115        @Override
 116        public void onServiceDisconnected(ComponentName arg0) {
 117            xmppConnectionServiceBound = false;
 118        }
 119    };
 120    private DisplayMetrics metrics;
 121    private long mLastUiRefresh = 0;
 122    private Handler mRefreshUiHandler = new Handler();
 123    private Runnable mRefreshUiRunnable = () -> {
 124        mLastUiRefresh = SystemClock.elapsedRealtime();
 125        refreshUiReal();
 126    };
 127    private UiCallback<Conversation> adhocCallback = new UiCallback<Conversation>() {
 128        @Override
 129        public void success(final Conversation conversation) {
 130            runOnUiThread(() -> {
 131                switchToConversation(conversation);
 132                hideToast();
 133            });
 134        }
 135
 136        @Override
 137        public void error(final int errorCode, Conversation object) {
 138            runOnUiThread(() -> replaceToast(getString(errorCode)));
 139        }
 140
 141        @Override
 142        public void userInputRequired(PendingIntent pi, Conversation object) {
 143
 144        }
 145    };
 146    public boolean mSkipBackgroundBinding = false;
 147
 148    public static boolean cancelPotentialWork(Message message, ImageView imageView) {
 149        final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
 150
 151        if (bitmapWorkerTask != null) {
 152            final Message oldMessage = bitmapWorkerTask.message;
 153            if (oldMessage == null || message != oldMessage) {
 154                bitmapWorkerTask.cancel(true);
 155            } else {
 156                return false;
 157            }
 158        }
 159        return true;
 160    }
 161
 162    private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
 163        if (imageView != null) {
 164            final Drawable drawable = imageView.getDrawable();
 165            if (drawable instanceof AsyncDrawable) {
 166                final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
 167                return asyncDrawable.getBitmapWorkerTask();
 168            }
 169        }
 170        return null;
 171    }
 172
 173    protected void hideToast() {
 174        if (mToast != null) {
 175            mToast.cancel();
 176        }
 177    }
 178
 179    protected void replaceToast(String msg) {
 180        replaceToast(msg, true);
 181    }
 182
 183    protected void replaceToast(String msg, boolean showlong) {
 184        hideToast();
 185        mToast = Toast.makeText(this, msg, showlong ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT);
 186        mToast.show();
 187    }
 188
 189    protected final void refreshUi() {
 190        final long diff = SystemClock.elapsedRealtime() - mLastUiRefresh;
 191        if (diff > Config.REFRESH_UI_INTERVAL) {
 192            mRefreshUiHandler.removeCallbacks(mRefreshUiRunnable);
 193            runOnUiThread(mRefreshUiRunnable);
 194        } else {
 195            final long next = Config.REFRESH_UI_INTERVAL - diff;
 196            mRefreshUiHandler.removeCallbacks(mRefreshUiRunnable);
 197            mRefreshUiHandler.postDelayed(mRefreshUiRunnable, next);
 198        }
 199    }
 200
 201    abstract protected void refreshUiReal();
 202
 203    @Override
 204    protected void onStart() {
 205        super.onStart();
 206        if (!xmppConnectionServiceBound) {
 207            if (this.mSkipBackgroundBinding) {
 208                Log.d(Config.LOGTAG, "skipping background binding");
 209            } else {
 210                connectToBackend();
 211            }
 212        } else {
 213            this.registerListeners();
 214            this.onBackendConnected();
 215        }
 216        this.mUsingEnterKey = usingEnterKey();
 217        this.mUseTor = useTor();
 218    }
 219
 220    public void connectToBackend() {
 221        Intent intent = new Intent(this, XmppConnectionService.class);
 222        intent.setAction("ui");
 223        try {
 224            startService(intent);
 225        } catch (IllegalStateException e) {
 226            Log.w(Config.LOGTAG, "unable to start service from " + getClass().getSimpleName());
 227        }
 228        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
 229    }
 230
 231    @Override
 232    protected void onStop() {
 233        super.onStop();
 234        if (xmppConnectionServiceBound) {
 235            this.unregisterListeners();
 236            unbindService(mConnection);
 237            xmppConnectionServiceBound = false;
 238        }
 239    }
 240
 241
 242    public boolean hasPgp() {
 243        return xmppConnectionService.getPgpEngine() != null;
 244    }
 245
 246    public void showInstallPgpDialog() {
 247        Builder builder = new AlertDialog.Builder(this);
 248        builder.setTitle(getString(R.string.openkeychain_required));
 249        builder.setIconAttribute(android.R.attr.alertDialogIcon);
 250        builder.setMessage(getText(R.string.openkeychain_required_long));
 251        builder.setNegativeButton(getString(R.string.cancel), null);
 252        builder.setNeutralButton(getString(R.string.restart),
 253                (dialog, which) -> {
 254                    if (xmppConnectionServiceBound) {
 255                        unbindService(mConnection);
 256                        xmppConnectionServiceBound = false;
 257                    }
 258                    stopService(new Intent(XmppActivity.this,
 259                            XmppConnectionService.class));
 260                    finish();
 261                });
 262        builder.setPositiveButton(getString(R.string.install),
 263                (dialog, which) -> {
 264                    Uri uri = Uri
 265                            .parse("market://details?id=org.sufficientlysecure.keychain");
 266                    Intent marketIntent = new Intent(Intent.ACTION_VIEW,
 267                            uri);
 268                    PackageManager manager = getApplicationContext()
 269                            .getPackageManager();
 270                    List<ResolveInfo> infos = manager
 271                            .queryIntentActivities(marketIntent, 0);
 272                    if (infos.size() > 0) {
 273                        startActivity(marketIntent);
 274                    } else {
 275                        uri = Uri.parse("http://www.openkeychain.org/");
 276                        Intent browserIntent = new Intent(
 277                                Intent.ACTION_VIEW, uri);
 278                        startActivity(browserIntent);
 279                    }
 280                    finish();
 281                });
 282        builder.create().show();
 283    }
 284
 285    abstract void onBackendConnected();
 286
 287    protected void registerListeners() {
 288        if (this instanceof XmppConnectionService.OnConversationUpdate) {
 289            this.xmppConnectionService.setOnConversationListChangedListener((XmppConnectionService.OnConversationUpdate) this);
 290        }
 291        if (this instanceof XmppConnectionService.OnAccountUpdate) {
 292            this.xmppConnectionService.setOnAccountListChangedListener((XmppConnectionService.OnAccountUpdate) this);
 293        }
 294        if (this instanceof XmppConnectionService.OnCaptchaRequested) {
 295            this.xmppConnectionService.setOnCaptchaRequestedListener((XmppConnectionService.OnCaptchaRequested) this);
 296        }
 297        if (this instanceof XmppConnectionService.OnRosterUpdate) {
 298            this.xmppConnectionService.setOnRosterUpdateListener((XmppConnectionService.OnRosterUpdate) this);
 299        }
 300        if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
 301            this.xmppConnectionService.setOnMucRosterUpdateListener((XmppConnectionService.OnMucRosterUpdate) this);
 302        }
 303        if (this instanceof OnUpdateBlocklist) {
 304            this.xmppConnectionService.setOnUpdateBlocklistListener((OnUpdateBlocklist) this);
 305        }
 306        if (this instanceof XmppConnectionService.OnShowErrorToast) {
 307            this.xmppConnectionService.setOnShowErrorToastListener((XmppConnectionService.OnShowErrorToast) this);
 308        }
 309        if (this instanceof OnKeyStatusUpdated) {
 310            this.xmppConnectionService.setOnKeyStatusUpdatedListener((OnKeyStatusUpdated) this);
 311        }
 312        if (this instanceof XmppConnectionService.OnJingleRtpConnectionUpdate) {
 313            this.xmppConnectionService.setOnRtpConnectionUpdateListener((XmppConnectionService.OnJingleRtpConnectionUpdate) this);
 314        }
 315    }
 316
 317    protected void unregisterListeners() {
 318        if (this instanceof XmppConnectionService.OnConversationUpdate) {
 319            this.xmppConnectionService.removeOnConversationListChangedListener((XmppConnectionService.OnConversationUpdate) this);
 320        }
 321        if (this instanceof XmppConnectionService.OnAccountUpdate) {
 322            this.xmppConnectionService.removeOnAccountListChangedListener((XmppConnectionService.OnAccountUpdate) this);
 323        }
 324        if (this instanceof XmppConnectionService.OnCaptchaRequested) {
 325            this.xmppConnectionService.removeOnCaptchaRequestedListener((XmppConnectionService.OnCaptchaRequested) this);
 326        }
 327        if (this instanceof XmppConnectionService.OnRosterUpdate) {
 328            this.xmppConnectionService.removeOnRosterUpdateListener((XmppConnectionService.OnRosterUpdate) this);
 329        }
 330        if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
 331            this.xmppConnectionService.removeOnMucRosterUpdateListener((XmppConnectionService.OnMucRosterUpdate) this);
 332        }
 333        if (this instanceof OnUpdateBlocklist) {
 334            this.xmppConnectionService.removeOnUpdateBlocklistListener((OnUpdateBlocklist) this);
 335        }
 336        if (this instanceof XmppConnectionService.OnShowErrorToast) {
 337            this.xmppConnectionService.removeOnShowErrorToastListener((XmppConnectionService.OnShowErrorToast) this);
 338        }
 339        if (this instanceof OnKeyStatusUpdated) {
 340            this.xmppConnectionService.removeOnNewKeysAvailableListener((OnKeyStatusUpdated) this);
 341        }
 342        if (this instanceof XmppConnectionService.OnJingleRtpConnectionUpdate) {
 343            this.xmppConnectionService.removeRtpConnectionUpdateListener((XmppConnectionService.OnJingleRtpConnectionUpdate) this);
 344        }
 345    }
 346
 347    @Override
 348    public boolean onOptionsItemSelected(final MenuItem item) {
 349        switch (item.getItemId()) {
 350            case R.id.action_settings:
 351                startActivity(new Intent(this, SettingsActivity.class));
 352                break;
 353            case R.id.action_accounts:
 354                AccountUtils.launchManageAccounts(this);
 355                break;
 356            case R.id.action_account:
 357                AccountUtils.launchManageAccount(this);
 358                break;
 359            case android.R.id.home:
 360                finish();
 361                break;
 362            case R.id.action_show_qr_code:
 363                showQrCode();
 364                break;
 365        }
 366        return super.onOptionsItemSelected(item);
 367    }
 368
 369    public void selectPresence(final Conversation conversation, final PresenceSelector.OnPresenceSelected listener) {
 370        final Contact contact = conversation.getContact();
 371        if (contact.showInRoster() || contact.isSelf()) {
 372            final Presences presences = contact.getPresences();
 373            if (presences.size() == 0) {
 374                if (contact.isSelf()) {
 375                    conversation.setNextCounterpart(null);
 376                    listener.onPresenceSelected();
 377                } else if (!contact.getOption(Contact.Options.TO)
 378                        && !contact.getOption(Contact.Options.ASKING)
 379                        && contact.getAccount().getStatus() == Account.State.ONLINE) {
 380                    showAskForPresenceDialog(contact);
 381                } else if (!contact.getOption(Contact.Options.TO)
 382                        || !contact.getOption(Contact.Options.FROM)) {
 383                    PresenceSelector.warnMutualPresenceSubscription(this, conversation, listener);
 384                } else {
 385                    conversation.setNextCounterpart(null);
 386                    listener.onPresenceSelected();
 387                }
 388            } else if (presences.size() == 1) {
 389                final String presence = presences.toResourceArray()[0];
 390                conversation.setNextCounterpart(PresenceSelector.getNextCounterpart(contact, presence));
 391                listener.onPresenceSelected();
 392            } else {
 393                PresenceSelector.showPresenceSelectionDialog(this, conversation, listener);
 394            }
 395        } else {
 396            showAddToRosterDialog(conversation.getContact());
 397        }
 398    }
 399
 400    @SuppressLint("UnsupportedChromeOsCameraSystemFeature")
 401    @Override
 402    protected void onCreate(Bundle savedInstanceState) {
 403        super.onCreate(savedInstanceState);
 404        metrics = getResources().getDisplayMetrics();
 405        ExceptionHelper.init(getApplicationContext());
 406        new EmojiService(this).init();
 407        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
 408            this.isCameraFeatureAvailable = getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
 409        } else {
 410            this.isCameraFeatureAvailable = getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA);
 411        }
 412        this.mTheme = findTheme();
 413        setTheme(this.mTheme);
 414    }
 415
 416    protected boolean isCameraFeatureAvailable() {
 417        return this.isCameraFeatureAvailable;
 418    }
 419
 420    public boolean isDarkTheme() {
 421        return ThemeHelper.isDark(mTheme);
 422    }
 423
 424    public int getThemeResource(int r_attr_name, int r_drawable_def) {
 425        int[] attrs = {r_attr_name};
 426        TypedArray ta = this.getTheme().obtainStyledAttributes(attrs);
 427
 428        int res = ta.getResourceId(0, r_drawable_def);
 429        ta.recycle();
 430
 431        return res;
 432    }
 433
 434    protected boolean isOptimizingBattery() {
 435        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
 436            final PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
 437            return pm != null
 438                    && !pm.isIgnoringBatteryOptimizations(getPackageName());
 439        } else {
 440            return false;
 441        }
 442    }
 443
 444    protected boolean isAffectedByDataSaver() {
 445        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
 446            final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
 447            return cm != null
 448                    && cm.isActiveNetworkMetered()
 449                    && cm.getRestrictBackgroundStatus() == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
 450        } else {
 451            return false;
 452        }
 453    }
 454
 455    private boolean usingEnterKey() {
 456        return getBooleanPreference("display_enter_key", R.bool.display_enter_key);
 457    }
 458
 459    private boolean useTor() {
 460        return QuickConversationsService.isConversations() && getBooleanPreference("use_tor", R.bool.use_tor);
 461    }
 462
 463    protected SharedPreferences getPreferences() {
 464        return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
 465    }
 466
 467    protected boolean getBooleanPreference(String name, @BoolRes int res) {
 468        return getPreferences().getBoolean(name, getResources().getBoolean(res));
 469    }
 470
 471    public void switchToConversation(Conversation conversation) {
 472        switchToConversation(conversation, null);
 473    }
 474
 475    public void switchToConversationAndQuote(Conversation conversation, String text) {
 476        switchToConversation(conversation, text, true, null, false, false);
 477    }
 478
 479    public void switchToConversation(Conversation conversation, String text) {
 480        switchToConversation(conversation, text, false, null, false, false);
 481    }
 482
 483    public void switchToConversationDoNotAppend(Conversation conversation, String text) {
 484        switchToConversation(conversation, text, false, null, false, true);
 485    }
 486
 487    public void highlightInMuc(Conversation conversation, String nick) {
 488        switchToConversation(conversation, null, false, nick, false, false);
 489    }
 490
 491    public void privateMsgInMuc(Conversation conversation, String nick) {
 492        switchToConversation(conversation, null, false, nick, true, false);
 493    }
 494
 495    private void switchToConversation(Conversation conversation, String text, boolean asQuote, String nick, boolean pm, boolean doNotAppend) {
 496        Intent intent = new Intent(this, ConversationsActivity.class);
 497        intent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
 498        intent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversation.getUuid());
 499        if (text != null) {
 500            intent.putExtra(Intent.EXTRA_TEXT, text);
 501            if (asQuote) {
 502                intent.putExtra(ConversationsActivity.EXTRA_AS_QUOTE, true);
 503            }
 504        }
 505        if (nick != null) {
 506            intent.putExtra(ConversationsActivity.EXTRA_NICK, nick);
 507            intent.putExtra(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, pm);
 508        }
 509        if (doNotAppend) {
 510            intent.putExtra(ConversationsActivity.EXTRA_DO_NOT_APPEND, true);
 511        }
 512        intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_CLEAR_TOP);
 513        startActivity(intent);
 514        finish();
 515    }
 516
 517    public void switchToContactDetails(Contact contact) {
 518        switchToContactDetails(contact, null);
 519    }
 520
 521    public void switchToContactDetails(Contact contact, String messageFingerprint) {
 522        Intent intent = new Intent(this, ContactDetailsActivity.class);
 523        intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT);
 524        intent.putExtra(EXTRA_ACCOUNT, contact.getAccount().getJid().asBareJid().toEscapedString());
 525        intent.putExtra("contact", contact.getJid().toEscapedString());
 526        intent.putExtra("fingerprint", messageFingerprint);
 527        startActivity(intent);
 528    }
 529
 530    public void switchToAccount(Account account, String fingerprint) {
 531        switchToAccount(account, false, fingerprint);
 532    }
 533
 534    public void switchToAccount(Account account) {
 535        switchToAccount(account, false, null);
 536    }
 537
 538    public void switchToAccount(Account account, boolean init, String fingerprint) {
 539        Intent intent = new Intent(this, EditAccountActivity.class);
 540        intent.putExtra("jid", account.getJid().asBareJid().toEscapedString());
 541        intent.putExtra("init", init);
 542        if (init) {
 543            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
 544        }
 545        if (fingerprint != null) {
 546            intent.putExtra("fingerprint", fingerprint);
 547        }
 548        startActivity(intent);
 549        if (init) {
 550            overridePendingTransition(0, 0);
 551        }
 552    }
 553
 554    protected void delegateUriPermissionsToService(Uri uri) {
 555        Intent intent = new Intent(this, XmppConnectionService.class);
 556        intent.setAction(Intent.ACTION_SEND);
 557        intent.setData(uri);
 558        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
 559        try {
 560            startService(intent);
 561        } catch (Exception e) {
 562            Log.e(Config.LOGTAG, "unable to delegate uri permission", e);
 563        }
 564    }
 565
 566    protected void inviteToConversation(Conversation conversation) {
 567        startActivityForResult(ChooseContactActivity.create(this, conversation), REQUEST_INVITE_TO_CONVERSATION);
 568    }
 569
 570    protected void announcePgp(final Account account, final Conversation conversation, Intent intent, final Runnable onSuccess) {
 571        if (account.getPgpId() == 0) {
 572            choosePgpSignId(account);
 573        } else {
 574            String status = null;
 575            if (manuallyChangePresence()) {
 576                status = account.getPresenceStatusMessage();
 577            }
 578            if (status == null) {
 579                status = "";
 580            }
 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    public void onResume() {
 829        super.onResume();
 830    }
 831
 832    protected int findTheme() {
 833        return ThemeHelper.find(this);
 834    }
 835
 836    @Override
 837    public void onPause() {
 838        super.onPause();
 839    }
 840
 841    @Override
 842    public boolean onMenuOpened(int id, Menu menu) {
 843        if (id == AppCompatDelegate.FEATURE_SUPPORT_ACTION_BAR && menu != null) {
 844            MenuDoubleTabUtil.recordMenuOpen();
 845        }
 846        return super.onMenuOpened(id, menu);
 847    }
 848
 849    protected void showQrCode() {
 850        showQrCode(getShareableUri());
 851    }
 852
 853    protected void showQrCode(final String uri) {
 854        if (uri == null || uri.isEmpty()) {
 855            return;
 856        }
 857        Point size = new Point();
 858        getWindowManager().getDefaultDisplay().getSize(size);
 859        final int width = (size.x < size.y ? size.x : size.y);
 860        Bitmap bitmap = BarcodeProvider.create2dBarcodeBitmap(uri, width);
 861        ImageView view = new ImageView(this);
 862        view.setBackgroundColor(Color.WHITE);
 863        view.setImageBitmap(bitmap);
 864        AlertDialog.Builder builder = new AlertDialog.Builder(this);
 865        builder.setView(view);
 866        builder.create().show();
 867    }
 868
 869    protected Account extractAccount(Intent intent) {
 870        final String jid = intent != null ? intent.getStringExtra(EXTRA_ACCOUNT) : null;
 871        try {
 872            return jid != null ? xmppConnectionService.findAccountByJid(Jid.ofEscaped(jid)) : null;
 873        } catch (IllegalArgumentException e) {
 874            return null;
 875        }
 876    }
 877
 878    public AvatarService avatarService() {
 879        return xmppConnectionService.getAvatarService();
 880    }
 881
 882    public void loadBitmap(Message message, ImageView imageView) {
 883        Bitmap bm;
 884        try {
 885            bm = xmppConnectionService.getFileBackend().getThumbnail(message, (int) (metrics.density * 288), true);
 886        } catch (IOException e) {
 887            bm = null;
 888        }
 889        if (bm != null) {
 890            cancelPotentialWork(message, imageView);
 891            imageView.setImageBitmap(bm);
 892            imageView.setBackgroundColor(0x00000000);
 893        } else {
 894            if (cancelPotentialWork(message, imageView)) {
 895                imageView.setBackgroundColor(0xff333333);
 896                imageView.setImageDrawable(null);
 897                final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
 898                final AsyncDrawable asyncDrawable = new AsyncDrawable(
 899                        getResources(), null, task);
 900                imageView.setImageDrawable(asyncDrawable);
 901                try {
 902                    task.execute(message);
 903                } catch (final RejectedExecutionException ignored) {
 904                    ignored.printStackTrace();
 905                }
 906            }
 907        }
 908    }
 909
 910    protected interface OnValueEdited {
 911        String onValueEdited(String value);
 912    }
 913
 914    public static class ConferenceInvite {
 915        private String uuid;
 916        private List<Jid> jids = new ArrayList<>();
 917
 918        public static ConferenceInvite parse(Intent data) {
 919            ConferenceInvite invite = new ConferenceInvite();
 920            invite.uuid = data.getStringExtra(ChooseContactActivity.EXTRA_CONVERSATION);
 921            if (invite.uuid == null) {
 922                return null;
 923            }
 924            invite.jids.addAll(ChooseContactActivity.extractJabberIds(data));
 925            return invite;
 926        }
 927
 928        public boolean execute(XmppActivity activity) {
 929            XmppConnectionService service = activity.xmppConnectionService;
 930            Conversation conversation = service.findConversationByUuid(this.uuid);
 931            if (conversation == null) {
 932                return false;
 933            }
 934            if (conversation.getMode() == Conversation.MODE_MULTI) {
 935                for (Jid jid : jids) {
 936                    service.invite(conversation, jid);
 937                }
 938                return false;
 939            } else {
 940                jids.add(conversation.getJid().asBareJid());
 941                return service.createAdhocConference(conversation.getAccount(), null, jids, activity.adhocCallback);
 942            }
 943        }
 944    }
 945
 946    static class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
 947        private final WeakReference<ImageView> imageViewReference;
 948        private Message message = null;
 949
 950        private BitmapWorkerTask(ImageView imageView) {
 951            this.imageViewReference = new WeakReference<>(imageView);
 952        }
 953
 954        @Override
 955        protected Bitmap doInBackground(Message... params) {
 956            if (isCancelled()) {
 957                return null;
 958            }
 959            message = params[0];
 960            try {
 961                final XmppActivity activity = find(imageViewReference);
 962                if (activity != null && activity.xmppConnectionService != null) {
 963                    return activity.xmppConnectionService.getFileBackend().getThumbnail(message, (int) (activity.metrics.density * 288), false);
 964                } else {
 965                    return null;
 966                }
 967            } catch (IOException e) {
 968                return null;
 969            }
 970        }
 971
 972        @Override
 973        protected void onPostExecute(final Bitmap bitmap) {
 974            if (!isCancelled()) {
 975                final ImageView imageView = imageViewReference.get();
 976                if (imageView != null) {
 977                    imageView.setImageBitmap(bitmap);
 978                    imageView.setBackgroundColor(bitmap == null ? 0xff333333 : 0x00000000);
 979                }
 980            }
 981        }
 982    }
 983
 984    private static class AsyncDrawable extends BitmapDrawable {
 985        private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
 986
 987        private AsyncDrawable(Resources res, Bitmap bitmap, BitmapWorkerTask bitmapWorkerTask) {
 988            super(res, bitmap);
 989            bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
 990        }
 991
 992        private BitmapWorkerTask getBitmapWorkerTask() {
 993            return bitmapWorkerTaskReference.get();
 994        }
 995    }
 996
 997    public static XmppActivity find(@NonNull WeakReference<ImageView> viewWeakReference) {
 998        final View view = viewWeakReference.get();
 999        return view == null ? null : find(view);
1000    }
1001
1002    public static XmppActivity find(@NonNull final View view) {
1003        Context context = view.getContext();
1004        while (context instanceof ContextWrapper) {
1005            if (context instanceof XmppActivity) {
1006                return (XmppActivity) context;
1007            }
1008            context = ((ContextWrapper) context).getBaseContext();
1009        }
1010        return null;
1011    }
1012}