XmppConnectionService.java

   1package eu.siacs.conversations.services;
   2
   3import android.Manifest;
   4import android.annotation.SuppressLint;
   5import android.annotation.TargetApi;
   6import android.app.AlarmManager;
   7import android.app.Notification;
   8import android.app.NotificationManager;
   9import android.app.PendingIntent;
  10import android.app.Service;
  11import android.content.BroadcastReceiver;
  12import android.content.ComponentName;
  13import android.content.Context;
  14import android.content.Intent;
  15import android.content.IntentFilter;
  16import android.content.SharedPreferences;
  17import android.content.pm.PackageManager;
  18import android.database.ContentObserver;
  19import android.graphics.Bitmap;
  20import android.media.AudioManager;
  21import android.net.ConnectivityManager;
  22import android.net.NetworkInfo;
  23import android.net.Uri;
  24import android.os.Binder;
  25import android.os.Build;
  26import android.os.Bundle;
  27import android.os.Environment;
  28import android.os.IBinder;
  29import android.os.PowerManager;
  30import android.os.PowerManager.WakeLock;
  31import android.os.SystemClock;
  32import android.preference.PreferenceManager;
  33import android.provider.ContactsContract;
  34import android.security.KeyChain;
  35import android.support.annotation.BoolRes;
  36import android.support.annotation.IntegerRes;
  37import android.support.v4.app.RemoteInput;
  38import android.support.v4.content.ContextCompat;
  39import android.telephony.PhoneStateListener;
  40import android.telephony.TelephonyManager;
  41import android.text.TextUtils;
  42import android.util.DisplayMetrics;
  43import android.util.Log;
  44import android.util.LruCache;
  45import android.util.Pair;
  46
  47import com.google.common.base.Objects;
  48import com.google.common.base.Strings;
  49
  50import org.conscrypt.Conscrypt;
  51import org.openintents.openpgp.IOpenPgpService2;
  52import org.openintents.openpgp.util.OpenPgpApi;
  53import org.openintents.openpgp.util.OpenPgpServiceConnection;
  54
  55import java.io.File;
  56import java.net.URL;
  57import java.security.SecureRandom;
  58import java.security.Security;
  59import java.security.cert.CertificateException;
  60import java.security.cert.X509Certificate;
  61import java.util.ArrayList;
  62import java.util.Arrays;
  63import java.util.Collection;
  64import java.util.Collections;
  65import java.util.HashSet;
  66import java.util.Hashtable;
  67import java.util.Iterator;
  68import java.util.List;
  69import java.util.ListIterator;
  70import java.util.Map;
  71import java.util.Set;
  72import java.util.WeakHashMap;
  73import java.util.concurrent.CopyOnWriteArrayList;
  74import java.util.concurrent.CountDownLatch;
  75import java.util.concurrent.atomic.AtomicBoolean;
  76import java.util.concurrent.atomic.AtomicLong;
  77import java.util.concurrent.atomic.AtomicReference;
  78
  79import eu.siacs.conversations.Config;
  80import eu.siacs.conversations.R;
  81import eu.siacs.conversations.android.JabberIdContact;
  82import eu.siacs.conversations.crypto.OmemoSetting;
  83import eu.siacs.conversations.crypto.PgpDecryptionService;
  84import eu.siacs.conversations.crypto.PgpEngine;
  85import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  86import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
  87import eu.siacs.conversations.crypto.axolotl.XmppAxolotlMessage;
  88import eu.siacs.conversations.entities.Account;
  89import eu.siacs.conversations.entities.Blockable;
  90import eu.siacs.conversations.entities.Bookmark;
  91import eu.siacs.conversations.entities.Contact;
  92import eu.siacs.conversations.entities.Conversation;
  93import eu.siacs.conversations.entities.Conversational;
  94import eu.siacs.conversations.entities.Message;
  95import eu.siacs.conversations.entities.MucOptions;
  96import eu.siacs.conversations.entities.MucOptions.OnRenameListener;
  97import eu.siacs.conversations.entities.Presence;
  98import eu.siacs.conversations.entities.PresenceTemplate;
  99import eu.siacs.conversations.entities.Roster;
 100import eu.siacs.conversations.entities.ServiceDiscoveryResult;
 101import eu.siacs.conversations.generator.AbstractGenerator;
 102import eu.siacs.conversations.generator.IqGenerator;
 103import eu.siacs.conversations.generator.MessageGenerator;
 104import eu.siacs.conversations.generator.PresenceGenerator;
 105import eu.siacs.conversations.http.CustomURLStreamHandlerFactory;
 106import eu.siacs.conversations.http.HttpConnectionManager;
 107import eu.siacs.conversations.parser.AbstractParser;
 108import eu.siacs.conversations.parser.IqParser;
 109import eu.siacs.conversations.parser.MessageParser;
 110import eu.siacs.conversations.parser.PresenceParser;
 111import eu.siacs.conversations.persistance.DatabaseBackend;
 112import eu.siacs.conversations.persistance.FileBackend;
 113import eu.siacs.conversations.ui.ChooseAccountForProfilePictureActivity;
 114import eu.siacs.conversations.ui.RtpSessionActivity;
 115import eu.siacs.conversations.ui.SettingsActivity;
 116import eu.siacs.conversations.ui.UiCallback;
 117import eu.siacs.conversations.ui.interfaces.OnAvatarPublication;
 118import eu.siacs.conversations.ui.interfaces.OnMediaLoaded;
 119import eu.siacs.conversations.ui.interfaces.OnSearchResultsAvailable;
 120import eu.siacs.conversations.utils.Compatibility;
 121import eu.siacs.conversations.utils.ConversationsFileObserver;
 122import eu.siacs.conversations.utils.CryptoHelper;
 123import eu.siacs.conversations.utils.ExceptionHelper;
 124import eu.siacs.conversations.utils.MimeUtils;
 125import eu.siacs.conversations.utils.PhoneHelper;
 126import eu.siacs.conversations.utils.QuickLoader;
 127import eu.siacs.conversations.utils.ReplacingSerialSingleThreadExecutor;
 128import eu.siacs.conversations.utils.ReplacingTaskManager;
 129import eu.siacs.conversations.utils.Resolver;
 130import eu.siacs.conversations.utils.SerialSingleThreadExecutor;
 131import eu.siacs.conversations.utils.StringUtils;
 132import eu.siacs.conversations.utils.TorServiceUtils;
 133import eu.siacs.conversations.utils.WakeLockHelper;
 134import eu.siacs.conversations.utils.XmppUri;
 135import eu.siacs.conversations.xml.Element;
 136import eu.siacs.conversations.xml.Namespace;
 137import eu.siacs.conversations.xmpp.OnBindListener;
 138import eu.siacs.conversations.xmpp.OnContactStatusChanged;
 139import eu.siacs.conversations.xmpp.OnIqPacketReceived;
 140import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
 141import eu.siacs.conversations.xmpp.OnMessageAcknowledged;
 142import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
 143import eu.siacs.conversations.xmpp.OnPresencePacketReceived;
 144import eu.siacs.conversations.xmpp.OnStatusChanged;
 145import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
 146import eu.siacs.conversations.xmpp.Patches;
 147import eu.siacs.conversations.xmpp.XmppConnection;
 148import eu.siacs.conversations.xmpp.chatstate.ChatState;
 149import eu.siacs.conversations.xmpp.forms.Data;
 150import eu.siacs.conversations.xmpp.jingle.AbstractJingleConnection;
 151import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
 152import eu.siacs.conversations.xmpp.jingle.Media;
 153import eu.siacs.conversations.xmpp.jingle.RtpEndUserState;
 154import eu.siacs.conversations.xmpp.mam.MamReference;
 155import eu.siacs.conversations.xmpp.pep.Avatar;
 156import eu.siacs.conversations.xmpp.pep.PublishOptions;
 157import eu.siacs.conversations.xmpp.stanzas.IqPacket;
 158import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
 159import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
 160import me.leolin.shortcutbadger.ShortcutBadger;
 161import eu.siacs.conversations.xmpp.Jid;
 162
 163public class XmppConnectionService extends Service {
 164
 165    public static final String ACTION_REPLY_TO_CONVERSATION = "reply_to_conversations";
 166    public static final String ACTION_MARK_AS_READ = "mark_as_read";
 167    public static final String ACTION_SNOOZE = "snooze";
 168    public static final String ACTION_CLEAR_NOTIFICATION = "clear_notification";
 169    public static final String ACTION_DISMISS_ERROR_NOTIFICATIONS = "dismiss_error";
 170    public static final String ACTION_TRY_AGAIN = "try_again";
 171    public static final String ACTION_IDLE_PING = "idle_ping";
 172    public static final String ACTION_FCM_TOKEN_REFRESH = "fcm_token_refresh";
 173    public static final String ACTION_FCM_MESSAGE_RECEIVED = "fcm_message_received";
 174    public static final String ACTION_DISMISS_CALL = "dismiss_call";
 175    public static final String ACTION_END_CALL = "end_call";
 176    public static final String ACTION_PROVISION_ACCOUNT = "provision_account";
 177    private static final String ACTION_POST_CONNECTIVITY_CHANGE = "eu.siacs.conversations.POST_CONNECTIVITY_CHANGE";
 178
 179    private static final String SETTING_LAST_ACTIVITY_TS = "last_activity_timestamp";
 180
 181    static {
 182        URL.setURLStreamHandlerFactory(new CustomURLStreamHandlerFactory());
 183    }
 184
 185    public final CountDownLatch restoredFromDatabaseLatch = new CountDownLatch(1);
 186    private final SerialSingleThreadExecutor mFileAddingExecutor = new SerialSingleThreadExecutor("FileAdding");
 187    private final SerialSingleThreadExecutor mVideoCompressionExecutor = new SerialSingleThreadExecutor("VideoCompression");
 188    private final SerialSingleThreadExecutor mDatabaseWriterExecutor = new SerialSingleThreadExecutor("DatabaseWriter");
 189    private final SerialSingleThreadExecutor mDatabaseReaderExecutor = new SerialSingleThreadExecutor("DatabaseReader");
 190    private final SerialSingleThreadExecutor mNotificationExecutor = new SerialSingleThreadExecutor("NotificationExecutor");
 191    private final ReplacingTaskManager mRosterSyncTaskManager = new ReplacingTaskManager();
 192    private final IBinder mBinder = new XmppConnectionBinder();
 193    private final List<Conversation> conversations = new CopyOnWriteArrayList<>();
 194    private final IqGenerator mIqGenerator = new IqGenerator(this);
 195    private final Set<String> mInProgressAvatarFetches = new HashSet<>();
 196    private final Set<String> mOmittedPepAvatarFetches = new HashSet<>();
 197    private final HashSet<Jid> mLowPingTimeoutMode = new HashSet<>();
 198    private final OnIqPacketReceived mDefaultIqHandler = (account, packet) -> {
 199        if (packet.getType() != IqPacket.TYPE.RESULT) {
 200            Element error = packet.findChild("error");
 201            String text = error != null ? error.findChildContent("text") : null;
 202            if (text != null) {
 203                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received iq error - " + text);
 204            }
 205        }
 206    };
 207    public DatabaseBackend databaseBackend;
 208    private ReplacingSerialSingleThreadExecutor mContactMergerExecutor = new ReplacingSerialSingleThreadExecutor("ContactMerger");
 209    private long mLastActivity = 0;
 210    private FileBackend fileBackend = new FileBackend(this);
 211    private MemorizingTrustManager mMemorizingTrustManager;
 212    private NotificationService mNotificationService = new NotificationService(this);
 213    private ChannelDiscoveryService mChannelDiscoveryService = new ChannelDiscoveryService(this);
 214    private ShortcutService mShortcutService = new ShortcutService(this);
 215    private AtomicBoolean mInitialAddressbookSyncCompleted = new AtomicBoolean(false);
 216    private AtomicBoolean mForceForegroundService = new AtomicBoolean(false);
 217    private AtomicBoolean mForceDuringOnCreate = new AtomicBoolean(false);
 218    private AtomicReference<OngoingCall> ongoingCall = new AtomicReference<>();
 219    private OnMessagePacketReceived mMessageParser = new MessageParser(this);
 220    private OnPresencePacketReceived mPresenceParser = new PresenceParser(this);
 221    private IqParser mIqParser = new IqParser(this);
 222    private MessageGenerator mMessageGenerator = new MessageGenerator(this);
 223    public OnContactStatusChanged onContactStatusChanged = (contact, online) -> {
 224        Conversation conversation = find(getConversations(), contact);
 225        if (conversation != null) {
 226            if (online) {
 227                if (contact.getPresences().size() == 1) {
 228                    sendUnsentMessages(conversation);
 229                }
 230            }
 231        }
 232    };
 233    private PresenceGenerator mPresenceGenerator = new PresenceGenerator(this);
 234    private List<Account> accounts;
 235    private JingleConnectionManager mJingleConnectionManager = new JingleConnectionManager(this);
 236    private HttpConnectionManager mHttpConnectionManager = new HttpConnectionManager(this);
 237    private AvatarService mAvatarService = new AvatarService(this);
 238    private MessageArchiveService mMessageArchiveService = new MessageArchiveService(this);
 239    private PushManagementService mPushManagementService = new PushManagementService(this);
 240    private QuickConversationsService mQuickConversationsService = new QuickConversationsService(this);
 241    private final ConversationsFileObserver fileObserver = new ConversationsFileObserver(
 242            Environment.getExternalStorageDirectory().getAbsolutePath()
 243    ) {
 244        @Override
 245        public void onEvent(final int event, final File file) {
 246            markFileDeleted(file);
 247        }
 248    };
 249    private final OnMessageAcknowledged mOnMessageAcknowledgedListener = new OnMessageAcknowledged() {
 250
 251        @Override
 252        public boolean onMessageAcknowledged(Account account, String uuid) {
 253            for (final Conversation conversation : getConversations()) {
 254                if (conversation.getAccount() == account) {
 255                    Message message = conversation.findUnsentMessageWithUuid(uuid);
 256                    if (message != null) {
 257                        message.setStatus(Message.STATUS_SEND);
 258                        message.setErrorMessage(null);
 259                        databaseBackend.updateMessage(message, false);
 260                        return true;
 261                    }
 262                }
 263            }
 264            return false;
 265        }
 266    };
 267    private final AtomicBoolean isPhoneInCall = new AtomicBoolean(false);
 268    private final PhoneStateListener phoneStateListener = new PhoneStateListener() {
 269        @Override
 270        public void onCallStateChanged(final int state, final String phoneNumber) {
 271            isPhoneInCall.set(state != 0);
 272        }
 273    };
 274
 275    private boolean destroyed = false;
 276
 277    private int unreadCount = -1;
 278
 279    //Ui callback listeners
 280    private final Set<OnConversationUpdate> mOnConversationUpdates = Collections.newSetFromMap(new WeakHashMap<OnConversationUpdate, Boolean>());
 281    private final Set<OnShowErrorToast> mOnShowErrorToasts = Collections.newSetFromMap(new WeakHashMap<OnShowErrorToast, Boolean>());
 282    private final Set<OnAccountUpdate> mOnAccountUpdates = Collections.newSetFromMap(new WeakHashMap<OnAccountUpdate, Boolean>());
 283    private final Set<OnCaptchaRequested> mOnCaptchaRequested = Collections.newSetFromMap(new WeakHashMap<OnCaptchaRequested, Boolean>());
 284    private final Set<OnRosterUpdate> mOnRosterUpdates = Collections.newSetFromMap(new WeakHashMap<OnRosterUpdate, Boolean>());
 285    private final Set<OnUpdateBlocklist> mOnUpdateBlocklist = Collections.newSetFromMap(new WeakHashMap<OnUpdateBlocklist, Boolean>());
 286    private final Set<OnMucRosterUpdate> mOnMucRosterUpdate = Collections.newSetFromMap(new WeakHashMap<OnMucRosterUpdate, Boolean>());
 287    private final Set<OnKeyStatusUpdated> mOnKeyStatusUpdated = Collections.newSetFromMap(new WeakHashMap<OnKeyStatusUpdated, Boolean>());
 288    private final Set<OnJingleRtpConnectionUpdate> onJingleRtpConnectionUpdate = Collections.newSetFromMap(new WeakHashMap<OnJingleRtpConnectionUpdate, Boolean>());
 289
 290    private final Object LISTENER_LOCK = new Object();
 291
 292
 293    public final Set<String> FILENAMES_TO_IGNORE_DELETION = new HashSet<>();
 294
 295
 296    private final OnBindListener mOnBindListener = new OnBindListener() {
 297
 298        @Override
 299        public void onBind(final Account account) {
 300            synchronized (mInProgressAvatarFetches) {
 301                for (Iterator<String> iterator = mInProgressAvatarFetches.iterator(); iterator.hasNext(); ) {
 302                    final String KEY = iterator.next();
 303                    if (KEY.startsWith(account.getJid().asBareJid() + "_")) {
 304                        iterator.remove();
 305                    }
 306                }
 307            }
 308            boolean loggedInSuccessfully = account.setOption(Account.OPTION_LOGGED_IN_SUCCESSFULLY, true);
 309            boolean gainedFeature = account.setOption(Account.OPTION_HTTP_UPLOAD_AVAILABLE, account.getXmppConnection().getFeatures().httpUpload(0));
 310            if (loggedInSuccessfully || gainedFeature) {
 311                databaseBackend.updateAccount(account);
 312            }
 313
 314            if (loggedInSuccessfully) {
 315                if (!TextUtils.isEmpty(account.getDisplayName())) {
 316                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": display name wasn't empty on first log in. publishing");
 317                    publishDisplayName(account);
 318                }
 319            }
 320
 321            account.getRoster().clearPresences();
 322            synchronized (account.inProgressConferenceJoins) {
 323                account.inProgressConferenceJoins.clear();
 324            }
 325            synchronized (account.inProgressConferencePings) {
 326                account.inProgressConferencePings.clear();
 327            }
 328            mJingleConnectionManager.notifyRebound();
 329            mQuickConversationsService.considerSyncBackground(false);
 330            fetchRosterFromServer(account);
 331
 332            final XmppConnection connection = account.getXmppConnection();
 333
 334            if (connection.getFeatures().bookmarks2()) {
 335                fetchBookmarks2(account);
 336            } else if (!account.getXmppConnection().getFeatures().bookmarksConversion()) {
 337                fetchBookmarks(account);
 338            }
 339            final boolean flexible = account.getXmppConnection().getFeatures().flexibleOfflineMessageRetrieval();
 340            final boolean catchup = getMessageArchiveService().inCatchup(account);
 341            if (flexible && catchup && account.getXmppConnection().isMamPreferenceAlways()) {
 342                sendIqPacket(account, mIqGenerator.purgeOfflineMessages(), (acc, packet) -> {
 343                    if (packet.getType() == IqPacket.TYPE.RESULT) {
 344                        Log.d(Config.LOGTAG, acc.getJid().asBareJid() + ": successfully purged offline messages");
 345                    }
 346                });
 347            }
 348            sendPresence(account);
 349            if (mPushManagementService.available(account)) {
 350                mPushManagementService.registerPushTokenOnServer(account);
 351            }
 352            connectMultiModeConversations(account);
 353            syncDirtyContacts(account);
 354        }
 355    };
 356    private AtomicLong mLastExpiryRun = new AtomicLong(0);
 357    private SecureRandom mRandom;
 358    private LruCache<Pair<String, String>, ServiceDiscoveryResult> discoCache = new LruCache<>(20);
 359    private OnStatusChanged statusListener = new OnStatusChanged() {
 360
 361        @Override
 362        public void onStatusChanged(final Account account) {
 363            XmppConnection connection = account.getXmppConnection();
 364            updateAccountUi();
 365
 366            if (account.getStatus() == Account.State.ONLINE || account.getStatus().isError()) {
 367                mQuickConversationsService.signalAccountStateChange();
 368            }
 369
 370            if (account.getStatus() == Account.State.ONLINE) {
 371                synchronized (mLowPingTimeoutMode) {
 372                    if (mLowPingTimeoutMode.remove(account.getJid().asBareJid())) {
 373                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": leaving low ping timeout mode");
 374                    }
 375                }
 376                if (account.setShowErrorNotification(true)) {
 377                    databaseBackend.updateAccount(account);
 378                }
 379                mMessageArchiveService.executePendingQueries(account);
 380                if (connection != null && connection.getFeatures().csi()) {
 381                    if (checkListeners()) {
 382                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + " sending csi//inactive");
 383                        connection.sendInactive();
 384                    } else {
 385                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + " sending csi//active");
 386                        connection.sendActive();
 387                    }
 388                }
 389                List<Conversation> conversations = getConversations();
 390                for (Conversation conversation : conversations) {
 391                    final boolean inProgressJoin;
 392                    synchronized (account.inProgressConferenceJoins) {
 393                        inProgressJoin = account.inProgressConferenceJoins.contains(conversation);
 394                    }
 395                    final boolean pendingJoin;
 396                    synchronized (account.pendingConferenceJoins) {
 397                        pendingJoin = account.pendingConferenceJoins.contains(conversation);
 398                    }
 399                    if (conversation.getAccount() == account
 400                            && !pendingJoin
 401                            && !inProgressJoin) {
 402                        sendUnsentMessages(conversation);
 403                    }
 404                }
 405                final List<Conversation> pendingLeaves;
 406                synchronized (account.pendingConferenceLeaves) {
 407                    pendingLeaves = new ArrayList<>(account.pendingConferenceLeaves);
 408                    account.pendingConferenceLeaves.clear();
 409
 410                }
 411                for (Conversation conversation : pendingLeaves) {
 412                    leaveMuc(conversation);
 413                }
 414                final List<Conversation> pendingJoins;
 415                synchronized (account.pendingConferenceJoins) {
 416                    pendingJoins = new ArrayList<>(account.pendingConferenceJoins);
 417                    account.pendingConferenceJoins.clear();
 418                }
 419                for (Conversation conversation : pendingJoins) {
 420                    joinMuc(conversation);
 421                }
 422                scheduleWakeUpCall(Config.PING_MAX_INTERVAL, account.getUuid().hashCode());
 423            } else if (account.getStatus() == Account.State.OFFLINE || account.getStatus() == Account.State.DISABLED) {
 424                resetSendingToWaiting(account);
 425                if (account.isEnabled() && isInLowPingTimeoutMode(account)) {
 426                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": went into offline state during low ping mode. reconnecting now");
 427                    reconnectAccount(account, true, false);
 428                } else {
 429                    int timeToReconnect = mRandom.nextInt(10) + 2;
 430                    scheduleWakeUpCall(timeToReconnect, account.getUuid().hashCode());
 431                }
 432            } else if (account.getStatus() == Account.State.REGISTRATION_SUCCESSFUL) {
 433                databaseBackend.updateAccount(account);
 434                reconnectAccount(account, true, false);
 435            } else if (account.getStatus() != Account.State.CONNECTING && account.getStatus() != Account.State.NO_INTERNET) {
 436                resetSendingToWaiting(account);
 437                if (connection != null && account.getStatus().isAttemptReconnect()) {
 438                    final int next = connection.getTimeToNextAttempt();
 439                    final boolean lowPingTimeoutMode = isInLowPingTimeoutMode(account);
 440                    if (next <= 0) {
 441                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": error connecting account. reconnecting now. lowPingTimeout=" + lowPingTimeoutMode);
 442                        reconnectAccount(account, true, false);
 443                    } else {
 444                        final int attempt = connection.getAttempt() + 1;
 445                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": error connecting account. try again in " + next + "s for the " + attempt + " time. lowPingTimeout=" + lowPingTimeoutMode);
 446                        scheduleWakeUpCall(next, account.getUuid().hashCode());
 447                    }
 448                }
 449            }
 450            getNotificationService().updateErrorNotification();
 451        }
 452    };
 453    private OpenPgpServiceConnection pgpServiceConnection;
 454    private PgpEngine mPgpEngine = null;
 455    private WakeLock wakeLock;
 456    private PowerManager pm;
 457    private LruCache<String, Bitmap> mBitmapCache;
 458    private BroadcastReceiver mInternalEventReceiver = new InternalEventReceiver();
 459    private BroadcastReceiver mInternalScreenEventReceiver = new InternalEventReceiver();
 460
 461    private static String generateFetchKey(Account account, final Avatar avatar) {
 462        return account.getJid().asBareJid() + "_" + avatar.owner + "_" + avatar.sha1sum;
 463    }
 464
 465    private boolean isInLowPingTimeoutMode(Account account) {
 466        synchronized (mLowPingTimeoutMode) {
 467            return mLowPingTimeoutMode.contains(account.getJid().asBareJid());
 468        }
 469    }
 470
 471    public void startForcingForegroundNotification() {
 472        mForceForegroundService.set(true);
 473        toggleForegroundService();
 474    }
 475
 476    public void stopForcingForegroundNotification() {
 477        mForceForegroundService.set(false);
 478        toggleForegroundService();
 479    }
 480
 481    public boolean areMessagesInitialized() {
 482        return this.restoredFromDatabaseLatch.getCount() == 0;
 483    }
 484
 485    public PgpEngine getPgpEngine() {
 486        if (!Config.supportOpenPgp()) {
 487            return null;
 488        } else if (pgpServiceConnection != null && pgpServiceConnection.isBound()) {
 489            if (this.mPgpEngine == null) {
 490                this.mPgpEngine = new PgpEngine(new OpenPgpApi(
 491                        getApplicationContext(),
 492                        pgpServiceConnection.getService()), this);
 493            }
 494            return mPgpEngine;
 495        } else {
 496            return null;
 497        }
 498
 499    }
 500
 501    public OpenPgpApi getOpenPgpApi() {
 502        if (!Config.supportOpenPgp()) {
 503            return null;
 504        } else if (pgpServiceConnection != null && pgpServiceConnection.isBound()) {
 505            return new OpenPgpApi(this, pgpServiceConnection.getService());
 506        } else {
 507            return null;
 508        }
 509    }
 510
 511    public FileBackend getFileBackend() {
 512        return this.fileBackend;
 513    }
 514
 515    public AvatarService getAvatarService() {
 516        return this.mAvatarService;
 517    }
 518
 519    public void attachLocationToConversation(final Conversation conversation, final Uri uri, final UiCallback<Message> callback) {
 520        int encryption = conversation.getNextEncryption();
 521        if (encryption == Message.ENCRYPTION_PGP) {
 522            encryption = Message.ENCRYPTION_DECRYPTED;
 523        }
 524        Message message = new Message(conversation, uri.toString(), encryption);
 525        Message.configurePrivateMessage(message);
 526        if (encryption == Message.ENCRYPTION_DECRYPTED) {
 527            getPgpEngine().encrypt(message, callback);
 528        } else {
 529            sendMessage(message);
 530            callback.success(message);
 531        }
 532    }
 533
 534    public void attachFileToConversation(final Conversation conversation, final Uri uri, final String type, final UiCallback<Message> callback) {
 535        final Message message;
 536        if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
 537            message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
 538        } else {
 539            message = new Message(conversation, "", conversation.getNextEncryption());
 540        }
 541        if (!Message.configurePrivateFileMessage(message)) {
 542            message.setCounterpart(conversation.getNextCounterpart());
 543            message.setType(Message.TYPE_FILE);
 544        }
 545        Log.d(Config.LOGTAG, "attachFile: type=" + message.getType());
 546        Log.d(Config.LOGTAG, "counterpart=" + message.getCounterpart());
 547        final AttachFileToConversationRunnable runnable = new AttachFileToConversationRunnable(this, uri, type, message, callback);
 548        if (runnable.isVideoMessage()) {
 549            mVideoCompressionExecutor.execute(runnable);
 550        } else {
 551            mFileAddingExecutor.execute(runnable);
 552        }
 553    }
 554
 555    public void attachImageToConversation(final Conversation conversation, final Uri uri, final UiCallback<Message> callback) {
 556        final String mimeType = MimeUtils.guessMimeTypeFromUri(this, uri);
 557        final String compressPictures = getCompressPicturesPreference();
 558
 559        if ("never".equals(compressPictures)
 560                || ("auto".equals(compressPictures) && getFileBackend().useImageAsIs(uri))
 561                || (mimeType != null && mimeType.endsWith("/gif"))
 562                || getFileBackend().unusualBounds(uri)) {
 563            Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": not compressing picture. sending as file");
 564            attachFileToConversation(conversation, uri, mimeType, callback);
 565            return;
 566        }
 567        final Message message;
 568        if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
 569            message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
 570        } else {
 571            message = new Message(conversation, "", conversation.getNextEncryption());
 572        }
 573        if (!Message.configurePrivateFileMessage(message)) {
 574            message.setCounterpart(conversation.getNextCounterpart());
 575            message.setType(Message.TYPE_IMAGE);
 576        }
 577        Log.d(Config.LOGTAG, "attachImage: type=" + message.getType());
 578        mFileAddingExecutor.execute(() -> {
 579            try {
 580                getFileBackend().copyImageToPrivateStorage(message, uri);
 581            } catch (FileBackend.NotAnImageFileException e) {
 582                attachFileToConversation(conversation, uri, mimeType, callback);
 583                return;
 584            } catch (final FileBackend.FileCopyException e) {
 585                callback.error(e.getResId(), message);
 586                return;
 587            }
 588            if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
 589                final PgpEngine pgpEngine = getPgpEngine();
 590                if (pgpEngine != null) {
 591                    pgpEngine.encrypt(message, callback);
 592                } else if (callback != null) {
 593                    callback.error(R.string.unable_to_connect_to_keychain, null);
 594                }
 595            } else {
 596                sendMessage(message);
 597                callback.success(message);
 598            }
 599        });
 600    }
 601
 602    public Conversation find(Bookmark bookmark) {
 603        return find(bookmark.getAccount(), bookmark.getJid());
 604    }
 605
 606    public Conversation find(final Account account, final Jid jid) {
 607        return find(getConversations(), account, jid);
 608    }
 609
 610    public boolean isMuc(final Account account, final Jid jid) {
 611        final Conversation c = find(account, jid);
 612        return c != null && c.getMode() == Conversational.MODE_MULTI;
 613    }
 614
 615    public void search(List<String> term, OnSearchResultsAvailable onSearchResultsAvailable) {
 616        MessageSearchTask.search(this, term, onSearchResultsAvailable);
 617    }
 618
 619    @Override
 620    public int onStartCommand(Intent intent, int flags, int startId) {
 621        final String action = intent == null ? null : intent.getAction();
 622        final boolean needsForegroundService = intent != null && intent.getBooleanExtra(EventReceiver.EXTRA_NEEDS_FOREGROUND_SERVICE, false);
 623        if (needsForegroundService) {
 624            Log.d(Config.LOGTAG, "toggle forced foreground service after receiving event (action=" + action + ")");
 625            toggleForegroundService(true);
 626        }
 627        String pushedAccountHash = null;
 628        boolean interactive = false;
 629        if (action != null) {
 630            final String uuid = intent.getStringExtra("uuid");
 631            switch (action) {
 632                case ConnectivityManager.CONNECTIVITY_ACTION:
 633                    if (hasInternetConnection()) {
 634                        if (Config.POST_CONNECTIVITY_CHANGE_PING_INTERVAL > 0) {
 635                            schedulePostConnectivityChange();
 636                        }
 637                        if (Config.RESET_ATTEMPT_COUNT_ON_NETWORK_CHANGE) {
 638                            resetAllAttemptCounts(true, false);
 639                        }
 640                    }
 641                    break;
 642                case Intent.ACTION_SHUTDOWN:
 643                    logoutAndSave(true);
 644                    return START_NOT_STICKY;
 645                case ACTION_CLEAR_NOTIFICATION:
 646                    mNotificationExecutor.execute(() -> {
 647                        try {
 648                            final Conversation c = findConversationByUuid(uuid);
 649                            if (c != null) {
 650                                mNotificationService.clear(c);
 651                            } else {
 652                                mNotificationService.clear();
 653                            }
 654                            restoredFromDatabaseLatch.await();
 655
 656                        } catch (InterruptedException e) {
 657                            Log.d(Config.LOGTAG, "unable to process clear notification");
 658                        }
 659                    });
 660                    break;
 661                case ACTION_DISMISS_CALL: {
 662                    final String sessionId = intent.getStringExtra(RtpSessionActivity.EXTRA_SESSION_ID);
 663                    Log.d(Config.LOGTAG, "received intent to dismiss call with session id " + sessionId);
 664                    mJingleConnectionManager.rejectRtpSession(sessionId);
 665                    break;
 666                }
 667                case TorServiceUtils.ACTION_STATUS:
 668                    final String status = intent.getStringExtra(TorServiceUtils.EXTRA_STATUS);
 669                    if ("ON".equals(status)) {
 670                        handleOrbotStartedEvent();
 671                        return START_STICKY;
 672                    }
 673                    break;
 674                case ACTION_END_CALL: {
 675                    final String sessionId = intent.getStringExtra(RtpSessionActivity.EXTRA_SESSION_ID);
 676                    Log.d(Config.LOGTAG, "received intent to end call with session id " + sessionId);
 677                    mJingleConnectionManager.endRtpSession(sessionId);
 678                }
 679                break;
 680                case ACTION_PROVISION_ACCOUNT: {
 681                    final String address = intent.getStringExtra("address");
 682                    final String password = intent.getStringExtra("password");
 683                    if (QuickConversationsService.isQuicksy() || Strings.isNullOrEmpty(address) || Strings.isNullOrEmpty(password)) {
 684                        break;
 685                    }
 686                    provisionAccount(address, password);
 687                    break;
 688                }
 689                case ACTION_DISMISS_ERROR_NOTIFICATIONS:
 690                    dismissErrorNotifications();
 691                    break;
 692                case ACTION_TRY_AGAIN:
 693                    resetAllAttemptCounts(false, true);
 694                    interactive = true;
 695                    break;
 696                case ACTION_REPLY_TO_CONVERSATION:
 697                    Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
 698                    if (remoteInput == null) {
 699                        break;
 700                    }
 701                    final CharSequence body = remoteInput.getCharSequence("text_reply");
 702                    final boolean dismissNotification = intent.getBooleanExtra("dismiss_notification", false);
 703                    if (body == null || body.length() <= 0) {
 704                        break;
 705                    }
 706                    mNotificationExecutor.execute(() -> {
 707                        try {
 708                            restoredFromDatabaseLatch.await();
 709                            final Conversation c = findConversationByUuid(uuid);
 710                            if (c != null) {
 711                                directReply(c, body.toString(), dismissNotification);
 712                            }
 713                        } catch (InterruptedException e) {
 714                            Log.d(Config.LOGTAG, "unable to process direct reply");
 715                        }
 716                    });
 717                    break;
 718                case ACTION_MARK_AS_READ:
 719                    mNotificationExecutor.execute(() -> {
 720                        final Conversation c = findConversationByUuid(uuid);
 721                        if (c == null) {
 722                            Log.d(Config.LOGTAG, "received mark read intent for unknown conversation (" + uuid + ")");
 723                            return;
 724                        }
 725                        try {
 726                            restoredFromDatabaseLatch.await();
 727                            sendReadMarker(c, null);
 728                        } catch (InterruptedException e) {
 729                            Log.d(Config.LOGTAG, "unable to process notification read marker for conversation " + c.getName());
 730                        }
 731
 732                    });
 733                    break;
 734                case ACTION_SNOOZE:
 735                    mNotificationExecutor.execute(() -> {
 736                        final Conversation c = findConversationByUuid(uuid);
 737                        if (c == null) {
 738                            Log.d(Config.LOGTAG, "received snooze intent for unknown conversation (" + uuid + ")");
 739                            return;
 740                        }
 741                        c.setMutedTill(System.currentTimeMillis() + 30 * 60 * 1000);
 742                        mNotificationService.clear(c);
 743                        updateConversation(c);
 744                    });
 745                case AudioManager.RINGER_MODE_CHANGED_ACTION:
 746                case NotificationManager.ACTION_INTERRUPTION_FILTER_CHANGED:
 747                    if (dndOnSilentMode()) {
 748                        refreshAllPresences();
 749                    }
 750                    break;
 751                case Intent.ACTION_SCREEN_ON:
 752                    deactivateGracePeriod();
 753                case Intent.ACTION_SCREEN_OFF:
 754                    if (awayWhenScreenOff()) {
 755                        refreshAllPresences();
 756                    }
 757                    break;
 758                case ACTION_FCM_TOKEN_REFRESH:
 759                    refreshAllFcmTokens();
 760                    break;
 761                case ACTION_IDLE_PING:
 762                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
 763                        scheduleNextIdlePing();
 764                    }
 765                    break;
 766                case ACTION_FCM_MESSAGE_RECEIVED:
 767                    pushedAccountHash = intent.getStringExtra("account");
 768                    Log.d(Config.LOGTAG, "push message arrived in service. account=" + pushedAccountHash);
 769                    break;
 770                case Intent.ACTION_SEND:
 771                    Uri uri = intent.getData();
 772                    if (uri != null) {
 773                        Log.d(Config.LOGTAG, "received uri permission for " + uri.toString());
 774                    }
 775                    return START_STICKY;
 776            }
 777        }
 778        synchronized (this) {
 779            WakeLockHelper.acquire(wakeLock);
 780            boolean pingNow = ConnectivityManager.CONNECTIVITY_ACTION.equals(action) || (Config.POST_CONNECTIVITY_CHANGE_PING_INTERVAL > 0 && ACTION_POST_CONNECTIVITY_CHANGE.equals(action));
 781            final HashSet<Account> pingCandidates = new HashSet<>();
 782            final String androidId = PhoneHelper.getAndroidId(this);
 783            for (Account account : accounts) {
 784                final boolean pushWasMeantForThisAccount = CryptoHelper.getAccountFingerprint(account, androidId).equals(pushedAccountHash);
 785                pingNow |= processAccountState(account,
 786                        interactive,
 787                        "ui".equals(action),
 788                        pushWasMeantForThisAccount,
 789                        pingCandidates);
 790            }
 791            if (pingNow) {
 792                for (Account account : pingCandidates) {
 793                    final boolean lowTimeout = isInLowPingTimeoutMode(account);
 794                    account.getXmppConnection().sendPing();
 795                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + " send ping (action=" + action + ",lowTimeout=" + Boolean.toString(lowTimeout) + ")");
 796                    scheduleWakeUpCall(lowTimeout ? Config.LOW_PING_TIMEOUT : Config.PING_TIMEOUT, account.getUuid().hashCode());
 797                }
 798            }
 799            WakeLockHelper.release(wakeLock);
 800        }
 801        if (SystemClock.elapsedRealtime() - mLastExpiryRun.get() >= Config.EXPIRY_INTERVAL) {
 802            expireOldMessages();
 803        }
 804        return START_STICKY;
 805    }
 806
 807    private void handleOrbotStartedEvent() {
 808        for (final Account account : accounts) {
 809            if (account.getStatus() == Account.State.TOR_NOT_AVAILABLE) {
 810                reconnectAccount(account, true, false);
 811            }
 812        }
 813    }
 814
 815    private boolean processAccountState(Account account, boolean interactive, boolean isUiAction, boolean isAccountPushed, HashSet<Account> pingCandidates) {
 816        boolean pingNow = false;
 817        if (account.getStatus().isAttemptReconnect()) {
 818            if (!hasInternetConnection()) {
 819                account.setStatus(Account.State.NO_INTERNET);
 820                if (statusListener != null) {
 821                    statusListener.onStatusChanged(account);
 822                }
 823            } else {
 824                if (account.getStatus() == Account.State.NO_INTERNET) {
 825                    account.setStatus(Account.State.OFFLINE);
 826                    if (statusListener != null) {
 827                        statusListener.onStatusChanged(account);
 828                    }
 829                }
 830                if (account.getStatus() == Account.State.ONLINE) {
 831                    synchronized (mLowPingTimeoutMode) {
 832                        long lastReceived = account.getXmppConnection().getLastPacketReceived();
 833                        long lastSent = account.getXmppConnection().getLastPingSent();
 834                        long pingInterval = isUiAction ? Config.PING_MIN_INTERVAL * 1000 : Config.PING_MAX_INTERVAL * 1000;
 835                        long msToNextPing = (Math.max(lastReceived, lastSent) + pingInterval) - SystemClock.elapsedRealtime();
 836                        int pingTimeout = mLowPingTimeoutMode.contains(account.getJid().asBareJid()) ? Config.LOW_PING_TIMEOUT * 1000 : Config.PING_TIMEOUT * 1000;
 837                        long pingTimeoutIn = (lastSent + pingTimeout) - SystemClock.elapsedRealtime();
 838                        if (lastSent > lastReceived) {
 839                            if (pingTimeoutIn < 0) {
 840                                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ping timeout");
 841                                this.reconnectAccount(account, true, interactive);
 842                            } else {
 843                                int secs = (int) (pingTimeoutIn / 1000);
 844                                this.scheduleWakeUpCall(secs, account.getUuid().hashCode());
 845                            }
 846                        } else {
 847                            pingCandidates.add(account);
 848                            if (isAccountPushed) {
 849                                pingNow = true;
 850                                if (mLowPingTimeoutMode.add(account.getJid().asBareJid())) {
 851                                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": entering low ping timeout mode");
 852                                }
 853                            } else if (msToNextPing <= 0) {
 854                                pingNow = true;
 855                            } else {
 856                                this.scheduleWakeUpCall((int) (msToNextPing / 1000), account.getUuid().hashCode());
 857                                if (mLowPingTimeoutMode.remove(account.getJid().asBareJid())) {
 858                                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": leaving low ping timeout mode");
 859                                }
 860                            }
 861                        }
 862                    }
 863                } else if (account.getStatus() == Account.State.OFFLINE) {
 864                    reconnectAccount(account, true, interactive);
 865                } else if (account.getStatus() == Account.State.CONNECTING) {
 866                    long secondsSinceLastConnect = (SystemClock.elapsedRealtime() - account.getXmppConnection().getLastConnect()) / 1000;
 867                    long secondsSinceLastDisco = (SystemClock.elapsedRealtime() - account.getXmppConnection().getLastDiscoStarted()) / 1000;
 868                    long discoTimeout = Config.CONNECT_DISCO_TIMEOUT - secondsSinceLastDisco;
 869                    long timeout = Config.CONNECT_TIMEOUT - secondsSinceLastConnect;
 870                    if (timeout < 0) {
 871                        Log.d(Config.LOGTAG, account.getJid() + ": time out during connect reconnecting (secondsSinceLast=" + secondsSinceLastConnect + ")");
 872                        account.getXmppConnection().resetAttemptCount(false);
 873                        reconnectAccount(account, true, interactive);
 874                    } else if (discoTimeout < 0) {
 875                        account.getXmppConnection().sendDiscoTimeout();
 876                        scheduleWakeUpCall((int) Math.min(timeout, discoTimeout), account.getUuid().hashCode());
 877                    } else {
 878                        scheduleWakeUpCall((int) Math.min(timeout, discoTimeout), account.getUuid().hashCode());
 879                    }
 880                } else {
 881                    if (account.getXmppConnection().getTimeToNextAttempt() <= 0) {
 882                        reconnectAccount(account, true, interactive);
 883                    }
 884                }
 885            }
 886        }
 887        return pingNow;
 888    }
 889
 890    public void reinitializeMuclumbusService() {
 891        mChannelDiscoveryService.initializeMuclumbusService();
 892    }
 893
 894    public void discoverChannels(String query, ChannelDiscoveryService.Method method, ChannelDiscoveryService.OnChannelSearchResultsFound onChannelSearchResultsFound) {
 895        mChannelDiscoveryService.discover(Strings.nullToEmpty(query).trim(), method, onChannelSearchResultsFound);
 896    }
 897
 898    public boolean isDataSaverDisabled() {
 899        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
 900            ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
 901            return !connectivityManager.isActiveNetworkMetered()
 902                    || connectivityManager.getRestrictBackgroundStatus() == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
 903        } else {
 904            return true;
 905        }
 906    }
 907
 908    private void directReply(Conversation conversation, String body, final boolean dismissAfterReply) {
 909        Message message = new Message(conversation, body, conversation.getNextEncryption());
 910        message.markUnread();
 911        if (message.getEncryption() == Message.ENCRYPTION_PGP) {
 912            getPgpEngine().encrypt(message, new UiCallback<Message>() {
 913                @Override
 914                public void success(Message message) {
 915                    if (dismissAfterReply) {
 916                        markRead((Conversation) message.getConversation(), true);
 917                    } else {
 918                        mNotificationService.pushFromDirectReply(message);
 919                    }
 920                }
 921
 922                @Override
 923                public void error(int errorCode, Message object) {
 924
 925                }
 926
 927                @Override
 928                public void userInputRequired(PendingIntent pi, Message object) {
 929
 930                }
 931            });
 932        } else {
 933            sendMessage(message);
 934            if (dismissAfterReply) {
 935                markRead(conversation, true);
 936            } else {
 937                mNotificationService.pushFromDirectReply(message);
 938            }
 939        }
 940    }
 941
 942    private boolean dndOnSilentMode() {
 943        return getBooleanPreference(SettingsActivity.DND_ON_SILENT_MODE, R.bool.dnd_on_silent_mode);
 944    }
 945
 946    private boolean manuallyChangePresence() {
 947        return getBooleanPreference(SettingsActivity.MANUALLY_CHANGE_PRESENCE, R.bool.manually_change_presence);
 948    }
 949
 950    private boolean treatVibrateAsSilent() {
 951        return getBooleanPreference(SettingsActivity.TREAT_VIBRATE_AS_SILENT, R.bool.treat_vibrate_as_silent);
 952    }
 953
 954    private boolean awayWhenScreenOff() {
 955        return getBooleanPreference(SettingsActivity.AWAY_WHEN_SCREEN_IS_OFF, R.bool.away_when_screen_off);
 956    }
 957
 958    private String getCompressPicturesPreference() {
 959        return getPreferences().getString("picture_compression", getResources().getString(R.string.picture_compression));
 960    }
 961
 962    private Presence.Status getTargetPresence() {
 963        if (dndOnSilentMode() && isPhoneSilenced()) {
 964            return Presence.Status.DND;
 965        } else if (awayWhenScreenOff() && !isInteractive()) {
 966            return Presence.Status.AWAY;
 967        } else {
 968            return Presence.Status.ONLINE;
 969        }
 970    }
 971
 972    @SuppressLint("NewApi")
 973    @SuppressWarnings("deprecation")
 974    public boolean isInteractive() {
 975        try {
 976            final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
 977
 978            final boolean isScreenOn;
 979            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
 980                isScreenOn = pm.isScreenOn();
 981            } else {
 982                isScreenOn = pm.isInteractive();
 983            }
 984            return isScreenOn;
 985        } catch (RuntimeException e) {
 986            return false;
 987        }
 988    }
 989
 990    private boolean isPhoneSilenced() {
 991        final boolean notificationDnd;
 992        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
 993            final NotificationManager notificationManager = getSystemService(NotificationManager.class);
 994            final int filter = notificationManager == null ? NotificationManager.INTERRUPTION_FILTER_UNKNOWN : notificationManager.getCurrentInterruptionFilter();
 995            notificationDnd = filter >= NotificationManager.INTERRUPTION_FILTER_PRIORITY;
 996        } else {
 997            notificationDnd = false;
 998        }
 999        final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
1000        final int ringerMode = audioManager == null ? AudioManager.RINGER_MODE_NORMAL : audioManager.getRingerMode();
1001        try {
1002            if (treatVibrateAsSilent()) {
1003                return notificationDnd || ringerMode != AudioManager.RINGER_MODE_NORMAL;
1004            } else {
1005                return notificationDnd || ringerMode == AudioManager.RINGER_MODE_SILENT;
1006            }
1007        } catch (Throwable throwable) {
1008            Log.d(Config.LOGTAG, "platform bug in isPhoneSilenced (" + throwable.getMessage() + ")");
1009            return notificationDnd;
1010        }
1011    }
1012
1013    private void resetAllAttemptCounts(boolean reallyAll, boolean retryImmediately) {
1014        Log.d(Config.LOGTAG, "resetting all attempt counts");
1015        for (Account account : accounts) {
1016            if (account.hasErrorStatus() || reallyAll) {
1017                final XmppConnection connection = account.getXmppConnection();
1018                if (connection != null) {
1019                    connection.resetAttemptCount(retryImmediately);
1020                }
1021            }
1022            if (account.setShowErrorNotification(true)) {
1023                mDatabaseWriterExecutor.execute(() -> databaseBackend.updateAccount(account));
1024            }
1025        }
1026        mNotificationService.updateErrorNotification();
1027    }
1028
1029    private void dismissErrorNotifications() {
1030        for (final Account account : this.accounts) {
1031            if (account.hasErrorStatus()) {
1032                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": dismissing error notification");
1033                if (account.setShowErrorNotification(false)) {
1034                    mDatabaseWriterExecutor.execute(() -> databaseBackend.updateAccount(account));
1035                }
1036            }
1037        }
1038    }
1039
1040    private void expireOldMessages() {
1041        expireOldMessages(false);
1042    }
1043
1044    public void expireOldMessages(final boolean resetHasMessagesLeftOnServer) {
1045        mLastExpiryRun.set(SystemClock.elapsedRealtime());
1046        mDatabaseWriterExecutor.execute(() -> {
1047            long timestamp = getAutomaticMessageDeletionDate();
1048            if (timestamp > 0) {
1049                databaseBackend.expireOldMessages(timestamp);
1050                synchronized (XmppConnectionService.this.conversations) {
1051                    for (Conversation conversation : XmppConnectionService.this.conversations) {
1052                        conversation.expireOldMessages(timestamp);
1053                        if (resetHasMessagesLeftOnServer) {
1054                            conversation.messagesLoaded.set(true);
1055                            conversation.setHasMessagesLeftOnServer(true);
1056                        }
1057                    }
1058                }
1059                updateConversationUi();
1060            }
1061        });
1062    }
1063
1064    public boolean hasInternetConnection() {
1065        final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
1066        try {
1067            final NetworkInfo activeNetwork = cm == null ? null : cm.getActiveNetworkInfo();
1068            return activeNetwork != null && (activeNetwork.isConnected() || activeNetwork.getType() == ConnectivityManager.TYPE_ETHERNET);
1069        } catch (RuntimeException e) {
1070            Log.d(Config.LOGTAG, "unable to check for internet connection", e);
1071            return true; //if internet connection can not be checked it is probably best to just try
1072        }
1073    }
1074
1075    @SuppressLint("TrulyRandom")
1076    @Override
1077    public void onCreate() {
1078        if (Compatibility.runsTwentySix()) {
1079            mNotificationService.initializeChannels();
1080        }
1081        mChannelDiscoveryService.initializeMuclumbusService();
1082        mForceDuringOnCreate.set(Compatibility.runsAndTargetsTwentySix(this));
1083        toggleForegroundService();
1084        this.destroyed = false;
1085        OmemoSetting.load(this);
1086        ExceptionHelper.init(getApplicationContext());
1087        try {
1088            Security.insertProviderAt(Conscrypt.newProvider(), 1);
1089        } catch (Throwable throwable) {
1090            Log.e(Config.LOGTAG, "unable to initialize security provider", throwable);
1091        }
1092        Resolver.init(this);
1093        this.mRandom = new SecureRandom();
1094        updateMemorizingTrustmanager();
1095        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
1096        final int cacheSize = maxMemory / 8;
1097        this.mBitmapCache = new LruCache<String, Bitmap>(cacheSize) {
1098            @Override
1099            protected int sizeOf(final String key, final Bitmap bitmap) {
1100                return bitmap.getByteCount() / 1024;
1101            }
1102        };
1103        if (mLastActivity == 0) {
1104            mLastActivity = getPreferences().getLong(SETTING_LAST_ACTIVITY_TS, System.currentTimeMillis());
1105        }
1106
1107        Log.d(Config.LOGTAG, "initializing database...");
1108        this.databaseBackend = DatabaseBackend.getInstance(getApplicationContext());
1109        Log.d(Config.LOGTAG, "restoring accounts...");
1110        this.accounts = databaseBackend.getAccounts();
1111        final SharedPreferences.Editor editor = getPreferences().edit();
1112        if (this.accounts.size() == 0 && Arrays.asList("Sony", "Sony Ericsson").contains(Build.MANUFACTURER)) {
1113            editor.putBoolean(SettingsActivity.KEEP_FOREGROUND_SERVICE, true);
1114            Log.d(Config.LOGTAG, Build.MANUFACTURER + " is on blacklist. enabling foreground service");
1115        }
1116        final boolean hasEnabledAccounts = hasEnabledAccounts();
1117        editor.putBoolean(EventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts).apply();
1118        editor.apply();
1119        toggleSetProfilePictureActivity(hasEnabledAccounts);
1120
1121        restoreFromDatabase();
1122
1123        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
1124            startContactObserver();
1125        }
1126        if (Compatibility.hasStoragePermission(this)) {
1127            Log.d(Config.LOGTAG, "starting file observer");
1128            mFileAddingExecutor.execute(this.fileObserver::startWatching);
1129            mFileAddingExecutor.execute(this::checkForDeletedFiles);
1130        }
1131        if (Config.supportOpenPgp()) {
1132            this.pgpServiceConnection = new OpenPgpServiceConnection(this, "org.sufficientlysecure.keychain", new OpenPgpServiceConnection.OnBound() {
1133                @Override
1134                public void onBound(IOpenPgpService2 service) {
1135                    for (Account account : accounts) {
1136                        final PgpDecryptionService pgp = account.getPgpDecryptionService();
1137                        if (pgp != null) {
1138                            pgp.continueDecryption(true);
1139                        }
1140                    }
1141                }
1142
1143                @Override
1144                public void onError(Exception e) {
1145                }
1146            });
1147            this.pgpServiceConnection.bindToService();
1148        }
1149
1150        this.pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
1151        this.wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Conversations:Service");
1152
1153        toggleForegroundService();
1154        updateUnreadCountBadge();
1155        toggleScreenEventReceiver();
1156        final IntentFilter intentFilter = new IntentFilter();
1157        intentFilter.addAction(TorServiceUtils.ACTION_STATUS);
1158        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1159            scheduleNextIdlePing();
1160            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
1161                intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1162            }
1163            intentFilter.addAction(NotificationManager.ACTION_INTERRUPTION_FILTER_CHANGED);
1164        }
1165        registerReceiver(this.mInternalEventReceiver, intentFilter);
1166        mForceDuringOnCreate.set(false);
1167        toggleForegroundService();
1168        setupPhoneStateListener();
1169    }
1170
1171
1172    private void setupPhoneStateListener() {
1173        final TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
1174        if (telephonyManager != null) {
1175            telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
1176        }
1177    }
1178
1179    public boolean isPhoneInCall() {
1180        return isPhoneInCall.get();
1181    }
1182
1183    private void checkForDeletedFiles() {
1184        if (destroyed) {
1185            Log.d(Config.LOGTAG, "Do not check for deleted files because service has been destroyed");
1186            return;
1187        }
1188        final long start = SystemClock.elapsedRealtime();
1189        final List<DatabaseBackend.FilePathInfo> relativeFilePaths = databaseBackend.getFilePathInfo();
1190        final List<DatabaseBackend.FilePathInfo> changed = new ArrayList<>();
1191        for (final DatabaseBackend.FilePathInfo filePath : relativeFilePaths) {
1192            if (destroyed) {
1193                Log.d(Config.LOGTAG, "Stop checking for deleted files because service has been destroyed");
1194                return;
1195            }
1196            final File file = fileBackend.getFileForPath(filePath.path);
1197            if (filePath.setDeleted(!file.exists())) {
1198                changed.add(filePath);
1199            }
1200        }
1201        final long duration = SystemClock.elapsedRealtime() - start;
1202        Log.d(Config.LOGTAG, "found " + changed.size() + " changed files on start up. total=" + relativeFilePaths.size() + ". (" + duration + "ms)");
1203        if (changed.size() > 0) {
1204            databaseBackend.markFilesAsChanged(changed);
1205            markChangedFiles(changed);
1206        }
1207    }
1208
1209    public void startContactObserver() {
1210        getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, new ContentObserver(null) {
1211            @Override
1212            public void onChange(boolean selfChange) {
1213                super.onChange(selfChange);
1214                if (restoredFromDatabaseLatch.getCount() == 0) {
1215                    loadPhoneContacts();
1216                }
1217            }
1218        });
1219    }
1220
1221    @Override
1222    public void onTrimMemory(int level) {
1223        super.onTrimMemory(level);
1224        if (level >= TRIM_MEMORY_COMPLETE) {
1225            Log.d(Config.LOGTAG, "clear cache due to low memory");
1226            getBitmapCache().evictAll();
1227        }
1228    }
1229
1230    @Override
1231    public void onDestroy() {
1232        try {
1233            unregisterReceiver(this.mInternalEventReceiver);
1234        } catch (final IllegalArgumentException e) {
1235            //ignored
1236        }
1237        destroyed = false;
1238        fileObserver.stopWatching();
1239        super.onDestroy();
1240    }
1241
1242    public void restartFileObserver() {
1243        Log.d(Config.LOGTAG, "restarting file observer");
1244        mFileAddingExecutor.execute(this.fileObserver::restartWatching);
1245        mFileAddingExecutor.execute(this::checkForDeletedFiles);
1246    }
1247
1248    public void toggleScreenEventReceiver() {
1249        if (awayWhenScreenOff() && !manuallyChangePresence()) {
1250            final IntentFilter filter = new IntentFilter();
1251            filter.addAction(Intent.ACTION_SCREEN_ON);
1252            filter.addAction(Intent.ACTION_SCREEN_OFF);
1253            registerReceiver(this.mInternalScreenEventReceiver, filter);
1254        } else {
1255            try {
1256                unregisterReceiver(this.mInternalScreenEventReceiver);
1257            } catch (IllegalArgumentException e) {
1258                //ignored
1259            }
1260        }
1261    }
1262
1263    public void toggleForegroundService() {
1264        toggleForegroundService(false);
1265    }
1266
1267    public void setOngoingCall(AbstractJingleConnection.Id id, Set<Media> media) {
1268        ongoingCall.set(new OngoingCall(id, media));
1269        toggleForegroundService(false);
1270    }
1271
1272    public void removeOngoingCall() {
1273        ongoingCall.set(null);
1274        toggleForegroundService(false);
1275    }
1276
1277    private void toggleForegroundService(boolean force) {
1278        final boolean status;
1279        final OngoingCall ongoing = ongoingCall.get();
1280        if (force || mForceDuringOnCreate.get() || mForceForegroundService.get() || ongoing != null || (Compatibility.keepForegroundService(this) && hasEnabledAccounts())) {
1281            final Notification notification;
1282            if (ongoing != null) {
1283                notification = this.mNotificationService.getOngoingCallNotification(ongoing.id, ongoing.media);
1284                startForeground(NotificationService.ONGOING_CALL_NOTIFICATION_ID, notification);
1285                mNotificationService.cancel(NotificationService.FOREGROUND_NOTIFICATION_ID);
1286            } else {
1287                notification = this.mNotificationService.createForegroundNotification();
1288                startForeground(NotificationService.FOREGROUND_NOTIFICATION_ID, notification);
1289            }
1290
1291            if (!mForceForegroundService.get()) {
1292                mNotificationService.notify(NotificationService.FOREGROUND_NOTIFICATION_ID, notification);
1293            }
1294            status = true;
1295        } else {
1296            stopForeground(true);
1297            status = false;
1298        }
1299        if (!mForceForegroundService.get()) {
1300            mNotificationService.cancel(NotificationService.FOREGROUND_NOTIFICATION_ID);
1301        }
1302        if (ongoing == null) {
1303            mNotificationService.cancel(NotificationService.ONGOING_CALL_NOTIFICATION_ID);
1304        }
1305        Log.d(Config.LOGTAG, "ForegroundService: " + (status ? "on" : "off"));
1306    }
1307
1308    public boolean foregroundNotificationNeedsUpdatingWhenErrorStateChanges() {
1309        return !mForceForegroundService.get() && ongoingCall.get() == null && Compatibility.keepForegroundService(this) && hasEnabledAccounts();
1310    }
1311
1312    @Override
1313    public void onTaskRemoved(final Intent rootIntent) {
1314        super.onTaskRemoved(rootIntent);
1315        if ((Compatibility.keepForegroundService(this) && hasEnabledAccounts()) || mForceForegroundService.get() || ongoingCall.get() != null) {
1316            Log.d(Config.LOGTAG, "ignoring onTaskRemoved because foreground service is activated");
1317        } else {
1318            this.logoutAndSave(false);
1319        }
1320    }
1321
1322    private void logoutAndSave(boolean stop) {
1323        int activeAccounts = 0;
1324        for (final Account account : accounts) {
1325            if (account.getStatus() != Account.State.DISABLED) {
1326                databaseBackend.writeRoster(account.getRoster());
1327                activeAccounts++;
1328            }
1329            if (account.getXmppConnection() != null) {
1330                new Thread(() -> disconnect(account, false)).start();
1331            }
1332        }
1333        if (stop || activeAccounts == 0) {
1334            Log.d(Config.LOGTAG, "good bye");
1335            stopSelf();
1336        }
1337    }
1338
1339    private void schedulePostConnectivityChange() {
1340        final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1341        if (alarmManager == null) {
1342            return;
1343        }
1344        final long triggerAtMillis = SystemClock.elapsedRealtime() + (Config.POST_CONNECTIVITY_CHANGE_PING_INTERVAL * 1000);
1345        final Intent intent = new Intent(this, EventReceiver.class);
1346        intent.setAction(ACTION_POST_CONNECTIVITY_CHANGE);
1347        try {
1348            final PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, 0);
1349            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1350                alarmManager.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, pendingIntent);
1351            } else {
1352                alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, pendingIntent);
1353            }
1354        } catch (RuntimeException e) {
1355            Log.e(Config.LOGTAG, "unable to schedule alarm for post connectivity change", e);
1356        }
1357    }
1358
1359    public void scheduleWakeUpCall(int seconds, int requestCode) {
1360        final long timeToWake = SystemClock.elapsedRealtime() + (seconds < 0 ? 1 : seconds + 1) * 1000;
1361        final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1362        if (alarmManager == null) {
1363            return;
1364        }
1365        final Intent intent = new Intent(this, EventReceiver.class);
1366        intent.setAction("ping");
1367        try {
1368            PendingIntent pendingIntent = PendingIntent.getBroadcast(this, requestCode, intent, 0);
1369            alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, pendingIntent);
1370        } catch (RuntimeException e) {
1371            Log.e(Config.LOGTAG, "unable to schedule alarm for ping", e);
1372        }
1373    }
1374
1375    @TargetApi(Build.VERSION_CODES.M)
1376    private void scheduleNextIdlePing() {
1377        final long timeToWake = SystemClock.elapsedRealtime() + (Config.IDLE_PING_INTERVAL * 1000);
1378        final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1379        if (alarmManager == null) {
1380            return;
1381        }
1382        final Intent intent = new Intent(this, EventReceiver.class);
1383        intent.setAction(ACTION_IDLE_PING);
1384        try {
1385            PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
1386            alarmManager.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, pendingIntent);
1387        } catch (RuntimeException e) {
1388            Log.d(Config.LOGTAG, "unable to schedule alarm for idle ping", e);
1389        }
1390    }
1391
1392    public XmppConnection createConnection(final Account account) {
1393        final XmppConnection connection = new XmppConnection(account, this);
1394        connection.setOnMessagePacketReceivedListener(this.mMessageParser);
1395        connection.setOnStatusChangedListener(this.statusListener);
1396        connection.setOnPresencePacketReceivedListener(this.mPresenceParser);
1397        connection.setOnUnregisteredIqPacketReceivedListener(this.mIqParser);
1398        connection.setOnJinglePacketReceivedListener(((a, jp) -> mJingleConnectionManager.deliverPacket(a, jp)));
1399        connection.setOnBindListener(this.mOnBindListener);
1400        connection.setOnMessageAcknowledgeListener(this.mOnMessageAcknowledgedListener);
1401        connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService);
1402        connection.addOnAdvancedStreamFeaturesAvailableListener(this.mAvatarService);
1403        AxolotlService axolotlService = account.getAxolotlService();
1404        if (axolotlService != null) {
1405            connection.addOnAdvancedStreamFeaturesAvailableListener(axolotlService);
1406        }
1407        return connection;
1408    }
1409
1410    public void sendChatState(Conversation conversation) {
1411        if (sendChatStates()) {
1412            MessagePacket packet = mMessageGenerator.generateChatState(conversation);
1413            sendMessagePacket(conversation.getAccount(), packet);
1414        }
1415    }
1416
1417    private void sendFileMessage(final Message message, final boolean delay) {
1418        Log.d(Config.LOGTAG, "send file message");
1419        final Account account = message.getConversation().getAccount();
1420        if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1421                || message.getConversation().getMode() == Conversation.MODE_MULTI) {
1422            mHttpConnectionManager.createNewUploadConnection(message, delay);
1423        } else {
1424            mJingleConnectionManager.startJingleFileTransfer(message);
1425        }
1426    }
1427
1428    public void sendMessage(final Message message) {
1429        sendMessage(message, false, false);
1430    }
1431
1432    private void sendMessage(final Message message, final boolean resend, final boolean delay) {
1433        final Account account = message.getConversation().getAccount();
1434        if (account.setShowErrorNotification(true)) {
1435            databaseBackend.updateAccount(account);
1436            mNotificationService.updateErrorNotification();
1437        }
1438        final Conversation conversation = (Conversation) message.getConversation();
1439        account.deactivateGracePeriod();
1440
1441
1442        if (QuickConversationsService.isQuicksy() && conversation.getMode() == Conversation.MODE_SINGLE) {
1443            final Contact contact = conversation.getContact();
1444            if (!contact.showInRoster() && contact.getOption(Contact.Options.SYNCED_VIA_OTHER)) {
1445                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": adding " + contact.getJid() + " on sending message");
1446                createContact(contact, true);
1447            }
1448        }
1449
1450        MessagePacket packet = null;
1451        final boolean addToConversation = (conversation.getMode() != Conversation.MODE_MULTI
1452                || !Patches.BAD_MUC_REFLECTION.contains(account.getServerIdentity()))
1453                && !message.edited();
1454        boolean saveInDb = addToConversation;
1455        message.setStatus(Message.STATUS_WAITING);
1456
1457        if (message.getEncryption() != Message.ENCRYPTION_NONE && conversation.getMode() == Conversation.MODE_MULTI && conversation.isPrivateAndNonAnonymous()) {
1458            if (conversation.setAttribute(Conversation.ATTRIBUTE_FORMERLY_PRIVATE_NON_ANONYMOUS, true)) {
1459                databaseBackend.updateConversation(conversation);
1460            }
1461        }
1462
1463        final boolean inProgressJoin = isJoinInProgress(conversation);
1464
1465
1466        if (account.isOnlineAndConnected() && !inProgressJoin) {
1467            switch (message.getEncryption()) {
1468                case Message.ENCRYPTION_NONE:
1469                    if (message.needsUploading()) {
1470                        if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1471                                || conversation.getMode() == Conversation.MODE_MULTI
1472                                || message.fixCounterpart()) {
1473                            this.sendFileMessage(message, delay);
1474                        } else {
1475                            break;
1476                        }
1477                    } else {
1478                        packet = mMessageGenerator.generateChat(message);
1479                    }
1480                    break;
1481                case Message.ENCRYPTION_PGP:
1482                case Message.ENCRYPTION_DECRYPTED:
1483                    if (message.needsUploading()) {
1484                        if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1485                                || conversation.getMode() == Conversation.MODE_MULTI
1486                                || message.fixCounterpart()) {
1487                            this.sendFileMessage(message, delay);
1488                        } else {
1489                            break;
1490                        }
1491                    } else {
1492                        packet = mMessageGenerator.generatePgpChat(message);
1493                    }
1494                    break;
1495                case Message.ENCRYPTION_AXOLOTL:
1496                    message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
1497                    if (message.needsUploading()) {
1498                        if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1499                                || conversation.getMode() == Conversation.MODE_MULTI
1500                                || message.fixCounterpart()) {
1501                            this.sendFileMessage(message, delay);
1502                        } else {
1503                            break;
1504                        }
1505                    } else {
1506                        XmppAxolotlMessage axolotlMessage = account.getAxolotlService().fetchAxolotlMessageFromCache(message);
1507                        if (axolotlMessage == null) {
1508                            account.getAxolotlService().preparePayloadMessage(message, delay);
1509                        } else {
1510                            packet = mMessageGenerator.generateAxolotlChat(message, axolotlMessage);
1511                        }
1512                    }
1513                    break;
1514
1515            }
1516            if (packet != null) {
1517                if (account.getXmppConnection().getFeatures().sm()
1518                        || (conversation.getMode() == Conversation.MODE_MULTI && message.getCounterpart().isBareJid())) {
1519                    message.setStatus(Message.STATUS_UNSEND);
1520                } else {
1521                    message.setStatus(Message.STATUS_SEND);
1522                }
1523            }
1524        } else {
1525            switch (message.getEncryption()) {
1526                case Message.ENCRYPTION_DECRYPTED:
1527                    if (!message.needsUploading()) {
1528                        String pgpBody = message.getEncryptedBody();
1529                        String decryptedBody = message.getBody();
1530                        message.setBody(pgpBody); //TODO might throw NPE
1531                        message.setEncryption(Message.ENCRYPTION_PGP);
1532                        if (message.edited()) {
1533                            message.setBody(decryptedBody);
1534                            message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1535                            if (!databaseBackend.updateMessage(message, message.getEditedId())) {
1536                                Log.e(Config.LOGTAG, "error updated message in DB after edit");
1537                            }
1538                            updateConversationUi();
1539                            return;
1540                        } else {
1541                            databaseBackend.createMessage(message);
1542                            saveInDb = false;
1543                            message.setBody(decryptedBody);
1544                            message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1545                        }
1546                    }
1547                    break;
1548                case Message.ENCRYPTION_AXOLOTL:
1549                    message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
1550                    break;
1551            }
1552        }
1553
1554
1555        boolean mucMessage = conversation.getMode() == Conversation.MODE_MULTI && !message.isPrivateMessage();
1556        if (mucMessage) {
1557            message.setCounterpart(conversation.getMucOptions().getSelf().getFullJid());
1558        }
1559
1560        if (resend) {
1561            if (packet != null && addToConversation) {
1562                if (account.getXmppConnection().getFeatures().sm() || mucMessage) {
1563                    markMessage(message, Message.STATUS_UNSEND);
1564                } else {
1565                    markMessage(message, Message.STATUS_SEND);
1566                }
1567            }
1568        } else {
1569            if (addToConversation) {
1570                conversation.add(message);
1571            }
1572            if (saveInDb) {
1573                databaseBackend.createMessage(message);
1574            } else if (message.edited()) {
1575                if (!databaseBackend.updateMessage(message, message.getEditedId())) {
1576                    Log.e(Config.LOGTAG, "error updated message in DB after edit");
1577                }
1578            }
1579            updateConversationUi();
1580        }
1581        if (packet != null) {
1582            if (delay) {
1583                mMessageGenerator.addDelay(packet, message.getTimeSent());
1584            }
1585            if (conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
1586                if (this.sendChatStates()) {
1587                    packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
1588                }
1589            }
1590            sendMessagePacket(account, packet);
1591        }
1592    }
1593
1594    private boolean isJoinInProgress(final Conversation conversation) {
1595        final Account account = conversation.getAccount();
1596        synchronized (account.inProgressConferenceJoins) {
1597            if (conversation.getMode() == Conversational.MODE_MULTI) {
1598                final boolean inProgress = account.inProgressConferenceJoins.contains(conversation);
1599                final boolean pending = account.pendingConferenceJoins.contains(conversation);
1600                final boolean inProgressJoin = inProgress || pending;
1601                if (inProgressJoin) {
1602                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": holding back message to group. inProgress=" + inProgress + ", pending=" + pending);
1603                }
1604                return inProgressJoin;
1605            } else {
1606                return false;
1607            }
1608        }
1609    }
1610
1611    private void sendUnsentMessages(final Conversation conversation) {
1612        conversation.findWaitingMessages(message -> resendMessage(message, true));
1613    }
1614
1615    public void resendMessage(final Message message, final boolean delay) {
1616        sendMessage(message, true, delay);
1617    }
1618
1619    public void fetchRosterFromServer(final Account account) {
1620        final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1621        if (!"".equals(account.getRosterVersion())) {
1622            Log.d(Config.LOGTAG, account.getJid().asBareJid()
1623                    + ": fetching roster version " + account.getRosterVersion());
1624        } else {
1625            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching roster");
1626        }
1627        iqPacket.query(Namespace.ROSTER).setAttribute("ver", account.getRosterVersion());
1628        sendIqPacket(account, iqPacket, mIqParser);
1629    }
1630
1631    public void fetchBookmarks(final Account account) {
1632        final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1633        final Element query = iqPacket.query("jabber:iq:private");
1634        query.addChild("storage", Namespace.BOOKMARKS);
1635        final OnIqPacketReceived callback = (a, response) -> {
1636            if (response.getType() == IqPacket.TYPE.RESULT) {
1637                final Element query1 = response.query();
1638                final Element storage = query1.findChild("storage", "storage:bookmarks");
1639                Map<Jid, Bookmark> bookmarks = Bookmark.parseFromStorage(storage, account);
1640                processBookmarksInitial(a, bookmarks, false);
1641            } else {
1642                Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": could not fetch bookmarks");
1643            }
1644        };
1645        sendIqPacket(account, iqPacket, callback);
1646    }
1647
1648    public void fetchBookmarks2(final Account account) {
1649        final IqPacket retrieve = mIqGenerator.retrieveBookmarks();
1650        sendIqPacket(account, retrieve, new OnIqPacketReceived() {
1651            @Override
1652            public void onIqPacketReceived(final Account account, final IqPacket response) {
1653                if (response.getType() == IqPacket.TYPE.RESULT) {
1654                    final Element pubsub = response.findChild("pubsub", Namespace.PUBSUB);
1655                    final Map<Jid, Bookmark> bookmarks = Bookmark.parseFromPubsub(pubsub, account);
1656                    processBookmarksInitial(account, bookmarks, true);
1657                }
1658            }
1659        });
1660    }
1661
1662    public void processBookmarksInitial(Account account, Map<Jid, Bookmark> bookmarks, final boolean pep) {
1663        final Set<Jid> previousBookmarks = account.getBookmarkedJids();
1664        final boolean synchronizeWithBookmarks = synchronizeWithBookmarks();
1665        for (Bookmark bookmark : bookmarks.values()) {
1666            previousBookmarks.remove(bookmark.getJid().asBareJid());
1667            processModifiedBookmark(bookmark, pep, synchronizeWithBookmarks);
1668        }
1669        if (pep && synchronizeWithBookmarks) {
1670            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": " + previousBookmarks.size() + " bookmarks have been removed");
1671            for (Jid jid : previousBookmarks) {
1672                processDeletedBookmark(account, jid);
1673            }
1674        }
1675        account.setBookmarks(bookmarks);
1676    }
1677
1678    public void processDeletedBookmark(Account account, Jid jid) {
1679        final Conversation conversation = find(account, jid);
1680        if (conversation != null && conversation.getMucOptions().getError() == MucOptions.Error.DESTROYED) {
1681            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving destroyed conference (" + conversation.getJid() + ") after receiving pep");
1682            archiveConversation(conversation, false);
1683        }
1684    }
1685
1686    private void processModifiedBookmark(Bookmark bookmark, final boolean pep, final boolean synchronizeWithBookmarks) {
1687        final Account account = bookmark.getAccount();
1688        Conversation conversation = find(bookmark);
1689        if (conversation != null) {
1690            if (conversation.getMode() != Conversation.MODE_MULTI) {
1691                return;
1692            }
1693            bookmark.setConversation(conversation);
1694            if (pep && synchronizeWithBookmarks && !bookmark.autojoin()) {
1695                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conference (" + conversation.getJid() + ") after receiving pep");
1696                archiveConversation(conversation, false);
1697            } else {
1698                final MucOptions mucOptions = conversation.getMucOptions();
1699                if (mucOptions.getError() == MucOptions.Error.NICK_IN_USE) {
1700                    final String current = mucOptions.getActualNick();
1701                    final String proposed = mucOptions.getProposedNick();
1702                    if (current != null && !current.equals(proposed)) {
1703                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": proposed nick changed after bookmark push " + current + "->" + proposed);
1704                        joinMuc(conversation);
1705                    }
1706                }
1707            }
1708        } else if (synchronizeWithBookmarks && bookmark.autojoin()) {
1709            conversation = findOrCreateConversation(account, bookmark.getFullJid(), true, true, false);
1710            bookmark.setConversation(conversation);
1711        }
1712    }
1713
1714    public void processModifiedBookmark(Bookmark bookmark) {
1715        final boolean synchronizeWithBookmarks = synchronizeWithBookmarks();
1716        processModifiedBookmark(bookmark, true, synchronizeWithBookmarks);
1717    }
1718
1719    public void createBookmark(final Account account, final Bookmark bookmark) {
1720        account.putBookmark(bookmark);
1721        final XmppConnection connection = account.getXmppConnection();
1722        if (connection.getFeatures().bookmarks2()) {
1723            final Element item = mIqGenerator.publishBookmarkItem(bookmark);
1724            pushNodeAndEnforcePublishOptions(account, Namespace.BOOKMARKS2, item, bookmark.getJid().asBareJid().toEscapedString(), PublishOptions.persistentWhitelistAccessMaxItems());
1725        } else if (connection.getFeatures().bookmarksConversion()) {
1726            pushBookmarksPep(account);
1727        } else {
1728            pushBookmarksPrivateXml(account);
1729        }
1730    }
1731
1732    public void deleteBookmark(final Account account, final Bookmark bookmark) {
1733        account.removeBookmark(bookmark);
1734        final XmppConnection connection = account.getXmppConnection();
1735        if (connection.getFeatures().bookmarks2()) {
1736            IqPacket request = mIqGenerator.deleteItem(Namespace.BOOKMARKS2, bookmark.getJid().asBareJid().toEscapedString());
1737            sendIqPacket(account, request, (a, response) -> {
1738                if (response.getType() == IqPacket.TYPE.ERROR) {
1739                    Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": unable to delete bookmark " + response.getError());
1740                }
1741            });
1742        } else if (connection.getFeatures().bookmarksConversion()) {
1743            pushBookmarksPep(account);
1744        } else {
1745            pushBookmarksPrivateXml(account);
1746        }
1747    }
1748
1749    private void pushBookmarksPrivateXml(Account account) {
1750        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via private xml");
1751        IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
1752        Element query = iqPacket.query("jabber:iq:private");
1753        Element storage = query.addChild("storage", "storage:bookmarks");
1754        for (Bookmark bookmark : account.getBookmarks()) {
1755            storage.addChild(bookmark);
1756        }
1757        sendIqPacket(account, iqPacket, mDefaultIqHandler);
1758    }
1759
1760    private void pushBookmarksPep(Account account) {
1761        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via pep");
1762        Element storage = new Element("storage", "storage:bookmarks");
1763        for (Bookmark bookmark : account.getBookmarks()) {
1764            storage.addChild(bookmark);
1765        }
1766        pushNodeAndEnforcePublishOptions(account, Namespace.BOOKMARKS, storage, "current", PublishOptions.persistentWhitelistAccess());
1767
1768    }
1769
1770    private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final String id, final Bundle options) {
1771        pushNodeAndEnforcePublishOptions(account, node, element, id, options, true);
1772
1773    }
1774
1775    private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final String id, final Bundle options, final boolean retry) {
1776        final IqPacket packet = mIqGenerator.publishElement(node, element, id, options);
1777        sendIqPacket(account, packet, (a, response) -> {
1778            if (response.getType() == IqPacket.TYPE.RESULT) {
1779                return;
1780            }
1781            if (retry && PublishOptions.preconditionNotMet(response)) {
1782                pushNodeConfiguration(account, node, options, new OnConfigurationPushed() {
1783                    @Override
1784                    public void onPushSucceeded() {
1785                        pushNodeAndEnforcePublishOptions(account, node, element, id, options, false);
1786                    }
1787
1788                    @Override
1789                    public void onPushFailed() {
1790                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to push node configuration (" + node + ")");
1791                    }
1792                });
1793            } else {
1794                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": error publishing bookmarks (retry=" + Boolean.toString(retry) + ") " + response);
1795            }
1796        });
1797    }
1798
1799    private void restoreFromDatabase() {
1800        synchronized (this.conversations) {
1801            final Map<String, Account> accountLookupTable = new Hashtable<>();
1802            for (Account account : this.accounts) {
1803                accountLookupTable.put(account.getUuid(), account);
1804            }
1805            Log.d(Config.LOGTAG, "restoring conversations...");
1806            final long startTimeConversationsRestore = SystemClock.elapsedRealtime();
1807            this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
1808            for (Iterator<Conversation> iterator = conversations.listIterator(); iterator.hasNext(); ) {
1809                Conversation conversation = iterator.next();
1810                Account account = accountLookupTable.get(conversation.getAccountUuid());
1811                if (account != null) {
1812                    conversation.setAccount(account);
1813                } else {
1814                    Log.e(Config.LOGTAG, "unable to restore Conversations with " + conversation.getJid());
1815                    iterator.remove();
1816                }
1817            }
1818            long diffConversationsRestore = SystemClock.elapsedRealtime() - startTimeConversationsRestore;
1819            Log.d(Config.LOGTAG, "finished restoring conversations in " + diffConversationsRestore + "ms");
1820            Runnable runnable = () -> {
1821                long deletionDate = getAutomaticMessageDeletionDate();
1822                mLastExpiryRun.set(SystemClock.elapsedRealtime());
1823                if (deletionDate > 0) {
1824                    Log.d(Config.LOGTAG, "deleting messages that are older than " + AbstractGenerator.getTimestamp(deletionDate));
1825                    databaseBackend.expireOldMessages(deletionDate);
1826                }
1827                Log.d(Config.LOGTAG, "restoring roster...");
1828                for (Account account : accounts) {
1829                    databaseBackend.readRoster(account.getRoster());
1830                    account.initAccountServices(XmppConnectionService.this); //roster needs to be loaded at this stage
1831                }
1832                getBitmapCache().evictAll();
1833                loadPhoneContacts();
1834                Log.d(Config.LOGTAG, "restoring messages...");
1835                final long startMessageRestore = SystemClock.elapsedRealtime();
1836                final Conversation quickLoad = QuickLoader.get(this.conversations);
1837                if (quickLoad != null) {
1838                    restoreMessages(quickLoad);
1839                    updateConversationUi();
1840                    final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
1841                    Log.d(Config.LOGTAG, "quickly restored " + quickLoad.getName() + " after " + diffMessageRestore + "ms");
1842                }
1843                for (Conversation conversation : this.conversations) {
1844                    if (quickLoad != conversation) {
1845                        restoreMessages(conversation);
1846                    }
1847                }
1848                mNotificationService.finishBacklog(false);
1849                restoredFromDatabaseLatch.countDown();
1850                final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
1851                Log.d(Config.LOGTAG, "finished restoring messages in " + diffMessageRestore + "ms");
1852                updateConversationUi();
1853            };
1854            mDatabaseReaderExecutor.execute(runnable); //will contain one write command (expiry) but that's fine
1855        }
1856    }
1857
1858    private void restoreMessages(Conversation conversation) {
1859        conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1860        conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
1861        conversation.findUnreadMessages(message -> mNotificationService.pushFromBacklog(message));
1862    }
1863
1864    public void loadPhoneContacts() {
1865        mContactMergerExecutor.execute(() -> {
1866            Map<Jid, JabberIdContact> contacts = JabberIdContact.load(this);
1867            Log.d(Config.LOGTAG, "start merging phone contacts with roster");
1868            for (Account account : accounts) {
1869                List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts(JabberIdContact.class);
1870                for (JabberIdContact jidContact : contacts.values()) {
1871                    final Contact contact = account.getRoster().getContact(jidContact.getJid());
1872                    boolean needsCacheClean = contact.setPhoneContact(jidContact);
1873                    if (needsCacheClean) {
1874                        getAvatarService().clear(contact);
1875                    }
1876                    withSystemAccounts.remove(contact);
1877                }
1878                for (Contact contact : withSystemAccounts) {
1879                    boolean needsCacheClean = contact.unsetPhoneContact(JabberIdContact.class);
1880                    if (needsCacheClean) {
1881                        getAvatarService().clear(contact);
1882                    }
1883                }
1884            }
1885            Log.d(Config.LOGTAG, "finished merging phone contacts");
1886            mShortcutService.refresh(mInitialAddressbookSyncCompleted.compareAndSet(false, true));
1887            updateRosterUi();
1888            mQuickConversationsService.considerSync();
1889        });
1890    }
1891
1892
1893    public void syncRoster(final Account account) {
1894        mRosterSyncTaskManager.execute(account, () -> databaseBackend.writeRoster(account.getRoster()));
1895    }
1896
1897    public List<Conversation> getConversations() {
1898        return this.conversations;
1899    }
1900
1901    private void markFileDeleted(final File file) {
1902        synchronized (FILENAMES_TO_IGNORE_DELETION) {
1903            if (FILENAMES_TO_IGNORE_DELETION.remove(file.getAbsolutePath())) {
1904                Log.d(Config.LOGTAG, "ignored deletion of " + file.getAbsolutePath());
1905                return;
1906            }
1907        }
1908        final boolean isInternalFile = fileBackend.isInternalFile(file);
1909        final List<String> uuids = databaseBackend.markFileAsDeleted(file, isInternalFile);
1910        Log.d(Config.LOGTAG, "deleted file " + file.getAbsolutePath() + " internal=" + isInternalFile + ", database hits=" + uuids.size());
1911        markUuidsAsDeletedFiles(uuids);
1912    }
1913
1914    private void markUuidsAsDeletedFiles(List<String> uuids) {
1915        boolean deleted = false;
1916        for (Conversation conversation : getConversations()) {
1917            deleted |= conversation.markAsDeleted(uuids);
1918        }
1919        for (final String uuid : uuids) {
1920            evictPreview(uuid);
1921        }
1922        if (deleted) {
1923            updateConversationUi();
1924        }
1925    }
1926
1927    private void markChangedFiles(List<DatabaseBackend.FilePathInfo> infos) {
1928        boolean changed = false;
1929        for (Conversation conversation : getConversations()) {
1930            changed |= conversation.markAsChanged(infos);
1931        }
1932        if (changed) {
1933            updateConversationUi();
1934        }
1935    }
1936
1937    public void populateWithOrderedConversations(final List<Conversation> list) {
1938        populateWithOrderedConversations(list, true, true);
1939    }
1940
1941    public void populateWithOrderedConversations(final List<Conversation> list, final boolean includeNoFileUpload) {
1942        populateWithOrderedConversations(list, includeNoFileUpload, true);
1943    }
1944
1945    public void populateWithOrderedConversations(final List<Conversation> list, final boolean includeNoFileUpload, final boolean sort) {
1946        final List<String> orderedUuids;
1947        if (sort) {
1948            orderedUuids = null;
1949        } else {
1950            orderedUuids = new ArrayList<>();
1951            for (Conversation conversation : list) {
1952                orderedUuids.add(conversation.getUuid());
1953            }
1954        }
1955        list.clear();
1956        if (includeNoFileUpload) {
1957            list.addAll(getConversations());
1958        } else {
1959            for (Conversation conversation : getConversations()) {
1960                if (conversation.getMode() == Conversation.MODE_SINGLE
1961                        || (conversation.getAccount().httpUploadAvailable() && conversation.getMucOptions().participating())) {
1962                    list.add(conversation);
1963                }
1964            }
1965        }
1966        try {
1967            if (orderedUuids != null) {
1968                Collections.sort(list, (a, b) -> {
1969                    final int indexA = orderedUuids.indexOf(a.getUuid());
1970                    final int indexB = orderedUuids.indexOf(b.getUuid());
1971                    if (indexA == -1 || indexB == -1 || indexA == indexB) {
1972                        return a.compareTo(b);
1973                    }
1974                    return indexA - indexB;
1975                });
1976            } else {
1977                Collections.sort(list);
1978            }
1979        } catch (IllegalArgumentException e) {
1980            //ignore
1981        }
1982    }
1983
1984    public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
1985        if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation, callback)) {
1986            return;
1987        } else if (timestamp == 0) {
1988            return;
1989        }
1990        Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
1991        final Runnable runnable = () -> {
1992            final Account account = conversation.getAccount();
1993            List<Message> messages = databaseBackend.getMessages(conversation, 50, timestamp);
1994            if (messages.size() > 0) {
1995                conversation.addAll(0, messages);
1996                callback.onMoreMessagesLoaded(messages.size(), conversation);
1997            } else if (conversation.hasMessagesLeftOnServer()
1998                    && account.isOnlineAndConnected()
1999                    && conversation.getLastClearHistory().getTimestamp() == 0) {
2000                final boolean mamAvailable;
2001                if (conversation.getMode() == Conversation.MODE_SINGLE) {
2002                    mamAvailable = account.getXmppConnection().getFeatures().mam() && !conversation.getContact().isBlocked();
2003                } else {
2004                    mamAvailable = conversation.getMucOptions().mamSupport();
2005                }
2006                if (mamAvailable) {
2007                    MessageArchiveService.Query query = getMessageArchiveService().query(conversation, new MamReference(0), timestamp, false);
2008                    if (query != null) {
2009                        query.setCallback(callback);
2010                        callback.informUser(R.string.fetching_history_from_server);
2011                    } else {
2012                        callback.informUser(R.string.not_fetching_history_retention_period);
2013                    }
2014
2015                }
2016            }
2017        };
2018        mDatabaseReaderExecutor.execute(runnable);
2019    }
2020
2021    public List<Account> getAccounts() {
2022        return this.accounts;
2023    }
2024
2025
2026    /**
2027     * This will find all conferences with the contact as member and also the conference that is the contact (that 'fake' contact is used to store the avatar)
2028     */
2029    public List<Conversation> findAllConferencesWith(Contact contact) {
2030        final ArrayList<Conversation> results = new ArrayList<>();
2031        for (final Conversation c : conversations) {
2032            if (c.getMode() != Conversation.MODE_MULTI) {
2033                continue;
2034            }
2035            final MucOptions mucOptions = c.getMucOptions();
2036            if (c.getJid().asBareJid().equals(contact.getJid().asBareJid()) || (mucOptions != null && mucOptions.isContactInRoom(contact))) {
2037                results.add(c);
2038            }
2039        }
2040        return results;
2041    }
2042
2043    public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
2044        for (final Conversation conversation : haystack) {
2045            if (conversation.getContact() == contact) {
2046                return conversation;
2047            }
2048        }
2049        return null;
2050    }
2051
2052    public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
2053        if (jid == null) {
2054            return null;
2055        }
2056        for (final Conversation conversation : haystack) {
2057            if ((account == null || conversation.getAccount() == account)
2058                    && (conversation.getJid().asBareJid().equals(jid.asBareJid()))) {
2059                return conversation;
2060            }
2061        }
2062        return null;
2063    }
2064
2065    public boolean isConversationsListEmpty(final Conversation ignore) {
2066        synchronized (this.conversations) {
2067            final int size = this.conversations.size();
2068            return size == 0 || size == 1 && this.conversations.get(0) == ignore;
2069        }
2070    }
2071
2072    public boolean isConversationStillOpen(final Conversation conversation) {
2073        synchronized (this.conversations) {
2074            for (Conversation current : this.conversations) {
2075                if (current == conversation) {
2076                    return true;
2077                }
2078            }
2079        }
2080        return false;
2081    }
2082
2083    public Conversation findOrCreateConversation(Account account, Jid jid, boolean muc, final boolean async) {
2084        return this.findOrCreateConversation(account, jid, muc, false, async);
2085    }
2086
2087    public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final boolean async) {
2088        return this.findOrCreateConversation(account, jid, muc, joinAfterCreate, null, async);
2089    }
2090
2091    public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final MessageArchiveService.Query query, final boolean async) {
2092        synchronized (this.conversations) {
2093            Conversation conversation = find(account, jid);
2094            if (conversation != null) {
2095                return conversation;
2096            }
2097            conversation = databaseBackend.findConversation(account, jid);
2098            final boolean loadMessagesFromDb;
2099            if (conversation != null) {
2100                conversation.setStatus(Conversation.STATUS_AVAILABLE);
2101                conversation.setAccount(account);
2102                if (muc) {
2103                    conversation.setMode(Conversation.MODE_MULTI);
2104                    conversation.setContactJid(jid);
2105                } else {
2106                    conversation.setMode(Conversation.MODE_SINGLE);
2107                    conversation.setContactJid(jid.asBareJid());
2108                }
2109                databaseBackend.updateConversation(conversation);
2110                loadMessagesFromDb = conversation.messagesLoaded.compareAndSet(true, false);
2111            } else {
2112                String conversationName;
2113                Contact contact = account.getRoster().getContact(jid);
2114                if (contact != null) {
2115                    conversationName = contact.getDisplayName();
2116                } else {
2117                    conversationName = jid.getLocal();
2118                }
2119                if (muc) {
2120                    conversation = new Conversation(conversationName, account, jid,
2121                            Conversation.MODE_MULTI);
2122                } else {
2123                    conversation = new Conversation(conversationName, account, jid.asBareJid(),
2124                            Conversation.MODE_SINGLE);
2125                }
2126                this.databaseBackend.createConversation(conversation);
2127                loadMessagesFromDb = false;
2128            }
2129            final Conversation c = conversation;
2130            final Runnable runnable = () -> {
2131                if (loadMessagesFromDb) {
2132                    c.addAll(0, databaseBackend.getMessages(c, Config.PAGE_SIZE));
2133                    updateConversationUi();
2134                    c.messagesLoaded.set(true);
2135                }
2136                if (account.getXmppConnection() != null
2137                        && !c.getContact().isBlocked()
2138                        && account.getXmppConnection().getFeatures().mam()
2139                        && !muc) {
2140                    if (query == null) {
2141                        mMessageArchiveService.query(c);
2142                    } else {
2143                        if (query.getConversation() == null) {
2144                            mMessageArchiveService.query(c, query.getStart(), query.isCatchup());
2145                        }
2146                    }
2147                }
2148                if (joinAfterCreate) {
2149                    joinMuc(c);
2150                }
2151            };
2152            if (async) {
2153                mDatabaseReaderExecutor.execute(runnable);
2154            } else {
2155                runnable.run();
2156            }
2157            this.conversations.add(conversation);
2158            updateConversationUi();
2159            return conversation;
2160        }
2161    }
2162
2163    public void archiveConversation(Conversation conversation) {
2164        archiveConversation(conversation, true);
2165    }
2166
2167    private void archiveConversation(Conversation conversation, final boolean maySynchronizeWithBookmarks) {
2168        getNotificationService().clear(conversation);
2169        conversation.setStatus(Conversation.STATUS_ARCHIVED);
2170        conversation.setNextMessage(null);
2171        synchronized (this.conversations) {
2172            getMessageArchiveService().kill(conversation);
2173            if (conversation.getMode() == Conversation.MODE_MULTI) {
2174                if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2175                    final Bookmark bookmark = conversation.getBookmark();
2176                    if (maySynchronizeWithBookmarks && bookmark != null && synchronizeWithBookmarks()) {
2177                        if (conversation.getMucOptions().getError() == MucOptions.Error.DESTROYED) {
2178                            Account account = bookmark.getAccount();
2179                            bookmark.setConversation(null);
2180                            deleteBookmark(account, bookmark);
2181                        } else if (bookmark.autojoin()) {
2182                            bookmark.setAutojoin(false);
2183                            createBookmark(bookmark.getAccount(), bookmark);
2184                        }
2185                    }
2186                }
2187                leaveMuc(conversation);
2188            } else {
2189                if (conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2190                    stopPresenceUpdatesTo(conversation.getContact());
2191                }
2192            }
2193            updateConversation(conversation);
2194            this.conversations.remove(conversation);
2195            updateConversationUi();
2196        }
2197    }
2198
2199    public void stopPresenceUpdatesTo(Contact contact) {
2200        Log.d(Config.LOGTAG, "Canceling presence request from " + contact.getJid().toString());
2201        sendPresencePacket(contact.getAccount(), mPresenceGenerator.stopPresenceUpdatesTo(contact));
2202        contact.resetOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
2203    }
2204
2205    public void createAccount(final Account account) {
2206        account.initAccountServices(this);
2207        databaseBackend.createAccount(account);
2208        this.accounts.add(account);
2209        this.reconnectAccountInBackground(account);
2210        updateAccountUi();
2211        syncEnabledAccountSetting();
2212        toggleForegroundService();
2213    }
2214
2215    private void syncEnabledAccountSetting() {
2216        final boolean hasEnabledAccounts = hasEnabledAccounts();
2217        getPreferences().edit().putBoolean(EventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts).apply();
2218        toggleSetProfilePictureActivity(hasEnabledAccounts);
2219    }
2220
2221    private void toggleSetProfilePictureActivity(final boolean enabled) {
2222        try {
2223            final ComponentName name = new ComponentName(this, ChooseAccountForProfilePictureActivity.class);
2224            final int targetState = enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
2225            getPackageManager().setComponentEnabledSetting(name, targetState, PackageManager.DONT_KILL_APP);
2226        } catch (IllegalStateException e) {
2227            Log.d(Config.LOGTAG, "unable to toggle profile picture actvitiy");
2228        }
2229    }
2230
2231    private void provisionAccount(final String address, final String password) {
2232        final Jid jid = Jid.ofEscaped(address);
2233        final Account account = new Account(jid, password);
2234        account.setOption(Account.OPTION_DISABLED, true);
2235        Log.d(Config.LOGTAG, jid.asBareJid().toEscapedString() + ": provisioning account");
2236        createAccount(account);
2237    }
2238
2239    public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
2240        new Thread(() -> {
2241            try {
2242                final X509Certificate[] chain = KeyChain.getCertificateChain(this, alias);
2243                final X509Certificate cert = chain != null && chain.length > 0 ? chain[0] : null;
2244                if (cert == null) {
2245                    callback.informUser(R.string.unable_to_parse_certificate);
2246                    return;
2247                }
2248                Pair<Jid, String> info = CryptoHelper.extractJidAndName(cert);
2249                if (info == null) {
2250                    callback.informUser(R.string.certificate_does_not_contain_jid);
2251                    return;
2252                }
2253                if (findAccountByJid(info.first) == null) {
2254                    final Account account = new Account(info.first, "");
2255                    account.setPrivateKeyAlias(alias);
2256                    account.setOption(Account.OPTION_DISABLED, true);
2257                    account.setOption(Account.OPTION_FIXED_USERNAME, true);
2258                    account.setDisplayName(info.second);
2259                    createAccount(account);
2260                    callback.onAccountCreated(account);
2261                    if (Config.X509_VERIFICATION) {
2262                        try {
2263                            getMemorizingTrustManager().getNonInteractive(account.getServer()).checkClientTrusted(chain, "RSA");
2264                        } catch (CertificateException e) {
2265                            callback.informUser(R.string.certificate_chain_is_not_trusted);
2266                        }
2267                    }
2268                } else {
2269                    callback.informUser(R.string.account_already_exists);
2270                }
2271            } catch (Exception e) {
2272                callback.informUser(R.string.unable_to_parse_certificate);
2273            }
2274        }).start();
2275
2276    }
2277
2278    public void updateKeyInAccount(final Account account, final String alias) {
2279        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": update key in account " + alias);
2280        try {
2281            X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
2282            Log.d(Config.LOGTAG, account.getJid().asBareJid() + " loaded certificate chain");
2283            Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
2284            if (info == null) {
2285                showErrorToastInUi(R.string.certificate_does_not_contain_jid);
2286                return;
2287            }
2288            if (account.getJid().asBareJid().equals(info.first)) {
2289                account.setPrivateKeyAlias(alias);
2290                account.setDisplayName(info.second);
2291                databaseBackend.updateAccount(account);
2292                if (Config.X509_VERIFICATION) {
2293                    try {
2294                        getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
2295                    } catch (CertificateException e) {
2296                        showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
2297                    }
2298                    account.getAxolotlService().regenerateKeys(true);
2299                }
2300            } else {
2301                showErrorToastInUi(R.string.jid_does_not_match_certificate);
2302            }
2303        } catch (Exception e) {
2304            e.printStackTrace();
2305        }
2306    }
2307
2308    public boolean updateAccount(final Account account) {
2309        if (databaseBackend.updateAccount(account)) {
2310            account.setShowErrorNotification(true);
2311            this.statusListener.onStatusChanged(account);
2312            databaseBackend.updateAccount(account);
2313            reconnectAccountInBackground(account);
2314            updateAccountUi();
2315            getNotificationService().updateErrorNotification();
2316            toggleForegroundService();
2317            syncEnabledAccountSetting();
2318            mChannelDiscoveryService.cleanCache();
2319            return true;
2320        } else {
2321            return false;
2322        }
2323    }
2324
2325    public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
2326        final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
2327        sendIqPacket(account, iq, (a, packet) -> {
2328            if (packet.getType() == IqPacket.TYPE.RESULT) {
2329                a.setPassword(newPassword);
2330                a.setOption(Account.OPTION_MAGIC_CREATE, false);
2331                databaseBackend.updateAccount(a);
2332                callback.onPasswordChangeSucceeded();
2333            } else {
2334                callback.onPasswordChangeFailed();
2335            }
2336        });
2337    }
2338
2339    public void deleteAccount(final Account account) {
2340        final boolean connected = account.getStatus() == Account.State.ONLINE;
2341        synchronized (this.conversations) {
2342            if (connected) {
2343                account.getAxolotlService().deleteOmemoIdentity();
2344            }
2345            for (final Conversation conversation : conversations) {
2346                if (conversation.getAccount() == account) {
2347                    if (conversation.getMode() == Conversation.MODE_MULTI) {
2348                        if (connected) {
2349                            leaveMuc(conversation);
2350                        }
2351                    }
2352                    conversations.remove(conversation);
2353                    mNotificationService.clear(conversation);
2354                }
2355            }
2356            if (account.getXmppConnection() != null) {
2357                new Thread(() -> disconnect(account, !connected)).start();
2358            }
2359            final Runnable runnable = () -> {
2360                if (!databaseBackend.deleteAccount(account)) {
2361                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to delete account");
2362                }
2363            };
2364            mDatabaseWriterExecutor.execute(runnable);
2365            this.accounts.remove(account);
2366            this.mRosterSyncTaskManager.clear(account);
2367            updateAccountUi();
2368            mNotificationService.updateErrorNotification();
2369            syncEnabledAccountSetting();
2370            toggleForegroundService();
2371        }
2372    }
2373
2374    public void setOnConversationListChangedListener(OnConversationUpdate listener) {
2375        final boolean remainingListeners;
2376        synchronized (LISTENER_LOCK) {
2377            remainingListeners = checkListeners();
2378            if (!this.mOnConversationUpdates.add(listener)) {
2379                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as ConversationListChangedListener");
2380            }
2381            this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
2382        }
2383        if (remainingListeners) {
2384            switchToForeground();
2385        }
2386    }
2387
2388    public void removeOnConversationListChangedListener(OnConversationUpdate listener) {
2389        final boolean remainingListeners;
2390        synchronized (LISTENER_LOCK) {
2391            this.mOnConversationUpdates.remove(listener);
2392            this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
2393            remainingListeners = checkListeners();
2394        }
2395        if (remainingListeners) {
2396            switchToBackground();
2397        }
2398    }
2399
2400    public void setOnShowErrorToastListener(OnShowErrorToast listener) {
2401        final boolean remainingListeners;
2402        synchronized (LISTENER_LOCK) {
2403            remainingListeners = checkListeners();
2404            if (!this.mOnShowErrorToasts.add(listener)) {
2405                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnShowErrorToastListener");
2406            }
2407        }
2408        if (remainingListeners) {
2409            switchToForeground();
2410        }
2411    }
2412
2413    public void removeOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
2414        final boolean remainingListeners;
2415        synchronized (LISTENER_LOCK) {
2416            this.mOnShowErrorToasts.remove(onShowErrorToast);
2417            remainingListeners = checkListeners();
2418        }
2419        if (remainingListeners) {
2420            switchToBackground();
2421        }
2422    }
2423
2424    public void setOnAccountListChangedListener(OnAccountUpdate listener) {
2425        final boolean remainingListeners;
2426        synchronized (LISTENER_LOCK) {
2427            remainingListeners = checkListeners();
2428            if (!this.mOnAccountUpdates.add(listener)) {
2429                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnAccountListChangedtListener");
2430            }
2431        }
2432        if (remainingListeners) {
2433            switchToForeground();
2434        }
2435    }
2436
2437    public void removeOnAccountListChangedListener(OnAccountUpdate listener) {
2438        final boolean remainingListeners;
2439        synchronized (LISTENER_LOCK) {
2440            this.mOnAccountUpdates.remove(listener);
2441            remainingListeners = checkListeners();
2442        }
2443        if (remainingListeners) {
2444            switchToBackground();
2445        }
2446    }
2447
2448    public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
2449        final boolean remainingListeners;
2450        synchronized (LISTENER_LOCK) {
2451            remainingListeners = checkListeners();
2452            if (!this.mOnCaptchaRequested.add(listener)) {
2453                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnCaptchaRequestListener");
2454            }
2455        }
2456        if (remainingListeners) {
2457            switchToForeground();
2458        }
2459    }
2460
2461    public void removeOnCaptchaRequestedListener(OnCaptchaRequested listener) {
2462        final boolean remainingListeners;
2463        synchronized (LISTENER_LOCK) {
2464            this.mOnCaptchaRequested.remove(listener);
2465            remainingListeners = checkListeners();
2466        }
2467        if (remainingListeners) {
2468            switchToBackground();
2469        }
2470    }
2471
2472    public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
2473        final boolean remainingListeners;
2474        synchronized (LISTENER_LOCK) {
2475            remainingListeners = checkListeners();
2476            if (!this.mOnRosterUpdates.add(listener)) {
2477                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnRosterUpdateListener");
2478            }
2479        }
2480        if (remainingListeners) {
2481            switchToForeground();
2482        }
2483    }
2484
2485    public void removeOnRosterUpdateListener(final OnRosterUpdate listener) {
2486        final boolean remainingListeners;
2487        synchronized (LISTENER_LOCK) {
2488            this.mOnRosterUpdates.remove(listener);
2489            remainingListeners = checkListeners();
2490        }
2491        if (remainingListeners) {
2492            switchToBackground();
2493        }
2494    }
2495
2496    public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2497        final boolean remainingListeners;
2498        synchronized (LISTENER_LOCK) {
2499            remainingListeners = checkListeners();
2500            if (!this.mOnUpdateBlocklist.add(listener)) {
2501                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnUpdateBlocklistListener");
2502            }
2503        }
2504        if (remainingListeners) {
2505            switchToForeground();
2506        }
2507    }
2508
2509    public void removeOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2510        final boolean remainingListeners;
2511        synchronized (LISTENER_LOCK) {
2512            this.mOnUpdateBlocklist.remove(listener);
2513            remainingListeners = checkListeners();
2514        }
2515        if (remainingListeners) {
2516            switchToBackground();
2517        }
2518    }
2519
2520    public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
2521        final boolean remainingListeners;
2522        synchronized (LISTENER_LOCK) {
2523            remainingListeners = checkListeners();
2524            if (!this.mOnKeyStatusUpdated.add(listener)) {
2525                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnKeyStatusUpdateListener");
2526            }
2527        }
2528        if (remainingListeners) {
2529            switchToForeground();
2530        }
2531    }
2532
2533    public void removeOnNewKeysAvailableListener(final OnKeyStatusUpdated listener) {
2534        final boolean remainingListeners;
2535        synchronized (LISTENER_LOCK) {
2536            this.mOnKeyStatusUpdated.remove(listener);
2537            remainingListeners = checkListeners();
2538        }
2539        if (remainingListeners) {
2540            switchToBackground();
2541        }
2542    }
2543
2544    public void setOnRtpConnectionUpdateListener(final OnJingleRtpConnectionUpdate listener) {
2545        final boolean remainingListeners;
2546        synchronized (LISTENER_LOCK) {
2547            remainingListeners = checkListeners();
2548            if (!this.onJingleRtpConnectionUpdate.add(listener)) {
2549                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnJingleRtpConnectionUpdate");
2550            }
2551        }
2552        if (remainingListeners) {
2553            switchToForeground();
2554        }
2555    }
2556
2557    public void removeRtpConnectionUpdateListener(final OnJingleRtpConnectionUpdate listener) {
2558        final boolean remainingListeners;
2559        synchronized (LISTENER_LOCK) {
2560            this.onJingleRtpConnectionUpdate.remove(listener);
2561            remainingListeners = checkListeners();
2562        }
2563        if (remainingListeners) {
2564            switchToBackground();
2565        }
2566    }
2567
2568    public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
2569        final boolean remainingListeners;
2570        synchronized (LISTENER_LOCK) {
2571            remainingListeners = checkListeners();
2572            if (!this.mOnMucRosterUpdate.add(listener)) {
2573                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnMucRosterListener");
2574            }
2575        }
2576        if (remainingListeners) {
2577            switchToForeground();
2578        }
2579    }
2580
2581    public void removeOnMucRosterUpdateListener(final OnMucRosterUpdate listener) {
2582        final boolean remainingListeners;
2583        synchronized (LISTENER_LOCK) {
2584            this.mOnMucRosterUpdate.remove(listener);
2585            remainingListeners = checkListeners();
2586        }
2587        if (remainingListeners) {
2588            switchToBackground();
2589        }
2590    }
2591
2592    public boolean checkListeners() {
2593        return (this.mOnAccountUpdates.size() == 0
2594                && this.mOnConversationUpdates.size() == 0
2595                && this.mOnRosterUpdates.size() == 0
2596                && this.mOnCaptchaRequested.size() == 0
2597                && this.mOnMucRosterUpdate.size() == 0
2598                && this.mOnUpdateBlocklist.size() == 0
2599                && this.mOnShowErrorToasts.size() == 0
2600                && this.onJingleRtpConnectionUpdate.size() == 0
2601                && this.mOnKeyStatusUpdated.size() == 0);
2602    }
2603
2604    private void switchToForeground() {
2605        final boolean broadcastLastActivity = broadcastLastActivity();
2606        for (Conversation conversation : getConversations()) {
2607            if (conversation.getMode() == Conversation.MODE_MULTI) {
2608                conversation.getMucOptions().resetChatState();
2609            } else {
2610                conversation.setIncomingChatState(Config.DEFAULT_CHAT_STATE);
2611            }
2612        }
2613        for (Account account : getAccounts()) {
2614            if (account.getStatus() == Account.State.ONLINE) {
2615                account.deactivateGracePeriod();
2616                final XmppConnection connection = account.getXmppConnection();
2617                if (connection != null) {
2618                    if (connection.getFeatures().csi()) {
2619                        connection.sendActive();
2620                    }
2621                    if (broadcastLastActivity) {
2622                        sendPresence(account, false); //send new presence but don't include idle because we are not
2623                    }
2624                }
2625            }
2626        }
2627        Log.d(Config.LOGTAG, "app switched into foreground");
2628    }
2629
2630    private void switchToBackground() {
2631        final boolean broadcastLastActivity = broadcastLastActivity();
2632        if (broadcastLastActivity) {
2633            mLastActivity = System.currentTimeMillis();
2634            final SharedPreferences.Editor editor = getPreferences().edit();
2635            editor.putLong(SETTING_LAST_ACTIVITY_TS, mLastActivity);
2636            editor.apply();
2637        }
2638        for (Account account : getAccounts()) {
2639            if (account.getStatus() == Account.State.ONLINE) {
2640                XmppConnection connection = account.getXmppConnection();
2641                if (connection != null) {
2642                    if (broadcastLastActivity) {
2643                        sendPresence(account, true);
2644                    }
2645                    if (connection.getFeatures().csi()) {
2646                        connection.sendInactive();
2647                    }
2648                }
2649            }
2650        }
2651        this.mNotificationService.setIsInForeground(false);
2652        Log.d(Config.LOGTAG, "app switched into background");
2653    }
2654
2655    private void connectMultiModeConversations(Account account) {
2656        List<Conversation> conversations = getConversations();
2657        for (Conversation conversation : conversations) {
2658            if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
2659                joinMuc(conversation);
2660            }
2661        }
2662    }
2663
2664    public void mucSelfPingAndRejoin(final Conversation conversation) {
2665        final Account account = conversation.getAccount();
2666        synchronized (account.inProgressConferenceJoins) {
2667            if (account.inProgressConferenceJoins.contains(conversation)) {
2668                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": canceling muc self ping because join is already under way");
2669                return;
2670            }
2671        }
2672        synchronized (account.inProgressConferencePings) {
2673            if (!account.inProgressConferencePings.add(conversation)) {
2674                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": canceling muc self ping because ping is already under way");
2675                return;
2676            }
2677        }
2678        final Jid self = conversation.getMucOptions().getSelf().getFullJid();
2679        final IqPacket ping = new IqPacket(IqPacket.TYPE.GET);
2680        ping.setTo(self);
2681        ping.addChild("ping", Namespace.PING);
2682        sendIqPacket(conversation.getAccount(), ping, (a, response) -> {
2683            if (response.getType() == IqPacket.TYPE.ERROR) {
2684                Element error = response.findChild("error");
2685                if (error == null || error.hasChild("service-unavailable") || error.hasChild("feature-not-implemented") || error.hasChild("item-not-found")) {
2686                    Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " came back as ignorable error");
2687                } else {
2688                    Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " failed. attempting rejoin");
2689                    joinMuc(conversation);
2690                }
2691            } else if (response.getType() == IqPacket.TYPE.RESULT) {
2692                Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " came back fine");
2693            }
2694            synchronized (account.inProgressConferencePings) {
2695                account.inProgressConferencePings.remove(conversation);
2696            }
2697        });
2698    }
2699
2700    public void joinMuc(Conversation conversation) {
2701        joinMuc(conversation, null, false);
2702    }
2703
2704    public void joinMuc(Conversation conversation, boolean followedInvite) {
2705        joinMuc(conversation, null, followedInvite);
2706    }
2707
2708    private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined) {
2709        joinMuc(conversation, onConferenceJoined, false);
2710    }
2711
2712    private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined, final boolean followedInvite) {
2713        final Account account = conversation.getAccount();
2714        synchronized (account.pendingConferenceJoins) {
2715            account.pendingConferenceJoins.remove(conversation);
2716        }
2717        synchronized (account.pendingConferenceLeaves) {
2718            account.pendingConferenceLeaves.remove(conversation);
2719        }
2720        if (account.getStatus() == Account.State.ONLINE) {
2721            synchronized (account.inProgressConferenceJoins) {
2722                account.inProgressConferenceJoins.add(conversation);
2723            }
2724            if (Config.MUC_LEAVE_BEFORE_JOIN) {
2725                sendPresencePacket(account, mPresenceGenerator.leave(conversation.getMucOptions()));
2726            }
2727            conversation.resetMucOptions();
2728            if (onConferenceJoined != null) {
2729                conversation.getMucOptions().flagNoAutoPushConfiguration();
2730            }
2731            conversation.setHasMessagesLeftOnServer(false);
2732            fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
2733
2734                private void join(Conversation conversation) {
2735                    Account account = conversation.getAccount();
2736                    final MucOptions mucOptions = conversation.getMucOptions();
2737
2738                    if (mucOptions.nonanonymous() && !mucOptions.membersOnly() && !conversation.getBooleanAttribute("accept_non_anonymous", false)) {
2739                        synchronized (account.inProgressConferenceJoins) {
2740                            account.inProgressConferenceJoins.remove(conversation);
2741                        }
2742                        mucOptions.setError(MucOptions.Error.NON_ANONYMOUS);
2743                        updateConversationUi();
2744                        if (onConferenceJoined != null) {
2745                            onConferenceJoined.onConferenceJoined(conversation);
2746                        }
2747                        return;
2748                    }
2749
2750                    final Jid joinJid = mucOptions.getSelf().getFullJid();
2751                    Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": joining conversation " + joinJid.toString());
2752                    PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous() || onConferenceJoined != null);
2753                    packet.setTo(joinJid);
2754                    Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
2755                    if (conversation.getMucOptions().getPassword() != null) {
2756                        x.addChild("password").setContent(mucOptions.getPassword());
2757                    }
2758
2759                    if (mucOptions.mamSupport()) {
2760                        // Use MAM instead of the limited muc history to get history
2761                        x.addChild("history").setAttribute("maxchars", "0");
2762                    } else {
2763                        // Fallback to muc history
2764                        x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted().getTimestamp()));
2765                    }
2766                    sendPresencePacket(account, packet);
2767                    if (onConferenceJoined != null) {
2768                        onConferenceJoined.onConferenceJoined(conversation);
2769                    }
2770                    if (!joinJid.equals(conversation.getJid())) {
2771                        conversation.setContactJid(joinJid);
2772                        databaseBackend.updateConversation(conversation);
2773                    }
2774
2775                    if (mucOptions.mamSupport()) {
2776                        getMessageArchiveService().catchupMUC(conversation);
2777                    }
2778                    if (mucOptions.isPrivateAndNonAnonymous()) {
2779                        fetchConferenceMembers(conversation);
2780
2781                        if (followedInvite) {
2782                            final Bookmark bookmark = conversation.getBookmark();
2783                            if (bookmark != null) {
2784                                if (!bookmark.autojoin()) {
2785                                    bookmark.setAutojoin(true);
2786                                    createBookmark(account, bookmark);
2787                                }
2788                            } else {
2789                                saveConversationAsBookmark(conversation, null);
2790                            }
2791                        }
2792                    }
2793                    synchronized (account.inProgressConferenceJoins) {
2794                        account.inProgressConferenceJoins.remove(conversation);
2795                        sendUnsentMessages(conversation);
2796                    }
2797                }
2798
2799                @Override
2800                public void onConferenceConfigurationFetched(Conversation conversation) {
2801                    if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
2802                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": conversation (" + conversation.getJid() + ") got archived before IQ result");
2803                        return;
2804                    }
2805                    join(conversation);
2806                }
2807
2808                @Override
2809                public void onFetchFailed(final Conversation conversation, Element error) {
2810                    if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
2811                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": conversation (" + conversation.getJid() + ") got archived before IQ result");
2812
2813                        return;
2814                    }
2815                    if (error != null && "remote-server-not-found".equals(error.getName())) {
2816                        synchronized (account.inProgressConferenceJoins) {
2817                            account.inProgressConferenceJoins.remove(conversation);
2818                        }
2819                        conversation.getMucOptions().setError(MucOptions.Error.SERVER_NOT_FOUND);
2820                        updateConversationUi();
2821                    } else {
2822                        join(conversation);
2823                        fetchConferenceConfiguration(conversation);
2824                    }
2825                }
2826            });
2827            updateConversationUi();
2828        } else {
2829            synchronized (account.pendingConferenceJoins) {
2830                account.pendingConferenceJoins.add(conversation);
2831            }
2832            conversation.resetMucOptions();
2833            conversation.setHasMessagesLeftOnServer(false);
2834            updateConversationUi();
2835        }
2836    }
2837
2838    private void fetchConferenceMembers(final Conversation conversation) {
2839        final Account account = conversation.getAccount();
2840        final AxolotlService axolotlService = account.getAxolotlService();
2841        final String[] affiliations = {"member", "admin", "owner"};
2842        OnIqPacketReceived callback = new OnIqPacketReceived() {
2843
2844            private int i = 0;
2845            private boolean success = true;
2846
2847            @Override
2848            public void onIqPacketReceived(Account account, IqPacket packet) {
2849                final boolean omemoEnabled = conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL;
2850                Element query = packet.query("http://jabber.org/protocol/muc#admin");
2851                if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2852                    for (Element child : query.getChildren()) {
2853                        if ("item".equals(child.getName())) {
2854                            MucOptions.User user = AbstractParser.parseItem(conversation, child);
2855                            if (!user.realJidMatchesAccount()) {
2856                                boolean isNew = conversation.getMucOptions().updateUser(user);
2857                                Contact contact = user.getContact();
2858                                if (omemoEnabled
2859                                        && isNew
2860                                        && user.getRealJid() != null
2861                                        && (contact == null || !contact.mutualPresenceSubscription())
2862                                        && axolotlService.hasEmptyDeviceList(user.getRealJid())) {
2863                                    axolotlService.fetchDeviceIds(user.getRealJid());
2864                                }
2865                            }
2866                        }
2867                    }
2868                } else {
2869                    success = false;
2870                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not request affiliation " + affiliations[i] + " in " + conversation.getJid().asBareJid());
2871                }
2872                ++i;
2873                if (i >= affiliations.length) {
2874                    List<Jid> members = conversation.getMucOptions().getMembers(true);
2875                    if (success) {
2876                        List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
2877                        boolean changed = false;
2878                        for (ListIterator<Jid> iterator = cryptoTargets.listIterator(); iterator.hasNext(); ) {
2879                            Jid jid = iterator.next();
2880                            if (!members.contains(jid) && !members.contains(jid.getDomain())) {
2881                                iterator.remove();
2882                                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
2883                                changed = true;
2884                            }
2885                        }
2886                        if (changed) {
2887                            conversation.setAcceptedCryptoTargets(cryptoTargets);
2888                            updateConversation(conversation);
2889                        }
2890                    }
2891                    getAvatarService().clear(conversation);
2892                    updateMucRosterUi();
2893                    updateConversationUi();
2894                }
2895            }
2896        };
2897        for (String affiliation : affiliations) {
2898            sendIqPacket(account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
2899        }
2900        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching members for " + conversation.getName());
2901    }
2902
2903    public void providePasswordForMuc(Conversation conversation, String password) {
2904        if (conversation.getMode() == Conversation.MODE_MULTI) {
2905            conversation.getMucOptions().setPassword(password);
2906            if (conversation.getBookmark() != null) {
2907                final Bookmark bookmark = conversation.getBookmark();
2908                if (synchronizeWithBookmarks()) {
2909                    bookmark.setAutojoin(true);
2910                }
2911                createBookmark(conversation.getAccount(), bookmark);
2912            }
2913            updateConversation(conversation);
2914            joinMuc(conversation);
2915        }
2916    }
2917
2918    private boolean hasEnabledAccounts() {
2919        if (this.accounts == null) {
2920            return false;
2921        }
2922        for (Account account : this.accounts) {
2923            if (account.isEnabled()) {
2924                return true;
2925            }
2926        }
2927        return false;
2928    }
2929
2930
2931    public void getAttachments(final Conversation conversation, int limit, final OnMediaLoaded onMediaLoaded) {
2932        getAttachments(conversation.getAccount(), conversation.getJid().asBareJid(), limit, onMediaLoaded);
2933    }
2934
2935    public void getAttachments(final Account account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
2936        getAttachments(account.getUuid(), jid.asBareJid(), limit, onMediaLoaded);
2937    }
2938
2939
2940    public void getAttachments(final String account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
2941        new Thread(() -> onMediaLoaded.onMediaLoaded(fileBackend.convertToAttachments(databaseBackend.getRelativeFilePaths(account, jid, limit)))).start();
2942    }
2943
2944    public void persistSelfNick(MucOptions.User self) {
2945        final Conversation conversation = self.getConversation();
2946        final boolean tookProposedNickFromBookmark = conversation.getMucOptions().isTookProposedNickFromBookmark();
2947        Jid full = self.getFullJid();
2948        if (!full.equals(conversation.getJid())) {
2949            Log.d(Config.LOGTAG, "nick changed. updating");
2950            conversation.setContactJid(full);
2951            databaseBackend.updateConversation(conversation);
2952        }
2953
2954        final Bookmark bookmark = conversation.getBookmark();
2955        final String bookmarkedNick = bookmark == null ? null : bookmark.getNick();
2956        if (bookmark != null && (tookProposedNickFromBookmark || TextUtils.isEmpty(bookmarkedNick)) && !full.getResource().equals(bookmarkedNick)) {
2957            final Account account = conversation.getAccount();
2958            final String defaultNick = MucOptions.defaultNick(account);
2959            if (TextUtils.isEmpty(bookmarkedNick) && full.getResource().equals(defaultNick)) {
2960                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": do not overwrite empty bookmark nick with default nick for " + conversation.getJid().asBareJid());
2961                return;
2962            }
2963            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": persist nick '" + full.getResource() + "' into bookmark for " + conversation.getJid().asBareJid());
2964            bookmark.setNick(full.getResource());
2965            createBookmark(bookmark.getAccount(), bookmark);
2966        }
2967    }
2968
2969    public boolean renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
2970        final MucOptions options = conversation.getMucOptions();
2971        final Jid joinJid = options.createJoinJid(nick);
2972        if (joinJid == null) {
2973            return false;
2974        }
2975        if (options.online()) {
2976            Account account = conversation.getAccount();
2977            options.setOnRenameListener(new OnRenameListener() {
2978
2979                @Override
2980                public void onSuccess() {
2981                    callback.success(conversation);
2982                }
2983
2984                @Override
2985                public void onFailure() {
2986                    callback.error(R.string.nick_in_use, conversation);
2987                }
2988            });
2989
2990            final PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, options.nonanonymous());
2991            packet.setTo(joinJid);
2992            sendPresencePacket(account, packet);
2993        } else {
2994            conversation.setContactJid(joinJid);
2995            databaseBackend.updateConversation(conversation);
2996            if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2997                Bookmark bookmark = conversation.getBookmark();
2998                if (bookmark != null) {
2999                    bookmark.setNick(nick);
3000                    createBookmark(bookmark.getAccount(), bookmark);
3001                }
3002                joinMuc(conversation);
3003            }
3004        }
3005        return true;
3006    }
3007
3008    public void leaveMuc(Conversation conversation) {
3009        leaveMuc(conversation, false);
3010    }
3011
3012    private void leaveMuc(Conversation conversation, boolean now) {
3013        final Account account = conversation.getAccount();
3014        synchronized (account.pendingConferenceJoins) {
3015            account.pendingConferenceJoins.remove(conversation);
3016        }
3017        synchronized (account.pendingConferenceLeaves) {
3018            account.pendingConferenceLeaves.remove(conversation);
3019        }
3020        if (account.getStatus() == Account.State.ONLINE || now) {
3021            sendPresencePacket(conversation.getAccount(), mPresenceGenerator.leave(conversation.getMucOptions()));
3022            conversation.getMucOptions().setOffline();
3023            Bookmark bookmark = conversation.getBookmark();
3024            if (bookmark != null) {
3025                bookmark.setConversation(null);
3026            }
3027            Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": leaving muc " + conversation.getJid());
3028        } else {
3029            synchronized (account.pendingConferenceLeaves) {
3030                account.pendingConferenceLeaves.add(conversation);
3031            }
3032        }
3033    }
3034
3035    public String findConferenceServer(final Account account) {
3036        String server;
3037        if (account.getXmppConnection() != null) {
3038            server = account.getXmppConnection().getMucServer();
3039            if (server != null) {
3040                return server;
3041            }
3042        }
3043        for (Account other : getAccounts()) {
3044            if (other != account && other.getXmppConnection() != null) {
3045                server = other.getXmppConnection().getMucServer();
3046                if (server != null) {
3047                    return server;
3048                }
3049            }
3050        }
3051        return null;
3052    }
3053
3054
3055    public void createPublicChannel(final Account account, final String name, final Jid address, final UiCallback<Conversation> callback) {
3056        joinMuc(findOrCreateConversation(account, address, true, false, true), conversation -> {
3057            final Bundle configuration = IqGenerator.defaultChannelConfiguration();
3058            if (!TextUtils.isEmpty(name)) {
3059                configuration.putString("muc#roomconfig_roomname", name);
3060            }
3061            pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
3062                @Override
3063                public void onPushSucceeded() {
3064                    saveConversationAsBookmark(conversation, name);
3065                    callback.success(conversation);
3066                }
3067
3068                @Override
3069                public void onPushFailed() {
3070                    if (conversation.getMucOptions().getSelf().getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
3071                        callback.error(R.string.unable_to_set_channel_configuration, conversation);
3072                    } else {
3073                        callback.error(R.string.joined_an_existing_channel, conversation);
3074                    }
3075                }
3076            });
3077        });
3078    }
3079
3080    public boolean createAdhocConference(final Account account,
3081                                         final String name,
3082                                         final Iterable<Jid> jids,
3083                                         final UiCallback<Conversation> callback) {
3084        Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": creating adhoc conference with " + jids.toString());
3085        if (account.getStatus() == Account.State.ONLINE) {
3086            try {
3087                String server = findConferenceServer(account);
3088                if (server == null) {
3089                    if (callback != null) {
3090                        callback.error(R.string.no_conference_server_found, null);
3091                    }
3092                    return false;
3093                }
3094                final Jid jid = Jid.of(CryptoHelper.pronounceable(getRNG()), server, null);
3095                final Conversation conversation = findOrCreateConversation(account, jid, true, false, true);
3096                joinMuc(conversation, new OnConferenceJoined() {
3097                    @Override
3098                    public void onConferenceJoined(final Conversation conversation) {
3099                        final Bundle configuration = IqGenerator.defaultGroupChatConfiguration();
3100                        if (!TextUtils.isEmpty(name)) {
3101                            configuration.putString("muc#roomconfig_roomname", name);
3102                        }
3103                        pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
3104                            @Override
3105                            public void onPushSucceeded() {
3106                                for (Jid invite : jids) {
3107                                    invite(conversation, invite);
3108                                }
3109                                for (String resource : account.getSelfContact().getPresences().toResourceArray()) {
3110                                    Jid other = account.getJid().withResource(resource);
3111                                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending direct invite to " + other);
3112                                    directInvite(conversation, other);
3113                                }
3114                                saveConversationAsBookmark(conversation, name);
3115                                if (callback != null) {
3116                                    callback.success(conversation);
3117                                }
3118                            }
3119
3120                            @Override
3121                            public void onPushFailed() {
3122                                archiveConversation(conversation);
3123                                if (callback != null) {
3124                                    callback.error(R.string.conference_creation_failed, conversation);
3125                                }
3126                            }
3127                        });
3128                    }
3129                });
3130                return true;
3131            } catch (IllegalArgumentException e) {
3132                if (callback != null) {
3133                    callback.error(R.string.conference_creation_failed, null);
3134                }
3135                return false;
3136            }
3137        } else {
3138            if (callback != null) {
3139                callback.error(R.string.not_connected_try_again, null);
3140            }
3141            return false;
3142        }
3143    }
3144
3145    public void fetchConferenceConfiguration(final Conversation conversation) {
3146        fetchConferenceConfiguration(conversation, null);
3147    }
3148
3149    public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
3150        IqPacket request = mIqGenerator.queryDiscoInfo(conversation.getJid().asBareJid());
3151        sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3152            @Override
3153            public void onIqPacketReceived(Account account, IqPacket packet) {
3154                if (packet.getType() == IqPacket.TYPE.RESULT) {
3155                    final MucOptions mucOptions = conversation.getMucOptions();
3156                    final Bookmark bookmark = conversation.getBookmark();
3157                    final boolean sameBefore = StringUtils.equals(bookmark == null ? null : bookmark.getBookmarkName(), mucOptions.getName());
3158
3159                    if (mucOptions.updateConfiguration(new ServiceDiscoveryResult(packet))) {
3160                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": muc configuration changed for " + conversation.getJid().asBareJid());
3161                        updateConversation(conversation);
3162                    }
3163
3164                    if (bookmark != null && (sameBefore || bookmark.getBookmarkName() == null)) {
3165                        if (bookmark.setBookmarkName(StringUtils.nullOnEmpty(mucOptions.getName()))) {
3166                            createBookmark(account, bookmark);
3167                        }
3168                    }
3169
3170
3171                    if (callback != null) {
3172                        callback.onConferenceConfigurationFetched(conversation);
3173                    }
3174
3175
3176                    updateConversationUi();
3177                } else if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
3178                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received timeout waiting for conference configuration fetch");
3179                } else {
3180                    if (callback != null) {
3181                        callback.onFetchFailed(conversation, packet.getError());
3182                    }
3183                }
3184            }
3185        });
3186    }
3187
3188    public void pushNodeConfiguration(Account account, final String node, final Bundle options, final OnConfigurationPushed callback) {
3189        pushNodeConfiguration(account, account.getJid().asBareJid(), node, options, callback);
3190    }
3191
3192    public void pushNodeConfiguration(Account account, final Jid jid, final String node, final Bundle options, final OnConfigurationPushed callback) {
3193        Log.d(Config.LOGTAG, "pushing node configuration");
3194        sendIqPacket(account, mIqGenerator.requestPubsubConfiguration(jid, node), new OnIqPacketReceived() {
3195            @Override
3196            public void onIqPacketReceived(Account account, IqPacket packet) {
3197                if (packet.getType() == IqPacket.TYPE.RESULT) {
3198                    Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub#owner");
3199                    Element configuration = pubsub == null ? null : pubsub.findChild("configure");
3200                    Element x = configuration == null ? null : configuration.findChild("x", Namespace.DATA);
3201                    if (x != null) {
3202                        Data data = Data.parse(x);
3203                        data.submit(options);
3204                        sendIqPacket(account, mIqGenerator.publishPubsubConfiguration(jid, node, data), new OnIqPacketReceived() {
3205                            @Override
3206                            public void onIqPacketReceived(Account account, IqPacket packet) {
3207                                if (packet.getType() == IqPacket.TYPE.RESULT && callback != null) {
3208                                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": successfully changed node configuration for node " + node);
3209                                    callback.onPushSucceeded();
3210                                } else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
3211                                    callback.onPushFailed();
3212                                }
3213                            }
3214                        });
3215                    } else if (callback != null) {
3216                        callback.onPushFailed();
3217                    }
3218                } else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
3219                    callback.onPushFailed();
3220                }
3221            }
3222        });
3223    }
3224
3225    public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConfigurationPushed callback) {
3226        if (options.getString("muc#roomconfig_whois", "moderators").equals("anyone")) {
3227            conversation.setAttribute("accept_non_anonymous", true);
3228            updateConversation(conversation);
3229        }
3230        if (options.containsKey("muc#roomconfig_moderatedroom")) {
3231            final boolean moderated = "1".equals(options.getString("muc#roomconfig_moderatedroom"));
3232            options.putString("members_by_default", moderated ? "0" : "1");
3233        }
3234        final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3235        request.setTo(conversation.getJid().asBareJid());
3236        request.query("http://jabber.org/protocol/muc#owner");
3237        sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3238            @Override
3239            public void onIqPacketReceived(Account account, IqPacket packet) {
3240                if (packet.getType() == IqPacket.TYPE.RESULT) {
3241                    final Data data = Data.parse(packet.query().findChild("x", Namespace.DATA));
3242                    data.submit(options);
3243                    final IqPacket set = new IqPacket(IqPacket.TYPE.SET);
3244                    set.setTo(conversation.getJid().asBareJid());
3245                    set.query("http://jabber.org/protocol/muc#owner").addChild(data);
3246                    sendIqPacket(account, set, new OnIqPacketReceived() {
3247                        @Override
3248                        public void onIqPacketReceived(Account account, IqPacket packet) {
3249                            if (callback != null) {
3250                                if (packet.getType() == IqPacket.TYPE.RESULT) {
3251                                    callback.onPushSucceeded();
3252                                } else {
3253                                    callback.onPushFailed();
3254                                }
3255                            }
3256                        }
3257                    });
3258                } else {
3259                    if (callback != null) {
3260                        callback.onPushFailed();
3261                    }
3262                }
3263            }
3264        });
3265    }
3266
3267    public void pushSubjectToConference(final Conversation conference, final String subject) {
3268        MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, StringUtils.nullOnEmpty(subject));
3269        this.sendMessagePacket(conference.getAccount(), packet);
3270    }
3271
3272    public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
3273        final Jid jid = user.asBareJid();
3274        IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
3275        sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
3276            @Override
3277            public void onIqPacketReceived(Account account, IqPacket packet) {
3278                if (packet.getType() == IqPacket.TYPE.RESULT) {
3279                    conference.getMucOptions().changeAffiliation(jid, affiliation);
3280                    getAvatarService().clear(conference);
3281                    callback.onAffiliationChangedSuccessful(jid);
3282                } else {
3283                    callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
3284                }
3285            }
3286        });
3287    }
3288
3289    public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
3290        List<Jid> jids = new ArrayList<>();
3291        for (MucOptions.User user : conference.getMucOptions().getUsers()) {
3292            if (user.getAffiliation() == before && user.getRealJid() != null) {
3293                jids.add(user.getRealJid());
3294            }
3295        }
3296        IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
3297        sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
3298    }
3299
3300    public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role) {
3301        IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
3302        Log.d(Config.LOGTAG, request.toString());
3303        sendIqPacket(conference.getAccount(), request, (account, packet) -> {
3304            if (packet.getType() != IqPacket.TYPE.RESULT) {
3305                Log.d(Config.LOGTAG, account.getJid().asBareJid() + " unable to change role of " + nick);
3306            }
3307        });
3308    }
3309
3310    public void destroyRoom(final Conversation conversation, final OnRoomDestroy callback) {
3311        IqPacket request = new IqPacket(IqPacket.TYPE.SET);
3312        request.setTo(conversation.getJid().asBareJid());
3313        request.query("http://jabber.org/protocol/muc#owner").addChild("destroy");
3314        sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3315            @Override
3316            public void onIqPacketReceived(Account account, IqPacket packet) {
3317                if (packet.getType() == IqPacket.TYPE.RESULT) {
3318                    if (callback != null) {
3319                        callback.onRoomDestroySucceeded();
3320                    }
3321                } else if (packet.getType() == IqPacket.TYPE.ERROR) {
3322                    if (callback != null) {
3323                        callback.onRoomDestroyFailed();
3324                    }
3325                }
3326            }
3327        });
3328    }
3329
3330    private void disconnect(Account account, boolean force) {
3331        if ((account.getStatus() == Account.State.ONLINE)
3332                || (account.getStatus() == Account.State.DISABLED)) {
3333            final XmppConnection connection = account.getXmppConnection();
3334            if (!force) {
3335                List<Conversation> conversations = getConversations();
3336                for (Conversation conversation : conversations) {
3337                    if (conversation.getAccount() == account) {
3338                        if (conversation.getMode() == Conversation.MODE_MULTI) {
3339                            leaveMuc(conversation, true);
3340                        }
3341                    }
3342                }
3343                sendOfflinePresence(account);
3344            }
3345            connection.disconnect(force);
3346        }
3347    }
3348
3349    @Override
3350    public IBinder onBind(Intent intent) {
3351        return mBinder;
3352    }
3353
3354    public void updateMessage(Message message) {
3355        updateMessage(message, true);
3356    }
3357
3358    public void updateMessage(Message message, boolean includeBody) {
3359        databaseBackend.updateMessage(message, includeBody);
3360        updateConversationUi();
3361    }
3362
3363    public void createMessageAsync(final Message message) {
3364        mDatabaseWriterExecutor.execute(() -> databaseBackend.createMessage(message));
3365    }
3366
3367    public void updateMessage(Message message, String uuid) {
3368        if (!databaseBackend.updateMessage(message, uuid)) {
3369            Log.e(Config.LOGTAG, "error updated message in DB after edit");
3370        }
3371        updateConversationUi();
3372    }
3373
3374    protected void syncDirtyContacts(Account account) {
3375        for (Contact contact : account.getRoster().getContacts()) {
3376            if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
3377                pushContactToServer(contact);
3378            }
3379            if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
3380                deleteContactOnServer(contact);
3381            }
3382        }
3383    }
3384
3385    public void createContact(Contact contact, boolean autoGrant) {
3386        if (autoGrant) {
3387            contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
3388            contact.setOption(Contact.Options.ASKING);
3389        }
3390        pushContactToServer(contact);
3391    }
3392
3393    public void pushContactToServer(final Contact contact) {
3394        contact.resetOption(Contact.Options.DIRTY_DELETE);
3395        contact.setOption(Contact.Options.DIRTY_PUSH);
3396        final Account account = contact.getAccount();
3397        if (account.getStatus() == Account.State.ONLINE) {
3398            final boolean ask = contact.getOption(Contact.Options.ASKING);
3399            final boolean sendUpdates = contact
3400                    .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
3401                    && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
3402            final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
3403            iq.query(Namespace.ROSTER).addChild(contact.asElement());
3404            account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
3405            if (sendUpdates) {
3406                sendPresencePacket(account, mPresenceGenerator.sendPresenceUpdatesTo(contact));
3407            }
3408            if (ask) {
3409                sendPresencePacket(account, mPresenceGenerator.requestPresenceUpdatesFrom(contact));
3410            }
3411        } else {
3412            syncRoster(contact.getAccount());
3413        }
3414    }
3415
3416    public void publishMucAvatar(final Conversation conversation, final Uri image, final OnAvatarPublication callback) {
3417        new Thread(() -> {
3418            final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
3419            final int size = Config.AVATAR_SIZE;
3420            final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
3421            if (avatar != null) {
3422                if (!getFileBackend().save(avatar)) {
3423                    callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
3424                    return;
3425                }
3426                avatar.owner = conversation.getJid().asBareJid();
3427                publishMucAvatar(conversation, avatar, callback);
3428            } else {
3429                callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
3430            }
3431        }).start();
3432    }
3433
3434    public void publishAvatar(final Account account, final Uri image, final OnAvatarPublication callback) {
3435        new Thread(() -> {
3436            final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
3437            final int size = Config.AVATAR_SIZE;
3438            final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
3439            if (avatar != null) {
3440                if (!getFileBackend().save(avatar)) {
3441                    Log.d(Config.LOGTAG, "unable to save vcard");
3442                    callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
3443                    return;
3444                }
3445                publishAvatar(account, avatar, callback);
3446            } else {
3447                callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
3448            }
3449        }).start();
3450
3451    }
3452
3453    private void publishMucAvatar(Conversation conversation, Avatar avatar, OnAvatarPublication callback) {
3454        final IqPacket retrieve = mIqGenerator.retrieveVcardAvatar(avatar);
3455        sendIqPacket(conversation.getAccount(), retrieve, (account, response) -> {
3456            boolean itemNotFound = response.getType() == IqPacket.TYPE.ERROR && response.hasChild("error") && response.findChild("error").hasChild("item-not-found");
3457            if (response.getType() == IqPacket.TYPE.RESULT || itemNotFound) {
3458                Element vcard = response.findChild("vCard", "vcard-temp");
3459                if (vcard == null) {
3460                    vcard = new Element("vCard", "vcard-temp");
3461                }
3462                Element photo = vcard.findChild("PHOTO");
3463                if (photo == null) {
3464                    photo = vcard.addChild("PHOTO");
3465                }
3466                photo.clearChildren();
3467                photo.addChild("TYPE").setContent(avatar.type);
3468                photo.addChild("BINVAL").setContent(avatar.image);
3469                IqPacket publication = new IqPacket(IqPacket.TYPE.SET);
3470                publication.setTo(conversation.getJid().asBareJid());
3471                publication.addChild(vcard);
3472                sendIqPacket(account, publication, (a1, publicationResponse) -> {
3473                    if (publicationResponse.getType() == IqPacket.TYPE.RESULT) {
3474                        callback.onAvatarPublicationSucceeded();
3475                    } else {
3476                        Log.d(Config.LOGTAG, "failed to publish vcard " + publicationResponse.getError());
3477                        callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3478                    }
3479                });
3480            } else {
3481                Log.d(Config.LOGTAG, "failed to request vcard " + response.toString());
3482                callback.onAvatarPublicationFailed(R.string.error_publish_avatar_no_server_support);
3483            }
3484        });
3485    }
3486
3487    public void publishAvatar(Account account, final Avatar avatar, final OnAvatarPublication callback) {
3488        final Bundle options;
3489        if (account.getXmppConnection().getFeatures().pepPublishOptions()) {
3490            options = PublishOptions.openAccess();
3491        } else {
3492            options = null;
3493        }
3494        publishAvatar(account, avatar, options, true, callback);
3495    }
3496
3497    public void publishAvatar(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
3498        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": publishing avatar. options=" + options);
3499        IqPacket packet = this.mIqGenerator.publishAvatar(avatar, options);
3500        this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3501
3502            @Override
3503            public void onIqPacketReceived(Account account, IqPacket result) {
3504                if (result.getType() == IqPacket.TYPE.RESULT) {
3505                    publishAvatarMetadata(account, avatar, options, true, callback);
3506                } else if (retry && PublishOptions.preconditionNotMet(result)) {
3507                    pushNodeConfiguration(account, "urn:xmpp:avatar:data", options, new OnConfigurationPushed() {
3508                        @Override
3509                        public void onPushSucceeded() {
3510                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": changed node configuration for avatar node");
3511                            publishAvatar(account, avatar, options, false, callback);
3512                        }
3513
3514                        @Override
3515                        public void onPushFailed() {
3516                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to change node configuration for avatar node");
3517                            publishAvatar(account, avatar, null, false, callback);
3518                        }
3519                    });
3520                } else {
3521                    Element error = result.findChild("error");
3522                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server rejected avatar " + (avatar.size / 1024) + "KiB " + (error != null ? error.toString() : ""));
3523                    if (callback != null) {
3524                        callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3525                    }
3526                }
3527            }
3528        });
3529    }
3530
3531    public void publishAvatarMetadata(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
3532        final IqPacket packet = XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar, options);
3533        sendIqPacket(account, packet, new OnIqPacketReceived() {
3534            @Override
3535            public void onIqPacketReceived(Account account, IqPacket result) {
3536                if (result.getType() == IqPacket.TYPE.RESULT) {
3537                    if (account.setAvatar(avatar.getFilename())) {
3538                        getAvatarService().clear(account);
3539                        databaseBackend.updateAccount(account);
3540                        notifyAccountAvatarHasChanged(account);
3541                    }
3542                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": published avatar " + (avatar.size / 1024) + "KiB");
3543                    if (callback != null) {
3544                        callback.onAvatarPublicationSucceeded();
3545                    }
3546                } else if (retry && PublishOptions.preconditionNotMet(result)) {
3547                    pushNodeConfiguration(account, "urn:xmpp:avatar:metadata", options, new OnConfigurationPushed() {
3548                        @Override
3549                        public void onPushSucceeded() {
3550                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": changed node configuration for avatar meta data node");
3551                            publishAvatarMetadata(account, avatar, options, false, callback);
3552                        }
3553
3554                        @Override
3555                        public void onPushFailed() {
3556                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to change node configuration for avatar meta data node");
3557                            publishAvatarMetadata(account, avatar, null, false, callback);
3558                        }
3559                    });
3560                } else {
3561                    if (callback != null) {
3562                        callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3563                    }
3564                }
3565            }
3566        });
3567    }
3568
3569    public void republishAvatarIfNeeded(Account account) {
3570        if (account.getAxolotlService().isPepBroken()) {
3571            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping republication of avatar because pep is broken");
3572            return;
3573        }
3574        IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
3575        this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3576
3577            private Avatar parseAvatar(IqPacket packet) {
3578                Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
3579                if (pubsub != null) {
3580                    Element items = pubsub.findChild("items");
3581                    if (items != null) {
3582                        return Avatar.parseMetadata(items);
3583                    }
3584                }
3585                return null;
3586            }
3587
3588            private boolean errorIsItemNotFound(IqPacket packet) {
3589                Element error = packet.findChild("error");
3590                return packet.getType() == IqPacket.TYPE.ERROR
3591                        && error != null
3592                        && error.hasChild("item-not-found");
3593            }
3594
3595            @Override
3596            public void onIqPacketReceived(Account account, IqPacket packet) {
3597                if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
3598                    Avatar serverAvatar = parseAvatar(packet);
3599                    if (serverAvatar == null && account.getAvatar() != null) {
3600                        Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
3601                        if (avatar != null) {
3602                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar on server was null. republishing");
3603                            publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
3604                        } else {
3605                            Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": error rereading avatar");
3606                        }
3607                    }
3608                }
3609            }
3610        });
3611    }
3612
3613    public void fetchAvatar(Account account, Avatar avatar) {
3614        fetchAvatar(account, avatar, null);
3615    }
3616
3617    public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3618        final String KEY = generateFetchKey(account, avatar);
3619        synchronized (this.mInProgressAvatarFetches) {
3620            if (mInProgressAvatarFetches.add(KEY)) {
3621                switch (avatar.origin) {
3622                    case PEP:
3623                        this.mInProgressAvatarFetches.add(KEY);
3624                        fetchAvatarPep(account, avatar, callback);
3625                        break;
3626                    case VCARD:
3627                        this.mInProgressAvatarFetches.add(KEY);
3628                        fetchAvatarVcard(account, avatar, callback);
3629                        break;
3630                }
3631            } else if (avatar.origin == Avatar.Origin.PEP) {
3632                mOmittedPepAvatarFetches.add(KEY);
3633            } else {
3634                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": already fetching " + avatar.origin + " avatar for " + avatar.owner);
3635            }
3636        }
3637    }
3638
3639    private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3640        IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
3641        sendIqPacket(account, packet, (a, result) -> {
3642            synchronized (mInProgressAvatarFetches) {
3643                mInProgressAvatarFetches.remove(generateFetchKey(a, avatar));
3644            }
3645            final String ERROR = a.getJid().asBareJid() + ": fetching avatar for " + avatar.owner + " failed ";
3646            if (result.getType() == IqPacket.TYPE.RESULT) {
3647                avatar.image = mIqParser.avatarData(result);
3648                if (avatar.image != null) {
3649                    if (getFileBackend().save(avatar)) {
3650                        if (a.getJid().asBareJid().equals(avatar.owner)) {
3651                            if (a.setAvatar(avatar.getFilename())) {
3652                                databaseBackend.updateAccount(a);
3653                            }
3654                            getAvatarService().clear(a);
3655                            updateConversationUi();
3656                            updateAccountUi();
3657                        } else {
3658                            Contact contact = a.getRoster().getContact(avatar.owner);
3659                            if (contact.setAvatar(avatar)) {
3660                                syncRoster(account);
3661                                getAvatarService().clear(contact);
3662                                updateConversationUi();
3663                                updateRosterUi();
3664                            }
3665                        }
3666                        if (callback != null) {
3667                            callback.success(avatar);
3668                        }
3669                        Log.d(Config.LOGTAG, a.getJid().asBareJid()
3670                                + ": successfully fetched pep avatar for " + avatar.owner);
3671                        return;
3672                    }
3673                } else {
3674
3675                    Log.d(Config.LOGTAG, ERROR + "(parsing error)");
3676                }
3677            } else {
3678                Element error = result.findChild("error");
3679                if (error == null) {
3680                    Log.d(Config.LOGTAG, ERROR + "(server error)");
3681                } else {
3682                    Log.d(Config.LOGTAG, ERROR + error.toString());
3683                }
3684            }
3685            if (callback != null) {
3686                callback.error(0, null);
3687            }
3688
3689        });
3690    }
3691
3692    private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3693        IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
3694        this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3695            @Override
3696            public void onIqPacketReceived(Account account, IqPacket packet) {
3697                final boolean previouslyOmittedPepFetch;
3698                synchronized (mInProgressAvatarFetches) {
3699                    final String KEY = generateFetchKey(account, avatar);
3700                    mInProgressAvatarFetches.remove(KEY);
3701                    previouslyOmittedPepFetch = mOmittedPepAvatarFetches.remove(KEY);
3702                }
3703                if (packet.getType() == IqPacket.TYPE.RESULT) {
3704                    Element vCard = packet.findChild("vCard", "vcard-temp");
3705                    Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
3706                    String image = photo != null ? photo.findChildContent("BINVAL") : null;
3707                    if (image != null) {
3708                        avatar.image = image;
3709                        if (getFileBackend().save(avatar)) {
3710                            Log.d(Config.LOGTAG, account.getJid().asBareJid()
3711                                    + ": successfully fetched vCard avatar for " + avatar.owner + " omittedPep=" + previouslyOmittedPepFetch);
3712                            if (avatar.owner.isBareJid()) {
3713                                if (account.getJid().asBareJid().equals(avatar.owner) && account.getAvatar() == null) {
3714                                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": had no avatar. replacing with vcard");
3715                                    account.setAvatar(avatar.getFilename());
3716                                    databaseBackend.updateAccount(account);
3717                                    getAvatarService().clear(account);
3718                                    updateAccountUi();
3719                                } else {
3720                                    Contact contact = account.getRoster().getContact(avatar.owner);
3721                                    if (contact.setAvatar(avatar, previouslyOmittedPepFetch)) {
3722                                        syncRoster(account);
3723                                        getAvatarService().clear(contact);
3724                                        updateRosterUi();
3725                                    }
3726                                }
3727                                updateConversationUi();
3728                            } else {
3729                                Conversation conversation = find(account, avatar.owner.asBareJid());
3730                                if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
3731                                    MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
3732                                    if (user != null) {
3733                                        if (user.setAvatar(avatar)) {
3734                                            getAvatarService().clear(user);
3735                                            updateConversationUi();
3736                                            updateMucRosterUi();
3737                                        }
3738                                        if (user.getRealJid() != null) {
3739                                            Contact contact = account.getRoster().getContact(user.getRealJid());
3740                                            if (contact.setAvatar(avatar)) {
3741                                                syncRoster(account);
3742                                                getAvatarService().clear(contact);
3743                                                updateRosterUi();
3744                                            }
3745                                        }
3746                                    }
3747                                }
3748                            }
3749                        }
3750                    }
3751                }
3752            }
3753        });
3754    }
3755
3756    public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
3757        IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
3758        this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3759
3760            @Override
3761            public void onIqPacketReceived(Account account, IqPacket packet) {
3762                if (packet.getType() == IqPacket.TYPE.RESULT) {
3763                    Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
3764                    if (pubsub != null) {
3765                        Element items = pubsub.findChild("items");
3766                        if (items != null) {
3767                            Avatar avatar = Avatar.parseMetadata(items);
3768                            if (avatar != null) {
3769                                avatar.owner = account.getJid().asBareJid();
3770                                if (fileBackend.isAvatarCached(avatar)) {
3771                                    if (account.setAvatar(avatar.getFilename())) {
3772                                        databaseBackend.updateAccount(account);
3773                                    }
3774                                    getAvatarService().clear(account);
3775                                    callback.success(avatar);
3776                                } else {
3777                                    fetchAvatarPep(account, avatar, callback);
3778                                }
3779                                return;
3780                            }
3781                        }
3782                    }
3783                }
3784                callback.error(0, null);
3785            }
3786        });
3787    }
3788
3789    public void notifyAccountAvatarHasChanged(final Account account) {
3790        final XmppConnection connection = account.getXmppConnection();
3791        if (connection != null && connection.getFeatures().bookmarksConversion()) {
3792            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar changed. resending presence to online group chats");
3793            for (Conversation conversation : conversations) {
3794                if (conversation.getAccount() == account && conversation.getMode() == Conversational.MODE_MULTI) {
3795                    final MucOptions mucOptions = conversation.getMucOptions();
3796                    if (mucOptions.online()) {
3797                        PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous());
3798                        packet.setTo(mucOptions.getSelf().getFullJid());
3799                        connection.sendPresencePacket(packet);
3800                    }
3801                }
3802            }
3803        }
3804    }
3805
3806    public void deleteContactOnServer(Contact contact) {
3807        contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
3808        contact.resetOption(Contact.Options.DIRTY_PUSH);
3809        contact.setOption(Contact.Options.DIRTY_DELETE);
3810        Account account = contact.getAccount();
3811        if (account.getStatus() == Account.State.ONLINE) {
3812            IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
3813            Element item = iq.query(Namespace.ROSTER).addChild("item");
3814            item.setAttribute("jid", contact.getJid());
3815            item.setAttribute("subscription", "remove");
3816            account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
3817        }
3818    }
3819
3820    public void updateConversation(final Conversation conversation) {
3821        mDatabaseWriterExecutor.execute(() -> databaseBackend.updateConversation(conversation));
3822    }
3823
3824    private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
3825        synchronized (account) {
3826            XmppConnection connection = account.getXmppConnection();
3827            if (connection == null) {
3828                connection = createConnection(account);
3829                account.setXmppConnection(connection);
3830            }
3831            boolean hasInternet = hasInternetConnection();
3832            if (account.isEnabled() && hasInternet) {
3833                if (!force) {
3834                    disconnect(account, false);
3835                }
3836                Thread thread = new Thread(connection);
3837                connection.setInteractive(interactive);
3838                connection.prepareNewConnection();
3839                connection.interrupt();
3840                thread.start();
3841                scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
3842            } else {
3843                disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
3844                account.getRoster().clearPresences();
3845                connection.resetEverything();
3846                final AxolotlService axolotlService = account.getAxolotlService();
3847                if (axolotlService != null) {
3848                    axolotlService.resetBrokenness();
3849                }
3850                if (!hasInternet) {
3851                    account.setStatus(Account.State.NO_INTERNET);
3852                }
3853            }
3854        }
3855    }
3856
3857    public void reconnectAccountInBackground(final Account account) {
3858        new Thread(() -> reconnectAccount(account, false, true)).start();
3859    }
3860
3861    public void invite(Conversation conversation, Jid contact) {
3862        Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": inviting " + contact + " to " + conversation.getJid().asBareJid());
3863        MessagePacket packet = mMessageGenerator.invite(conversation, contact);
3864        sendMessagePacket(conversation.getAccount(), packet);
3865    }
3866
3867    public void directInvite(Conversation conversation, Jid jid) {
3868        MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
3869        sendMessagePacket(conversation.getAccount(), packet);
3870    }
3871
3872    public void resetSendingToWaiting(Account account) {
3873        for (Conversation conversation : getConversations()) {
3874            if (conversation.getAccount() == account) {
3875                conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
3876            }
3877        }
3878    }
3879
3880    public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
3881        return markMessage(account, recipient, uuid, status, null);
3882    }
3883
3884    public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status, String errorMessage) {
3885        if (uuid == null) {
3886            return null;
3887        }
3888        for (Conversation conversation : getConversations()) {
3889            if (conversation.getJid().asBareJid().equals(recipient) && conversation.getAccount() == account) {
3890                final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
3891                if (message != null) {
3892                    markMessage(message, status, errorMessage);
3893                }
3894                return message;
3895            }
3896        }
3897        return null;
3898    }
3899
3900    public boolean markMessage(Conversation conversation, String uuid, int status, String serverMessageId) {
3901        if (uuid == null) {
3902            return false;
3903        } else {
3904            Message message = conversation.findSentMessageWithUuid(uuid);
3905            if (message != null) {
3906                if (message.getServerMsgId() == null) {
3907                    message.setServerMsgId(serverMessageId);
3908                }
3909                markMessage(message, status);
3910                return true;
3911            } else {
3912                return false;
3913            }
3914        }
3915    }
3916
3917    public void markMessage(Message message, int status) {
3918        markMessage(message, status, null);
3919    }
3920
3921
3922    public void markMessage(Message message, int status, String errorMessage) {
3923        final int oldStatus = message.getStatus();
3924        if (status == Message.STATUS_SEND_FAILED && (oldStatus == Message.STATUS_SEND_RECEIVED || oldStatus == Message.STATUS_SEND_DISPLAYED)) {
3925            return;
3926        }
3927        if (status == Message.STATUS_SEND_RECEIVED && oldStatus == Message.STATUS_SEND_DISPLAYED) {
3928            return;
3929        }
3930        message.setErrorMessage(errorMessage);
3931        message.setStatus(status);
3932        databaseBackend.updateMessage(message, false);
3933        updateConversationUi();
3934    }
3935
3936    private SharedPreferences getPreferences() {
3937        return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
3938    }
3939
3940    public long getAutomaticMessageDeletionDate() {
3941        final long timeout = getLongPreference(SettingsActivity.AUTOMATIC_MESSAGE_DELETION, R.integer.automatic_message_deletion);
3942        return timeout == 0 ? timeout : (System.currentTimeMillis() - (timeout * 1000));
3943    }
3944
3945    public long getLongPreference(String name, @IntegerRes int res) {
3946        long defaultValue = getResources().getInteger(res);
3947        try {
3948            return Long.parseLong(getPreferences().getString(name, String.valueOf(defaultValue)));
3949        } catch (NumberFormatException e) {
3950            return defaultValue;
3951        }
3952    }
3953
3954    public boolean getBooleanPreference(String name, @BoolRes int res) {
3955        return getPreferences().getBoolean(name, getResources().getBoolean(res));
3956    }
3957
3958    public boolean confirmMessages() {
3959        return getBooleanPreference("confirm_messages", R.bool.confirm_messages);
3960    }
3961
3962    public boolean allowMessageCorrection() {
3963        return getBooleanPreference("allow_message_correction", R.bool.allow_message_correction);
3964    }
3965
3966    public boolean sendChatStates() {
3967        return getBooleanPreference("chat_states", R.bool.chat_states);
3968    }
3969
3970    private boolean synchronizeWithBookmarks() {
3971        return getBooleanPreference("autojoin", R.bool.autojoin);
3972    }
3973
3974    public boolean useTorToConnect() {
3975        return QuickConversationsService.isConversations() && getBooleanPreference("use_tor", R.bool.use_tor);
3976    }
3977
3978    public boolean showExtendedConnectionOptions() {
3979        return QuickConversationsService.isConversations() && getBooleanPreference("show_connection_options", R.bool.show_connection_options);
3980    }
3981
3982    public boolean broadcastLastActivity() {
3983        return getBooleanPreference(SettingsActivity.BROADCAST_LAST_ACTIVITY, R.bool.last_activity);
3984    }
3985
3986    public int unreadCount() {
3987        int count = 0;
3988        for (Conversation conversation : getConversations()) {
3989            count += conversation.unreadCount();
3990        }
3991        return count;
3992    }
3993
3994
3995    private <T> List<T> threadSafeList(Set<T> set) {
3996        synchronized (LISTENER_LOCK) {
3997            return set.size() == 0 ? Collections.emptyList() : new ArrayList<>(set);
3998        }
3999    }
4000
4001    public void showErrorToastInUi(int resId) {
4002        for (OnShowErrorToast listener : threadSafeList(this.mOnShowErrorToasts)) {
4003            listener.onShowErrorToast(resId);
4004        }
4005    }
4006
4007    public void updateConversationUi() {
4008        for (OnConversationUpdate listener : threadSafeList(this.mOnConversationUpdates)) {
4009            listener.onConversationUpdate();
4010        }
4011    }
4012
4013    public void notifyJingleRtpConnectionUpdate(final Account account, final Jid with, final String sessionId, final RtpEndUserState state) {
4014        for (OnJingleRtpConnectionUpdate listener : threadSafeList(this.onJingleRtpConnectionUpdate)) {
4015            listener.onJingleRtpConnectionUpdate(account, with, sessionId, state);
4016        }
4017    }
4018
4019    public void notifyJingleRtpConnectionUpdate(AppRTCAudioManager.AudioDevice selectedAudioDevice, Set<AppRTCAudioManager.AudioDevice> availableAudioDevices) {
4020        for (OnJingleRtpConnectionUpdate listener : threadSafeList(this.onJingleRtpConnectionUpdate)) {
4021            listener.onAudioDeviceChanged(selectedAudioDevice, availableAudioDevices);
4022        }
4023    }
4024
4025    public void updateAccountUi() {
4026        for (OnAccountUpdate listener : threadSafeList(this.mOnAccountUpdates)) {
4027            listener.onAccountUpdate();
4028        }
4029    }
4030
4031    public void updateRosterUi() {
4032        for (OnRosterUpdate listener : threadSafeList(this.mOnRosterUpdates)) {
4033            listener.onRosterUpdate();
4034        }
4035    }
4036
4037    public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
4038        if (mOnCaptchaRequested.size() > 0) {
4039            DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
4040            Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
4041                    (int) (captcha.getHeight() * metrics.scaledDensity), false);
4042            for (OnCaptchaRequested listener : threadSafeList(this.mOnCaptchaRequested)) {
4043                listener.onCaptchaRequested(account, id, data, scaled);
4044            }
4045            return true;
4046        }
4047        return false;
4048    }
4049
4050    public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
4051        for (OnUpdateBlocklist listener : threadSafeList(this.mOnUpdateBlocklist)) {
4052            listener.OnUpdateBlocklist(status);
4053        }
4054    }
4055
4056    public void updateMucRosterUi() {
4057        for (OnMucRosterUpdate listener : threadSafeList(this.mOnMucRosterUpdate)) {
4058            listener.onMucRosterUpdate();
4059        }
4060    }
4061
4062    public void keyStatusUpdated(AxolotlService.FetchStatus report) {
4063        for (OnKeyStatusUpdated listener : threadSafeList(this.mOnKeyStatusUpdated)) {
4064            listener.onKeyStatusUpdated(report);
4065        }
4066    }
4067
4068    public Account findAccountByJid(final Jid jid) {
4069        for (final Account account : this.accounts) {
4070            if (account.getJid().asBareJid().equals(jid.asBareJid())) {
4071                return account;
4072            }
4073        }
4074        return null;
4075    }
4076
4077    public Account findAccountByUuid(final String uuid) {
4078        for (Account account : this.accounts) {
4079            if (account.getUuid().equals(uuid)) {
4080                return account;
4081            }
4082        }
4083        return null;
4084    }
4085
4086    public Conversation findConversationByUuid(String uuid) {
4087        for (Conversation conversation : getConversations()) {
4088            if (conversation.getUuid().equals(uuid)) {
4089                return conversation;
4090            }
4091        }
4092        return null;
4093    }
4094
4095    public Conversation findUniqueConversationByJid(XmppUri xmppUri) {
4096        List<Conversation> findings = new ArrayList<>();
4097        for (Conversation c : getConversations()) {
4098            if (c.getAccount().isEnabled() && c.getJid().asBareJid().equals(xmppUri.getJid()) && ((c.getMode() == Conversational.MODE_MULTI) == xmppUri.isAction(XmppUri.ACTION_JOIN))) {
4099                findings.add(c);
4100            }
4101        }
4102        return findings.size() == 1 ? findings.get(0) : null;
4103    }
4104
4105    public boolean markRead(final Conversation conversation, boolean dismiss) {
4106        return markRead(conversation, null, dismiss).size() > 0;
4107    }
4108
4109    public void markRead(final Conversation conversation) {
4110        markRead(conversation, null, true);
4111    }
4112
4113    public List<Message> markRead(final Conversation conversation, String upToUuid, boolean dismiss) {
4114        if (dismiss) {
4115            mNotificationService.clear(conversation);
4116        }
4117        final List<Message> readMessages = conversation.markRead(upToUuid);
4118        if (readMessages.size() > 0) {
4119            Runnable runnable = () -> {
4120                for (Message message : readMessages) {
4121                    databaseBackend.updateMessage(message, false);
4122                }
4123            };
4124            mDatabaseWriterExecutor.execute(runnable);
4125            updateConversationUi();
4126            updateUnreadCountBadge();
4127            return readMessages;
4128        } else {
4129            return readMessages;
4130        }
4131    }
4132
4133    public synchronized void updateUnreadCountBadge() {
4134        int count = unreadCount();
4135        if (unreadCount != count) {
4136            Log.d(Config.LOGTAG, "update unread count to " + count);
4137            if (count > 0) {
4138                ShortcutBadger.applyCount(getApplicationContext(), count);
4139            } else {
4140                ShortcutBadger.removeCount(getApplicationContext());
4141            }
4142            unreadCount = count;
4143        }
4144    }
4145
4146    public void sendReadMarker(final Conversation conversation, String upToUuid) {
4147        final boolean isPrivateAndNonAnonymousMuc = conversation.getMode() == Conversation.MODE_MULTI && conversation.isPrivateAndNonAnonymous();
4148        final List<Message> readMessages = this.markRead(conversation, upToUuid, true);
4149        if (readMessages.size() > 0) {
4150            updateConversationUi();
4151        }
4152        final Message markable = Conversation.getLatestMarkableMessage(readMessages, isPrivateAndNonAnonymousMuc);
4153        if (confirmMessages()
4154                && markable != null
4155                && (markable.trusted() || isPrivateAndNonAnonymousMuc)
4156                && markable.getRemoteMsgId() != null) {
4157            Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
4158            final Account account = conversation.getAccount();
4159            final MessagePacket packet = mMessageGenerator.confirm(markable);
4160            this.sendMessagePacket(account, packet);
4161        }
4162    }
4163
4164    public SecureRandom getRNG() {
4165        return this.mRandom;
4166    }
4167
4168    public MemorizingTrustManager getMemorizingTrustManager() {
4169        return this.mMemorizingTrustManager;
4170    }
4171
4172    public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
4173        this.mMemorizingTrustManager = trustManager;
4174    }
4175
4176    public void updateMemorizingTrustmanager() {
4177        final MemorizingTrustManager tm;
4178        final boolean dontTrustSystemCAs = getBooleanPreference("dont_trust_system_cas", R.bool.dont_trust_system_cas);
4179        if (dontTrustSystemCAs) {
4180            tm = new MemorizingTrustManager(getApplicationContext(), null);
4181        } else {
4182            tm = new MemorizingTrustManager(getApplicationContext());
4183        }
4184        setMemorizingTrustManager(tm);
4185    }
4186
4187    public LruCache<String, Bitmap> getBitmapCache() {
4188        return this.mBitmapCache;
4189    }
4190
4191    public Collection<String> getKnownHosts() {
4192        final Set<String> hosts = new HashSet<>();
4193        for (final Account account : getAccounts()) {
4194            hosts.add(account.getServer());
4195            for (final Contact contact : account.getRoster().getContacts()) {
4196                if (contact.showInRoster()) {
4197                    final String server = contact.getServer();
4198                    if (server != null) {
4199                        hosts.add(server);
4200                    }
4201                }
4202            }
4203        }
4204        if (Config.QUICKSY_DOMAIN != null) {
4205            hosts.remove(Config.QUICKSY_DOMAIN.toEscapedString()); //we only want to show this when we type a e164 number
4206        }
4207        if (Config.DOMAIN_LOCK != null) {
4208            hosts.add(Config.DOMAIN_LOCK);
4209        }
4210        if (Config.MAGIC_CREATE_DOMAIN != null) {
4211            hosts.add(Config.MAGIC_CREATE_DOMAIN);
4212        }
4213        return hosts;
4214    }
4215
4216    public Collection<String> getKnownConferenceHosts() {
4217        final Set<String> mucServers = new HashSet<>();
4218        for (final Account account : accounts) {
4219            if (account.getXmppConnection() != null) {
4220                mucServers.addAll(account.getXmppConnection().getMucServers());
4221                for (Bookmark bookmark : account.getBookmarks()) {
4222                    final Jid jid = bookmark.getJid();
4223                    final String s = jid == null ? null : jid.getDomain().toEscapedString();
4224                    if (s != null) {
4225                        mucServers.add(s);
4226                    }
4227                }
4228            }
4229        }
4230        return mucServers;
4231    }
4232
4233    public void sendMessagePacket(Account account, MessagePacket packet) {
4234        XmppConnection connection = account.getXmppConnection();
4235        if (connection != null) {
4236            connection.sendMessagePacket(packet);
4237        }
4238    }
4239
4240    public void sendPresencePacket(Account account, PresencePacket packet) {
4241        XmppConnection connection = account.getXmppConnection();
4242        if (connection != null) {
4243            connection.sendPresencePacket(packet);
4244        }
4245    }
4246
4247    public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
4248        final XmppConnection connection = account.getXmppConnection();
4249        if (connection != null) {
4250            IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
4251            connection.sendUnmodifiedIqPacket(request, connection.registrationResponseListener, true);
4252        }
4253    }
4254
4255    public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
4256        final XmppConnection connection = account.getXmppConnection();
4257        if (connection != null) {
4258            connection.sendIqPacket(packet, callback);
4259        } else if (callback != null) {
4260            callback.onIqPacketReceived(account, new IqPacket(IqPacket.TYPE.TIMEOUT));
4261        }
4262    }
4263
4264    public void sendPresence(final Account account) {
4265        sendPresence(account, checkListeners() && broadcastLastActivity());
4266    }
4267
4268    private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
4269        Presence.Status status;
4270        if (manuallyChangePresence()) {
4271            status = account.getPresenceStatus();
4272        } else {
4273            status = getTargetPresence();
4274        }
4275        final PresencePacket packet = mPresenceGenerator.selfPresence(account, status);
4276        if (mLastActivity > 0 && includeIdleTimestamp) {
4277            long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
4278            packet.addChild("idle", Namespace.IDLE).setAttribute("since", AbstractGenerator.getTimestamp(since));
4279        }
4280        sendPresencePacket(account, packet);
4281    }
4282
4283    private void deactivateGracePeriod() {
4284        for (Account account : getAccounts()) {
4285            account.deactivateGracePeriod();
4286        }
4287    }
4288
4289    public void refreshAllPresences() {
4290        boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
4291        for (Account account : getAccounts()) {
4292            if (account.isEnabled()) {
4293                sendPresence(account, includeIdleTimestamp);
4294            }
4295        }
4296    }
4297
4298    private void refreshAllFcmTokens() {
4299        for (Account account : getAccounts()) {
4300            if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
4301                mPushManagementService.registerPushTokenOnServer(account);
4302                //TODO renew mucs
4303            }
4304        }
4305    }
4306
4307    private void sendOfflinePresence(final Account account) {
4308        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending offline presence");
4309        sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
4310    }
4311
4312    public MessageGenerator getMessageGenerator() {
4313        return this.mMessageGenerator;
4314    }
4315
4316    public PresenceGenerator getPresenceGenerator() {
4317        return this.mPresenceGenerator;
4318    }
4319
4320    public IqGenerator getIqGenerator() {
4321        return this.mIqGenerator;
4322    }
4323
4324    public IqParser getIqParser() {
4325        return this.mIqParser;
4326    }
4327
4328    public JingleConnectionManager getJingleConnectionManager() {
4329        return this.mJingleConnectionManager;
4330    }
4331
4332    public MessageArchiveService getMessageArchiveService() {
4333        return this.mMessageArchiveService;
4334    }
4335
4336    public QuickConversationsService getQuickConversationsService() {
4337        return this.mQuickConversationsService;
4338    }
4339
4340    public List<Contact> findContacts(Jid jid, String accountJid) {
4341        ArrayList<Contact> contacts = new ArrayList<>();
4342        for (Account account : getAccounts()) {
4343            if ((account.isEnabled() || accountJid != null)
4344                    && (accountJid == null || accountJid.equals(account.getJid().asBareJid().toString()))) {
4345                Contact contact = account.getRoster().getContactFromContactList(jid);
4346                if (contact != null) {
4347                    contacts.add(contact);
4348                }
4349            }
4350        }
4351        return contacts;
4352    }
4353
4354    public Conversation findFirstMuc(Jid jid) {
4355        for (Conversation conversation : getConversations()) {
4356            if (conversation.getAccount().isEnabled() && conversation.getJid().asBareJid().equals(jid.asBareJid()) && conversation.getMode() == Conversation.MODE_MULTI) {
4357                return conversation;
4358            }
4359        }
4360        return null;
4361    }
4362
4363    public NotificationService getNotificationService() {
4364        return this.mNotificationService;
4365    }
4366
4367    public HttpConnectionManager getHttpConnectionManager() {
4368        return this.mHttpConnectionManager;
4369    }
4370
4371    public void resendFailedMessages(final Message message) {
4372        final Collection<Message> messages = new ArrayList<>();
4373        Message current = message;
4374        while (current.getStatus() == Message.STATUS_SEND_FAILED) {
4375            messages.add(current);
4376            if (current.mergeable(current.next())) {
4377                current = current.next();
4378            } else {
4379                break;
4380            }
4381        }
4382        for (final Message msg : messages) {
4383            msg.setTime(System.currentTimeMillis());
4384            markMessage(msg, Message.STATUS_WAITING);
4385            this.resendMessage(msg, false);
4386        }
4387        if (message.getConversation() instanceof Conversation) {
4388            ((Conversation) message.getConversation()).sort();
4389        }
4390        updateConversationUi();
4391    }
4392
4393    public void clearConversationHistory(final Conversation conversation) {
4394        final long clearDate;
4395        final String reference;
4396        if (conversation.countMessages() > 0) {
4397            Message latestMessage = conversation.getLatestMessage();
4398            clearDate = latestMessage.getTimeSent() + 1000;
4399            reference = latestMessage.getServerMsgId();
4400        } else {
4401            clearDate = System.currentTimeMillis();
4402            reference = null;
4403        }
4404        conversation.clearMessages();
4405        conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
4406        conversation.setLastClearHistory(clearDate, reference);
4407        Runnable runnable = () -> {
4408            databaseBackend.deleteMessagesInConversation(conversation);
4409            databaseBackend.updateConversation(conversation);
4410        };
4411        mDatabaseWriterExecutor.execute(runnable);
4412    }
4413
4414    public boolean sendBlockRequest(final Blockable blockable, boolean reportSpam) {
4415        if (blockable != null && blockable.getBlockedJid() != null) {
4416            final Jid jid = blockable.getBlockedJid();
4417            this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid, reportSpam), (a, response) -> {
4418                if (response.getType() == IqPacket.TYPE.RESULT) {
4419                    a.getBlocklist().add(jid);
4420                    updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
4421                }
4422            });
4423            if (blockable.getBlockedJid().isFullJid()) {
4424                return false;
4425            } else if (removeBlockedConversations(blockable.getAccount(), jid)) {
4426                updateConversationUi();
4427                return true;
4428            } else {
4429                return false;
4430            }
4431        } else {
4432            return false;
4433        }
4434    }
4435
4436    public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
4437        boolean removed = false;
4438        synchronized (this.conversations) {
4439            boolean domainJid = blockedJid.getLocal() == null;
4440            for (Conversation conversation : this.conversations) {
4441                boolean jidMatches = (domainJid && blockedJid.getDomain().equals(conversation.getJid().getDomain()))
4442                        || blockedJid.equals(conversation.getJid().asBareJid());
4443                if (conversation.getAccount() == account
4444                        && conversation.getMode() == Conversation.MODE_SINGLE
4445                        && jidMatches) {
4446                    this.conversations.remove(conversation);
4447                    markRead(conversation);
4448                    conversation.setStatus(Conversation.STATUS_ARCHIVED);
4449                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conversation " + conversation.getJid().asBareJid() + " because jid was blocked");
4450                    updateConversation(conversation);
4451                    removed = true;
4452                }
4453            }
4454        }
4455        return removed;
4456    }
4457
4458    public void sendUnblockRequest(final Blockable blockable) {
4459        if (blockable != null && blockable.getJid() != null) {
4460            final Jid jid = blockable.getBlockedJid();
4461            this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
4462                @Override
4463                public void onIqPacketReceived(final Account account, final IqPacket packet) {
4464                    if (packet.getType() == IqPacket.TYPE.RESULT) {
4465                        account.getBlocklist().remove(jid);
4466                        updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
4467                    }
4468                }
4469            });
4470        }
4471    }
4472
4473    public void publishDisplayName(Account account) {
4474        String displayName = account.getDisplayName();
4475        final IqPacket request;
4476        if (TextUtils.isEmpty(displayName)) {
4477            request = mIqGenerator.deleteNode(Namespace.NICK);
4478        } else {
4479            request = mIqGenerator.publishNick(displayName);
4480        }
4481        mAvatarService.clear(account);
4482        sendIqPacket(account, request, (account1, packet) -> {
4483            if (packet.getType() == IqPacket.TYPE.ERROR) {
4484                Log.d(Config.LOGTAG, account1.getJid().asBareJid() + ": unable to modify nick name " + packet.toString());
4485            }
4486        });
4487    }
4488
4489    public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
4490        ServiceDiscoveryResult result = discoCache.get(key);
4491        if (result != null) {
4492            return result;
4493        } else {
4494            result = databaseBackend.findDiscoveryResult(key.first, key.second);
4495            if (result != null) {
4496                discoCache.put(key, result);
4497            }
4498            return result;
4499        }
4500    }
4501
4502    public void fetchCaps(Account account, final Jid jid, final Presence presence) {
4503        final Pair<String, String> key = new Pair<>(presence.getHash(), presence.getVer());
4504        final ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
4505        if (disco != null) {
4506            presence.setServiceDiscoveryResult(disco);
4507        } else {
4508            if (account.inProgressDiscoFetches.contains(key)) {
4509                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping duplicate disco request for " + key.second + " to " + jid);
4510                return;
4511            }
4512            account.inProgressDiscoFetches.add(key);
4513            final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
4514            request.setTo(jid);
4515            final String node = presence.getNode();
4516            final String ver = presence.getVer();
4517            final Element query = request.query(Namespace.DISCO_INFO);
4518            if (node != null && ver != null) {
4519                query.setAttribute("node", node + "#" + ver);
4520            }
4521            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": making disco request for " + key.second + " to " + jid);
4522            sendIqPacket(account, request, (a, response) -> {
4523                if (response.getType() == IqPacket.TYPE.RESULT) {
4524                    ServiceDiscoveryResult discoveryResult = new ServiceDiscoveryResult(response);
4525                    if (presence.getVer().equals(discoveryResult.getVer())) {
4526                        databaseBackend.insertDiscoveryResult(discoveryResult);
4527                        injectServiceDiscoveryResult(a.getRoster(), presence.getHash(), presence.getVer(), discoveryResult);
4528                    } else {
4529                        Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + discoveryResult.getVer());
4530                    }
4531                } else {
4532                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to fetch caps from " + jid);
4533                }
4534                a.inProgressDiscoFetches.remove(key);
4535            });
4536        }
4537    }
4538
4539    private void injectServiceDiscoveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
4540        for (final Contact contact : roster.getContacts()) {
4541            for (final Presence presence : contact.getPresences().getPresences()) {
4542                if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
4543                    presence.setServiceDiscoveryResult(disco);
4544                }
4545            }
4546        }
4547    }
4548
4549    public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
4550        final MessageArchiveService.Version version = MessageArchiveService.Version.get(account);
4551        IqPacket request = new IqPacket(IqPacket.TYPE.GET);
4552        request.addChild("prefs", version.namespace);
4553        sendIqPacket(account, request, (account1, packet) -> {
4554            Element prefs = packet.findChild("prefs", version.namespace);
4555            if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
4556                callback.onPreferencesFetched(prefs);
4557            } else {
4558                callback.onPreferencesFetchFailed();
4559            }
4560        });
4561    }
4562
4563    public PushManagementService getPushManagementService() {
4564        return mPushManagementService;
4565    }
4566
4567    public void changeStatus(Account account, PresenceTemplate template, String signature) {
4568        if (!template.getStatusMessage().isEmpty()) {
4569            databaseBackend.insertPresenceTemplate(template);
4570        }
4571        account.setPgpSignature(signature);
4572        account.setPresenceStatus(template.getStatus());
4573        account.setPresenceStatusMessage(template.getStatusMessage());
4574        databaseBackend.updateAccount(account);
4575        sendPresence(account);
4576    }
4577
4578    public List<PresenceTemplate> getPresenceTemplates(Account account) {
4579        List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
4580        for (PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
4581            if (!templates.contains(template)) {
4582                templates.add(0, template);
4583            }
4584        }
4585        return templates;
4586    }
4587
4588    public void saveConversationAsBookmark(Conversation conversation, String name) {
4589        final Account account = conversation.getAccount();
4590        final Bookmark bookmark = new Bookmark(account, conversation.getJid().asBareJid());
4591        final String nick = conversation.getJid().getResource();
4592        if (nick != null && !nick.isEmpty() && !nick.equals(MucOptions.defaultNick(account))) {
4593            bookmark.setNick(nick);
4594        }
4595        if (!TextUtils.isEmpty(name)) {
4596            bookmark.setBookmarkName(name);
4597        }
4598        bookmark.setAutojoin(getPreferences().getBoolean("autojoin", getResources().getBoolean(R.bool.autojoin)));
4599        createBookmark(account, bookmark);
4600        bookmark.setConversation(conversation);
4601    }
4602
4603    public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
4604        boolean performedVerification = false;
4605        final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
4606        for (XmppUri.Fingerprint fp : fingerprints) {
4607            if (fp.type == XmppUri.FingerprintType.OMEMO) {
4608                String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
4609                FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
4610                if (fingerprintStatus != null) {
4611                    if (!fingerprintStatus.isVerified()) {
4612                        performedVerification = true;
4613                        axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
4614                    }
4615                } else {
4616                    axolotlService.preVerifyFingerprint(contact, fingerprint);
4617                }
4618            }
4619        }
4620        return performedVerification;
4621    }
4622
4623    public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
4624        final AxolotlService axolotlService = account.getAxolotlService();
4625        boolean verifiedSomething = false;
4626        for (XmppUri.Fingerprint fp : fingerprints) {
4627            if (fp.type == XmppUri.FingerprintType.OMEMO) {
4628                String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
4629                Log.d(Config.LOGTAG, "trying to verify own fp=" + fingerprint);
4630                FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
4631                if (fingerprintStatus != null) {
4632                    if (!fingerprintStatus.isVerified()) {
4633                        axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
4634                        verifiedSomething = true;
4635                    }
4636                } else {
4637                    axolotlService.preVerifyFingerprint(account, fingerprint);
4638                    verifiedSomething = true;
4639                }
4640            }
4641        }
4642        return verifiedSomething;
4643    }
4644
4645    public boolean blindTrustBeforeVerification() {
4646        return getBooleanPreference(SettingsActivity.BLIND_TRUST_BEFORE_VERIFICATION, R.bool.btbv);
4647    }
4648
4649    public ShortcutService getShortcutService() {
4650        return mShortcutService;
4651    }
4652
4653    public void pushMamPreferences(Account account, Element prefs) {
4654        IqPacket set = new IqPacket(IqPacket.TYPE.SET);
4655        set.addChild(prefs);
4656        sendIqPacket(account, set, null);
4657    }
4658
4659    public void evictPreview(String uuid) {
4660        if (mBitmapCache.remove(uuid) != null) {
4661            Log.d(Config.LOGTAG, "deleted cached preview");
4662        }
4663    }
4664
4665    public interface OnMamPreferencesFetched {
4666        void onPreferencesFetched(Element prefs);
4667
4668        void onPreferencesFetchFailed();
4669    }
4670
4671    public interface OnAccountCreated {
4672        void onAccountCreated(Account account);
4673
4674        void informUser(int r);
4675    }
4676
4677    public interface OnMoreMessagesLoaded {
4678        void onMoreMessagesLoaded(int count, Conversation conversation);
4679
4680        void informUser(int r);
4681    }
4682
4683    public interface OnAccountPasswordChanged {
4684        void onPasswordChangeSucceeded();
4685
4686        void onPasswordChangeFailed();
4687    }
4688
4689    public interface OnRoomDestroy {
4690        void onRoomDestroySucceeded();
4691
4692        void onRoomDestroyFailed();
4693    }
4694
4695    public interface OnAffiliationChanged {
4696        void onAffiliationChangedSuccessful(Jid jid);
4697
4698        void onAffiliationChangeFailed(Jid jid, int resId);
4699    }
4700
4701    public interface OnConversationUpdate {
4702        void onConversationUpdate();
4703    }
4704
4705    public interface OnJingleRtpConnectionUpdate {
4706        void onJingleRtpConnectionUpdate(final Account account, final Jid with, final String sessionId, final RtpEndUserState state);
4707
4708        void onAudioDeviceChanged(AppRTCAudioManager.AudioDevice selectedAudioDevice, Set<AppRTCAudioManager.AudioDevice> availableAudioDevices);
4709    }
4710
4711    public interface OnAccountUpdate {
4712        void onAccountUpdate();
4713    }
4714
4715    public interface OnCaptchaRequested {
4716        void onCaptchaRequested(Account account, String id, Data data, Bitmap captcha);
4717    }
4718
4719    public interface OnRosterUpdate {
4720        void onRosterUpdate();
4721    }
4722
4723    public interface OnMucRosterUpdate {
4724        void onMucRosterUpdate();
4725    }
4726
4727    public interface OnConferenceConfigurationFetched {
4728        void onConferenceConfigurationFetched(Conversation conversation);
4729
4730        void onFetchFailed(Conversation conversation, Element error);
4731    }
4732
4733    public interface OnConferenceJoined {
4734        void onConferenceJoined(Conversation conversation);
4735    }
4736
4737    public interface OnConfigurationPushed {
4738        void onPushSucceeded();
4739
4740        void onPushFailed();
4741    }
4742
4743    public interface OnShowErrorToast {
4744        void onShowErrorToast(int resId);
4745    }
4746
4747    public class XmppConnectionBinder extends Binder {
4748        public XmppConnectionService getService() {
4749            return XmppConnectionService.this;
4750        }
4751    }
4752
4753    private class InternalEventReceiver extends BroadcastReceiver {
4754
4755        @Override
4756        public void onReceive(Context context, Intent intent) {
4757            onStartCommand(intent, 0, 0);
4758        }
4759    }
4760
4761    public static class OngoingCall {
4762        private final AbstractJingleConnection.Id id;
4763        private final Set<Media> media;
4764
4765        public OngoingCall(AbstractJingleConnection.Id id, Set<Media> media) {
4766            this.id = id;
4767            this.media = media;
4768        }
4769
4770        @Override
4771        public boolean equals(Object o) {
4772            if (this == o) return true;
4773            if (o == null || getClass() != o.getClass()) return false;
4774            OngoingCall that = (OngoingCall) o;
4775            return Objects.equal(id, that.id);
4776        }
4777
4778        @Override
4779        public int hashCode() {
4780            return Objects.hashCode(id);
4781        }
4782    }
4783}