XmppActivity.java

   1package eu.siacs.conversations.ui;
   2
   3import android.telephony.TelephonyManager;
   4
   5import android.Manifest;
   6import android.annotation.SuppressLint;
   7import android.annotation.TargetApi;
   8import android.app.PendingIntent;
   9import android.content.ActivityNotFoundException;
  10import android.content.ClipData;
  11import android.content.ClipboardManager;
  12import android.content.ComponentName;
  13import android.content.Context;
  14import android.content.ContextWrapper;
  15import android.content.DialogInterface;
  16import android.content.Intent;
  17import android.content.IntentSender.SendIntentException;
  18import android.content.ServiceConnection;
  19import android.content.SharedPreferences;
  20import android.content.pm.PackageManager;
  21import android.content.pm.ResolveInfo;
  22import android.content.res.Resources;
  23import android.content.res.TypedArray;
  24import android.graphics.Bitmap;
  25import android.graphics.Color;
  26import android.graphics.Point;
  27import android.graphics.drawable.AnimatedImageDrawable;
  28import android.graphics.drawable.BitmapDrawable;
  29import android.graphics.drawable.Drawable;
  30import android.net.ConnectivityManager;
  31import android.net.Uri;
  32import android.os.AsyncTask;
  33import android.os.Build;
  34import android.os.Bundle;
  35import android.os.Handler;
  36import android.os.IBinder;
  37import android.os.PowerManager;
  38import android.os.SystemClock;
  39import android.preference.PreferenceManager;
  40import android.text.Html;
  41import android.text.InputType;
  42import android.util.DisplayMetrics;
  43import android.util.Log;
  44import android.view.Menu;
  45import android.view.MenuItem;
  46import android.view.View;
  47import android.widget.ImageView;
  48import android.widget.Toast;
  49
  50import androidx.annotation.BoolRes;
  51import androidx.annotation.NonNull;
  52import androidx.annotation.RequiresApi;
  53import androidx.annotation.StringRes;
  54import androidx.appcompat.app.AlertDialog;
  55import androidx.appcompat.app.AlertDialog.Builder;
  56import androidx.appcompat.app.AppCompatDelegate;
  57import androidx.databinding.DataBindingUtil;
  58
  59import com.google.common.base.Strings;
  60
  61import java.io.IOException;
  62import java.lang.ref.WeakReference;
  63import java.util.ArrayList;
  64import java.util.List;
  65import java.util.concurrent.RejectedExecutionException;
  66
  67import eu.siacs.conversations.Config;
  68import eu.siacs.conversations.R;
  69import eu.siacs.conversations.crypto.PgpEngine;
  70import eu.siacs.conversations.databinding.DialogQuickeditBinding;
  71import eu.siacs.conversations.entities.Account;
  72import eu.siacs.conversations.entities.Contact;
  73import eu.siacs.conversations.entities.Conversation;
  74import eu.siacs.conversations.entities.Message;
  75import eu.siacs.conversations.entities.Presences;
  76import eu.siacs.conversations.services.AvatarService;
  77import eu.siacs.conversations.services.BarcodeProvider;
  78import eu.siacs.conversations.services.EmojiInitializationService;
  79import eu.siacs.conversations.services.QuickConversationsService;
  80import eu.siacs.conversations.services.XmppConnectionService;
  81import eu.siacs.conversations.services.XmppConnectionService.XmppConnectionBinder;
  82import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
  83import eu.siacs.conversations.ui.util.PresenceSelector;
  84import eu.siacs.conversations.ui.util.SoftKeyboardUtils;
  85import eu.siacs.conversations.utils.AccountUtils;
  86import eu.siacs.conversations.utils.Compatibility;
  87import eu.siacs.conversations.utils.ExceptionHelper;
  88import eu.siacs.conversations.ui.util.SettingsUtils;
  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    abstract void onBackendConnected();
 296
 297    protected void registerListeners() {
 298        if (this instanceof XmppConnectionService.OnConversationUpdate) {
 299            this.xmppConnectionService.setOnConversationListChangedListener((XmppConnectionService.OnConversationUpdate) this);
 300        }
 301        if (this instanceof XmppConnectionService.OnAccountUpdate) {
 302            this.xmppConnectionService.setOnAccountListChangedListener((XmppConnectionService.OnAccountUpdate) this);
 303        }
 304        if (this instanceof XmppConnectionService.OnCaptchaRequested) {
 305            this.xmppConnectionService.setOnCaptchaRequestedListener((XmppConnectionService.OnCaptchaRequested) this);
 306        }
 307        if (this instanceof XmppConnectionService.OnRosterUpdate) {
 308            this.xmppConnectionService.setOnRosterUpdateListener((XmppConnectionService.OnRosterUpdate) this);
 309        }
 310        if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
 311            this.xmppConnectionService.setOnMucRosterUpdateListener((XmppConnectionService.OnMucRosterUpdate) this);
 312        }
 313        if (this instanceof OnUpdateBlocklist) {
 314            this.xmppConnectionService.setOnUpdateBlocklistListener((OnUpdateBlocklist) this);
 315        }
 316        if (this instanceof XmppConnectionService.OnShowErrorToast) {
 317            this.xmppConnectionService.setOnShowErrorToastListener((XmppConnectionService.OnShowErrorToast) this);
 318        }
 319        if (this instanceof OnKeyStatusUpdated) {
 320            this.xmppConnectionService.setOnKeyStatusUpdatedListener((OnKeyStatusUpdated) this);
 321        }
 322        if (this instanceof XmppConnectionService.OnJingleRtpConnectionUpdate) {
 323            this.xmppConnectionService.setOnRtpConnectionUpdateListener((XmppConnectionService.OnJingleRtpConnectionUpdate) this);
 324        }
 325    }
 326
 327    protected void unregisterListeners() {
 328        if (this instanceof XmppConnectionService.OnConversationUpdate) {
 329            this.xmppConnectionService.removeOnConversationListChangedListener((XmppConnectionService.OnConversationUpdate) this);
 330        }
 331        if (this instanceof XmppConnectionService.OnAccountUpdate) {
 332            this.xmppConnectionService.removeOnAccountListChangedListener((XmppConnectionService.OnAccountUpdate) this);
 333        }
 334        if (this instanceof XmppConnectionService.OnCaptchaRequested) {
 335            this.xmppConnectionService.removeOnCaptchaRequestedListener((XmppConnectionService.OnCaptchaRequested) this);
 336        }
 337        if (this instanceof XmppConnectionService.OnRosterUpdate) {
 338            this.xmppConnectionService.removeOnRosterUpdateListener((XmppConnectionService.OnRosterUpdate) this);
 339        }
 340        if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
 341            this.xmppConnectionService.removeOnMucRosterUpdateListener((XmppConnectionService.OnMucRosterUpdate) this);
 342        }
 343        if (this instanceof OnUpdateBlocklist) {
 344            this.xmppConnectionService.removeOnUpdateBlocklistListener((OnUpdateBlocklist) this);
 345        }
 346        if (this instanceof XmppConnectionService.OnShowErrorToast) {
 347            this.xmppConnectionService.removeOnShowErrorToastListener((XmppConnectionService.OnShowErrorToast) this);
 348        }
 349        if (this instanceof OnKeyStatusUpdated) {
 350            this.xmppConnectionService.removeOnNewKeysAvailableListener((OnKeyStatusUpdated) this);
 351        }
 352        if (this instanceof XmppConnectionService.OnJingleRtpConnectionUpdate) {
 353            this.xmppConnectionService.removeRtpConnectionUpdateListener((XmppConnectionService.OnJingleRtpConnectionUpdate) this);
 354        }
 355    }
 356
 357    @Override
 358    public boolean onOptionsItemSelected(final MenuItem item) {
 359        switch (item.getItemId()) {
 360            case R.id.action_settings:
 361                startActivity(new Intent(this, SettingsActivity.class));
 362                break;
 363            case R.id.action_accounts:
 364                AccountUtils.launchManageAccounts(this);
 365                break;
 366            case R.id.action_account:
 367                AccountUtils.launchManageAccount(this);
 368                break;
 369            case android.R.id.home:
 370                finish();
 371                break;
 372            case R.id.action_show_qr_code:
 373                showQrCode();
 374                break;
 375        }
 376        return super.onOptionsItemSelected(item);
 377    }
 378
 379    public void selectPresence(final Conversation conversation, final PresenceSelector.OnPresenceSelected listener) {
 380        final Contact contact = conversation.getContact();
 381        if (contact.showInRoster() || contact.isSelf()) {
 382            final Presences presences = contact.getPresences();
 383            if (presences.size() == 0) {
 384                if (contact.isSelf()) {
 385                    conversation.setNextCounterpart(null);
 386                    listener.onPresenceSelected();
 387                } else if (!contact.getOption(Contact.Options.TO)
 388                        && !contact.getOption(Contact.Options.ASKING)
 389                        && contact.getAccount().getStatus() == Account.State.ONLINE) {
 390                    showAskForPresenceDialog(contact);
 391                } else if (!contact.getOption(Contact.Options.TO)
 392                        || !contact.getOption(Contact.Options.FROM)) {
 393                    PresenceSelector.warnMutualPresenceSubscription(this, conversation, listener);
 394                } else {
 395                    conversation.setNextCounterpart(null);
 396                    listener.onPresenceSelected();
 397                }
 398            } else if (presences.size() == 1) {
 399                final String presence = presences.toResourceArray()[0];
 400                conversation.setNextCounterpart(PresenceSelector.getNextCounterpart(contact, presence));
 401                listener.onPresenceSelected();
 402            } else {
 403                PresenceSelector.showPresenceSelectionDialog(this, conversation, listener);
 404            }
 405        } else {
 406            showAddToRosterDialog(conversation.getContact());
 407        }
 408    }
 409
 410    @SuppressLint("UnsupportedChromeOsCameraSystemFeature")
 411    @Override
 412    protected void onCreate(Bundle savedInstanceState) {
 413        super.onCreate(savedInstanceState);
 414        metrics = getResources().getDisplayMetrics();
 415        ExceptionHelper.init(getApplicationContext());
 416        EmojiInitializationService.execute(this);
 417        this.isCameraFeatureAvailable = getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
 418        this.mTheme = findTheme();
 419        setTheme(this.mTheme);
 420    }
 421
 422    protected boolean isCameraFeatureAvailable() {
 423        return this.isCameraFeatureAvailable;
 424    }
 425
 426    public boolean isDarkTheme() {
 427        return ThemeHelper.isDark(mTheme);
 428    }
 429
 430    public int getThemeResource(int r_attr_name, int r_drawable_def) {
 431        int[] attrs = {r_attr_name};
 432        TypedArray ta = this.getTheme().obtainStyledAttributes(attrs);
 433
 434        int res = ta.getResourceId(0, r_drawable_def);
 435        ta.recycle();
 436
 437        return res;
 438    }
 439
 440    protected boolean isOptimizingBattery() {
 441        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
 442            final PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
 443            return pm != null
 444                    && !pm.isIgnoringBatteryOptimizations(getPackageName());
 445        } else {
 446            return false;
 447        }
 448    }
 449
 450    protected boolean isAffectedByDataSaver() {
 451        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
 452            final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
 453            return cm != null
 454                    && cm.isActiveNetworkMetered()
 455                    && Compatibility.getRestrictBackgroundStatus(cm) == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
 456        } else {
 457            return false;
 458        }
 459    }
 460
 461    private boolean usingEnterKey() {
 462        return getBooleanPreference("display_enter_key", R.bool.display_enter_key);
 463    }
 464
 465    private boolean useTor() {
 466        return getBooleanPreference("use_tor", R.bool.use_tor);
 467    }
 468
 469    protected SharedPreferences getPreferences() {
 470        return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
 471    }
 472
 473    protected boolean getBooleanPreference(String name, @BoolRes int res) {
 474        return getPreferences().getBoolean(name, getResources().getBoolean(res));
 475    }
 476
 477    public void startCommand(final Account account, final Jid jid, final String node) {
 478        Intent intent = new Intent(this, ConversationsActivity.class);
 479        intent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
 480        intent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, xmppConnectionService.findOrCreateConversation(account, jid, false, false).getUuid());
 481        intent.putExtra(ConversationsActivity.EXTRA_POST_INIT_ACTION, "command");
 482        intent.putExtra(ConversationsActivity.EXTRA_NODE, node);
 483        intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_CLEAR_TOP);
 484        startActivity(intent);
 485    }
 486
 487    public void switchToConversation(Conversation conversation) {
 488        switchToConversation(conversation, null);
 489    }
 490
 491    public void switchToConversationAndQuote(Conversation conversation, String text) {
 492        switchToConversation(conversation, text, true, null, false, false);
 493    }
 494
 495    public void switchToConversation(Conversation conversation, String text) {
 496        switchToConversation(conversation, text, false, null, false, false);
 497    }
 498
 499    public void switchToConversationDoNotAppend(Conversation conversation, String text) {
 500        switchToConversation(conversation, text, false, null, false, true);
 501    }
 502
 503    public void highlightInMuc(Conversation conversation, String nick) {
 504        switchToConversation(conversation, null, false, nick, false, false);
 505    }
 506
 507    public void privateMsgInMuc(Conversation conversation, String nick) {
 508        switchToConversation(conversation, null, false, nick, true, false);
 509    }
 510
 511    private void switchToConversation(Conversation conversation, String text, boolean asQuote, String nick, boolean pm, boolean doNotAppend) {
 512        Intent intent = new Intent(this, ConversationsActivity.class);
 513        intent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
 514        intent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversation.getUuid());
 515        if (text != null) {
 516            intent.putExtra(Intent.EXTRA_TEXT, text);
 517            if (asQuote) {
 518                intent.putExtra(ConversationsActivity.EXTRA_AS_QUOTE, true);
 519            }
 520        }
 521        if (nick != null) {
 522            intent.putExtra(ConversationsActivity.EXTRA_NICK, nick);
 523            intent.putExtra(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, pm);
 524        }
 525        if (doNotAppend) {
 526            intent.putExtra(ConversationsActivity.EXTRA_DO_NOT_APPEND, true);
 527        }
 528        intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_CLEAR_TOP);
 529        startActivity(intent);
 530        finish();
 531    }
 532
 533    public void switchToContactDetails(Contact contact) {
 534        switchToContactDetails(contact, null);
 535    }
 536
 537    public void switchToContactDetails(Contact contact, String messageFingerprint) {
 538        Intent intent = new Intent(this, ContactDetailsActivity.class);
 539        intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT);
 540        intent.putExtra(EXTRA_ACCOUNT, contact.getAccount().getJid().asBareJid().toEscapedString());
 541        intent.putExtra("contact", contact.getJid().toEscapedString());
 542        intent.putExtra("fingerprint", messageFingerprint);
 543        startActivity(intent);
 544    }
 545
 546    public void switchToAccount(Account account, String fingerprint) {
 547        switchToAccount(account, false, fingerprint);
 548    }
 549
 550    public void switchToAccount(Account account) {
 551        switchToAccount(account, false, null);
 552    }
 553
 554    public void switchToAccount(Account account, boolean init, String fingerprint) {
 555        Intent intent = new Intent(this, EditAccountActivity.class);
 556        intent.putExtra("jid", account.getJid().asBareJid().toEscapedString());
 557        intent.putExtra("init", init);
 558        if (init) {
 559            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
 560        }
 561        if (fingerprint != null) {
 562            intent.putExtra("fingerprint", fingerprint);
 563        }
 564        startActivity(intent);
 565        if (init) {
 566            overridePendingTransition(0, 0);
 567        }
 568    }
 569
 570    protected void delegateUriPermissionsToService(Uri uri) {
 571        Intent intent = new Intent(this, XmppConnectionService.class);
 572        intent.setAction(Intent.ACTION_SEND);
 573        intent.setData(uri);
 574        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
 575        try {
 576            startService(intent);
 577        } catch (Exception e) {
 578            Log.e(Config.LOGTAG, "unable to delegate uri permission", e);
 579        }
 580    }
 581
 582    protected void inviteToConversation(Conversation conversation) {
 583        startActivityForResult(ChooseContactActivity.create(this, conversation), REQUEST_INVITE_TO_CONVERSATION);
 584    }
 585
 586    protected void announcePgp(final Account account, final Conversation conversation, Intent intent, final Runnable onSuccess) {
 587        if (account.getPgpId() == 0) {
 588            choosePgpSignId(account);
 589        } else {
 590            final String status = Strings.nullToEmpty(account.getPresenceStatusMessage());
 591            xmppConnectionService.getPgpEngine().generateSignature(intent, account, status, new UiCallback<String>() {
 592
 593                @Override
 594                public void userInputRequired(PendingIntent pi, String signature) {
 595                    try {
 596                        startIntentSenderForResult(pi.getIntentSender(), REQUEST_ANNOUNCE_PGP, null, 0, 0, 0);
 597                    } catch (final SendIntentException ignored) {
 598                    }
 599                }
 600
 601                @Override
 602                public void success(String signature) {
 603                    account.setPgpSignature(signature);
 604                    xmppConnectionService.databaseBackend.updateAccount(account);
 605                    xmppConnectionService.sendPresence(account);
 606                    if (conversation != null) {
 607                        conversation.setNextEncryption(Message.ENCRYPTION_PGP);
 608                        xmppConnectionService.updateConversation(conversation);
 609                        refreshUi();
 610                    }
 611                    if (onSuccess != null) {
 612                        runOnUiThread(onSuccess);
 613                    }
 614                }
 615
 616                @Override
 617                public void error(int error, String signature) {
 618                    if (error == 0) {
 619                        account.setPgpSignId(0);
 620                        account.unsetPgpSignature();
 621                        xmppConnectionService.databaseBackend.updateAccount(account);
 622                        choosePgpSignId(account);
 623                    } else {
 624                        displayErrorDialog(error);
 625                    }
 626                }
 627            });
 628        }
 629    }
 630
 631    @SuppressWarnings("deprecation")
 632    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
 633    protected void setListItemBackgroundOnView(View view) {
 634        int sdk = android.os.Build.VERSION.SDK_INT;
 635        if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
 636            view.setBackgroundDrawable(getResources().getDrawable(R.drawable.greybackground));
 637        } else {
 638            view.setBackground(getResources().getDrawable(R.drawable.greybackground));
 639        }
 640    }
 641
 642    protected void choosePgpSignId(Account account) {
 643        xmppConnectionService.getPgpEngine().chooseKey(account, new UiCallback<Account>() {
 644            @Override
 645            public void success(Account account1) {
 646            }
 647
 648            @Override
 649            public void error(int errorCode, Account object) {
 650
 651            }
 652
 653            @Override
 654            public void userInputRequired(PendingIntent pi, Account object) {
 655                try {
 656                    startIntentSenderForResult(pi.getIntentSender(),
 657                            REQUEST_CHOOSE_PGP_ID, null, 0, 0, 0);
 658                } catch (final SendIntentException ignored) {
 659                }
 660            }
 661        });
 662    }
 663
 664    protected void displayErrorDialog(final int errorCode) {
 665        runOnUiThread(() -> {
 666            Builder builder = new Builder(XmppActivity.this);
 667            builder.setIconAttribute(android.R.attr.alertDialogIcon);
 668            builder.setTitle(getString(R.string.error));
 669            builder.setMessage(errorCode);
 670            builder.setNeutralButton(R.string.accept, null);
 671            builder.create().show();
 672        });
 673
 674    }
 675
 676    protected void showAddToRosterDialog(final Contact contact) {
 677        AlertDialog.Builder builder = new AlertDialog.Builder(this);
 678        builder.setTitle(contact.getJid().toString());
 679        builder.setMessage(getString(R.string.not_in_roster));
 680        builder.setNegativeButton(getString(R.string.cancel), null);
 681        builder.setPositiveButton(getString(R.string.add_contact), (dialog, which) -> xmppConnectionService.createContact(contact, true));
 682        builder.create().show();
 683    }
 684
 685    private void showAskForPresenceDialog(final Contact contact) {
 686        AlertDialog.Builder builder = new AlertDialog.Builder(this);
 687        builder.setTitle(contact.getJid().toString());
 688        builder.setMessage(R.string.request_presence_updates);
 689        builder.setNegativeButton(R.string.cancel, null);
 690        builder.setPositiveButton(R.string.request_now,
 691                (dialog, which) -> {
 692                    if (xmppConnectionServiceBound) {
 693                        xmppConnectionService.sendPresencePacket(contact
 694                                .getAccount(), xmppConnectionService
 695                                .getPresenceGenerator()
 696                                .requestPresenceUpdatesFrom(contact));
 697                    }
 698                });
 699        builder.create().show();
 700    }
 701
 702    protected void quickEdit(String previousValue, @StringRes int hint, OnValueEdited callback) {
 703        quickEdit(previousValue, callback, hint, false, false);
 704    }
 705
 706    protected void quickEdit(String previousValue, @StringRes int hint, OnValueEdited callback, boolean permitEmpty) {
 707        quickEdit(previousValue, callback, hint, false, permitEmpty);
 708    }
 709
 710    protected void quickPasswordEdit(String previousValue, OnValueEdited callback) {
 711        quickEdit(previousValue, callback, R.string.password, true, false);
 712    }
 713
 714    @SuppressLint("InflateParams")
 715    private void quickEdit(final String previousValue,
 716                           final OnValueEdited callback,
 717                           final @StringRes int hint,
 718                           boolean password,
 719                           boolean permitEmpty) {
 720        AlertDialog.Builder builder = new AlertDialog.Builder(this);
 721        DialogQuickeditBinding binding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.dialog_quickedit, null, false);
 722        if (password) {
 723            binding.inputEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
 724        }
 725        builder.setPositiveButton(R.string.accept, null);
 726        if (hint != 0) {
 727            binding.inputLayout.setHint(getString(hint));
 728        }
 729        binding.inputEditText.requestFocus();
 730        if (previousValue != null) {
 731            binding.inputEditText.getText().append(previousValue);
 732        }
 733        builder.setView(binding.getRoot());
 734        builder.setNegativeButton(R.string.cancel, null);
 735        final AlertDialog dialog = builder.create();
 736        dialog.setOnShowListener(d -> SoftKeyboardUtils.showKeyboard(binding.inputEditText));
 737        dialog.show();
 738        View.OnClickListener clickListener = v -> {
 739            String value = binding.inputEditText.getText().toString();
 740            if (!value.equals(previousValue) && (!value.trim().isEmpty() || permitEmpty)) {
 741                String error = callback.onValueEdited(value);
 742                if (error != null) {
 743                    binding.inputLayout.setError(error);
 744                    return;
 745                }
 746            }
 747            SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
 748            dialog.dismiss();
 749        };
 750        dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(clickListener);
 751        dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setOnClickListener((v -> {
 752            SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
 753            dialog.dismiss();
 754        }));
 755        dialog.setCanceledOnTouchOutside(false);
 756        dialog.setOnDismissListener(dialog1 -> {
 757            SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
 758        });
 759    }
 760
 761    protected boolean hasStoragePermission(int requestCode) {
 762        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
 763            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
 764                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
 765                return false;
 766            } else {
 767                return true;
 768            }
 769        } else {
 770            return true;
 771        }
 772    }
 773
 774    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
 775        super.onActivityResult(requestCode, resultCode, data);
 776        if (requestCode == REQUEST_INVITE_TO_CONVERSATION && resultCode == RESULT_OK) {
 777            mPendingConferenceInvite = ConferenceInvite.parse(data);
 778            if (xmppConnectionServiceBound && mPendingConferenceInvite != null) {
 779                if (mPendingConferenceInvite.execute(this)) {
 780                    mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
 781                    mToast.show();
 782                }
 783                mPendingConferenceInvite = null;
 784            }
 785        }
 786    }
 787
 788    public boolean copyTextToClipboard(String text, int labelResId) {
 789        ClipboardManager mClipBoardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
 790        String label = getResources().getString(labelResId);
 791        if (mClipBoardManager != null) {
 792            ClipData mClipData = ClipData.newPlainText(label, text);
 793            mClipBoardManager.setPrimaryClip(mClipData);
 794            return true;
 795        }
 796        return false;
 797    }
 798
 799    protected boolean manuallyChangePresence() {
 800        return getBooleanPreference(SettingsActivity.MANUALLY_CHANGE_PRESENCE, R.bool.manually_change_presence);
 801    }
 802
 803    protected String getShareableUri() {
 804        return getShareableUri(false);
 805    }
 806
 807    protected String getShareableUri(boolean http) {
 808        return null;
 809    }
 810
 811    protected void shareLink(boolean http) {
 812        String uri = getShareableUri(http);
 813        if (uri == null || uri.isEmpty()) {
 814            return;
 815        }
 816        Intent intent = new Intent(Intent.ACTION_SEND);
 817        intent.setType("text/plain");
 818        intent.putExtra(Intent.EXTRA_TEXT, getShareableUri(http));
 819        try {
 820            startActivity(Intent.createChooser(intent, getText(R.string.share_uri_with)));
 821        } catch (ActivityNotFoundException e) {
 822            Toast.makeText(this, R.string.no_application_to_share_uri, Toast.LENGTH_SHORT).show();
 823        }
 824    }
 825
 826    protected void launchOpenKeyChain(long keyId) {
 827        PgpEngine pgp = XmppActivity.this.xmppConnectionService.getPgpEngine();
 828        try {
 829            startIntentSenderForResult(
 830                    pgp.getIntentForKey(keyId).getIntentSender(), 0, null, 0,
 831                    0, 0);
 832        } catch (Throwable e) {
 833            Toast.makeText(XmppActivity.this, R.string.openpgp_error, Toast.LENGTH_SHORT).show();
 834        }
 835    }
 836
 837    @Override
 838    protected void onResume(){
 839        super.onResume();
 840        SettingsUtils.applyScreenshotPreventionSetting(this);
 841    }
 842
 843    protected int findTheme() {
 844        return ThemeHelper.find(this);
 845    }
 846
 847    @Override
 848    public void onPause() {
 849        super.onPause();
 850    }
 851
 852    @Override
 853    public boolean onMenuOpened(int id, Menu menu) {
 854        if (id == AppCompatDelegate.FEATURE_SUPPORT_ACTION_BAR && menu != null) {
 855            MenuDoubleTabUtil.recordMenuOpen();
 856        }
 857        return super.onMenuOpened(id, menu);
 858    }
 859
 860    protected void showQrCode() {
 861        showQrCode(getShareableUri());
 862    }
 863
 864    protected void showQrCode(final String uri) {
 865        if (uri == null || uri.isEmpty()) {
 866            return;
 867        }
 868        Point size = new Point();
 869        getWindowManager().getDefaultDisplay().getSize(size);
 870        final int width = (size.x < size.y ? size.x : size.y);
 871        Bitmap bitmap = BarcodeProvider.create2dBarcodeBitmap(uri, width);
 872        ImageView view = new ImageView(this);
 873        view.setBackgroundColor(Color.WHITE);
 874        view.setImageBitmap(bitmap);
 875        AlertDialog.Builder builder = new AlertDialog.Builder(this);
 876        builder.setView(view);
 877        builder.create().show();
 878    }
 879
 880    protected Account extractAccount(Intent intent) {
 881        final String jid = intent != null ? intent.getStringExtra(EXTRA_ACCOUNT) : null;
 882        try {
 883            return jid != null ? xmppConnectionService.findAccountByJid(Jid.ofEscaped(jid)) : null;
 884        } catch (IllegalArgumentException e) {
 885            return null;
 886        }
 887    }
 888
 889    public AvatarService avatarService() {
 890        return xmppConnectionService.getAvatarService();
 891    }
 892
 893    public void loadBitmap(Message message, ImageView imageView) {
 894        Drawable bm;
 895        try {
 896            bm = xmppConnectionService.getFileBackend().getThumbnail(message, getResources(), (int) (metrics.density * 288), true);
 897        } catch (IOException e) {
 898            bm = null;
 899        }
 900        if (bm != null) {
 901            cancelPotentialWork(message, imageView);
 902            imageView.setImageDrawable(bm);
 903            imageView.setBackgroundColor(0x00000000);
 904            if (Build.VERSION.SDK_INT >= 28 && bm instanceof AnimatedImageDrawable) {
 905                ((AnimatedImageDrawable) bm).start();
 906            }
 907        } else {
 908            if (cancelPotentialWork(message, imageView)) {
 909                imageView.setBackgroundColor(0xff333333);
 910                imageView.setImageDrawable(null);
 911                final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
 912                final AsyncDrawable asyncDrawable = new AsyncDrawable(
 913                        getResources(), null, task);
 914                imageView.setImageDrawable(asyncDrawable);
 915                try {
 916                    task.execute(message);
 917                } catch (final RejectedExecutionException ignored) {
 918                    ignored.printStackTrace();
 919                }
 920            }
 921        }
 922    }
 923
 924    protected interface OnValueEdited {
 925        String onValueEdited(String value);
 926    }
 927
 928    public static class ConferenceInvite {
 929        private String uuid;
 930        private final List<Jid> jids = new ArrayList<>();
 931
 932        public static ConferenceInvite parse(Intent data) {
 933            ConferenceInvite invite = new ConferenceInvite();
 934            invite.uuid = data.getStringExtra(ChooseContactActivity.EXTRA_CONVERSATION);
 935            if (invite.uuid == null) {
 936                return null;
 937            }
 938            invite.jids.addAll(ChooseContactActivity.extractJabberIds(data));
 939            return invite;
 940        }
 941
 942        public boolean execute(XmppActivity activity) {
 943            XmppConnectionService service = activity.xmppConnectionService;
 944            Conversation conversation = service.findConversationByUuid(this.uuid);
 945            if (conversation == null) {
 946                return false;
 947            }
 948            if (conversation.getMode() == Conversation.MODE_MULTI) {
 949                for (Jid jid : jids) {
 950                    service.invite(conversation, jid);
 951                }
 952                return false;
 953            } else {
 954                jids.add(conversation.getJid().asBareJid());
 955                return service.createAdhocConference(conversation.getAccount(), null, jids, activity.adhocCallback);
 956            }
 957        }
 958    }
 959
 960    static class BitmapWorkerTask extends AsyncTask<Message, Void, Drawable> {
 961        private final WeakReference<ImageView> imageViewReference;
 962        private Message message = null;
 963
 964        private BitmapWorkerTask(ImageView imageView) {
 965            this.imageViewReference = new WeakReference<>(imageView);
 966        }
 967
 968        @Override
 969        protected Drawable doInBackground(Message... params) {
 970            if (isCancelled()) {
 971                return null;
 972            }
 973            message = params[0];
 974            try {
 975                final XmppActivity activity = find(imageViewReference);
 976                if (activity != null && activity.xmppConnectionService != null) {
 977                    return activity.xmppConnectionService.getFileBackend().getThumbnail(message, imageViewReference.get().getContext().getResources(), (int) (activity.metrics.density * 288), false);
 978                } else {
 979                    return null;
 980                }
 981            } catch (IOException e) {
 982                return null;
 983            }
 984        }
 985
 986        @Override
 987        protected void onPostExecute(final Drawable drawable) {
 988            if (!isCancelled()) {
 989                final ImageView imageView = imageViewReference.get();
 990                if (imageView != null) {
 991                    imageView.setImageDrawable(drawable);
 992                    imageView.setBackgroundColor(drawable == null ? 0xff333333 : 0x00000000);
 993                    if (Build.VERSION.SDK_INT >= 28 && drawable instanceof AnimatedImageDrawable) {
 994                        ((AnimatedImageDrawable) drawable).start();
 995                    }
 996                }
 997            }
 998        }
 999    }
1000
1001    private static class AsyncDrawable extends BitmapDrawable {
1002        private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
1003
1004        private AsyncDrawable(Resources res, Bitmap bitmap, BitmapWorkerTask bitmapWorkerTask) {
1005            super(res, bitmap);
1006            bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
1007        }
1008
1009        private BitmapWorkerTask getBitmapWorkerTask() {
1010            return bitmapWorkerTaskReference.get();
1011        }
1012    }
1013
1014    public static XmppActivity find(@NonNull WeakReference<ImageView> viewWeakReference) {
1015        final View view = viewWeakReference.get();
1016        return view == null ? null : find(view);
1017    }
1018
1019    public static XmppActivity find(@NonNull final View view) {
1020        Context context = view.getContext();
1021        while (context instanceof ContextWrapper) {
1022            if (context instanceof XmppActivity) {
1023                return (XmppActivity) context;
1024            }
1025            context = ((ContextWrapper) context).getBaseContext();
1026        }
1027        return null;
1028    }
1029}