XmppActivity.java

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