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