XmppConnectionService.java

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