XmppActivity.java

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