XmppConnectionService.java

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