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