XmppConnectionService.java

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