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