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