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