XmppConnectionService.java

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