XmppConnectionService.java

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