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