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