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