XmppConnectionService.java

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