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        if (Compatibility.hasStoragePermission(this)) {
1131            Log.d(Config.LOGTAG, "starting file observer");
1132            mFileAddingExecutor.execute(this.fileObserver::startWatching);
1133            mFileAddingExecutor.execute(this::checkForDeletedFiles);
1134        }
1135        if (Config.supportOpenPgp()) {
1136            this.pgpServiceConnection = new OpenPgpServiceConnection(this, "org.sufficientlysecure.keychain", new OpenPgpServiceConnection.OnBound() {
1137                @Override
1138                public void onBound(IOpenPgpService2 service) {
1139                    for (Account account : accounts) {
1140                        final PgpDecryptionService pgp = account.getPgpDecryptionService();
1141                        if (pgp != null) {
1142                            pgp.continueDecryption(true);
1143                        }
1144                    }
1145                }
1146
1147                @Override
1148                public void onError(Exception e) {
1149                }
1150            });
1151            this.pgpServiceConnection.bindToService();
1152        }
1153
1154        this.pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
1155        this.wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Conversations:Service");
1156
1157        toggleForegroundService();
1158        updateUnreadCountBadge();
1159        toggleScreenEventReceiver();
1160        final IntentFilter intentFilter = new IntentFilter();
1161        intentFilter.addAction(TorServiceUtils.ACTION_STATUS);
1162        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1163            scheduleNextIdlePing();
1164            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
1165                intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1166            }
1167            intentFilter.addAction(NotificationManager.ACTION_INTERRUPTION_FILTER_CHANGED);
1168        }
1169        registerReceiver(this.mInternalEventReceiver, intentFilter);
1170        mForceDuringOnCreate.set(false);
1171        toggleForegroundService();
1172        setupPhoneStateListener();
1173    }
1174
1175
1176    private void setupPhoneStateListener() {
1177        final TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
1178        if (telephonyManager != null) {
1179            telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
1180        }
1181    }
1182
1183    public boolean isPhoneInCall() {
1184        return isPhoneInCall.get();
1185    }
1186
1187    private void checkForDeletedFiles() {
1188        if (destroyed) {
1189            Log.d(Config.LOGTAG, "Do not check for deleted files because service has been destroyed");
1190            return;
1191        }
1192        final long start = SystemClock.elapsedRealtime();
1193        final List<DatabaseBackend.FilePathInfo> relativeFilePaths = databaseBackend.getFilePathInfo();
1194        final List<DatabaseBackend.FilePathInfo> changed = new ArrayList<>();
1195        for (final DatabaseBackend.FilePathInfo filePath : relativeFilePaths) {
1196            if (destroyed) {
1197                Log.d(Config.LOGTAG, "Stop checking for deleted files because service has been destroyed");
1198                return;
1199            }
1200            final File file = fileBackend.getFileForPath(filePath.path);
1201            if (filePath.setDeleted(!file.exists())) {
1202                changed.add(filePath);
1203            }
1204        }
1205        final long duration = SystemClock.elapsedRealtime() - start;
1206        Log.d(Config.LOGTAG, "found " + changed.size() + " changed files on start up. total=" + relativeFilePaths.size() + ". (" + duration + "ms)");
1207        if (changed.size() > 0) {
1208            databaseBackend.markFilesAsChanged(changed);
1209            markChangedFiles(changed);
1210        }
1211    }
1212
1213    public void startContactObserver() {
1214        getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, new ContentObserver(null) {
1215            @Override
1216            public void onChange(boolean selfChange) {
1217                super.onChange(selfChange);
1218                if (restoredFromDatabaseLatch.getCount() == 0) {
1219                    loadPhoneContacts();
1220                }
1221            }
1222        });
1223    }
1224
1225    @Override
1226    public void onTrimMemory(int level) {
1227        super.onTrimMemory(level);
1228        if (level >= TRIM_MEMORY_COMPLETE) {
1229            Log.d(Config.LOGTAG, "clear cache due to low memory");
1230            getBitmapCache().evictAll();
1231        }
1232    }
1233
1234    @Override
1235    public void onDestroy() {
1236        try {
1237            unregisterReceiver(this.mInternalEventReceiver);
1238        } catch (final IllegalArgumentException e) {
1239            //ignored
1240        }
1241        destroyed = false;
1242        fileObserver.stopWatching();
1243        super.onDestroy();
1244    }
1245
1246    public void restartFileObserver() {
1247        Log.d(Config.LOGTAG, "restarting file observer");
1248        mFileAddingExecutor.execute(this.fileObserver::restartWatching);
1249        mFileAddingExecutor.execute(this::checkForDeletedFiles);
1250    }
1251
1252    public void toggleScreenEventReceiver() {
1253        if (awayWhenScreenOff() && !manuallyChangePresence()) {
1254            final IntentFilter filter = new IntentFilter();
1255            filter.addAction(Intent.ACTION_SCREEN_ON);
1256            filter.addAction(Intent.ACTION_SCREEN_OFF);
1257            registerReceiver(this.mInternalScreenEventReceiver, filter);
1258        } else {
1259            try {
1260                unregisterReceiver(this.mInternalScreenEventReceiver);
1261            } catch (IllegalArgumentException e) {
1262                //ignored
1263            }
1264        }
1265    }
1266
1267    public void toggleForegroundService() {
1268        toggleForegroundService(false);
1269    }
1270
1271    public void setOngoingCall(AbstractJingleConnection.Id id, Set<Media> media) {
1272        ongoingCall.set(new OngoingCall(id, media));
1273        toggleForegroundService(false);
1274    }
1275
1276    public void removeOngoingCall() {
1277        ongoingCall.set(null);
1278        toggleForegroundService(false);
1279    }
1280
1281    private void toggleForegroundService(boolean force) {
1282        final boolean status;
1283        final OngoingCall ongoing = ongoingCall.get();
1284        if (force || mForceDuringOnCreate.get() || mForceForegroundService.get() || ongoing != null || (Compatibility.keepForegroundService(this) && hasEnabledAccounts())) {
1285            final Notification notification;
1286            if (ongoing != null) {
1287                notification = this.mNotificationService.getOngoingCallNotification(ongoing.id, ongoing.media);
1288                startForeground(NotificationService.ONGOING_CALL_NOTIFICATION_ID, notification);
1289                mNotificationService.cancel(NotificationService.FOREGROUND_NOTIFICATION_ID);
1290            } else {
1291                notification = this.mNotificationService.createForegroundNotification();
1292                startForeground(NotificationService.FOREGROUND_NOTIFICATION_ID, notification);
1293            }
1294
1295            if (!mForceForegroundService.get()) {
1296                mNotificationService.notify(NotificationService.FOREGROUND_NOTIFICATION_ID, notification);
1297            }
1298            status = true;
1299        } else {
1300            stopForeground(true);
1301            status = false;
1302        }
1303        if (!mForceForegroundService.get()) {
1304            mNotificationService.cancel(NotificationService.FOREGROUND_NOTIFICATION_ID);
1305        }
1306        if (ongoing == null) {
1307            mNotificationService.cancel(NotificationService.ONGOING_CALL_NOTIFICATION_ID);
1308        }
1309        Log.d(Config.LOGTAG, "ForegroundService: " + (status ? "on" : "off"));
1310    }
1311
1312    public boolean foregroundNotificationNeedsUpdatingWhenErrorStateChanges() {
1313        return !mForceForegroundService.get() && ongoingCall.get() == null && Compatibility.keepForegroundService(this) && hasEnabledAccounts();
1314    }
1315
1316    @Override
1317    public void onTaskRemoved(final Intent rootIntent) {
1318        super.onTaskRemoved(rootIntent);
1319        if ((Compatibility.keepForegroundService(this) && hasEnabledAccounts()) || mForceForegroundService.get() || ongoingCall.get() != null) {
1320            Log.d(Config.LOGTAG, "ignoring onTaskRemoved because foreground service is activated");
1321        } else {
1322            this.logoutAndSave(false);
1323        }
1324    }
1325
1326    private void logoutAndSave(boolean stop) {
1327        int activeAccounts = 0;
1328        for (final Account account : accounts) {
1329            if (account.getStatus() != Account.State.DISABLED) {
1330                databaseBackend.writeRoster(account.getRoster());
1331                activeAccounts++;
1332            }
1333            if (account.getXmppConnection() != null) {
1334                new Thread(() -> disconnect(account, false)).start();
1335            }
1336        }
1337        if (stop || activeAccounts == 0) {
1338            Log.d(Config.LOGTAG, "good bye");
1339            stopSelf();
1340        }
1341    }
1342
1343    private void schedulePostConnectivityChange() {
1344        final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1345        if (alarmManager == null) {
1346            return;
1347        }
1348        final long triggerAtMillis = SystemClock.elapsedRealtime() + (Config.POST_CONNECTIVITY_CHANGE_PING_INTERVAL * 1000);
1349        final Intent intent = new Intent(this, EventReceiver.class);
1350        intent.setAction(ACTION_POST_CONNECTIVITY_CHANGE);
1351        try {
1352            final PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, 0);
1353            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1354                alarmManager.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, pendingIntent);
1355            } else {
1356                alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, pendingIntent);
1357            }
1358        } catch (RuntimeException e) {
1359            Log.e(Config.LOGTAG, "unable to schedule alarm for post connectivity change", e);
1360        }
1361    }
1362
1363    public void scheduleWakeUpCall(int seconds, int requestCode) {
1364        final long timeToWake = SystemClock.elapsedRealtime() + (seconds < 0 ? 1 : seconds + 1) * 1000;
1365        final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1366        if (alarmManager == null) {
1367            return;
1368        }
1369        final Intent intent = new Intent(this, EventReceiver.class);
1370        intent.setAction("ping");
1371        try {
1372            PendingIntent pendingIntent = PendingIntent.getBroadcast(this, requestCode, intent, 0);
1373            alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, pendingIntent);
1374        } catch (RuntimeException e) {
1375            Log.e(Config.LOGTAG, "unable to schedule alarm for ping", e);
1376        }
1377    }
1378
1379    @TargetApi(Build.VERSION_CODES.M)
1380    private void scheduleNextIdlePing() {
1381        final long timeToWake = SystemClock.elapsedRealtime() + (Config.IDLE_PING_INTERVAL * 1000);
1382        final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1383        if (alarmManager == null) {
1384            return;
1385        }
1386        final Intent intent = new Intent(this, EventReceiver.class);
1387        intent.setAction(ACTION_IDLE_PING);
1388        try {
1389            PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
1390            alarmManager.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, pendingIntent);
1391        } catch (RuntimeException e) {
1392            Log.d(Config.LOGTAG, "unable to schedule alarm for idle ping", e);
1393        }
1394    }
1395
1396    public XmppConnection createConnection(final Account account) {
1397        final XmppConnection connection = new XmppConnection(account, this);
1398        connection.setOnMessagePacketReceivedListener(this.mMessageParser);
1399        connection.setOnStatusChangedListener(this.statusListener);
1400        connection.setOnPresencePacketReceivedListener(this.mPresenceParser);
1401        connection.setOnUnregisteredIqPacketReceivedListener(this.mIqParser);
1402        connection.setOnJinglePacketReceivedListener(((a, jp) -> mJingleConnectionManager.deliverPacket(a, jp)));
1403        connection.setOnBindListener(this.mOnBindListener);
1404        connection.setOnMessageAcknowledgeListener(this.mOnMessageAcknowledgedListener);
1405        connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService);
1406        connection.addOnAdvancedStreamFeaturesAvailableListener(this.mAvatarService);
1407        AxolotlService axolotlService = account.getAxolotlService();
1408        if (axolotlService != null) {
1409            connection.addOnAdvancedStreamFeaturesAvailableListener(axolotlService);
1410        }
1411        return connection;
1412    }
1413
1414    public void sendChatState(Conversation conversation) {
1415        if (sendChatStates()) {
1416            MessagePacket packet = mMessageGenerator.generateChatState(conversation);
1417            sendMessagePacket(conversation.getAccount(), packet);
1418        }
1419    }
1420
1421    private void sendFileMessage(final Message message, final boolean delay) {
1422        Log.d(Config.LOGTAG, "send file message");
1423        final Account account = message.getConversation().getAccount();
1424        if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1425                || message.getConversation().getMode() == Conversation.MODE_MULTI) {
1426            mHttpConnectionManager.createNewUploadConnection(message, delay);
1427        } else {
1428            mJingleConnectionManager.startJingleFileTransfer(message);
1429        }
1430    }
1431
1432    public void sendMessage(final Message message) {
1433        sendMessage(message, false, false);
1434    }
1435
1436    private void sendMessage(final Message message, final boolean resend, final boolean delay) {
1437        final Account account = message.getConversation().getAccount();
1438        if (account.setShowErrorNotification(true)) {
1439            databaseBackend.updateAccount(account);
1440            mNotificationService.updateErrorNotification();
1441        }
1442        final Conversation conversation = (Conversation) message.getConversation();
1443        account.deactivateGracePeriod();
1444
1445
1446        if (QuickConversationsService.isQuicksy() && conversation.getMode() == Conversation.MODE_SINGLE) {
1447            final Contact contact = conversation.getContact();
1448            if (!contact.showInRoster() && contact.getOption(Contact.Options.SYNCED_VIA_OTHER)) {
1449                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": adding " + contact.getJid() + " on sending message");
1450                createContact(contact, true);
1451            }
1452        }
1453
1454        MessagePacket packet = null;
1455        final boolean addToConversation = (conversation.getMode() != Conversation.MODE_MULTI
1456                || !Patches.BAD_MUC_REFLECTION.contains(account.getServerIdentity()))
1457                && !message.edited();
1458        boolean saveInDb = addToConversation;
1459        message.setStatus(Message.STATUS_WAITING);
1460
1461        if (message.getEncryption() != Message.ENCRYPTION_NONE && conversation.getMode() == Conversation.MODE_MULTI && conversation.isPrivateAndNonAnonymous()) {
1462            if (conversation.setAttribute(Conversation.ATTRIBUTE_FORMERLY_PRIVATE_NON_ANONYMOUS, true)) {
1463                databaseBackend.updateConversation(conversation);
1464            }
1465        }
1466
1467        final boolean inProgressJoin = isJoinInProgress(conversation);
1468
1469
1470        if (account.isOnlineAndConnected() && !inProgressJoin) {
1471            switch (message.getEncryption()) {
1472                case Message.ENCRYPTION_NONE:
1473                    if (message.needsUploading()) {
1474                        if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1475                                || conversation.getMode() == Conversation.MODE_MULTI
1476                                || message.fixCounterpart()) {
1477                            this.sendFileMessage(message, delay);
1478                        } else {
1479                            break;
1480                        }
1481                    } else {
1482                        packet = mMessageGenerator.generateChat(message);
1483                    }
1484                    break;
1485                case Message.ENCRYPTION_PGP:
1486                case Message.ENCRYPTION_DECRYPTED:
1487                    if (message.needsUploading()) {
1488                        if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1489                                || conversation.getMode() == Conversation.MODE_MULTI
1490                                || message.fixCounterpart()) {
1491                            this.sendFileMessage(message, delay);
1492                        } else {
1493                            break;
1494                        }
1495                    } else {
1496                        packet = mMessageGenerator.generatePgpChat(message);
1497                    }
1498                    break;
1499                case Message.ENCRYPTION_AXOLOTL:
1500                    message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
1501                    if (message.needsUploading()) {
1502                        if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1503                                || conversation.getMode() == Conversation.MODE_MULTI
1504                                || message.fixCounterpart()) {
1505                            this.sendFileMessage(message, delay);
1506                        } else {
1507                            break;
1508                        }
1509                    } else {
1510                        XmppAxolotlMessage axolotlMessage = account.getAxolotlService().fetchAxolotlMessageFromCache(message);
1511                        if (axolotlMessage == null) {
1512                            account.getAxolotlService().preparePayloadMessage(message, delay);
1513                        } else {
1514                            packet = mMessageGenerator.generateAxolotlChat(message, axolotlMessage);
1515                        }
1516                    }
1517                    break;
1518
1519            }
1520            if (packet != null) {
1521                if (account.getXmppConnection().getFeatures().sm()
1522                        || (conversation.getMode() == Conversation.MODE_MULTI && message.getCounterpart().isBareJid())) {
1523                    message.setStatus(Message.STATUS_UNSEND);
1524                } else {
1525                    message.setStatus(Message.STATUS_SEND);
1526                }
1527            }
1528        } else {
1529            switch (message.getEncryption()) {
1530                case Message.ENCRYPTION_DECRYPTED:
1531                    if (!message.needsUploading()) {
1532                        String pgpBody = message.getEncryptedBody();
1533                        String decryptedBody = message.getBody();
1534                        message.setBody(pgpBody); //TODO might throw NPE
1535                        message.setEncryption(Message.ENCRYPTION_PGP);
1536                        if (message.edited()) {
1537                            message.setBody(decryptedBody);
1538                            message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1539                            if (!databaseBackend.updateMessage(message, message.getEditedId())) {
1540                                Log.e(Config.LOGTAG, "error updated message in DB after edit");
1541                            }
1542                            updateConversationUi();
1543                            return;
1544                        } else {
1545                            databaseBackend.createMessage(message);
1546                            saveInDb = false;
1547                            message.setBody(decryptedBody);
1548                            message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1549                        }
1550                    }
1551                    break;
1552                case Message.ENCRYPTION_AXOLOTL:
1553                    message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
1554                    break;
1555            }
1556        }
1557
1558
1559        boolean mucMessage = conversation.getMode() == Conversation.MODE_MULTI && !message.isPrivateMessage();
1560        if (mucMessage) {
1561            message.setCounterpart(conversation.getMucOptions().getSelf().getFullJid());
1562        }
1563
1564        if (resend) {
1565            if (packet != null && addToConversation) {
1566                if (account.getXmppConnection().getFeatures().sm() || mucMessage) {
1567                    markMessage(message, Message.STATUS_UNSEND);
1568                } else {
1569                    markMessage(message, Message.STATUS_SEND);
1570                }
1571            }
1572        } else {
1573            if (addToConversation) {
1574                conversation.add(message);
1575            }
1576            if (saveInDb) {
1577                databaseBackend.createMessage(message);
1578            } else if (message.edited()) {
1579                if (!databaseBackend.updateMessage(message, message.getEditedId())) {
1580                    Log.e(Config.LOGTAG, "error updated message in DB after edit");
1581                }
1582            }
1583            updateConversationUi();
1584        }
1585        if (packet != null) {
1586            if (delay) {
1587                mMessageGenerator.addDelay(packet, message.getTimeSent());
1588            }
1589            if (conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
1590                if (this.sendChatStates()) {
1591                    packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
1592                }
1593            }
1594            sendMessagePacket(account, packet);
1595        }
1596    }
1597
1598    private boolean isJoinInProgress(final Conversation conversation) {
1599        final Account account = conversation.getAccount();
1600        synchronized (account.inProgressConferenceJoins) {
1601            if (conversation.getMode() == Conversational.MODE_MULTI) {
1602                final boolean inProgress = account.inProgressConferenceJoins.contains(conversation);
1603                final boolean pending = account.pendingConferenceJoins.contains(conversation);
1604                final boolean inProgressJoin = inProgress || pending;
1605                if (inProgressJoin) {
1606                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": holding back message to group. inProgress=" + inProgress + ", pending=" + pending);
1607                }
1608                return inProgressJoin;
1609            } else {
1610                return false;
1611            }
1612        }
1613    }
1614
1615    private void sendUnsentMessages(final Conversation conversation) {
1616        conversation.findWaitingMessages(message -> resendMessage(message, true));
1617    }
1618
1619    public void resendMessage(final Message message, final boolean delay) {
1620        sendMessage(message, true, delay);
1621    }
1622
1623    public void requestEasyOnboardingInvite(final Account account, final EasyOnboardingInvite.OnInviteRequested callback) {
1624        final XmppConnection connection = account.getXmppConnection();
1625        final Jid jid = connection == null ? null : connection.getJidForCommand(Namespace.EASY_ONBOARDING_INVITE);
1626        if (jid == null) {
1627            callback.inviteRequestFailed(getString(R.string.server_does_not_support_easy_onboarding_invites));
1628            return;
1629        }
1630        final IqPacket request = new IqPacket(IqPacket.TYPE.SET);
1631        request.setTo(jid);
1632        final Element command = request.addChild("command", Namespace.COMMANDS);
1633        command.setAttribute("node", Namespace.COMMANDS);
1634        command.setAttribute("action", "execute");
1635        sendIqPacket(account, request, (a, response) -> {
1636            if (response.getType() == IqPacket.TYPE.RESULT) {
1637                final Element resultCommand = response.findChild("command", Namespace.COMMANDS);
1638                final Element x = resultCommand == null ? null : resultCommand.findChild("x", Namespace.DATA);
1639                if (x != null) {
1640                    final Data data = Data.parse(x);
1641                    final String uri = data.getValue("uri");
1642                    final String landingUrl = data.getValue("landing-url");
1643                    if (uri != null) {
1644                        final EasyOnboardingInvite invite = new EasyOnboardingInvite(jid.getDomain().toEscapedString(), uri, landingUrl);
1645                        callback.inviteRequested(invite);
1646                        return;
1647                    }
1648                }
1649                callback.inviteRequestFailed(getString(R.string.unable_to_parse_invite));
1650                Log.d(Config.LOGTAG, response.toString());
1651            } else if (response.getType() == IqPacket.TYPE.ERROR) {
1652                callback.inviteRequestFailed(IqParser.extractErrorMessage(response));
1653            } else {
1654                callback.inviteRequestFailed(getString(R.string.remote_server_timeout));
1655            }
1656        });
1657
1658    }
1659
1660    public void fetchRosterFromServer(final Account account) {
1661        final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1662        if (!"".equals(account.getRosterVersion())) {
1663            Log.d(Config.LOGTAG, account.getJid().asBareJid()
1664                    + ": fetching roster version " + account.getRosterVersion());
1665        } else {
1666            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching roster");
1667        }
1668        iqPacket.query(Namespace.ROSTER).setAttribute("ver", account.getRosterVersion());
1669        sendIqPacket(account, iqPacket, mIqParser);
1670    }
1671
1672    public void fetchBookmarks(final Account account) {
1673        final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1674        final Element query = iqPacket.query("jabber:iq:private");
1675        query.addChild("storage", Namespace.BOOKMARKS);
1676        final OnIqPacketReceived callback = (a, response) -> {
1677            if (response.getType() == IqPacket.TYPE.RESULT) {
1678                final Element query1 = response.query();
1679                final Element storage = query1.findChild("storage", "storage:bookmarks");
1680                Map<Jid, Bookmark> bookmarks = Bookmark.parseFromStorage(storage, account);
1681                processBookmarksInitial(a, bookmarks, false);
1682            } else {
1683                Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": could not fetch bookmarks");
1684            }
1685        };
1686        sendIqPacket(account, iqPacket, callback);
1687    }
1688
1689    public void fetchBookmarks2(final Account account) {
1690        final IqPacket retrieve = mIqGenerator.retrieveBookmarks();
1691        sendIqPacket(account, retrieve, new OnIqPacketReceived() {
1692            @Override
1693            public void onIqPacketReceived(final Account account, final IqPacket response) {
1694                if (response.getType() == IqPacket.TYPE.RESULT) {
1695                    final Element pubsub = response.findChild("pubsub", Namespace.PUBSUB);
1696                    final Map<Jid, Bookmark> bookmarks = Bookmark.parseFromPubsub(pubsub, account);
1697                    processBookmarksInitial(account, bookmarks, true);
1698                }
1699            }
1700        });
1701    }
1702
1703    public void processBookmarksInitial(Account account, Map<Jid, Bookmark> bookmarks, final boolean pep) {
1704        final Set<Jid> previousBookmarks = account.getBookmarkedJids();
1705        final boolean synchronizeWithBookmarks = synchronizeWithBookmarks();
1706        for (Bookmark bookmark : bookmarks.values()) {
1707            previousBookmarks.remove(bookmark.getJid().asBareJid());
1708            processModifiedBookmark(bookmark, pep, synchronizeWithBookmarks);
1709        }
1710        if (pep && synchronizeWithBookmarks) {
1711            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": " + previousBookmarks.size() + " bookmarks have been removed");
1712            for (Jid jid : previousBookmarks) {
1713                processDeletedBookmark(account, jid);
1714            }
1715        }
1716        account.setBookmarks(bookmarks);
1717    }
1718
1719    public void processDeletedBookmark(Account account, Jid jid) {
1720        final Conversation conversation = find(account, jid);
1721        if (conversation != null && conversation.getMucOptions().getError() == MucOptions.Error.DESTROYED) {
1722            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving destroyed conference (" + conversation.getJid() + ") after receiving pep");
1723            archiveConversation(conversation, false);
1724        }
1725    }
1726
1727    private void processModifiedBookmark(Bookmark bookmark, final boolean pep, final boolean synchronizeWithBookmarks) {
1728        final Account account = bookmark.getAccount();
1729        Conversation conversation = find(bookmark);
1730        if (conversation != null) {
1731            if (conversation.getMode() != Conversation.MODE_MULTI) {
1732                return;
1733            }
1734            bookmark.setConversation(conversation);
1735            if (pep && synchronizeWithBookmarks && !bookmark.autojoin()) {
1736                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conference (" + conversation.getJid() + ") after receiving pep");
1737                archiveConversation(conversation, false);
1738            } else {
1739                final MucOptions mucOptions = conversation.getMucOptions();
1740                if (mucOptions.getError() == MucOptions.Error.NICK_IN_USE) {
1741                    final String current = mucOptions.getActualNick();
1742                    final String proposed = mucOptions.getProposedNick();
1743                    if (current != null && !current.equals(proposed)) {
1744                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": proposed nick changed after bookmark push " + current + "->" + proposed);
1745                        joinMuc(conversation);
1746                    }
1747                }
1748            }
1749        } else if (synchronizeWithBookmarks && bookmark.autojoin()) {
1750            conversation = findOrCreateConversation(account, bookmark.getFullJid(), true, true, false);
1751            bookmark.setConversation(conversation);
1752        }
1753    }
1754
1755    public void processModifiedBookmark(Bookmark bookmark) {
1756        final boolean synchronizeWithBookmarks = synchronizeWithBookmarks();
1757        processModifiedBookmark(bookmark, true, synchronizeWithBookmarks);
1758    }
1759
1760    public void createBookmark(final Account account, final Bookmark bookmark) {
1761        account.putBookmark(bookmark);
1762        final XmppConnection connection = account.getXmppConnection();
1763        if (connection.getFeatures().bookmarks2()) {
1764            final Element item = mIqGenerator.publishBookmarkItem(bookmark);
1765            pushNodeAndEnforcePublishOptions(account, Namespace.BOOKMARKS2, item, bookmark.getJid().asBareJid().toEscapedString(), PublishOptions.persistentWhitelistAccessMaxItems());
1766        } else if (connection.getFeatures().bookmarksConversion()) {
1767            pushBookmarksPep(account);
1768        } else {
1769            pushBookmarksPrivateXml(account);
1770        }
1771    }
1772
1773    public void deleteBookmark(final Account account, final Bookmark bookmark) {
1774        account.removeBookmark(bookmark);
1775        final XmppConnection connection = account.getXmppConnection();
1776        if (connection.getFeatures().bookmarks2()) {
1777            IqPacket request = mIqGenerator.deleteItem(Namespace.BOOKMARKS2, bookmark.getJid().asBareJid().toEscapedString());
1778            sendIqPacket(account, request, (a, response) -> {
1779                if (response.getType() == IqPacket.TYPE.ERROR) {
1780                    Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": unable to delete bookmark " + response.getError());
1781                }
1782            });
1783        } else if (connection.getFeatures().bookmarksConversion()) {
1784            pushBookmarksPep(account);
1785        } else {
1786            pushBookmarksPrivateXml(account);
1787        }
1788    }
1789
1790    private void pushBookmarksPrivateXml(Account account) {
1791        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via private xml");
1792        IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
1793        Element query = iqPacket.query("jabber:iq:private");
1794        Element storage = query.addChild("storage", "storage:bookmarks");
1795        for (Bookmark bookmark : account.getBookmarks()) {
1796            storage.addChild(bookmark);
1797        }
1798        sendIqPacket(account, iqPacket, mDefaultIqHandler);
1799    }
1800
1801    private void pushBookmarksPep(Account account) {
1802        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via pep");
1803        Element storage = new Element("storage", "storage:bookmarks");
1804        for (Bookmark bookmark : account.getBookmarks()) {
1805            storage.addChild(bookmark);
1806        }
1807        pushNodeAndEnforcePublishOptions(account, Namespace.BOOKMARKS, storage, "current", PublishOptions.persistentWhitelistAccess());
1808
1809    }
1810
1811    private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final String id, final Bundle options) {
1812        pushNodeAndEnforcePublishOptions(account, node, element, id, options, true);
1813
1814    }
1815
1816    private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final String id, final Bundle options, final boolean retry) {
1817        final IqPacket packet = mIqGenerator.publishElement(node, element, id, options);
1818        sendIqPacket(account, packet, (a, response) -> {
1819            if (response.getType() == IqPacket.TYPE.RESULT) {
1820                return;
1821            }
1822            if (retry && PublishOptions.preconditionNotMet(response)) {
1823                pushNodeConfiguration(account, node, options, new OnConfigurationPushed() {
1824                    @Override
1825                    public void onPushSucceeded() {
1826                        pushNodeAndEnforcePublishOptions(account, node, element, id, options, false);
1827                    }
1828
1829                    @Override
1830                    public void onPushFailed() {
1831                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to push node configuration (" + node + ")");
1832                    }
1833                });
1834            } else {
1835                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": error publishing bookmarks (retry=" + Boolean.toString(retry) + ") " + response);
1836            }
1837        });
1838    }
1839
1840    private void restoreFromDatabase() {
1841        synchronized (this.conversations) {
1842            final Map<String, Account> accountLookupTable = new Hashtable<>();
1843            for (Account account : this.accounts) {
1844                accountLookupTable.put(account.getUuid(), account);
1845            }
1846            Log.d(Config.LOGTAG, "restoring conversations...");
1847            final long startTimeConversationsRestore = SystemClock.elapsedRealtime();
1848            this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
1849            for (Iterator<Conversation> iterator = conversations.listIterator(); iterator.hasNext(); ) {
1850                Conversation conversation = iterator.next();
1851                Account account = accountLookupTable.get(conversation.getAccountUuid());
1852                if (account != null) {
1853                    conversation.setAccount(account);
1854                } else {
1855                    Log.e(Config.LOGTAG, "unable to restore Conversations with " + conversation.getJid());
1856                    iterator.remove();
1857                }
1858            }
1859            long diffConversationsRestore = SystemClock.elapsedRealtime() - startTimeConversationsRestore;
1860            Log.d(Config.LOGTAG, "finished restoring conversations in " + diffConversationsRestore + "ms");
1861            Runnable runnable = () -> {
1862                long deletionDate = getAutomaticMessageDeletionDate();
1863                mLastExpiryRun.set(SystemClock.elapsedRealtime());
1864                if (deletionDate > 0) {
1865                    Log.d(Config.LOGTAG, "deleting messages that are older than " + AbstractGenerator.getTimestamp(deletionDate));
1866                    databaseBackend.expireOldMessages(deletionDate);
1867                }
1868                Log.d(Config.LOGTAG, "restoring roster...");
1869                for (Account account : accounts) {
1870                    databaseBackend.readRoster(account.getRoster());
1871                    account.initAccountServices(XmppConnectionService.this); //roster needs to be loaded at this stage
1872                }
1873                getBitmapCache().evictAll();
1874                loadPhoneContacts();
1875                Log.d(Config.LOGTAG, "restoring messages...");
1876                final long startMessageRestore = SystemClock.elapsedRealtime();
1877                final Conversation quickLoad = QuickLoader.get(this.conversations);
1878                if (quickLoad != null) {
1879                    restoreMessages(quickLoad);
1880                    updateConversationUi();
1881                    final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
1882                    Log.d(Config.LOGTAG, "quickly restored " + quickLoad.getName() + " after " + diffMessageRestore + "ms");
1883                }
1884                for (Conversation conversation : this.conversations) {
1885                    if (quickLoad != conversation) {
1886                        restoreMessages(conversation);
1887                    }
1888                }
1889                mNotificationService.finishBacklog(false);
1890                restoredFromDatabaseLatch.countDown();
1891                final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
1892                Log.d(Config.LOGTAG, "finished restoring messages in " + diffMessageRestore + "ms");
1893                updateConversationUi();
1894            };
1895            mDatabaseReaderExecutor.execute(runnable); //will contain one write command (expiry) but that's fine
1896        }
1897    }
1898
1899    private void restoreMessages(Conversation conversation) {
1900        conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1901        conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
1902        conversation.findUnreadMessages(message -> mNotificationService.pushFromBacklog(message));
1903    }
1904
1905    public void loadPhoneContacts() {
1906        mContactMergerExecutor.execute(() -> {
1907            Map<Jid, JabberIdContact> contacts = JabberIdContact.load(this);
1908            Log.d(Config.LOGTAG, "start merging phone contacts with roster");
1909            for (Account account : accounts) {
1910                List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts(JabberIdContact.class);
1911                for (JabberIdContact jidContact : contacts.values()) {
1912                    final Contact contact = account.getRoster().getContact(jidContact.getJid());
1913                    boolean needsCacheClean = contact.setPhoneContact(jidContact);
1914                    if (needsCacheClean) {
1915                        getAvatarService().clear(contact);
1916                    }
1917                    withSystemAccounts.remove(contact);
1918                }
1919                for (Contact contact : withSystemAccounts) {
1920                    boolean needsCacheClean = contact.unsetPhoneContact(JabberIdContact.class);
1921                    if (needsCacheClean) {
1922                        getAvatarService().clear(contact);
1923                    }
1924                }
1925            }
1926            Log.d(Config.LOGTAG, "finished merging phone contacts");
1927            mShortcutService.refresh(mInitialAddressbookSyncCompleted.compareAndSet(false, true));
1928            updateRosterUi();
1929            mQuickConversationsService.considerSync();
1930        });
1931    }
1932
1933
1934    public void syncRoster(final Account account) {
1935        mRosterSyncTaskManager.execute(account, () -> databaseBackend.writeRoster(account.getRoster()));
1936    }
1937
1938    public List<Conversation> getConversations() {
1939        return this.conversations;
1940    }
1941
1942    private void markFileDeleted(final File file) {
1943        synchronized (FILENAMES_TO_IGNORE_DELETION) {
1944            if (FILENAMES_TO_IGNORE_DELETION.remove(file.getAbsolutePath())) {
1945                Log.d(Config.LOGTAG, "ignored deletion of " + file.getAbsolutePath());
1946                return;
1947            }
1948        }
1949        final boolean isInternalFile = fileBackend.isInternalFile(file);
1950        final List<String> uuids = databaseBackend.markFileAsDeleted(file, isInternalFile);
1951        Log.d(Config.LOGTAG, "deleted file " + file.getAbsolutePath() + " internal=" + isInternalFile + ", database hits=" + uuids.size());
1952        markUuidsAsDeletedFiles(uuids);
1953    }
1954
1955    private void markUuidsAsDeletedFiles(List<String> uuids) {
1956        boolean deleted = false;
1957        for (Conversation conversation : getConversations()) {
1958            deleted |= conversation.markAsDeleted(uuids);
1959        }
1960        for (final String uuid : uuids) {
1961            evictPreview(uuid);
1962        }
1963        if (deleted) {
1964            updateConversationUi();
1965        }
1966    }
1967
1968    private void markChangedFiles(List<DatabaseBackend.FilePathInfo> infos) {
1969        boolean changed = false;
1970        for (Conversation conversation : getConversations()) {
1971            changed |= conversation.markAsChanged(infos);
1972        }
1973        if (changed) {
1974            updateConversationUi();
1975        }
1976    }
1977
1978    public void populateWithOrderedConversations(final List<Conversation> list) {
1979        populateWithOrderedConversations(list, true, true);
1980    }
1981
1982    public void populateWithOrderedConversations(final List<Conversation> list, final boolean includeNoFileUpload) {
1983        populateWithOrderedConversations(list, includeNoFileUpload, true);
1984    }
1985
1986    public void populateWithOrderedConversations(final List<Conversation> list, final boolean includeNoFileUpload, final boolean sort) {
1987        final List<String> orderedUuids;
1988        if (sort) {
1989            orderedUuids = null;
1990        } else {
1991            orderedUuids = new ArrayList<>();
1992            for (Conversation conversation : list) {
1993                orderedUuids.add(conversation.getUuid());
1994            }
1995        }
1996        list.clear();
1997        if (includeNoFileUpload) {
1998            list.addAll(getConversations());
1999        } else {
2000            for (Conversation conversation : getConversations()) {
2001                if (conversation.getMode() == Conversation.MODE_SINGLE
2002                        || (conversation.getAccount().httpUploadAvailable() && conversation.getMucOptions().participating())) {
2003                    list.add(conversation);
2004                }
2005            }
2006        }
2007        try {
2008            if (orderedUuids != null) {
2009                Collections.sort(list, (a, b) -> {
2010                    final int indexA = orderedUuids.indexOf(a.getUuid());
2011                    final int indexB = orderedUuids.indexOf(b.getUuid());
2012                    if (indexA == -1 || indexB == -1 || indexA == indexB) {
2013                        return a.compareTo(b);
2014                    }
2015                    return indexA - indexB;
2016                });
2017            } else {
2018                Collections.sort(list);
2019            }
2020        } catch (IllegalArgumentException e) {
2021            //ignore
2022        }
2023    }
2024
2025    public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
2026        if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation, callback)) {
2027            return;
2028        } else if (timestamp == 0) {
2029            return;
2030        }
2031        Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
2032        final Runnable runnable = () -> {
2033            final Account account = conversation.getAccount();
2034            List<Message> messages = databaseBackend.getMessages(conversation, 50, timestamp);
2035            if (messages.size() > 0) {
2036                conversation.addAll(0, messages);
2037                callback.onMoreMessagesLoaded(messages.size(), conversation);
2038            } else if (conversation.hasMessagesLeftOnServer()
2039                    && account.isOnlineAndConnected()
2040                    && conversation.getLastClearHistory().getTimestamp() == 0) {
2041                final boolean mamAvailable;
2042                if (conversation.getMode() == Conversation.MODE_SINGLE) {
2043                    mamAvailable = account.getXmppConnection().getFeatures().mam() && !conversation.getContact().isBlocked();
2044                } else {
2045                    mamAvailable = conversation.getMucOptions().mamSupport();
2046                }
2047                if (mamAvailable) {
2048                    MessageArchiveService.Query query = getMessageArchiveService().query(conversation, new MamReference(0), timestamp, false);
2049                    if (query != null) {
2050                        query.setCallback(callback);
2051                        callback.informUser(R.string.fetching_history_from_server);
2052                    } else {
2053                        callback.informUser(R.string.not_fetching_history_retention_period);
2054                    }
2055
2056                }
2057            }
2058        };
2059        mDatabaseReaderExecutor.execute(runnable);
2060    }
2061
2062    public List<Account> getAccounts() {
2063        return this.accounts;
2064    }
2065
2066
2067    /**
2068     * 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)
2069     */
2070    public List<Conversation> findAllConferencesWith(Contact contact) {
2071        final ArrayList<Conversation> results = new ArrayList<>();
2072        for (final Conversation c : conversations) {
2073            if (c.getMode() != Conversation.MODE_MULTI) {
2074                continue;
2075            }
2076            final MucOptions mucOptions = c.getMucOptions();
2077            if (c.getJid().asBareJid().equals(contact.getJid().asBareJid()) || (mucOptions != null && mucOptions.isContactInRoom(contact))) {
2078                results.add(c);
2079            }
2080        }
2081        return results;
2082    }
2083
2084    public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
2085        for (final Conversation conversation : haystack) {
2086            if (conversation.getContact() == contact) {
2087                return conversation;
2088            }
2089        }
2090        return null;
2091    }
2092
2093    public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
2094        if (jid == null) {
2095            return null;
2096        }
2097        for (final Conversation conversation : haystack) {
2098            if ((account == null || conversation.getAccount() == account)
2099                    && (conversation.getJid().asBareJid().equals(jid.asBareJid()))) {
2100                return conversation;
2101            }
2102        }
2103        return null;
2104    }
2105
2106    public boolean isConversationsListEmpty(final Conversation ignore) {
2107        synchronized (this.conversations) {
2108            final int size = this.conversations.size();
2109            return size == 0 || size == 1 && this.conversations.get(0) == ignore;
2110        }
2111    }
2112
2113    public boolean isConversationStillOpen(final Conversation conversation) {
2114        synchronized (this.conversations) {
2115            for (Conversation current : this.conversations) {
2116                if (current == conversation) {
2117                    return true;
2118                }
2119            }
2120        }
2121        return false;
2122    }
2123
2124    public Conversation findOrCreateConversation(Account account, Jid jid, boolean muc, final boolean async) {
2125        return this.findOrCreateConversation(account, jid, muc, false, async);
2126    }
2127
2128    public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final boolean async) {
2129        return this.findOrCreateConversation(account, jid, muc, joinAfterCreate, null, async);
2130    }
2131
2132    public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final MessageArchiveService.Query query, final boolean async) {
2133        synchronized (this.conversations) {
2134            Conversation conversation = find(account, jid);
2135            if (conversation != null) {
2136                return conversation;
2137            }
2138            conversation = databaseBackend.findConversation(account, jid);
2139            final boolean loadMessagesFromDb;
2140            if (conversation != null) {
2141                conversation.setStatus(Conversation.STATUS_AVAILABLE);
2142                conversation.setAccount(account);
2143                if (muc) {
2144                    conversation.setMode(Conversation.MODE_MULTI);
2145                    conversation.setContactJid(jid);
2146                } else {
2147                    conversation.setMode(Conversation.MODE_SINGLE);
2148                    conversation.setContactJid(jid.asBareJid());
2149                }
2150                databaseBackend.updateConversation(conversation);
2151                loadMessagesFromDb = conversation.messagesLoaded.compareAndSet(true, false);
2152            } else {
2153                String conversationName;
2154                Contact contact = account.getRoster().getContact(jid);
2155                if (contact != null) {
2156                    conversationName = contact.getDisplayName();
2157                } else {
2158                    conversationName = jid.getLocal();
2159                }
2160                if (muc) {
2161                    conversation = new Conversation(conversationName, account, jid,
2162                            Conversation.MODE_MULTI);
2163                } else {
2164                    conversation = new Conversation(conversationName, account, jid.asBareJid(),
2165                            Conversation.MODE_SINGLE);
2166                }
2167                this.databaseBackend.createConversation(conversation);
2168                loadMessagesFromDb = false;
2169            }
2170            final Conversation c = conversation;
2171            final Runnable runnable = () -> {
2172                if (loadMessagesFromDb) {
2173                    c.addAll(0, databaseBackend.getMessages(c, Config.PAGE_SIZE));
2174                    updateConversationUi();
2175                    c.messagesLoaded.set(true);
2176                }
2177                if (account.getXmppConnection() != null
2178                        && !c.getContact().isBlocked()
2179                        && account.getXmppConnection().getFeatures().mam()
2180                        && !muc) {
2181                    if (query == null) {
2182                        mMessageArchiveService.query(c);
2183                    } else {
2184                        if (query.getConversation() == null) {
2185                            mMessageArchiveService.query(c, query.getStart(), query.isCatchup());
2186                        }
2187                    }
2188                }
2189                if (joinAfterCreate) {
2190                    joinMuc(c);
2191                }
2192            };
2193            if (async) {
2194                mDatabaseReaderExecutor.execute(runnable);
2195            } else {
2196                runnable.run();
2197            }
2198            this.conversations.add(conversation);
2199            updateConversationUi();
2200            return conversation;
2201        }
2202    }
2203
2204    public void archiveConversation(Conversation conversation) {
2205        archiveConversation(conversation, true);
2206    }
2207
2208    private void archiveConversation(Conversation conversation, final boolean maySynchronizeWithBookmarks) {
2209        getNotificationService().clear(conversation);
2210        conversation.setStatus(Conversation.STATUS_ARCHIVED);
2211        conversation.setNextMessage(null);
2212        synchronized (this.conversations) {
2213            getMessageArchiveService().kill(conversation);
2214            if (conversation.getMode() == Conversation.MODE_MULTI) {
2215                if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2216                    final Bookmark bookmark = conversation.getBookmark();
2217                    if (maySynchronizeWithBookmarks && bookmark != null && synchronizeWithBookmarks()) {
2218                        if (conversation.getMucOptions().getError() == MucOptions.Error.DESTROYED) {
2219                            Account account = bookmark.getAccount();
2220                            bookmark.setConversation(null);
2221                            deleteBookmark(account, bookmark);
2222                        } else if (bookmark.autojoin()) {
2223                            bookmark.setAutojoin(false);
2224                            createBookmark(bookmark.getAccount(), bookmark);
2225                        }
2226                    }
2227                }
2228                leaveMuc(conversation);
2229            } else {
2230                if (conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2231                    stopPresenceUpdatesTo(conversation.getContact());
2232                }
2233            }
2234            updateConversation(conversation);
2235            this.conversations.remove(conversation);
2236            updateConversationUi();
2237        }
2238    }
2239
2240    public void stopPresenceUpdatesTo(Contact contact) {
2241        Log.d(Config.LOGTAG, "Canceling presence request from " + contact.getJid().toString());
2242        sendPresencePacket(contact.getAccount(), mPresenceGenerator.stopPresenceUpdatesTo(contact));
2243        contact.resetOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
2244    }
2245
2246    public void createAccount(final Account account) {
2247        account.initAccountServices(this);
2248        databaseBackend.createAccount(account);
2249        this.accounts.add(account);
2250        this.reconnectAccountInBackground(account);
2251        updateAccountUi();
2252        syncEnabledAccountSetting();
2253        toggleForegroundService();
2254    }
2255
2256    private void syncEnabledAccountSetting() {
2257        final boolean hasEnabledAccounts = hasEnabledAccounts();
2258        getPreferences().edit().putBoolean(EventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts).apply();
2259        toggleSetProfilePictureActivity(hasEnabledAccounts);
2260    }
2261
2262    private void toggleSetProfilePictureActivity(final boolean enabled) {
2263        try {
2264            final ComponentName name = new ComponentName(this, ChooseAccountForProfilePictureActivity.class);
2265            final int targetState = enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
2266            getPackageManager().setComponentEnabledSetting(name, targetState, PackageManager.DONT_KILL_APP);
2267        } catch (IllegalStateException e) {
2268            Log.d(Config.LOGTAG, "unable to toggle profile picture actvitiy");
2269        }
2270    }
2271
2272    private void provisionAccount(final String address, final String password) {
2273        final Jid jid = Jid.ofEscaped(address);
2274        final Account account = new Account(jid, password);
2275        account.setOption(Account.OPTION_DISABLED, true);
2276        Log.d(Config.LOGTAG, jid.asBareJid().toEscapedString() + ": provisioning account");
2277        createAccount(account);
2278    }
2279
2280    public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
2281        new Thread(() -> {
2282            try {
2283                final X509Certificate[] chain = KeyChain.getCertificateChain(this, alias);
2284                final X509Certificate cert = chain != null && chain.length > 0 ? chain[0] : null;
2285                if (cert == null) {
2286                    callback.informUser(R.string.unable_to_parse_certificate);
2287                    return;
2288                }
2289                Pair<Jid, String> info = CryptoHelper.extractJidAndName(cert);
2290                if (info == null) {
2291                    callback.informUser(R.string.certificate_does_not_contain_jid);
2292                    return;
2293                }
2294                if (findAccountByJid(info.first) == null) {
2295                    final Account account = new Account(info.first, "");
2296                    account.setPrivateKeyAlias(alias);
2297                    account.setOption(Account.OPTION_DISABLED, true);
2298                    account.setOption(Account.OPTION_FIXED_USERNAME, true);
2299                    account.setDisplayName(info.second);
2300                    createAccount(account);
2301                    callback.onAccountCreated(account);
2302                    if (Config.X509_VERIFICATION) {
2303                        try {
2304                            getMemorizingTrustManager().getNonInteractive(account.getServer()).checkClientTrusted(chain, "RSA");
2305                        } catch (CertificateException e) {
2306                            callback.informUser(R.string.certificate_chain_is_not_trusted);
2307                        }
2308                    }
2309                } else {
2310                    callback.informUser(R.string.account_already_exists);
2311                }
2312            } catch (Exception e) {
2313                callback.informUser(R.string.unable_to_parse_certificate);
2314            }
2315        }).start();
2316
2317    }
2318
2319    public void updateKeyInAccount(final Account account, final String alias) {
2320        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": update key in account " + alias);
2321        try {
2322            X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
2323            Log.d(Config.LOGTAG, account.getJid().asBareJid() + " loaded certificate chain");
2324            Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
2325            if (info == null) {
2326                showErrorToastInUi(R.string.certificate_does_not_contain_jid);
2327                return;
2328            }
2329            if (account.getJid().asBareJid().equals(info.first)) {
2330                account.setPrivateKeyAlias(alias);
2331                account.setDisplayName(info.second);
2332                databaseBackend.updateAccount(account);
2333                if (Config.X509_VERIFICATION) {
2334                    try {
2335                        getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
2336                    } catch (CertificateException e) {
2337                        showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
2338                    }
2339                    account.getAxolotlService().regenerateKeys(true);
2340                }
2341            } else {
2342                showErrorToastInUi(R.string.jid_does_not_match_certificate);
2343            }
2344        } catch (Exception e) {
2345            e.printStackTrace();
2346        }
2347    }
2348
2349    public boolean updateAccount(final Account account) {
2350        if (databaseBackend.updateAccount(account)) {
2351            account.setShowErrorNotification(true);
2352            this.statusListener.onStatusChanged(account);
2353            databaseBackend.updateAccount(account);
2354            reconnectAccountInBackground(account);
2355            updateAccountUi();
2356            getNotificationService().updateErrorNotification();
2357            toggleForegroundService();
2358            syncEnabledAccountSetting();
2359            mChannelDiscoveryService.cleanCache();
2360            return true;
2361        } else {
2362            return false;
2363        }
2364    }
2365
2366    public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
2367        final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
2368        sendIqPacket(account, iq, (a, packet) -> {
2369            if (packet.getType() == IqPacket.TYPE.RESULT) {
2370                a.setPassword(newPassword);
2371                a.setOption(Account.OPTION_MAGIC_CREATE, false);
2372                databaseBackend.updateAccount(a);
2373                callback.onPasswordChangeSucceeded();
2374            } else {
2375                callback.onPasswordChangeFailed();
2376            }
2377        });
2378    }
2379
2380    public void deleteAccount(final Account account) {
2381        final boolean connected = account.getStatus() == Account.State.ONLINE;
2382        synchronized (this.conversations) {
2383            if (connected) {
2384                account.getAxolotlService().deleteOmemoIdentity();
2385            }
2386            for (final Conversation conversation : conversations) {
2387                if (conversation.getAccount() == account) {
2388                    if (conversation.getMode() == Conversation.MODE_MULTI) {
2389                        if (connected) {
2390                            leaveMuc(conversation);
2391                        }
2392                    }
2393                    conversations.remove(conversation);
2394                    mNotificationService.clear(conversation);
2395                }
2396            }
2397            if (account.getXmppConnection() != null) {
2398                new Thread(() -> disconnect(account, !connected)).start();
2399            }
2400            final Runnable runnable = () -> {
2401                if (!databaseBackend.deleteAccount(account)) {
2402                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to delete account");
2403                }
2404            };
2405            mDatabaseWriterExecutor.execute(runnable);
2406            this.accounts.remove(account);
2407            this.mRosterSyncTaskManager.clear(account);
2408            updateAccountUi();
2409            mNotificationService.updateErrorNotification();
2410            syncEnabledAccountSetting();
2411            toggleForegroundService();
2412        }
2413    }
2414
2415    public void setOnConversationListChangedListener(OnConversationUpdate listener) {
2416        final boolean remainingListeners;
2417        synchronized (LISTENER_LOCK) {
2418            remainingListeners = checkListeners();
2419            if (!this.mOnConversationUpdates.add(listener)) {
2420                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as ConversationListChangedListener");
2421            }
2422            this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
2423        }
2424        if (remainingListeners) {
2425            switchToForeground();
2426        }
2427    }
2428
2429    public void removeOnConversationListChangedListener(OnConversationUpdate listener) {
2430        final boolean remainingListeners;
2431        synchronized (LISTENER_LOCK) {
2432            this.mOnConversationUpdates.remove(listener);
2433            this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
2434            remainingListeners = checkListeners();
2435        }
2436        if (remainingListeners) {
2437            switchToBackground();
2438        }
2439    }
2440
2441    public void setOnShowErrorToastListener(OnShowErrorToast listener) {
2442        final boolean remainingListeners;
2443        synchronized (LISTENER_LOCK) {
2444            remainingListeners = checkListeners();
2445            if (!this.mOnShowErrorToasts.add(listener)) {
2446                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnShowErrorToastListener");
2447            }
2448        }
2449        if (remainingListeners) {
2450            switchToForeground();
2451        }
2452    }
2453
2454    public void removeOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
2455        final boolean remainingListeners;
2456        synchronized (LISTENER_LOCK) {
2457            this.mOnShowErrorToasts.remove(onShowErrorToast);
2458            remainingListeners = checkListeners();
2459        }
2460        if (remainingListeners) {
2461            switchToBackground();
2462        }
2463    }
2464
2465    public void setOnAccountListChangedListener(OnAccountUpdate listener) {
2466        final boolean remainingListeners;
2467        synchronized (LISTENER_LOCK) {
2468            remainingListeners = checkListeners();
2469            if (!this.mOnAccountUpdates.add(listener)) {
2470                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnAccountListChangedtListener");
2471            }
2472        }
2473        if (remainingListeners) {
2474            switchToForeground();
2475        }
2476    }
2477
2478    public void removeOnAccountListChangedListener(OnAccountUpdate listener) {
2479        final boolean remainingListeners;
2480        synchronized (LISTENER_LOCK) {
2481            this.mOnAccountUpdates.remove(listener);
2482            remainingListeners = checkListeners();
2483        }
2484        if (remainingListeners) {
2485            switchToBackground();
2486        }
2487    }
2488
2489    public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
2490        final boolean remainingListeners;
2491        synchronized (LISTENER_LOCK) {
2492            remainingListeners = checkListeners();
2493            if (!this.mOnCaptchaRequested.add(listener)) {
2494                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnCaptchaRequestListener");
2495            }
2496        }
2497        if (remainingListeners) {
2498            switchToForeground();
2499        }
2500    }
2501
2502    public void removeOnCaptchaRequestedListener(OnCaptchaRequested listener) {
2503        final boolean remainingListeners;
2504        synchronized (LISTENER_LOCK) {
2505            this.mOnCaptchaRequested.remove(listener);
2506            remainingListeners = checkListeners();
2507        }
2508        if (remainingListeners) {
2509            switchToBackground();
2510        }
2511    }
2512
2513    public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
2514        final boolean remainingListeners;
2515        synchronized (LISTENER_LOCK) {
2516            remainingListeners = checkListeners();
2517            if (!this.mOnRosterUpdates.add(listener)) {
2518                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnRosterUpdateListener");
2519            }
2520        }
2521        if (remainingListeners) {
2522            switchToForeground();
2523        }
2524    }
2525
2526    public void removeOnRosterUpdateListener(final OnRosterUpdate listener) {
2527        final boolean remainingListeners;
2528        synchronized (LISTENER_LOCK) {
2529            this.mOnRosterUpdates.remove(listener);
2530            remainingListeners = checkListeners();
2531        }
2532        if (remainingListeners) {
2533            switchToBackground();
2534        }
2535    }
2536
2537    public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2538        final boolean remainingListeners;
2539        synchronized (LISTENER_LOCK) {
2540            remainingListeners = checkListeners();
2541            if (!this.mOnUpdateBlocklist.add(listener)) {
2542                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnUpdateBlocklistListener");
2543            }
2544        }
2545        if (remainingListeners) {
2546            switchToForeground();
2547        }
2548    }
2549
2550    public void removeOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2551        final boolean remainingListeners;
2552        synchronized (LISTENER_LOCK) {
2553            this.mOnUpdateBlocklist.remove(listener);
2554            remainingListeners = checkListeners();
2555        }
2556        if (remainingListeners) {
2557            switchToBackground();
2558        }
2559    }
2560
2561    public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
2562        final boolean remainingListeners;
2563        synchronized (LISTENER_LOCK) {
2564            remainingListeners = checkListeners();
2565            if (!this.mOnKeyStatusUpdated.add(listener)) {
2566                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnKeyStatusUpdateListener");
2567            }
2568        }
2569        if (remainingListeners) {
2570            switchToForeground();
2571        }
2572    }
2573
2574    public void removeOnNewKeysAvailableListener(final OnKeyStatusUpdated listener) {
2575        final boolean remainingListeners;
2576        synchronized (LISTENER_LOCK) {
2577            this.mOnKeyStatusUpdated.remove(listener);
2578            remainingListeners = checkListeners();
2579        }
2580        if (remainingListeners) {
2581            switchToBackground();
2582        }
2583    }
2584
2585    public void setOnRtpConnectionUpdateListener(final OnJingleRtpConnectionUpdate listener) {
2586        final boolean remainingListeners;
2587        synchronized (LISTENER_LOCK) {
2588            remainingListeners = checkListeners();
2589            if (!this.onJingleRtpConnectionUpdate.add(listener)) {
2590                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnJingleRtpConnectionUpdate");
2591            }
2592        }
2593        if (remainingListeners) {
2594            switchToForeground();
2595        }
2596    }
2597
2598    public void removeRtpConnectionUpdateListener(final OnJingleRtpConnectionUpdate listener) {
2599        final boolean remainingListeners;
2600        synchronized (LISTENER_LOCK) {
2601            this.onJingleRtpConnectionUpdate.remove(listener);
2602            remainingListeners = checkListeners();
2603        }
2604        if (remainingListeners) {
2605            switchToBackground();
2606        }
2607    }
2608
2609    public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
2610        final boolean remainingListeners;
2611        synchronized (LISTENER_LOCK) {
2612            remainingListeners = checkListeners();
2613            if (!this.mOnMucRosterUpdate.add(listener)) {
2614                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnMucRosterListener");
2615            }
2616        }
2617        if (remainingListeners) {
2618            switchToForeground();
2619        }
2620    }
2621
2622    public void removeOnMucRosterUpdateListener(final OnMucRosterUpdate listener) {
2623        final boolean remainingListeners;
2624        synchronized (LISTENER_LOCK) {
2625            this.mOnMucRosterUpdate.remove(listener);
2626            remainingListeners = checkListeners();
2627        }
2628        if (remainingListeners) {
2629            switchToBackground();
2630        }
2631    }
2632
2633    public boolean checkListeners() {
2634        return (this.mOnAccountUpdates.size() == 0
2635                && this.mOnConversationUpdates.size() == 0
2636                && this.mOnRosterUpdates.size() == 0
2637                && this.mOnCaptchaRequested.size() == 0
2638                && this.mOnMucRosterUpdate.size() == 0
2639                && this.mOnUpdateBlocklist.size() == 0
2640                && this.mOnShowErrorToasts.size() == 0
2641                && this.onJingleRtpConnectionUpdate.size() == 0
2642                && this.mOnKeyStatusUpdated.size() == 0);
2643    }
2644
2645    private void switchToForeground() {
2646        final boolean broadcastLastActivity = broadcastLastActivity();
2647        for (Conversation conversation : getConversations()) {
2648            if (conversation.getMode() == Conversation.MODE_MULTI) {
2649                conversation.getMucOptions().resetChatState();
2650            } else {
2651                conversation.setIncomingChatState(Config.DEFAULT_CHAT_STATE);
2652            }
2653        }
2654        for (Account account : getAccounts()) {
2655            if (account.getStatus() == Account.State.ONLINE) {
2656                account.deactivateGracePeriod();
2657                final XmppConnection connection = account.getXmppConnection();
2658                if (connection != null) {
2659                    if (connection.getFeatures().csi()) {
2660                        connection.sendActive();
2661                    }
2662                    if (broadcastLastActivity) {
2663                        sendPresence(account, false); //send new presence but don't include idle because we are not
2664                    }
2665                }
2666            }
2667        }
2668        Log.d(Config.LOGTAG, "app switched into foreground");
2669    }
2670
2671    private void switchToBackground() {
2672        final boolean broadcastLastActivity = broadcastLastActivity();
2673        if (broadcastLastActivity) {
2674            mLastActivity = System.currentTimeMillis();
2675            final SharedPreferences.Editor editor = getPreferences().edit();
2676            editor.putLong(SETTING_LAST_ACTIVITY_TS, mLastActivity);
2677            editor.apply();
2678        }
2679        for (Account account : getAccounts()) {
2680            if (account.getStatus() == Account.State.ONLINE) {
2681                XmppConnection connection = account.getXmppConnection();
2682                if (connection != null) {
2683                    if (broadcastLastActivity) {
2684                        sendPresence(account, true);
2685                    }
2686                    if (connection.getFeatures().csi()) {
2687                        connection.sendInactive();
2688                    }
2689                }
2690            }
2691        }
2692        this.mNotificationService.setIsInForeground(false);
2693        Log.d(Config.LOGTAG, "app switched into background");
2694    }
2695
2696    private void connectMultiModeConversations(Account account) {
2697        List<Conversation> conversations = getConversations();
2698        for (Conversation conversation : conversations) {
2699            if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
2700                joinMuc(conversation);
2701            }
2702        }
2703    }
2704
2705    public void mucSelfPingAndRejoin(final Conversation conversation) {
2706        final Account account = conversation.getAccount();
2707        synchronized (account.inProgressConferenceJoins) {
2708            if (account.inProgressConferenceJoins.contains(conversation)) {
2709                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": canceling muc self ping because join is already under way");
2710                return;
2711            }
2712        }
2713        synchronized (account.inProgressConferencePings) {
2714            if (!account.inProgressConferencePings.add(conversation)) {
2715                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": canceling muc self ping because ping is already under way");
2716                return;
2717            }
2718        }
2719        final Jid self = conversation.getMucOptions().getSelf().getFullJid();
2720        final IqPacket ping = new IqPacket(IqPacket.TYPE.GET);
2721        ping.setTo(self);
2722        ping.addChild("ping", Namespace.PING);
2723        sendIqPacket(conversation.getAccount(), ping, (a, response) -> {
2724            if (response.getType() == IqPacket.TYPE.ERROR) {
2725                Element error = response.findChild("error");
2726                if (error == null || error.hasChild("service-unavailable") || error.hasChild("feature-not-implemented") || error.hasChild("item-not-found")) {
2727                    Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " came back as ignorable error");
2728                } else {
2729                    Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " failed. attempting rejoin");
2730                    joinMuc(conversation);
2731                }
2732            } else if (response.getType() == IqPacket.TYPE.RESULT) {
2733                Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " came back fine");
2734            }
2735            synchronized (account.inProgressConferencePings) {
2736                account.inProgressConferencePings.remove(conversation);
2737            }
2738        });
2739    }
2740
2741    public void joinMuc(Conversation conversation) {
2742        joinMuc(conversation, null, false);
2743    }
2744
2745    public void joinMuc(Conversation conversation, boolean followedInvite) {
2746        joinMuc(conversation, null, followedInvite);
2747    }
2748
2749    private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined) {
2750        joinMuc(conversation, onConferenceJoined, false);
2751    }
2752
2753    private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined, final boolean followedInvite) {
2754        final Account account = conversation.getAccount();
2755        synchronized (account.pendingConferenceJoins) {
2756            account.pendingConferenceJoins.remove(conversation);
2757        }
2758        synchronized (account.pendingConferenceLeaves) {
2759            account.pendingConferenceLeaves.remove(conversation);
2760        }
2761        if (account.getStatus() == Account.State.ONLINE) {
2762            synchronized (account.inProgressConferenceJoins) {
2763                account.inProgressConferenceJoins.add(conversation);
2764            }
2765            if (Config.MUC_LEAVE_BEFORE_JOIN) {
2766                sendPresencePacket(account, mPresenceGenerator.leave(conversation.getMucOptions()));
2767            }
2768            conversation.resetMucOptions();
2769            if (onConferenceJoined != null) {
2770                conversation.getMucOptions().flagNoAutoPushConfiguration();
2771            }
2772            conversation.setHasMessagesLeftOnServer(false);
2773            fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
2774
2775                private void join(Conversation conversation) {
2776                    Account account = conversation.getAccount();
2777                    final MucOptions mucOptions = conversation.getMucOptions();
2778
2779                    if (mucOptions.nonanonymous() && !mucOptions.membersOnly() && !conversation.getBooleanAttribute("accept_non_anonymous", false)) {
2780                        synchronized (account.inProgressConferenceJoins) {
2781                            account.inProgressConferenceJoins.remove(conversation);
2782                        }
2783                        mucOptions.setError(MucOptions.Error.NON_ANONYMOUS);
2784                        updateConversationUi();
2785                        if (onConferenceJoined != null) {
2786                            onConferenceJoined.onConferenceJoined(conversation);
2787                        }
2788                        return;
2789                    }
2790
2791                    final Jid joinJid = mucOptions.getSelf().getFullJid();
2792                    Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": joining conversation " + joinJid.toString());
2793                    PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous() || onConferenceJoined != null);
2794                    packet.setTo(joinJid);
2795                    Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
2796                    if (conversation.getMucOptions().getPassword() != null) {
2797                        x.addChild("password").setContent(mucOptions.getPassword());
2798                    }
2799
2800                    if (mucOptions.mamSupport()) {
2801                        // Use MAM instead of the limited muc history to get history
2802                        x.addChild("history").setAttribute("maxchars", "0");
2803                    } else {
2804                        // Fallback to muc history
2805                        x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted().getTimestamp()));
2806                    }
2807                    sendPresencePacket(account, packet);
2808                    if (onConferenceJoined != null) {
2809                        onConferenceJoined.onConferenceJoined(conversation);
2810                    }
2811                    if (!joinJid.equals(conversation.getJid())) {
2812                        conversation.setContactJid(joinJid);
2813                        databaseBackend.updateConversation(conversation);
2814                    }
2815
2816                    if (mucOptions.mamSupport()) {
2817                        getMessageArchiveService().catchupMUC(conversation);
2818                    }
2819                    if (mucOptions.isPrivateAndNonAnonymous()) {
2820                        fetchConferenceMembers(conversation);
2821
2822                        if (followedInvite) {
2823                            final Bookmark bookmark = conversation.getBookmark();
2824                            if (bookmark != null) {
2825                                if (!bookmark.autojoin()) {
2826                                    bookmark.setAutojoin(true);
2827                                    createBookmark(account, bookmark);
2828                                }
2829                            } else {
2830                                saveConversationAsBookmark(conversation, null);
2831                            }
2832                        }
2833                    }
2834                    synchronized (account.inProgressConferenceJoins) {
2835                        account.inProgressConferenceJoins.remove(conversation);
2836                        sendUnsentMessages(conversation);
2837                    }
2838                }
2839
2840                @Override
2841                public void onConferenceConfigurationFetched(Conversation conversation) {
2842                    if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
2843                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": conversation (" + conversation.getJid() + ") got archived before IQ result");
2844                        return;
2845                    }
2846                    join(conversation);
2847                }
2848
2849                @Override
2850                public void onFetchFailed(final Conversation conversation, Element error) {
2851                    if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
2852                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": conversation (" + conversation.getJid() + ") got archived before IQ result");
2853
2854                        return;
2855                    }
2856                    if (error != null && "remote-server-not-found".equals(error.getName())) {
2857                        synchronized (account.inProgressConferenceJoins) {
2858                            account.inProgressConferenceJoins.remove(conversation);
2859                        }
2860                        conversation.getMucOptions().setError(MucOptions.Error.SERVER_NOT_FOUND);
2861                        updateConversationUi();
2862                    } else {
2863                        join(conversation);
2864                        fetchConferenceConfiguration(conversation);
2865                    }
2866                }
2867            });
2868            updateConversationUi();
2869        } else {
2870            synchronized (account.pendingConferenceJoins) {
2871                account.pendingConferenceJoins.add(conversation);
2872            }
2873            conversation.resetMucOptions();
2874            conversation.setHasMessagesLeftOnServer(false);
2875            updateConversationUi();
2876        }
2877    }
2878
2879    private void fetchConferenceMembers(final Conversation conversation) {
2880        final Account account = conversation.getAccount();
2881        final AxolotlService axolotlService = account.getAxolotlService();
2882        final String[] affiliations = {"member", "admin", "owner"};
2883        OnIqPacketReceived callback = new OnIqPacketReceived() {
2884
2885            private int i = 0;
2886            private boolean success = true;
2887
2888            @Override
2889            public void onIqPacketReceived(Account account, IqPacket packet) {
2890                final boolean omemoEnabled = conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL;
2891                Element query = packet.query("http://jabber.org/protocol/muc#admin");
2892                if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2893                    for (Element child : query.getChildren()) {
2894                        if ("item".equals(child.getName())) {
2895                            MucOptions.User user = AbstractParser.parseItem(conversation, child);
2896                            if (!user.realJidMatchesAccount()) {
2897                                boolean isNew = conversation.getMucOptions().updateUser(user);
2898                                Contact contact = user.getContact();
2899                                if (omemoEnabled
2900                                        && isNew
2901                                        && user.getRealJid() != null
2902                                        && (contact == null || !contact.mutualPresenceSubscription())
2903                                        && axolotlService.hasEmptyDeviceList(user.getRealJid())) {
2904                                    axolotlService.fetchDeviceIds(user.getRealJid());
2905                                }
2906                            }
2907                        }
2908                    }
2909                } else {
2910                    success = false;
2911                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not request affiliation " + affiliations[i] + " in " + conversation.getJid().asBareJid());
2912                }
2913                ++i;
2914                if (i >= affiliations.length) {
2915                    List<Jid> members = conversation.getMucOptions().getMembers(true);
2916                    if (success) {
2917                        List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
2918                        boolean changed = false;
2919                        for (ListIterator<Jid> iterator = cryptoTargets.listIterator(); iterator.hasNext(); ) {
2920                            Jid jid = iterator.next();
2921                            if (!members.contains(jid) && !members.contains(jid.getDomain())) {
2922                                iterator.remove();
2923                                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
2924                                changed = true;
2925                            }
2926                        }
2927                        if (changed) {
2928                            conversation.setAcceptedCryptoTargets(cryptoTargets);
2929                            updateConversation(conversation);
2930                        }
2931                    }
2932                    getAvatarService().clear(conversation);
2933                    updateMucRosterUi();
2934                    updateConversationUi();
2935                }
2936            }
2937        };
2938        for (String affiliation : affiliations) {
2939            sendIqPacket(account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
2940        }
2941        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching members for " + conversation.getName());
2942    }
2943
2944    public void providePasswordForMuc(Conversation conversation, String password) {
2945        if (conversation.getMode() == Conversation.MODE_MULTI) {
2946            conversation.getMucOptions().setPassword(password);
2947            if (conversation.getBookmark() != null) {
2948                final Bookmark bookmark = conversation.getBookmark();
2949                if (synchronizeWithBookmarks()) {
2950                    bookmark.setAutojoin(true);
2951                }
2952                createBookmark(conversation.getAccount(), bookmark);
2953            }
2954            updateConversation(conversation);
2955            joinMuc(conversation);
2956        }
2957    }
2958
2959    private boolean hasEnabledAccounts() {
2960        if (this.accounts == null) {
2961            return false;
2962        }
2963        for (Account account : this.accounts) {
2964            if (account.isEnabled()) {
2965                return true;
2966            }
2967        }
2968        return false;
2969    }
2970
2971
2972    public void getAttachments(final Conversation conversation, int limit, final OnMediaLoaded onMediaLoaded) {
2973        getAttachments(conversation.getAccount(), conversation.getJid().asBareJid(), limit, onMediaLoaded);
2974    }
2975
2976    public void getAttachments(final Account account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
2977        getAttachments(account.getUuid(), jid.asBareJid(), limit, onMediaLoaded);
2978    }
2979
2980
2981    public void getAttachments(final String account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
2982        new Thread(() -> onMediaLoaded.onMediaLoaded(fileBackend.convertToAttachments(databaseBackend.getRelativeFilePaths(account, jid, limit)))).start();
2983    }
2984
2985    public void persistSelfNick(MucOptions.User self) {
2986        final Conversation conversation = self.getConversation();
2987        final boolean tookProposedNickFromBookmark = conversation.getMucOptions().isTookProposedNickFromBookmark();
2988        Jid full = self.getFullJid();
2989        if (!full.equals(conversation.getJid())) {
2990            Log.d(Config.LOGTAG, "nick changed. updating");
2991            conversation.setContactJid(full);
2992            databaseBackend.updateConversation(conversation);
2993        }
2994
2995        final Bookmark bookmark = conversation.getBookmark();
2996        final String bookmarkedNick = bookmark == null ? null : bookmark.getNick();
2997        if (bookmark != null && (tookProposedNickFromBookmark || TextUtils.isEmpty(bookmarkedNick)) && !full.getResource().equals(bookmarkedNick)) {
2998            final Account account = conversation.getAccount();
2999            final String defaultNick = MucOptions.defaultNick(account);
3000            if (TextUtils.isEmpty(bookmarkedNick) && full.getResource().equals(defaultNick)) {
3001                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": do not overwrite empty bookmark nick with default nick for " + conversation.getJid().asBareJid());
3002                return;
3003            }
3004            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": persist nick '" + full.getResource() + "' into bookmark for " + conversation.getJid().asBareJid());
3005            bookmark.setNick(full.getResource());
3006            createBookmark(bookmark.getAccount(), bookmark);
3007        }
3008    }
3009
3010    public boolean renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
3011        final MucOptions options = conversation.getMucOptions();
3012        final Jid joinJid = options.createJoinJid(nick);
3013        if (joinJid == null) {
3014            return false;
3015        }
3016        if (options.online()) {
3017            Account account = conversation.getAccount();
3018            options.setOnRenameListener(new OnRenameListener() {
3019
3020                @Override
3021                public void onSuccess() {
3022                    callback.success(conversation);
3023                }
3024
3025                @Override
3026                public void onFailure() {
3027                    callback.error(R.string.nick_in_use, conversation);
3028                }
3029            });
3030
3031            final PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, options.nonanonymous());
3032            packet.setTo(joinJid);
3033            sendPresencePacket(account, packet);
3034        } else {
3035            conversation.setContactJid(joinJid);
3036            databaseBackend.updateConversation(conversation);
3037            if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
3038                Bookmark bookmark = conversation.getBookmark();
3039                if (bookmark != null) {
3040                    bookmark.setNick(nick);
3041                    createBookmark(bookmark.getAccount(), bookmark);
3042                }
3043                joinMuc(conversation);
3044            }
3045        }
3046        return true;
3047    }
3048
3049    public void leaveMuc(Conversation conversation) {
3050        leaveMuc(conversation, false);
3051    }
3052
3053    private void leaveMuc(Conversation conversation, boolean now) {
3054        final Account account = conversation.getAccount();
3055        synchronized (account.pendingConferenceJoins) {
3056            account.pendingConferenceJoins.remove(conversation);
3057        }
3058        synchronized (account.pendingConferenceLeaves) {
3059            account.pendingConferenceLeaves.remove(conversation);
3060        }
3061        if (account.getStatus() == Account.State.ONLINE || now) {
3062            sendPresencePacket(conversation.getAccount(), mPresenceGenerator.leave(conversation.getMucOptions()));
3063            conversation.getMucOptions().setOffline();
3064            Bookmark bookmark = conversation.getBookmark();
3065            if (bookmark != null) {
3066                bookmark.setConversation(null);
3067            }
3068            Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": leaving muc " + conversation.getJid());
3069        } else {
3070            synchronized (account.pendingConferenceLeaves) {
3071                account.pendingConferenceLeaves.add(conversation);
3072            }
3073        }
3074    }
3075
3076    public String findConferenceServer(final Account account) {
3077        String server;
3078        if (account.getXmppConnection() != null) {
3079            server = account.getXmppConnection().getMucServer();
3080            if (server != null) {
3081                return server;
3082            }
3083        }
3084        for (Account other : getAccounts()) {
3085            if (other != account && other.getXmppConnection() != null) {
3086                server = other.getXmppConnection().getMucServer();
3087                if (server != null) {
3088                    return server;
3089                }
3090            }
3091        }
3092        return null;
3093    }
3094
3095
3096    public void createPublicChannel(final Account account, final String name, final Jid address, final UiCallback<Conversation> callback) {
3097        joinMuc(findOrCreateConversation(account, address, true, false, true), conversation -> {
3098            final Bundle configuration = IqGenerator.defaultChannelConfiguration();
3099            if (!TextUtils.isEmpty(name)) {
3100                configuration.putString("muc#roomconfig_roomname", name);
3101            }
3102            pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
3103                @Override
3104                public void onPushSucceeded() {
3105                    saveConversationAsBookmark(conversation, name);
3106                    callback.success(conversation);
3107                }
3108
3109                @Override
3110                public void onPushFailed() {
3111                    if (conversation.getMucOptions().getSelf().getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
3112                        callback.error(R.string.unable_to_set_channel_configuration, conversation);
3113                    } else {
3114                        callback.error(R.string.joined_an_existing_channel, conversation);
3115                    }
3116                }
3117            });
3118        });
3119    }
3120
3121    public boolean createAdhocConference(final Account account,
3122                                         final String name,
3123                                         final Iterable<Jid> jids,
3124                                         final UiCallback<Conversation> callback) {
3125        Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": creating adhoc conference with " + jids.toString());
3126        if (account.getStatus() == Account.State.ONLINE) {
3127            try {
3128                String server = findConferenceServer(account);
3129                if (server == null) {
3130                    if (callback != null) {
3131                        callback.error(R.string.no_conference_server_found, null);
3132                    }
3133                    return false;
3134                }
3135                final Jid jid = Jid.of(CryptoHelper.pronounceable(getRNG()), server, null);
3136                final Conversation conversation = findOrCreateConversation(account, jid, true, false, true);
3137                joinMuc(conversation, new OnConferenceJoined() {
3138                    @Override
3139                    public void onConferenceJoined(final Conversation conversation) {
3140                        final Bundle configuration = IqGenerator.defaultGroupChatConfiguration();
3141                        if (!TextUtils.isEmpty(name)) {
3142                            configuration.putString("muc#roomconfig_roomname", name);
3143                        }
3144                        pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
3145                            @Override
3146                            public void onPushSucceeded() {
3147                                for (Jid invite : jids) {
3148                                    invite(conversation, invite);
3149                                }
3150                                for (String resource : account.getSelfContact().getPresences().toResourceArray()) {
3151                                    Jid other = account.getJid().withResource(resource);
3152                                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending direct invite to " + other);
3153                                    directInvite(conversation, other);
3154                                }
3155                                saveConversationAsBookmark(conversation, name);
3156                                if (callback != null) {
3157                                    callback.success(conversation);
3158                                }
3159                            }
3160
3161                            @Override
3162                            public void onPushFailed() {
3163                                archiveConversation(conversation);
3164                                if (callback != null) {
3165                                    callback.error(R.string.conference_creation_failed, conversation);
3166                                }
3167                            }
3168                        });
3169                    }
3170                });
3171                return true;
3172            } catch (IllegalArgumentException e) {
3173                if (callback != null) {
3174                    callback.error(R.string.conference_creation_failed, null);
3175                }
3176                return false;
3177            }
3178        } else {
3179            if (callback != null) {
3180                callback.error(R.string.not_connected_try_again, null);
3181            }
3182            return false;
3183        }
3184    }
3185
3186    public void fetchConferenceConfiguration(final Conversation conversation) {
3187        fetchConferenceConfiguration(conversation, null);
3188    }
3189
3190    public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
3191        IqPacket request = mIqGenerator.queryDiscoInfo(conversation.getJid().asBareJid());
3192        sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3193            @Override
3194            public void onIqPacketReceived(Account account, IqPacket packet) {
3195                if (packet.getType() == IqPacket.TYPE.RESULT) {
3196                    final MucOptions mucOptions = conversation.getMucOptions();
3197                    final Bookmark bookmark = conversation.getBookmark();
3198                    final boolean sameBefore = StringUtils.equals(bookmark == null ? null : bookmark.getBookmarkName(), mucOptions.getName());
3199
3200                    if (mucOptions.updateConfiguration(new ServiceDiscoveryResult(packet))) {
3201                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": muc configuration changed for " + conversation.getJid().asBareJid());
3202                        updateConversation(conversation);
3203                    }
3204
3205                    if (bookmark != null && (sameBefore || bookmark.getBookmarkName() == null)) {
3206                        if (bookmark.setBookmarkName(StringUtils.nullOnEmpty(mucOptions.getName()))) {
3207                            createBookmark(account, bookmark);
3208                        }
3209                    }
3210
3211
3212                    if (callback != null) {
3213                        callback.onConferenceConfigurationFetched(conversation);
3214                    }
3215
3216
3217                    updateConversationUi();
3218                } else if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
3219                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received timeout waiting for conference configuration fetch");
3220                } else {
3221                    if (callback != null) {
3222                        callback.onFetchFailed(conversation, packet.getError());
3223                    }
3224                }
3225            }
3226        });
3227    }
3228
3229    public void pushNodeConfiguration(Account account, final String node, final Bundle options, final OnConfigurationPushed callback) {
3230        pushNodeConfiguration(account, account.getJid().asBareJid(), node, options, callback);
3231    }
3232
3233    public void pushNodeConfiguration(Account account, final Jid jid, final String node, final Bundle options, final OnConfigurationPushed callback) {
3234        Log.d(Config.LOGTAG, "pushing node configuration");
3235        sendIqPacket(account, mIqGenerator.requestPubsubConfiguration(jid, node), new OnIqPacketReceived() {
3236            @Override
3237            public void onIqPacketReceived(Account account, IqPacket packet) {
3238                if (packet.getType() == IqPacket.TYPE.RESULT) {
3239                    Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub#owner");
3240                    Element configuration = pubsub == null ? null : pubsub.findChild("configure");
3241                    Element x = configuration == null ? null : configuration.findChild("x", Namespace.DATA);
3242                    if (x != null) {
3243                        Data data = Data.parse(x);
3244                        data.submit(options);
3245                        sendIqPacket(account, mIqGenerator.publishPubsubConfiguration(jid, node, data), new OnIqPacketReceived() {
3246                            @Override
3247                            public void onIqPacketReceived(Account account, IqPacket packet) {
3248                                if (packet.getType() == IqPacket.TYPE.RESULT && callback != null) {
3249                                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": successfully changed node configuration for node " + node);
3250                                    callback.onPushSucceeded();
3251                                } else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
3252                                    callback.onPushFailed();
3253                                }
3254                            }
3255                        });
3256                    } else if (callback != null) {
3257                        callback.onPushFailed();
3258                    }
3259                } else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
3260                    callback.onPushFailed();
3261                }
3262            }
3263        });
3264    }
3265
3266    public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConfigurationPushed callback) {
3267        if (options.getString("muc#roomconfig_whois", "moderators").equals("anyone")) {
3268            conversation.setAttribute("accept_non_anonymous", true);
3269            updateConversation(conversation);
3270        }
3271        if (options.containsKey("muc#roomconfig_moderatedroom")) {
3272            final boolean moderated = "1".equals(options.getString("muc#roomconfig_moderatedroom"));
3273            options.putString("members_by_default", moderated ? "0" : "1");
3274        }
3275        final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3276        request.setTo(conversation.getJid().asBareJid());
3277        request.query("http://jabber.org/protocol/muc#owner");
3278        sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3279            @Override
3280            public void onIqPacketReceived(Account account, IqPacket packet) {
3281                if (packet.getType() == IqPacket.TYPE.RESULT) {
3282                    final Data data = Data.parse(packet.query().findChild("x", Namespace.DATA));
3283                    data.submit(options);
3284                    final IqPacket set = new IqPacket(IqPacket.TYPE.SET);
3285                    set.setTo(conversation.getJid().asBareJid());
3286                    set.query("http://jabber.org/protocol/muc#owner").addChild(data);
3287                    sendIqPacket(account, set, new OnIqPacketReceived() {
3288                        @Override
3289                        public void onIqPacketReceived(Account account, IqPacket packet) {
3290                            if (callback != null) {
3291                                if (packet.getType() == IqPacket.TYPE.RESULT) {
3292                                    callback.onPushSucceeded();
3293                                } else {
3294                                    callback.onPushFailed();
3295                                }
3296                            }
3297                        }
3298                    });
3299                } else {
3300                    if (callback != null) {
3301                        callback.onPushFailed();
3302                    }
3303                }
3304            }
3305        });
3306    }
3307
3308    public void pushSubjectToConference(final Conversation conference, final String subject) {
3309        MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, StringUtils.nullOnEmpty(subject));
3310        this.sendMessagePacket(conference.getAccount(), packet);
3311    }
3312
3313    public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
3314        final Jid jid = user.asBareJid();
3315        IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
3316        sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
3317            @Override
3318            public void onIqPacketReceived(Account account, IqPacket packet) {
3319                if (packet.getType() == IqPacket.TYPE.RESULT) {
3320                    conference.getMucOptions().changeAffiliation(jid, affiliation);
3321                    getAvatarService().clear(conference);
3322                    callback.onAffiliationChangedSuccessful(jid);
3323                } else {
3324                    callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
3325                }
3326            }
3327        });
3328    }
3329
3330    public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
3331        List<Jid> jids = new ArrayList<>();
3332        for (MucOptions.User user : conference.getMucOptions().getUsers()) {
3333            if (user.getAffiliation() == before && user.getRealJid() != null) {
3334                jids.add(user.getRealJid());
3335            }
3336        }
3337        IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
3338        sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
3339    }
3340
3341    public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role) {
3342        IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
3343        Log.d(Config.LOGTAG, request.toString());
3344        sendIqPacket(conference.getAccount(), request, (account, packet) -> {
3345            if (packet.getType() != IqPacket.TYPE.RESULT) {
3346                Log.d(Config.LOGTAG, account.getJid().asBareJid() + " unable to change role of " + nick);
3347            }
3348        });
3349    }
3350
3351    public void destroyRoom(final Conversation conversation, final OnRoomDestroy callback) {
3352        IqPacket request = new IqPacket(IqPacket.TYPE.SET);
3353        request.setTo(conversation.getJid().asBareJid());
3354        request.query("http://jabber.org/protocol/muc#owner").addChild("destroy");
3355        sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3356            @Override
3357            public void onIqPacketReceived(Account account, IqPacket packet) {
3358                if (packet.getType() == IqPacket.TYPE.RESULT) {
3359                    if (callback != null) {
3360                        callback.onRoomDestroySucceeded();
3361                    }
3362                } else if (packet.getType() == IqPacket.TYPE.ERROR) {
3363                    if (callback != null) {
3364                        callback.onRoomDestroyFailed();
3365                    }
3366                }
3367            }
3368        });
3369    }
3370
3371    private void disconnect(Account account, boolean force) {
3372        if ((account.getStatus() == Account.State.ONLINE)
3373                || (account.getStatus() == Account.State.DISABLED)) {
3374            final XmppConnection connection = account.getXmppConnection();
3375            if (!force) {
3376                List<Conversation> conversations = getConversations();
3377                for (Conversation conversation : conversations) {
3378                    if (conversation.getAccount() == account) {
3379                        if (conversation.getMode() == Conversation.MODE_MULTI) {
3380                            leaveMuc(conversation, true);
3381                        }
3382                    }
3383                }
3384                sendOfflinePresence(account);
3385            }
3386            connection.disconnect(force);
3387        }
3388    }
3389
3390    @Override
3391    public IBinder onBind(Intent intent) {
3392        return mBinder;
3393    }
3394
3395    public void updateMessage(Message message) {
3396        updateMessage(message, true);
3397    }
3398
3399    public void updateMessage(Message message, boolean includeBody) {
3400        databaseBackend.updateMessage(message, includeBody);
3401        updateConversationUi();
3402    }
3403
3404    public void createMessageAsync(final Message message) {
3405        mDatabaseWriterExecutor.execute(() -> databaseBackend.createMessage(message));
3406    }
3407
3408    public void updateMessage(Message message, String uuid) {
3409        if (!databaseBackend.updateMessage(message, uuid)) {
3410            Log.e(Config.LOGTAG, "error updated message in DB after edit");
3411        }
3412        updateConversationUi();
3413    }
3414
3415    protected void syncDirtyContacts(Account account) {
3416        for (Contact contact : account.getRoster().getContacts()) {
3417            if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
3418                pushContactToServer(contact);
3419            }
3420            if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
3421                deleteContactOnServer(contact);
3422            }
3423        }
3424    }
3425
3426    public void createContact(Contact contact, boolean autoGrant) {
3427        if (autoGrant) {
3428            contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
3429            contact.setOption(Contact.Options.ASKING);
3430        }
3431        pushContactToServer(contact);
3432    }
3433
3434    public void pushContactToServer(final Contact contact) {
3435        contact.resetOption(Contact.Options.DIRTY_DELETE);
3436        contact.setOption(Contact.Options.DIRTY_PUSH);
3437        final Account account = contact.getAccount();
3438        if (account.getStatus() == Account.State.ONLINE) {
3439            final boolean ask = contact.getOption(Contact.Options.ASKING);
3440            final boolean sendUpdates = contact
3441                    .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
3442                    && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
3443            final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
3444            iq.query(Namespace.ROSTER).addChild(contact.asElement());
3445            account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
3446            if (sendUpdates) {
3447                sendPresencePacket(account, mPresenceGenerator.sendPresenceUpdatesTo(contact));
3448            }
3449            if (ask) {
3450                sendPresencePacket(account, mPresenceGenerator.requestPresenceUpdatesFrom(contact));
3451            }
3452        } else {
3453            syncRoster(contact.getAccount());
3454        }
3455    }
3456
3457    public void publishMucAvatar(final Conversation conversation, final Uri image, final OnAvatarPublication callback) {
3458        new Thread(() -> {
3459            final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
3460            final int size = Config.AVATAR_SIZE;
3461            final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
3462            if (avatar != null) {
3463                if (!getFileBackend().save(avatar)) {
3464                    callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
3465                    return;
3466                }
3467                avatar.owner = conversation.getJid().asBareJid();
3468                publishMucAvatar(conversation, avatar, callback);
3469            } else {
3470                callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
3471            }
3472        }).start();
3473    }
3474
3475    public void publishAvatar(final Account account, final Uri image, final OnAvatarPublication callback) {
3476        new Thread(() -> {
3477            final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
3478            final int size = Config.AVATAR_SIZE;
3479            final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
3480            if (avatar != null) {
3481                if (!getFileBackend().save(avatar)) {
3482                    Log.d(Config.LOGTAG, "unable to save vcard");
3483                    callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
3484                    return;
3485                }
3486                publishAvatar(account, avatar, callback);
3487            } else {
3488                callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
3489            }
3490        }).start();
3491
3492    }
3493
3494    private void publishMucAvatar(Conversation conversation, Avatar avatar, OnAvatarPublication callback) {
3495        final IqPacket retrieve = mIqGenerator.retrieveVcardAvatar(avatar);
3496        sendIqPacket(conversation.getAccount(), retrieve, (account, response) -> {
3497            boolean itemNotFound = response.getType() == IqPacket.TYPE.ERROR && response.hasChild("error") && response.findChild("error").hasChild("item-not-found");
3498            if (response.getType() == IqPacket.TYPE.RESULT || itemNotFound) {
3499                Element vcard = response.findChild("vCard", "vcard-temp");
3500                if (vcard == null) {
3501                    vcard = new Element("vCard", "vcard-temp");
3502                }
3503                Element photo = vcard.findChild("PHOTO");
3504                if (photo == null) {
3505                    photo = vcard.addChild("PHOTO");
3506                }
3507                photo.clearChildren();
3508                photo.addChild("TYPE").setContent(avatar.type);
3509                photo.addChild("BINVAL").setContent(avatar.image);
3510                IqPacket publication = new IqPacket(IqPacket.TYPE.SET);
3511                publication.setTo(conversation.getJid().asBareJid());
3512                publication.addChild(vcard);
3513                sendIqPacket(account, publication, (a1, publicationResponse) -> {
3514                    if (publicationResponse.getType() == IqPacket.TYPE.RESULT) {
3515                        callback.onAvatarPublicationSucceeded();
3516                    } else {
3517                        Log.d(Config.LOGTAG, "failed to publish vcard " + publicationResponse.getError());
3518                        callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3519                    }
3520                });
3521            } else {
3522                Log.d(Config.LOGTAG, "failed to request vcard " + response.toString());
3523                callback.onAvatarPublicationFailed(R.string.error_publish_avatar_no_server_support);
3524            }
3525        });
3526    }
3527
3528    public void publishAvatar(Account account, final Avatar avatar, final OnAvatarPublication callback) {
3529        final Bundle options;
3530        if (account.getXmppConnection().getFeatures().pepPublishOptions()) {
3531            options = PublishOptions.openAccess();
3532        } else {
3533            options = null;
3534        }
3535        publishAvatar(account, avatar, options, true, callback);
3536    }
3537
3538    public void publishAvatar(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
3539        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": publishing avatar. options=" + options);
3540        IqPacket packet = this.mIqGenerator.publishAvatar(avatar, options);
3541        this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3542
3543            @Override
3544            public void onIqPacketReceived(Account account, IqPacket result) {
3545                if (result.getType() == IqPacket.TYPE.RESULT) {
3546                    publishAvatarMetadata(account, avatar, options, true, callback);
3547                } else if (retry && PublishOptions.preconditionNotMet(result)) {
3548                    pushNodeConfiguration(account, "urn:xmpp:avatar:data", options, new OnConfigurationPushed() {
3549                        @Override
3550                        public void onPushSucceeded() {
3551                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": changed node configuration for avatar node");
3552                            publishAvatar(account, avatar, options, false, callback);
3553                        }
3554
3555                        @Override
3556                        public void onPushFailed() {
3557                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to change node configuration for avatar node");
3558                            publishAvatar(account, avatar, null, false, callback);
3559                        }
3560                    });
3561                } else {
3562                    Element error = result.findChild("error");
3563                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server rejected avatar " + (avatar.size / 1024) + "KiB " + (error != null ? error.toString() : ""));
3564                    if (callback != null) {
3565                        callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3566                    }
3567                }
3568            }
3569        });
3570    }
3571
3572    public void publishAvatarMetadata(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
3573        final IqPacket packet = XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar, options);
3574        sendIqPacket(account, packet, new OnIqPacketReceived() {
3575            @Override
3576            public void onIqPacketReceived(Account account, IqPacket result) {
3577                if (result.getType() == IqPacket.TYPE.RESULT) {
3578                    if (account.setAvatar(avatar.getFilename())) {
3579                        getAvatarService().clear(account);
3580                        databaseBackend.updateAccount(account);
3581                        notifyAccountAvatarHasChanged(account);
3582                    }
3583                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": published avatar " + (avatar.size / 1024) + "KiB");
3584                    if (callback != null) {
3585                        callback.onAvatarPublicationSucceeded();
3586                    }
3587                } else if (retry && PublishOptions.preconditionNotMet(result)) {
3588                    pushNodeConfiguration(account, "urn:xmpp:avatar:metadata", options, new OnConfigurationPushed() {
3589                        @Override
3590                        public void onPushSucceeded() {
3591                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": changed node configuration for avatar meta data node");
3592                            publishAvatarMetadata(account, avatar, options, false, callback);
3593                        }
3594
3595                        @Override
3596                        public void onPushFailed() {
3597                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to change node configuration for avatar meta data node");
3598                            publishAvatarMetadata(account, avatar, null, false, callback);
3599                        }
3600                    });
3601                } else {
3602                    if (callback != null) {
3603                        callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3604                    }
3605                }
3606            }
3607        });
3608    }
3609
3610    public void republishAvatarIfNeeded(Account account) {
3611        if (account.getAxolotlService().isPepBroken()) {
3612            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping republication of avatar because pep is broken");
3613            return;
3614        }
3615        IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
3616        this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3617
3618            private Avatar parseAvatar(IqPacket packet) {
3619                Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
3620                if (pubsub != null) {
3621                    Element items = pubsub.findChild("items");
3622                    if (items != null) {
3623                        return Avatar.parseMetadata(items);
3624                    }
3625                }
3626                return null;
3627            }
3628
3629            private boolean errorIsItemNotFound(IqPacket packet) {
3630                Element error = packet.findChild("error");
3631                return packet.getType() == IqPacket.TYPE.ERROR
3632                        && error != null
3633                        && error.hasChild("item-not-found");
3634            }
3635
3636            @Override
3637            public void onIqPacketReceived(Account account, IqPacket packet) {
3638                if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
3639                    Avatar serverAvatar = parseAvatar(packet);
3640                    if (serverAvatar == null && account.getAvatar() != null) {
3641                        Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
3642                        if (avatar != null) {
3643                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar on server was null. republishing");
3644                            publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
3645                        } else {
3646                            Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": error rereading avatar");
3647                        }
3648                    }
3649                }
3650            }
3651        });
3652    }
3653
3654    public void fetchAvatar(Account account, Avatar avatar) {
3655        fetchAvatar(account, avatar, null);
3656    }
3657
3658    public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3659        final String KEY = generateFetchKey(account, avatar);
3660        synchronized (this.mInProgressAvatarFetches) {
3661            if (mInProgressAvatarFetches.add(KEY)) {
3662                switch (avatar.origin) {
3663                    case PEP:
3664                        this.mInProgressAvatarFetches.add(KEY);
3665                        fetchAvatarPep(account, avatar, callback);
3666                        break;
3667                    case VCARD:
3668                        this.mInProgressAvatarFetches.add(KEY);
3669                        fetchAvatarVcard(account, avatar, callback);
3670                        break;
3671                }
3672            } else if (avatar.origin == Avatar.Origin.PEP) {
3673                mOmittedPepAvatarFetches.add(KEY);
3674            } else {
3675                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": already fetching " + avatar.origin + " avatar for " + avatar.owner);
3676            }
3677        }
3678    }
3679
3680    private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3681        IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
3682        sendIqPacket(account, packet, (a, result) -> {
3683            synchronized (mInProgressAvatarFetches) {
3684                mInProgressAvatarFetches.remove(generateFetchKey(a, avatar));
3685            }
3686            final String ERROR = a.getJid().asBareJid() + ": fetching avatar for " + avatar.owner + " failed ";
3687            if (result.getType() == IqPacket.TYPE.RESULT) {
3688                avatar.image = mIqParser.avatarData(result);
3689                if (avatar.image != null) {
3690                    if (getFileBackend().save(avatar)) {
3691                        if (a.getJid().asBareJid().equals(avatar.owner)) {
3692                            if (a.setAvatar(avatar.getFilename())) {
3693                                databaseBackend.updateAccount(a);
3694                            }
3695                            getAvatarService().clear(a);
3696                            updateConversationUi();
3697                            updateAccountUi();
3698                        } else {
3699                            Contact contact = a.getRoster().getContact(avatar.owner);
3700                            if (contact.setAvatar(avatar)) {
3701                                syncRoster(account);
3702                                getAvatarService().clear(contact);
3703                                updateConversationUi();
3704                                updateRosterUi();
3705                            }
3706                        }
3707                        if (callback != null) {
3708                            callback.success(avatar);
3709                        }
3710                        Log.d(Config.LOGTAG, a.getJid().asBareJid()
3711                                + ": successfully fetched pep avatar for " + avatar.owner);
3712                        return;
3713                    }
3714                } else {
3715
3716                    Log.d(Config.LOGTAG, ERROR + "(parsing error)");
3717                }
3718            } else {
3719                Element error = result.findChild("error");
3720                if (error == null) {
3721                    Log.d(Config.LOGTAG, ERROR + "(server error)");
3722                } else {
3723                    Log.d(Config.LOGTAG, ERROR + error.toString());
3724                }
3725            }
3726            if (callback != null) {
3727                callback.error(0, null);
3728            }
3729
3730        });
3731    }
3732
3733    private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3734        IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
3735        this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3736            @Override
3737            public void onIqPacketReceived(Account account, IqPacket packet) {
3738                final boolean previouslyOmittedPepFetch;
3739                synchronized (mInProgressAvatarFetches) {
3740                    final String KEY = generateFetchKey(account, avatar);
3741                    mInProgressAvatarFetches.remove(KEY);
3742                    previouslyOmittedPepFetch = mOmittedPepAvatarFetches.remove(KEY);
3743                }
3744                if (packet.getType() == IqPacket.TYPE.RESULT) {
3745                    Element vCard = packet.findChild("vCard", "vcard-temp");
3746                    Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
3747                    String image = photo != null ? photo.findChildContent("BINVAL") : null;
3748                    if (image != null) {
3749                        avatar.image = image;
3750                        if (getFileBackend().save(avatar)) {
3751                            Log.d(Config.LOGTAG, account.getJid().asBareJid()
3752                                    + ": successfully fetched vCard avatar for " + avatar.owner + " omittedPep=" + previouslyOmittedPepFetch);
3753                            if (avatar.owner.isBareJid()) {
3754                                if (account.getJid().asBareJid().equals(avatar.owner) && account.getAvatar() == null) {
3755                                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": had no avatar. replacing with vcard");
3756                                    account.setAvatar(avatar.getFilename());
3757                                    databaseBackend.updateAccount(account);
3758                                    getAvatarService().clear(account);
3759                                    updateAccountUi();
3760                                } else {
3761                                    Contact contact = account.getRoster().getContact(avatar.owner);
3762                                    if (contact.setAvatar(avatar, previouslyOmittedPepFetch)) {
3763                                        syncRoster(account);
3764                                        getAvatarService().clear(contact);
3765                                        updateRosterUi();
3766                                    }
3767                                }
3768                                updateConversationUi();
3769                            } else {
3770                                Conversation conversation = find(account, avatar.owner.asBareJid());
3771                                if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
3772                                    MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
3773                                    if (user != null) {
3774                                        if (user.setAvatar(avatar)) {
3775                                            getAvatarService().clear(user);
3776                                            updateConversationUi();
3777                                            updateMucRosterUi();
3778                                        }
3779                                        if (user.getRealJid() != null) {
3780                                            Contact contact = account.getRoster().getContact(user.getRealJid());
3781                                            if (contact.setAvatar(avatar)) {
3782                                                syncRoster(account);
3783                                                getAvatarService().clear(contact);
3784                                                updateRosterUi();
3785                                            }
3786                                        }
3787                                    }
3788                                }
3789                            }
3790                        }
3791                    }
3792                }
3793            }
3794        });
3795    }
3796
3797    public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
3798        IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
3799        this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3800
3801            @Override
3802            public void onIqPacketReceived(Account account, IqPacket packet) {
3803                if (packet.getType() == IqPacket.TYPE.RESULT) {
3804                    Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
3805                    if (pubsub != null) {
3806                        Element items = pubsub.findChild("items");
3807                        if (items != null) {
3808                            Avatar avatar = Avatar.parseMetadata(items);
3809                            if (avatar != null) {
3810                                avatar.owner = account.getJid().asBareJid();
3811                                if (fileBackend.isAvatarCached(avatar)) {
3812                                    if (account.setAvatar(avatar.getFilename())) {
3813                                        databaseBackend.updateAccount(account);
3814                                    }
3815                                    getAvatarService().clear(account);
3816                                    callback.success(avatar);
3817                                } else {
3818                                    fetchAvatarPep(account, avatar, callback);
3819                                }
3820                                return;
3821                            }
3822                        }
3823                    }
3824                }
3825                callback.error(0, null);
3826            }
3827        });
3828    }
3829
3830    public void notifyAccountAvatarHasChanged(final Account account) {
3831        final XmppConnection connection = account.getXmppConnection();
3832        if (connection != null && connection.getFeatures().bookmarksConversion()) {
3833            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar changed. resending presence to online group chats");
3834            for (Conversation conversation : conversations) {
3835                if (conversation.getAccount() == account && conversation.getMode() == Conversational.MODE_MULTI) {
3836                    final MucOptions mucOptions = conversation.getMucOptions();
3837                    if (mucOptions.online()) {
3838                        PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous());
3839                        packet.setTo(mucOptions.getSelf().getFullJid());
3840                        connection.sendPresencePacket(packet);
3841                    }
3842                }
3843            }
3844        }
3845    }
3846
3847    public void deleteContactOnServer(Contact contact) {
3848        contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
3849        contact.resetOption(Contact.Options.DIRTY_PUSH);
3850        contact.setOption(Contact.Options.DIRTY_DELETE);
3851        Account account = contact.getAccount();
3852        if (account.getStatus() == Account.State.ONLINE) {
3853            IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
3854            Element item = iq.query(Namespace.ROSTER).addChild("item");
3855            item.setAttribute("jid", contact.getJid());
3856            item.setAttribute("subscription", "remove");
3857            account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
3858        }
3859    }
3860
3861    public void updateConversation(final Conversation conversation) {
3862        mDatabaseWriterExecutor.execute(() -> databaseBackend.updateConversation(conversation));
3863    }
3864
3865    private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
3866        synchronized (account) {
3867            XmppConnection connection = account.getXmppConnection();
3868            if (connection == null) {
3869                connection = createConnection(account);
3870                account.setXmppConnection(connection);
3871            }
3872            boolean hasInternet = hasInternetConnection();
3873            if (account.isEnabled() && hasInternet) {
3874                if (!force) {
3875                    disconnect(account, false);
3876                }
3877                Thread thread = new Thread(connection);
3878                connection.setInteractive(interactive);
3879                connection.prepareNewConnection();
3880                connection.interrupt();
3881                thread.start();
3882                scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
3883            } else {
3884                disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
3885                account.getRoster().clearPresences();
3886                connection.resetEverything();
3887                final AxolotlService axolotlService = account.getAxolotlService();
3888                if (axolotlService != null) {
3889                    axolotlService.resetBrokenness();
3890                }
3891                if (!hasInternet) {
3892                    account.setStatus(Account.State.NO_INTERNET);
3893                }
3894            }
3895        }
3896    }
3897
3898    public void reconnectAccountInBackground(final Account account) {
3899        new Thread(() -> reconnectAccount(account, false, true)).start();
3900    }
3901
3902    public void invite(Conversation conversation, Jid contact) {
3903        Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": inviting " + contact + " to " + conversation.getJid().asBareJid());
3904        MessagePacket packet = mMessageGenerator.invite(conversation, contact);
3905        sendMessagePacket(conversation.getAccount(), packet);
3906    }
3907
3908    public void directInvite(Conversation conversation, Jid jid) {
3909        MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
3910        sendMessagePacket(conversation.getAccount(), packet);
3911    }
3912
3913    public void resetSendingToWaiting(Account account) {
3914        for (Conversation conversation : getConversations()) {
3915            if (conversation.getAccount() == account) {
3916                conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
3917            }
3918        }
3919    }
3920
3921    public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
3922        return markMessage(account, recipient, uuid, status, null);
3923    }
3924
3925    public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status, String errorMessage) {
3926        if (uuid == null) {
3927            return null;
3928        }
3929        for (Conversation conversation : getConversations()) {
3930            if (conversation.getJid().asBareJid().equals(recipient) && conversation.getAccount() == account) {
3931                final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
3932                if (message != null) {
3933                    markMessage(message, status, errorMessage);
3934                }
3935                return message;
3936            }
3937        }
3938        return null;
3939    }
3940
3941    public boolean markMessage(Conversation conversation, String uuid, int status, String serverMessageId) {
3942        if (uuid == null) {
3943            return false;
3944        } else {
3945            Message message = conversation.findSentMessageWithUuid(uuid);
3946            if (message != null) {
3947                if (message.getServerMsgId() == null) {
3948                    message.setServerMsgId(serverMessageId);
3949                }
3950                markMessage(message, status);
3951                return true;
3952            } else {
3953                return false;
3954            }
3955        }
3956    }
3957
3958    public void markMessage(Message message, int status) {
3959        markMessage(message, status, null);
3960    }
3961
3962
3963    public void markMessage(final Message message, final int status, final String errorMessage) {
3964        final int oldStatus = message.getStatus();
3965        if (status == Message.STATUS_SEND_FAILED && (oldStatus == Message.STATUS_SEND_RECEIVED || oldStatus == Message.STATUS_SEND_DISPLAYED)) {
3966            return;
3967        }
3968        if (status == Message.STATUS_SEND_RECEIVED && oldStatus == Message.STATUS_SEND_DISPLAYED) {
3969            return;
3970        }
3971        message.setErrorMessage(errorMessage);
3972        message.setStatus(status);
3973        databaseBackend.updateMessage(message, false);
3974        updateConversationUi();
3975        if (oldStatus != status && status == Message.STATUS_SEND_FAILED) {
3976            mNotificationService.pushFailedDelivery(message);
3977        }
3978    }
3979
3980    private SharedPreferences getPreferences() {
3981        return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
3982    }
3983
3984    public long getAutomaticMessageDeletionDate() {
3985        final long timeout = getLongPreference(SettingsActivity.AUTOMATIC_MESSAGE_DELETION, R.integer.automatic_message_deletion);
3986        return timeout == 0 ? timeout : (System.currentTimeMillis() - (timeout * 1000));
3987    }
3988
3989    public long getLongPreference(String name, @IntegerRes int res) {
3990        long defaultValue = getResources().getInteger(res);
3991        try {
3992            return Long.parseLong(getPreferences().getString(name, String.valueOf(defaultValue)));
3993        } catch (NumberFormatException e) {
3994            return defaultValue;
3995        }
3996    }
3997
3998    public boolean getBooleanPreference(String name, @BoolRes int res) {
3999        return getPreferences().getBoolean(name, getResources().getBoolean(res));
4000    }
4001
4002    public boolean confirmMessages() {
4003        return getBooleanPreference("confirm_messages", R.bool.confirm_messages);
4004    }
4005
4006    public boolean allowMessageCorrection() {
4007        return getBooleanPreference("allow_message_correction", R.bool.allow_message_correction);
4008    }
4009
4010    public boolean sendChatStates() {
4011        return getBooleanPreference("chat_states", R.bool.chat_states);
4012    }
4013
4014    private boolean synchronizeWithBookmarks() {
4015        return getBooleanPreference("autojoin", R.bool.autojoin);
4016    }
4017
4018    public boolean useTorToConnect() {
4019        return QuickConversationsService.isConversations() && getBooleanPreference("use_tor", R.bool.use_tor);
4020    }
4021
4022    public boolean showExtendedConnectionOptions() {
4023        return QuickConversationsService.isConversations() && getBooleanPreference("show_connection_options", R.bool.show_connection_options);
4024    }
4025
4026    public boolean broadcastLastActivity() {
4027        return getBooleanPreference(SettingsActivity.BROADCAST_LAST_ACTIVITY, R.bool.last_activity);
4028    }
4029
4030    public int unreadCount() {
4031        int count = 0;
4032        for (Conversation conversation : getConversations()) {
4033            count += conversation.unreadCount();
4034        }
4035        return count;
4036    }
4037
4038
4039    private <T> List<T> threadSafeList(Set<T> set) {
4040        synchronized (LISTENER_LOCK) {
4041            return set.size() == 0 ? Collections.emptyList() : new ArrayList<>(set);
4042        }
4043    }
4044
4045    public void showErrorToastInUi(int resId) {
4046        for (OnShowErrorToast listener : threadSafeList(this.mOnShowErrorToasts)) {
4047            listener.onShowErrorToast(resId);
4048        }
4049    }
4050
4051    public void updateConversationUi() {
4052        for (OnConversationUpdate listener : threadSafeList(this.mOnConversationUpdates)) {
4053            listener.onConversationUpdate();
4054        }
4055    }
4056
4057    public void notifyJingleRtpConnectionUpdate(final Account account, final Jid with, final String sessionId, final RtpEndUserState state) {
4058        for (OnJingleRtpConnectionUpdate listener : threadSafeList(this.onJingleRtpConnectionUpdate)) {
4059            listener.onJingleRtpConnectionUpdate(account, with, sessionId, state);
4060        }
4061    }
4062
4063    public void notifyJingleRtpConnectionUpdate(AppRTCAudioManager.AudioDevice selectedAudioDevice, Set<AppRTCAudioManager.AudioDevice> availableAudioDevices) {
4064        for (OnJingleRtpConnectionUpdate listener : threadSafeList(this.onJingleRtpConnectionUpdate)) {
4065            listener.onAudioDeviceChanged(selectedAudioDevice, availableAudioDevices);
4066        }
4067    }
4068
4069    public void updateAccountUi() {
4070        for (OnAccountUpdate listener : threadSafeList(this.mOnAccountUpdates)) {
4071            listener.onAccountUpdate();
4072        }
4073    }
4074
4075    public void updateRosterUi() {
4076        for (OnRosterUpdate listener : threadSafeList(this.mOnRosterUpdates)) {
4077            listener.onRosterUpdate();
4078        }
4079    }
4080
4081    public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
4082        if (mOnCaptchaRequested.size() > 0) {
4083            DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
4084            Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
4085                    (int) (captcha.getHeight() * metrics.scaledDensity), false);
4086            for (OnCaptchaRequested listener : threadSafeList(this.mOnCaptchaRequested)) {
4087                listener.onCaptchaRequested(account, id, data, scaled);
4088            }
4089            return true;
4090        }
4091        return false;
4092    }
4093
4094    public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
4095        for (OnUpdateBlocklist listener : threadSafeList(this.mOnUpdateBlocklist)) {
4096            listener.OnUpdateBlocklist(status);
4097        }
4098    }
4099
4100    public void updateMucRosterUi() {
4101        for (OnMucRosterUpdate listener : threadSafeList(this.mOnMucRosterUpdate)) {
4102            listener.onMucRosterUpdate();
4103        }
4104    }
4105
4106    public void keyStatusUpdated(AxolotlService.FetchStatus report) {
4107        for (OnKeyStatusUpdated listener : threadSafeList(this.mOnKeyStatusUpdated)) {
4108            listener.onKeyStatusUpdated(report);
4109        }
4110    }
4111
4112    public Account findAccountByJid(final Jid jid) {
4113        for (final Account account : this.accounts) {
4114            if (account.getJid().asBareJid().equals(jid.asBareJid())) {
4115                return account;
4116            }
4117        }
4118        return null;
4119    }
4120
4121    public Account findAccountByUuid(final String uuid) {
4122        for (Account account : this.accounts) {
4123            if (account.getUuid().equals(uuid)) {
4124                return account;
4125            }
4126        }
4127        return null;
4128    }
4129
4130    public Conversation findConversationByUuid(String uuid) {
4131        for (Conversation conversation : getConversations()) {
4132            if (conversation.getUuid().equals(uuid)) {
4133                return conversation;
4134            }
4135        }
4136        return null;
4137    }
4138
4139    public Conversation findUniqueConversationByJid(XmppUri xmppUri) {
4140        List<Conversation> findings = new ArrayList<>();
4141        for (Conversation c : getConversations()) {
4142            if (c.getAccount().isEnabled() && c.getJid().asBareJid().equals(xmppUri.getJid()) && ((c.getMode() == Conversational.MODE_MULTI) == xmppUri.isAction(XmppUri.ACTION_JOIN))) {
4143                findings.add(c);
4144            }
4145        }
4146        return findings.size() == 1 ? findings.get(0) : null;
4147    }
4148
4149    public boolean markRead(final Conversation conversation, boolean dismiss) {
4150        return markRead(conversation, null, dismiss).size() > 0;
4151    }
4152
4153    public void markRead(final Conversation conversation) {
4154        markRead(conversation, null, true);
4155    }
4156
4157    public List<Message> markRead(final Conversation conversation, String upToUuid, boolean dismiss) {
4158        if (dismiss) {
4159            mNotificationService.clear(conversation);
4160        }
4161        final List<Message> readMessages = conversation.markRead(upToUuid);
4162        if (readMessages.size() > 0) {
4163            Runnable runnable = () -> {
4164                for (Message message : readMessages) {
4165                    databaseBackend.updateMessage(message, false);
4166                }
4167            };
4168            mDatabaseWriterExecutor.execute(runnable);
4169            updateConversationUi();
4170            updateUnreadCountBadge();
4171            return readMessages;
4172        } else {
4173            return readMessages;
4174        }
4175    }
4176
4177    public synchronized void updateUnreadCountBadge() {
4178        int count = unreadCount();
4179        if (unreadCount != count) {
4180            Log.d(Config.LOGTAG, "update unread count to " + count);
4181            if (count > 0) {
4182                ShortcutBadger.applyCount(getApplicationContext(), count);
4183            } else {
4184                ShortcutBadger.removeCount(getApplicationContext());
4185            }
4186            unreadCount = count;
4187        }
4188    }
4189
4190    public void sendReadMarker(final Conversation conversation, String upToUuid) {
4191        final boolean isPrivateAndNonAnonymousMuc = conversation.getMode() == Conversation.MODE_MULTI && conversation.isPrivateAndNonAnonymous();
4192        final List<Message> readMessages = this.markRead(conversation, upToUuid, true);
4193        if (readMessages.size() > 0) {
4194            updateConversationUi();
4195        }
4196        final Message markable = Conversation.getLatestMarkableMessage(readMessages, isPrivateAndNonAnonymousMuc);
4197        if (confirmMessages()
4198                && markable != null
4199                && (markable.trusted() || isPrivateAndNonAnonymousMuc)
4200                && markable.getRemoteMsgId() != null) {
4201            Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
4202            final Account account = conversation.getAccount();
4203            final MessagePacket packet = mMessageGenerator.confirm(markable);
4204            this.sendMessagePacket(account, packet);
4205        }
4206    }
4207
4208    public SecureRandom getRNG() {
4209        return this.mRandom;
4210    }
4211
4212    public MemorizingTrustManager getMemorizingTrustManager() {
4213        return this.mMemorizingTrustManager;
4214    }
4215
4216    public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
4217        this.mMemorizingTrustManager = trustManager;
4218    }
4219
4220    public void updateMemorizingTrustmanager() {
4221        final MemorizingTrustManager tm;
4222        final boolean dontTrustSystemCAs = getBooleanPreference("dont_trust_system_cas", R.bool.dont_trust_system_cas);
4223        if (dontTrustSystemCAs) {
4224            tm = new MemorizingTrustManager(getApplicationContext(), null);
4225        } else {
4226            tm = new MemorizingTrustManager(getApplicationContext());
4227        }
4228        setMemorizingTrustManager(tm);
4229    }
4230
4231    public LruCache<String, Bitmap> getBitmapCache() {
4232        return this.mBitmapCache;
4233    }
4234
4235    public Collection<String> getKnownHosts() {
4236        final Set<String> hosts = new HashSet<>();
4237        for (final Account account : getAccounts()) {
4238            hosts.add(account.getServer());
4239            for (final Contact contact : account.getRoster().getContacts()) {
4240                if (contact.showInRoster()) {
4241                    final String server = contact.getServer();
4242                    if (server != null) {
4243                        hosts.add(server);
4244                    }
4245                }
4246            }
4247        }
4248        if (Config.QUICKSY_DOMAIN != null) {
4249            hosts.remove(Config.QUICKSY_DOMAIN.toEscapedString()); //we only want to show this when we type a e164 number
4250        }
4251        if (Config.DOMAIN_LOCK != null) {
4252            hosts.add(Config.DOMAIN_LOCK);
4253        }
4254        if (Config.MAGIC_CREATE_DOMAIN != null) {
4255            hosts.add(Config.MAGIC_CREATE_DOMAIN);
4256        }
4257        return hosts;
4258    }
4259
4260    public Collection<String> getKnownConferenceHosts() {
4261        final Set<String> mucServers = new HashSet<>();
4262        for (final Account account : accounts) {
4263            if (account.getXmppConnection() != null) {
4264                mucServers.addAll(account.getXmppConnection().getMucServers());
4265                for (Bookmark bookmark : account.getBookmarks()) {
4266                    final Jid jid = bookmark.getJid();
4267                    final String s = jid == null ? null : jid.getDomain().toEscapedString();
4268                    if (s != null) {
4269                        mucServers.add(s);
4270                    }
4271                }
4272            }
4273        }
4274        return mucServers;
4275    }
4276
4277    public void sendMessagePacket(Account account, MessagePacket packet) {
4278        XmppConnection connection = account.getXmppConnection();
4279        if (connection != null) {
4280            connection.sendMessagePacket(packet);
4281        }
4282    }
4283
4284    public void sendPresencePacket(Account account, PresencePacket packet) {
4285        XmppConnection connection = account.getXmppConnection();
4286        if (connection != null) {
4287            connection.sendPresencePacket(packet);
4288        }
4289    }
4290
4291    public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
4292        final XmppConnection connection = account.getXmppConnection();
4293        if (connection != null) {
4294            IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
4295            connection.sendUnmodifiedIqPacket(request, connection.registrationResponseListener, true);
4296        }
4297    }
4298
4299    public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
4300        final XmppConnection connection = account.getXmppConnection();
4301        if (connection != null) {
4302            connection.sendIqPacket(packet, callback);
4303        } else if (callback != null) {
4304            callback.onIqPacketReceived(account, new IqPacket(IqPacket.TYPE.TIMEOUT));
4305        }
4306    }
4307
4308    public void sendPresence(final Account account) {
4309        sendPresence(account, checkListeners() && broadcastLastActivity());
4310    }
4311
4312    private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
4313        Presence.Status status;
4314        if (manuallyChangePresence()) {
4315            status = account.getPresenceStatus();
4316        } else {
4317            status = getTargetPresence();
4318        }
4319        final PresencePacket packet = mPresenceGenerator.selfPresence(account, status);
4320        if (mLastActivity > 0 && includeIdleTimestamp) {
4321            long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
4322            packet.addChild("idle", Namespace.IDLE).setAttribute("since", AbstractGenerator.getTimestamp(since));
4323        }
4324        sendPresencePacket(account, packet);
4325    }
4326
4327    private void deactivateGracePeriod() {
4328        for (Account account : getAccounts()) {
4329            account.deactivateGracePeriod();
4330        }
4331    }
4332
4333    public void refreshAllPresences() {
4334        boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
4335        for (Account account : getAccounts()) {
4336            if (account.isEnabled()) {
4337                sendPresence(account, includeIdleTimestamp);
4338            }
4339        }
4340    }
4341
4342    private void refreshAllFcmTokens() {
4343        for (Account account : getAccounts()) {
4344            if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
4345                mPushManagementService.registerPushTokenOnServer(account);
4346                //TODO renew mucs
4347            }
4348        }
4349    }
4350
4351    private void sendOfflinePresence(final Account account) {
4352        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending offline presence");
4353        sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
4354    }
4355
4356    public MessageGenerator getMessageGenerator() {
4357        return this.mMessageGenerator;
4358    }
4359
4360    public PresenceGenerator getPresenceGenerator() {
4361        return this.mPresenceGenerator;
4362    }
4363
4364    public IqGenerator getIqGenerator() {
4365        return this.mIqGenerator;
4366    }
4367
4368    public IqParser getIqParser() {
4369        return this.mIqParser;
4370    }
4371
4372    public JingleConnectionManager getJingleConnectionManager() {
4373        return this.mJingleConnectionManager;
4374    }
4375
4376    public MessageArchiveService getMessageArchiveService() {
4377        return this.mMessageArchiveService;
4378    }
4379
4380    public QuickConversationsService getQuickConversationsService() {
4381        return this.mQuickConversationsService;
4382    }
4383
4384    public List<Contact> findContacts(Jid jid, String accountJid) {
4385        ArrayList<Contact> contacts = new ArrayList<>();
4386        for (Account account : getAccounts()) {
4387            if ((account.isEnabled() || accountJid != null)
4388                    && (accountJid == null || accountJid.equals(account.getJid().asBareJid().toString()))) {
4389                Contact contact = account.getRoster().getContactFromContactList(jid);
4390                if (contact != null) {
4391                    contacts.add(contact);
4392                }
4393            }
4394        }
4395        return contacts;
4396    }
4397
4398    public Conversation findFirstMuc(Jid jid) {
4399        for (Conversation conversation : getConversations()) {
4400            if (conversation.getAccount().isEnabled() && conversation.getJid().asBareJid().equals(jid.asBareJid()) && conversation.getMode() == Conversation.MODE_MULTI) {
4401                return conversation;
4402            }
4403        }
4404        return null;
4405    }
4406
4407    public NotificationService getNotificationService() {
4408        return this.mNotificationService;
4409    }
4410
4411    public HttpConnectionManager getHttpConnectionManager() {
4412        return this.mHttpConnectionManager;
4413    }
4414
4415    public void resendFailedMessages(final Message message) {
4416        final Collection<Message> messages = new ArrayList<>();
4417        Message current = message;
4418        while (current.getStatus() == Message.STATUS_SEND_FAILED) {
4419            messages.add(current);
4420            if (current.mergeable(current.next())) {
4421                current = current.next();
4422            } else {
4423                break;
4424            }
4425        }
4426        for (final Message msg : messages) {
4427            msg.setTime(System.currentTimeMillis());
4428            markMessage(msg, Message.STATUS_WAITING);
4429            this.resendMessage(msg, false);
4430        }
4431        if (message.getConversation() instanceof Conversation) {
4432            ((Conversation) message.getConversation()).sort();
4433        }
4434        updateConversationUi();
4435    }
4436
4437    public void clearConversationHistory(final Conversation conversation) {
4438        final long clearDate;
4439        final String reference;
4440        if (conversation.countMessages() > 0) {
4441            Message latestMessage = conversation.getLatestMessage();
4442            clearDate = latestMessage.getTimeSent() + 1000;
4443            reference = latestMessage.getServerMsgId();
4444        } else {
4445            clearDate = System.currentTimeMillis();
4446            reference = null;
4447        }
4448        conversation.clearMessages();
4449        conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
4450        conversation.setLastClearHistory(clearDate, reference);
4451        Runnable runnable = () -> {
4452            databaseBackend.deleteMessagesInConversation(conversation);
4453            databaseBackend.updateConversation(conversation);
4454        };
4455        mDatabaseWriterExecutor.execute(runnable);
4456    }
4457
4458    public boolean sendBlockRequest(final Blockable blockable, boolean reportSpam) {
4459        if (blockable != null && blockable.getBlockedJid() != null) {
4460            final Jid jid = blockable.getBlockedJid();
4461            this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid, reportSpam), (a, response) -> {
4462                if (response.getType() == IqPacket.TYPE.RESULT) {
4463                    a.getBlocklist().add(jid);
4464                    updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
4465                }
4466            });
4467            if (blockable.getBlockedJid().isFullJid()) {
4468                return false;
4469            } else if (removeBlockedConversations(blockable.getAccount(), jid)) {
4470                updateConversationUi();
4471                return true;
4472            } else {
4473                return false;
4474            }
4475        } else {
4476            return false;
4477        }
4478    }
4479
4480    public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
4481        boolean removed = false;
4482        synchronized (this.conversations) {
4483            boolean domainJid = blockedJid.getLocal() == null;
4484            for (Conversation conversation : this.conversations) {
4485                boolean jidMatches = (domainJid && blockedJid.getDomain().equals(conversation.getJid().getDomain()))
4486                        || blockedJid.equals(conversation.getJid().asBareJid());
4487                if (conversation.getAccount() == account
4488                        && conversation.getMode() == Conversation.MODE_SINGLE
4489                        && jidMatches) {
4490                    this.conversations.remove(conversation);
4491                    markRead(conversation);
4492                    conversation.setStatus(Conversation.STATUS_ARCHIVED);
4493                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conversation " + conversation.getJid().asBareJid() + " because jid was blocked");
4494                    updateConversation(conversation);
4495                    removed = true;
4496                }
4497            }
4498        }
4499        return removed;
4500    }
4501
4502    public void sendUnblockRequest(final Blockable blockable) {
4503        if (blockable != null && blockable.getJid() != null) {
4504            final Jid jid = blockable.getBlockedJid();
4505            this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
4506                @Override
4507                public void onIqPacketReceived(final Account account, final IqPacket packet) {
4508                    if (packet.getType() == IqPacket.TYPE.RESULT) {
4509                        account.getBlocklist().remove(jid);
4510                        updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
4511                    }
4512                }
4513            });
4514        }
4515    }
4516
4517    public void publishDisplayName(Account account) {
4518        String displayName = account.getDisplayName();
4519        final IqPacket request;
4520        if (TextUtils.isEmpty(displayName)) {
4521            request = mIqGenerator.deleteNode(Namespace.NICK);
4522        } else {
4523            request = mIqGenerator.publishNick(displayName);
4524        }
4525        mAvatarService.clear(account);
4526        sendIqPacket(account, request, (account1, packet) -> {
4527            if (packet.getType() == IqPacket.TYPE.ERROR) {
4528                Log.d(Config.LOGTAG, account1.getJid().asBareJid() + ": unable to modify nick name " + packet.toString());
4529            }
4530        });
4531    }
4532
4533    public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
4534        ServiceDiscoveryResult result = discoCache.get(key);
4535        if (result != null) {
4536            return result;
4537        } else {
4538            result = databaseBackend.findDiscoveryResult(key.first, key.second);
4539            if (result != null) {
4540                discoCache.put(key, result);
4541            }
4542            return result;
4543        }
4544    }
4545
4546    public void fetchCaps(Account account, final Jid jid, final Presence presence) {
4547        final Pair<String, String> key = new Pair<>(presence.getHash(), presence.getVer());
4548        final ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
4549        if (disco != null) {
4550            presence.setServiceDiscoveryResult(disco);
4551        } else {
4552            if (account.inProgressDiscoFetches.contains(key)) {
4553                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping duplicate disco request for " + key.second + " to " + jid);
4554                return;
4555            }
4556            account.inProgressDiscoFetches.add(key);
4557            final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
4558            request.setTo(jid);
4559            final String node = presence.getNode();
4560            final String ver = presence.getVer();
4561            final Element query = request.query(Namespace.DISCO_INFO);
4562            if (node != null && ver != null) {
4563                query.setAttribute("node", node + "#" + ver);
4564            }
4565            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": making disco request for " + key.second + " to " + jid);
4566            sendIqPacket(account, request, (a, response) -> {
4567                if (response.getType() == IqPacket.TYPE.RESULT) {
4568                    ServiceDiscoveryResult discoveryResult = new ServiceDiscoveryResult(response);
4569                    if (presence.getVer().equals(discoveryResult.getVer())) {
4570                        databaseBackend.insertDiscoveryResult(discoveryResult);
4571                        injectServiceDiscoveryResult(a.getRoster(), presence.getHash(), presence.getVer(), discoveryResult);
4572                    } else {
4573                        Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + discoveryResult.getVer());
4574                    }
4575                } else {
4576                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to fetch caps from " + jid);
4577                }
4578                a.inProgressDiscoFetches.remove(key);
4579            });
4580        }
4581    }
4582
4583    private void injectServiceDiscoveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
4584        for (final Contact contact : roster.getContacts()) {
4585            for (final Presence presence : contact.getPresences().getPresences()) {
4586                if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
4587                    presence.setServiceDiscoveryResult(disco);
4588                }
4589            }
4590        }
4591    }
4592
4593    public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
4594        final MessageArchiveService.Version version = MessageArchiveService.Version.get(account);
4595        IqPacket request = new IqPacket(IqPacket.TYPE.GET);
4596        request.addChild("prefs", version.namespace);
4597        sendIqPacket(account, request, (account1, packet) -> {
4598            Element prefs = packet.findChild("prefs", version.namespace);
4599            if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
4600                callback.onPreferencesFetched(prefs);
4601            } else {
4602                callback.onPreferencesFetchFailed();
4603            }
4604        });
4605    }
4606
4607    public PushManagementService getPushManagementService() {
4608        return mPushManagementService;
4609    }
4610
4611    public void changeStatus(Account account, PresenceTemplate template, String signature) {
4612        if (!template.getStatusMessage().isEmpty()) {
4613            databaseBackend.insertPresenceTemplate(template);
4614        }
4615        account.setPgpSignature(signature);
4616        account.setPresenceStatus(template.getStatus());
4617        account.setPresenceStatusMessage(template.getStatusMessage());
4618        databaseBackend.updateAccount(account);
4619        sendPresence(account);
4620    }
4621
4622    public List<PresenceTemplate> getPresenceTemplates(Account account) {
4623        List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
4624        for (PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
4625            if (!templates.contains(template)) {
4626                templates.add(0, template);
4627            }
4628        }
4629        return templates;
4630    }
4631
4632    public void saveConversationAsBookmark(Conversation conversation, String name) {
4633        final Account account = conversation.getAccount();
4634        final Bookmark bookmark = new Bookmark(account, conversation.getJid().asBareJid());
4635        final String nick = conversation.getJid().getResource();
4636        if (nick != null && !nick.isEmpty() && !nick.equals(MucOptions.defaultNick(account))) {
4637            bookmark.setNick(nick);
4638        }
4639        if (!TextUtils.isEmpty(name)) {
4640            bookmark.setBookmarkName(name);
4641        }
4642        bookmark.setAutojoin(getPreferences().getBoolean("autojoin", getResources().getBoolean(R.bool.autojoin)));
4643        createBookmark(account, bookmark);
4644        bookmark.setConversation(conversation);
4645    }
4646
4647    public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
4648        boolean performedVerification = false;
4649        final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
4650        for (XmppUri.Fingerprint fp : fingerprints) {
4651            if (fp.type == XmppUri.FingerprintType.OMEMO) {
4652                String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
4653                FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
4654                if (fingerprintStatus != null) {
4655                    if (!fingerprintStatus.isVerified()) {
4656                        performedVerification = true;
4657                        axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
4658                    }
4659                } else {
4660                    axolotlService.preVerifyFingerprint(contact, fingerprint);
4661                }
4662            }
4663        }
4664        return performedVerification;
4665    }
4666
4667    public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
4668        final AxolotlService axolotlService = account.getAxolotlService();
4669        boolean verifiedSomething = false;
4670        for (XmppUri.Fingerprint fp : fingerprints) {
4671            if (fp.type == XmppUri.FingerprintType.OMEMO) {
4672                String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
4673                Log.d(Config.LOGTAG, "trying to verify own fp=" + fingerprint);
4674                FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
4675                if (fingerprintStatus != null) {
4676                    if (!fingerprintStatus.isVerified()) {
4677                        axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
4678                        verifiedSomething = true;
4679                    }
4680                } else {
4681                    axolotlService.preVerifyFingerprint(account, fingerprint);
4682                    verifiedSomething = true;
4683                }
4684            }
4685        }
4686        return verifiedSomething;
4687    }
4688
4689    public boolean blindTrustBeforeVerification() {
4690        return getBooleanPreference(SettingsActivity.BLIND_TRUST_BEFORE_VERIFICATION, R.bool.btbv);
4691    }
4692
4693    public ShortcutService getShortcutService() {
4694        return mShortcutService;
4695    }
4696
4697    public void pushMamPreferences(Account account, Element prefs) {
4698        IqPacket set = new IqPacket(IqPacket.TYPE.SET);
4699        set.addChild(prefs);
4700        sendIqPacket(account, set, null);
4701    }
4702
4703    public void evictPreview(String uuid) {
4704        if (mBitmapCache.remove(uuid) != null) {
4705            Log.d(Config.LOGTAG, "deleted cached preview");
4706        }
4707    }
4708
4709    public interface OnMamPreferencesFetched {
4710        void onPreferencesFetched(Element prefs);
4711
4712        void onPreferencesFetchFailed();
4713    }
4714
4715    public interface OnAccountCreated {
4716        void onAccountCreated(Account account);
4717
4718        void informUser(int r);
4719    }
4720
4721    public interface OnMoreMessagesLoaded {
4722        void onMoreMessagesLoaded(int count, Conversation conversation);
4723
4724        void informUser(int r);
4725    }
4726
4727    public interface OnAccountPasswordChanged {
4728        void onPasswordChangeSucceeded();
4729
4730        void onPasswordChangeFailed();
4731    }
4732
4733    public interface OnRoomDestroy {
4734        void onRoomDestroySucceeded();
4735
4736        void onRoomDestroyFailed();
4737    }
4738
4739    public interface OnAffiliationChanged {
4740        void onAffiliationChangedSuccessful(Jid jid);
4741
4742        void onAffiliationChangeFailed(Jid jid, int resId);
4743    }
4744
4745    public interface OnConversationUpdate {
4746        void onConversationUpdate();
4747    }
4748
4749    public interface OnJingleRtpConnectionUpdate {
4750        void onJingleRtpConnectionUpdate(final Account account, final Jid with, final String sessionId, final RtpEndUserState state);
4751
4752        void onAudioDeviceChanged(AppRTCAudioManager.AudioDevice selectedAudioDevice, Set<AppRTCAudioManager.AudioDevice> availableAudioDevices);
4753    }
4754
4755    public interface OnAccountUpdate {
4756        void onAccountUpdate();
4757    }
4758
4759    public interface OnCaptchaRequested {
4760        void onCaptchaRequested(Account account, String id, Data data, Bitmap captcha);
4761    }
4762
4763    public interface OnRosterUpdate {
4764        void onRosterUpdate();
4765    }
4766
4767    public interface OnMucRosterUpdate {
4768        void onMucRosterUpdate();
4769    }
4770
4771    public interface OnConferenceConfigurationFetched {
4772        void onConferenceConfigurationFetched(Conversation conversation);
4773
4774        void onFetchFailed(Conversation conversation, Element error);
4775    }
4776
4777    public interface OnConferenceJoined {
4778        void onConferenceJoined(Conversation conversation);
4779    }
4780
4781    public interface OnConfigurationPushed {
4782        void onPushSucceeded();
4783
4784        void onPushFailed();
4785    }
4786
4787    public interface OnShowErrorToast {
4788        void onShowErrorToast(int resId);
4789    }
4790
4791    public class XmppConnectionBinder extends Binder {
4792        public XmppConnectionService getService() {
4793            return XmppConnectionService.this;
4794        }
4795    }
4796
4797    private class InternalEventReceiver extends BroadcastReceiver {
4798
4799        @Override
4800        public void onReceive(Context context, Intent intent) {
4801            onStartCommand(intent, 0, 0);
4802        }
4803    }
4804
4805    public static class OngoingCall {
4806        private final AbstractJingleConnection.Id id;
4807        private final Set<Media> media;
4808
4809        public OngoingCall(AbstractJingleConnection.Id id, Set<Media> media) {
4810            this.id = id;
4811            this.media = media;
4812        }
4813
4814        @Override
4815        public boolean equals(Object o) {
4816            if (this == o) return true;
4817            if (o == null || getClass() != o.getClass()) return false;
4818            OngoingCall that = (OngoingCall) o;
4819            return Objects.equal(id, that.id);
4820        }
4821
4822        @Override
4823        public int hashCode() {
4824            return Objects.hashCode(id);
4825        }
4826    }
4827}