XmppConnectionService.java

   1package eu.siacs.conversations.services;
   2
   3import android.annotation.SuppressLint;
   4import android.annotation.TargetApi;
   5import android.app.AlarmManager;
   6import android.app.PendingIntent;
   7import android.app.Service;
   8import android.content.Context;
   9import android.content.Intent;
  10import android.content.IntentFilter;
  11import android.content.SharedPreferences;
  12import android.database.ContentObserver;
  13import android.graphics.Bitmap;
  14import android.media.AudioManager;
  15import android.net.ConnectivityManager;
  16import android.net.NetworkInfo;
  17import android.net.Uri;
  18import android.os.Binder;
  19import android.os.Build;
  20import android.os.Bundle;
  21import android.os.Environment;
  22import android.os.IBinder;
  23import android.os.PowerManager;
  24import android.os.PowerManager.WakeLock;
  25import android.os.SystemClock;
  26import android.preference.PreferenceManager;
  27import android.provider.ContactsContract;
  28import android.security.KeyChain;
  29import android.support.annotation.BoolRes;
  30import android.support.annotation.IntegerRes;
  31import android.support.v4.app.RemoteInput;
  32import android.util.DisplayMetrics;
  33import android.util.Log;
  34import android.util.LruCache;
  35import android.util.Pair;
  36
  37import net.java.otr4j.OtrException;
  38import net.java.otr4j.session.Session;
  39import net.java.otr4j.session.SessionID;
  40import net.java.otr4j.session.SessionImpl;
  41import net.java.otr4j.session.SessionStatus;
  42
  43import org.openintents.openpgp.IOpenPgpService2;
  44import org.openintents.openpgp.util.OpenPgpApi;
  45import org.openintents.openpgp.util.OpenPgpServiceConnection;
  46
  47import java.math.BigInteger;
  48import java.net.URL;
  49import java.security.SecureRandom;
  50import java.security.cert.CertificateException;
  51import java.security.cert.X509Certificate;
  52import java.util.ArrayList;
  53import java.util.Arrays;
  54import java.util.Collection;
  55import java.util.Collections;
  56import java.util.HashMap;
  57import java.util.HashSet;
  58import java.util.Hashtable;
  59import java.util.Iterator;
  60import java.util.List;
  61import java.util.ListIterator;
  62import java.util.Locale;
  63import java.util.Map;
  64import java.util.concurrent.CopyOnWriteArrayList;
  65import java.util.concurrent.CountDownLatch;
  66import java.util.concurrent.atomic.AtomicBoolean;
  67import java.util.concurrent.atomic.AtomicLong;
  68
  69import de.duenndns.ssl.MemorizingTrustManager;
  70import eu.siacs.conversations.Config;
  71import eu.siacs.conversations.R;
  72import eu.siacs.conversations.crypto.PgpDecryptionService;
  73import eu.siacs.conversations.crypto.PgpEngine;
  74import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  75import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
  76import eu.siacs.conversations.crypto.axolotl.XmppAxolotlMessage;
  77import eu.siacs.conversations.entities.Account;
  78import eu.siacs.conversations.entities.Blockable;
  79import eu.siacs.conversations.entities.Bookmark;
  80import eu.siacs.conversations.entities.Contact;
  81import eu.siacs.conversations.entities.Conversation;
  82import eu.siacs.conversations.entities.DownloadableFile;
  83import eu.siacs.conversations.entities.Message;
  84import eu.siacs.conversations.entities.MucOptions;
  85import eu.siacs.conversations.entities.MucOptions.OnRenameListener;
  86import eu.siacs.conversations.entities.Presence;
  87import eu.siacs.conversations.entities.PresenceTemplate;
  88import eu.siacs.conversations.entities.Roster;
  89import eu.siacs.conversations.entities.ServiceDiscoveryResult;
  90import eu.siacs.conversations.entities.Transferable;
  91import eu.siacs.conversations.entities.TransferablePlaceholder;
  92import eu.siacs.conversations.generator.AbstractGenerator;
  93import eu.siacs.conversations.generator.IqGenerator;
  94import eu.siacs.conversations.generator.MessageGenerator;
  95import eu.siacs.conversations.generator.PresenceGenerator;
  96import eu.siacs.conversations.http.HttpConnectionManager;
  97import eu.siacs.conversations.http.AesGcmURLStreamHandlerFactory;
  98import eu.siacs.conversations.parser.AbstractParser;
  99import eu.siacs.conversations.parser.IqParser;
 100import eu.siacs.conversations.parser.MessageParser;
 101import eu.siacs.conversations.parser.PresenceParser;
 102import eu.siacs.conversations.persistance.DatabaseBackend;
 103import eu.siacs.conversations.persistance.FileBackend;
 104import eu.siacs.conversations.ui.SettingsActivity;
 105import eu.siacs.conversations.ui.UiCallback;
 106import eu.siacs.conversations.utils.ConversationsFileObserver;
 107import eu.siacs.conversations.utils.CryptoHelper;
 108import eu.siacs.conversations.utils.ExceptionHelper;
 109import eu.siacs.conversations.utils.MimeUtils;
 110import eu.siacs.conversations.utils.OnPhoneContactsLoadedListener;
 111import eu.siacs.conversations.utils.PRNGFixes;
 112import eu.siacs.conversations.utils.PhoneHelper;
 113import eu.siacs.conversations.utils.ReplacingSerialSingleThreadExecutor;
 114import eu.siacs.conversations.utils.Resolver;
 115import eu.siacs.conversations.utils.SerialSingleThreadExecutor;
 116import eu.siacs.conversations.xml.Namespace;
 117import eu.siacs.conversations.utils.XmppUri;
 118import eu.siacs.conversations.xml.Element;
 119import eu.siacs.conversations.xmpp.OnBindListener;
 120import eu.siacs.conversations.xmpp.OnContactStatusChanged;
 121import eu.siacs.conversations.xmpp.OnIqPacketReceived;
 122import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
 123import eu.siacs.conversations.xmpp.OnMessageAcknowledged;
 124import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
 125import eu.siacs.conversations.xmpp.OnPresencePacketReceived;
 126import eu.siacs.conversations.xmpp.OnStatusChanged;
 127import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
 128import eu.siacs.conversations.xmpp.Patches;
 129import eu.siacs.conversations.xmpp.XmppConnection;
 130import eu.siacs.conversations.xmpp.chatstate.ChatState;
 131import eu.siacs.conversations.xmpp.forms.Data;
 132import eu.siacs.conversations.xmpp.jid.InvalidJidException;
 133import eu.siacs.conversations.xmpp.jid.Jid;
 134import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
 135import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
 136import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
 137import eu.siacs.conversations.xmpp.mam.MamReference;
 138import eu.siacs.conversations.xmpp.pep.Avatar;
 139import eu.siacs.conversations.xmpp.stanzas.IqPacket;
 140import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
 141import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
 142import me.leolin.shortcutbadger.ShortcutBadger;
 143
 144public class XmppConnectionService extends Service {
 145
 146	static {
 147		URL.setURLStreamHandlerFactory(new AesGcmURLStreamHandlerFactory());
 148	}
 149
 150	public static final String ACTION_REPLY_TO_CONVERSATION = "reply_to_conversations";
 151	public static final String ACTION_MARK_AS_READ = "mark_as_read";
 152	public static final String ACTION_CLEAR_NOTIFICATION = "clear_notification";
 153	public static final String ACTION_DISMISS_ERROR_NOTIFICATIONS = "dismiss_error";
 154	public static final String ACTION_TRY_AGAIN = "try_again";
 155	public static final String ACTION_IDLE_PING = "idle_ping";
 156	private static final String ACTION_MERGE_PHONE_CONTACTS = "merge_phone_contacts";
 157	public static final String ACTION_GCM_TOKEN_REFRESH = "gcm_token_refresh";
 158	public static final String ACTION_GCM_MESSAGE_RECEIVED = "gcm_message_received";
 159	private final SerialSingleThreadExecutor mFileAddingExecutor = new SerialSingleThreadExecutor("FileAdding");
 160	private final SerialSingleThreadExecutor mVideoCompressionExecutor = new SerialSingleThreadExecutor("VideoCompression");
 161	private final SerialSingleThreadExecutor mDatabaseWriterExecutor = new SerialSingleThreadExecutor("DatabaseWriter");
 162	private final SerialSingleThreadExecutor mDatabaseReaderExecutor = new SerialSingleThreadExecutor("DatabaseReader");
 163	private final SerialSingleThreadExecutor mNotificationExecutor = new SerialSingleThreadExecutor("NotificationExecutor");
 164	private ReplacingSerialSingleThreadExecutor mContactMergerExecutor = new ReplacingSerialSingleThreadExecutor(true);
 165	private final IBinder mBinder = new XmppConnectionBinder();
 166	private final List<Conversation> conversations = new CopyOnWriteArrayList<>();
 167	private final IqGenerator mIqGenerator = new IqGenerator(this);
 168	private final List<String> mInProgressAvatarFetches = new ArrayList<>();
 169	private final HashSet<Jid> mLowPingTimeoutMode = new HashSet<>();
 170
 171	private long mLastActivity = 0;
 172
 173	public DatabaseBackend databaseBackend;
 174	private ContentObserver contactObserver = new ContentObserver(null) {
 175		@Override
 176		public void onChange(boolean selfChange) {
 177			super.onChange(selfChange);
 178			Intent intent = new Intent(getApplicationContext(),
 179					XmppConnectionService.class);
 180			intent.setAction(ACTION_MERGE_PHONE_CONTACTS);
 181			startService(intent);
 182		}
 183	};
 184	private FileBackend fileBackend = new FileBackend(this);
 185	private MemorizingTrustManager mMemorizingTrustManager;
 186	private NotificationService mNotificationService = new NotificationService(this);
 187	private ShortcutService mShortcutService = new ShortcutService(this);
 188	private AtomicBoolean mInitialAddressbookSyncCompleted = new AtomicBoolean(false);
 189	private AtomicBoolean mForceForegroundService = new AtomicBoolean(false);
 190	private OnMessagePacketReceived mMessageParser = new MessageParser(this);
 191	private OnPresencePacketReceived mPresenceParser = new PresenceParser(this);
 192	private IqParser mIqParser = new IqParser(this);
 193	private OnIqPacketReceived mDefaultIqHandler = new OnIqPacketReceived() {
 194		@Override
 195		public void onIqPacketReceived(Account account, IqPacket packet) {
 196			if (packet.getType() != IqPacket.TYPE.RESULT) {
 197				Element error = packet.findChild("error");
 198				String text = error != null ? error.findChildContent("text") : null;
 199				if (text != null) {
 200					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": received iq error - " + text);
 201				}
 202			}
 203		}
 204	};
 205	private MessageGenerator mMessageGenerator = new MessageGenerator(this);
 206	private PresenceGenerator mPresenceGenerator = new PresenceGenerator(this);
 207	private List<Account> accounts;
 208	private JingleConnectionManager mJingleConnectionManager = new JingleConnectionManager(
 209			this);
 210	public OnContactStatusChanged onContactStatusChanged = new OnContactStatusChanged() {
 211
 212		@Override
 213		public void onContactStatusChanged(Contact contact, boolean online) {
 214			Conversation conversation = find(getConversations(), contact);
 215			if (conversation != null) {
 216				if (online) {
 217					conversation.endOtrIfNeeded();
 218					if (contact.getPresences().size() == 1) {
 219						sendUnsentMessages(conversation);
 220					}
 221				} else {
 222					//check if the resource we are haveing a conversation with is still online
 223					if (conversation.hasValidOtrSession()) {
 224						String otrResource = conversation.getOtrSession().getSessionID().getUserID();
 225						if (!(Arrays.asList(contact.getPresences().toResourceArray()).contains(otrResource))) {
 226							conversation.endOtrIfNeeded();
 227						}
 228					}
 229				}
 230			}
 231		}
 232	};
 233	private HttpConnectionManager mHttpConnectionManager = new HttpConnectionManager(
 234			this);
 235	private AvatarService mAvatarService = new AvatarService(this);
 236	private MessageArchiveService mMessageArchiveService = new MessageArchiveService(this);
 237	private PushManagementService mPushManagementService = new PushManagementService(this);
 238	private OnConversationUpdate mOnConversationUpdate = null;
 239
 240
 241	private final ConversationsFileObserver fileObserver = new ConversationsFileObserver(
 242			Environment.getExternalStorageDirectory().getAbsolutePath()
 243	) {
 244		@Override
 245		public void onEvent(int event, String path) {
 246			markFileDeleted(path);
 247		}
 248	};
 249	private final OnJinglePacketReceived jingleListener = new OnJinglePacketReceived() {
 250
 251		@Override
 252		public void onJinglePacketReceived(Account account, JinglePacket packet) {
 253			mJingleConnectionManager.deliverPacket(account, packet);
 254		}
 255	};
 256	private final OnMessageAcknowledged mOnMessageAcknowledgedListener = new OnMessageAcknowledged() {
 257
 258		@Override
 259		public void onMessageAcknowledged(Account account, String uuid) {
 260			for (final Conversation conversation : getConversations()) {
 261				if (conversation.getAccount() == account) {
 262					Message message = conversation.findUnsentMessageWithUuid(uuid);
 263					if (message != null) {
 264						markMessage(message, Message.STATUS_SEND);
 265					}
 266				}
 267			}
 268		}
 269	};
 270	private int convChangedListenerCount = 0;
 271	private OnShowErrorToast mOnShowErrorToast = null;
 272	private int showErrorToastListenerCount = 0;
 273	private int unreadCount = -1;
 274	private OnAccountUpdate mOnAccountUpdate = null;
 275	private OnCaptchaRequested mOnCaptchaRequested = null;
 276	private int accountChangedListenerCount = 0;
 277	private int captchaRequestedListenerCount = 0;
 278	private OnRosterUpdate mOnRosterUpdate = null;
 279	private OnUpdateBlocklist mOnUpdateBlocklist = null;
 280	private int updateBlocklistListenerCount = 0;
 281	private int rosterChangedListenerCount = 0;
 282	private OnMucRosterUpdate mOnMucRosterUpdate = null;
 283	private int mucRosterChangedListenerCount = 0;
 284	private OnKeyStatusUpdated mOnKeyStatusUpdated = null;
 285	private int keyStatusUpdatedListenerCount = 0;
 286	private AtomicLong mLastExpiryRun = new AtomicLong(0);
 287	private SecureRandom mRandom;
 288	private LruCache<Pair<String, String>, ServiceDiscoveryResult> discoCache = new LruCache<>(20);
 289	private final OnBindListener mOnBindListener = new OnBindListener() {
 290
 291		@Override
 292		public void onBind(final Account account) {
 293			synchronized (mInProgressAvatarFetches) {
 294				for (Iterator<String> iterator = mInProgressAvatarFetches.iterator(); iterator.hasNext(); ) {
 295					final String KEY = iterator.next();
 296					if (KEY.startsWith(account.getJid().toBareJid() + "_")) {
 297						iterator.remove();
 298					}
 299				}
 300			}
 301			if (account.setOption(Account.OPTION_LOGGED_IN_SUCCESSFULLY, true)) {
 302				databaseBackend.updateAccount(account);
 303			}
 304			account.getRoster().clearPresences();
 305			mJingleConnectionManager.cancelInTransmission();
 306			fetchRosterFromServer(account);
 307			fetchBookmarks(account);
 308			final boolean flexible= account.getXmppConnection().getFeatures().flexibleOfflineMessageRetrieval();
 309			final boolean catchup = getMessageArchiveService().inCatchup(account);
 310			if (flexible && catchup) {
 311				sendIqPacket(account, mIqGenerator.purgeOfflineMessages(), (acc, packet) -> {
 312					if (packet.getType() == IqPacket.TYPE.RESULT) {
 313						Log.d(Config.LOGTAG, acc.getJid().toBareJid()+": successfully purged offline messages");
 314					}
 315				});
 316			}
 317			sendPresence(account);
 318			if (mPushManagementService.available(account)) {
 319				mPushManagementService.registerPushTokenOnServer(account);
 320			}
 321			connectMultiModeConversations(account);
 322			syncDirtyContacts(account);
 323		}
 324	};
 325	private OnStatusChanged statusListener = new OnStatusChanged() {
 326
 327		@Override
 328		public void onStatusChanged(final Account account) {
 329			XmppConnection connection = account.getXmppConnection();
 330			if (mOnAccountUpdate != null) {
 331				mOnAccountUpdate.onAccountUpdate();
 332			}
 333			if (account.getStatus() == Account.State.ONLINE) {
 334				synchronized (mLowPingTimeoutMode) {
 335					if (mLowPingTimeoutMode.remove(account.getJid().toBareJid())) {
 336						Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": leaving low ping timeout mode");
 337					}
 338				}
 339				if (account.setShowErrorNotification(true)) {
 340					databaseBackend.updateAccount(account);
 341				}
 342				mMessageArchiveService.executePendingQueries(account);
 343				if (connection != null && connection.getFeatures().csi()) {
 344					if (checkListeners()) {
 345						Log.d(Config.LOGTAG, account.getJid().toBareJid() + " sending csi//inactive");
 346						connection.sendInactive();
 347					} else {
 348						Log.d(Config.LOGTAG, account.getJid().toBareJid() + " sending csi//active");
 349						connection.sendActive();
 350					}
 351				}
 352				List<Conversation> conversations = getConversations();
 353				for (Conversation conversation : conversations) {
 354					if (conversation.getAccount() == account
 355							&& !account.pendingConferenceJoins.contains(conversation)) {
 356						if (!conversation.startOtrIfNeeded()) {
 357							Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": couldn't start OTR with " + conversation.getContact().getJid() + " when needed");
 358						}
 359						sendUnsentMessages(conversation);
 360					}
 361				}
 362				for (Conversation conversation : account.pendingConferenceLeaves) {
 363					leaveMuc(conversation);
 364				}
 365				account.pendingConferenceLeaves.clear();
 366				for (Conversation conversation : account.pendingConferenceJoins) {
 367					joinMuc(conversation);
 368				}
 369				account.pendingConferenceJoins.clear();
 370				scheduleWakeUpCall(Config.PING_MAX_INTERVAL, account.getUuid().hashCode());
 371			} else if (account.getStatus() == Account.State.OFFLINE || account.getStatus() == Account.State.DISABLED) {
 372				resetSendingToWaiting(account);
 373				if (account.isEnabled() && isInLowPingTimeoutMode(account)) {
 374					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": went into offline state during low ping mode. reconnecting now");
 375					reconnectAccount(account, true, false);
 376				} else {
 377					int timeToReconnect = mRandom.nextInt(10) + 2;
 378					scheduleWakeUpCall(timeToReconnect, account.getUuid().hashCode());
 379				}
 380			} else if (account.getStatus() == Account.State.REGISTRATION_SUCCESSFUL) {
 381				databaseBackend.updateAccount(account);
 382				reconnectAccount(account, true, false);
 383			} else if (account.getStatus() != Account.State.CONNECTING && account.getStatus() != Account.State.NO_INTERNET) {
 384				resetSendingToWaiting(account);
 385				if (connection != null && account.getStatus().isAttemptReconnect()) {
 386					final int next = connection.getTimeToNextAttempt();
 387					final boolean lowPingTimeoutMode = isInLowPingTimeoutMode(account);
 388					if (next <= 0) {
 389						Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": error connecting account. reconnecting now. lowPingTimeout=" + Boolean.toString(lowPingTimeoutMode));
 390						reconnectAccount(account, true, false);
 391					} else {
 392						final int attempt = connection.getAttempt() + 1;
 393						Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": error connecting account. try again in " + next + "s for the " + attempt + " time. lowPingTimeout=" + Boolean.toString(lowPingTimeoutMode));
 394						scheduleWakeUpCall(next, account.getUuid().hashCode());
 395					}
 396				}
 397			}
 398			getNotificationService().updateErrorNotification();
 399		}
 400	};
 401
 402	private boolean isInLowPingTimeoutMode(Account account) {
 403		synchronized (mLowPingTimeoutMode) {
 404			return mLowPingTimeoutMode.contains(account.getJid().toBareJid());
 405		}
 406	}
 407
 408	public void startForcingForegroundNotification() {
 409		mForceForegroundService.set(true);
 410		toggleForegroundService();
 411	}
 412
 413	public void stopForcingForegroundNotification() {
 414		mForceForegroundService.set(false);
 415		toggleForegroundService();
 416	}
 417
 418	private OpenPgpServiceConnection pgpServiceConnection;
 419	private PgpEngine mPgpEngine = null;
 420	private WakeLock wakeLock;
 421	private PowerManager pm;
 422	private LruCache<String, Bitmap> mBitmapCache;
 423	private EventReceiver mEventReceiver = new EventReceiver();
 424
 425	public final CountDownLatch restoredFromDatabaseLatch = new CountDownLatch(1);
 426
 427	private static String generateFetchKey(Account account, final Avatar avatar) {
 428		return account.getJid().toBareJid() + "_" + avatar.owner + "_" + avatar.sha1sum;
 429	}
 430
 431	public boolean areMessagesInitialized() {
 432		return this.restoredFromDatabaseLatch.getCount() == 0;
 433	}
 434
 435	public PgpEngine getPgpEngine() {
 436		if (!Config.supportOpenPgp()) {
 437			return null;
 438		} else if (pgpServiceConnection != null && pgpServiceConnection.isBound()) {
 439			if (this.mPgpEngine == null) {
 440				this.mPgpEngine = new PgpEngine(new OpenPgpApi(
 441						getApplicationContext(),
 442						pgpServiceConnection.getService()), this);
 443			}
 444			return mPgpEngine;
 445		} else {
 446			return null;
 447		}
 448
 449	}
 450
 451	public OpenPgpApi getOpenPgpApi() {
 452		if (!Config.supportOpenPgp()) {
 453			return null;
 454		} else if (pgpServiceConnection != null && pgpServiceConnection.isBound()) {
 455			return new OpenPgpApi(this, pgpServiceConnection.getService());
 456		} else {
 457			return null;
 458		}
 459	}
 460
 461	public FileBackend getFileBackend() {
 462		return this.fileBackend;
 463	}
 464
 465	public AvatarService getAvatarService() {
 466		return this.mAvatarService;
 467	}
 468
 469	public void attachLocationToConversation(final Conversation conversation,
 470	                                         final Uri uri,
 471	                                         final UiCallback<Message> callback) {
 472		int encryption = conversation.getNextEncryption();
 473		if (encryption == Message.ENCRYPTION_PGP) {
 474			encryption = Message.ENCRYPTION_DECRYPTED;
 475		}
 476		Message message = new Message(conversation, uri.toString(), encryption);
 477		if (conversation.getNextCounterpart() != null) {
 478			message.setCounterpart(conversation.getNextCounterpart());
 479		}
 480		if (encryption == Message.ENCRYPTION_DECRYPTED) {
 481			getPgpEngine().encrypt(message, callback);
 482		} else {
 483			callback.success(message);
 484		}
 485	}
 486
 487	public void attachFileToConversation(final Conversation conversation,
 488	                                     final Uri uri,
 489	                                     final UiCallback<Message> callback) {
 490		if (FileBackend.weOwnFile(this, uri)) {
 491			Log.d(Config.LOGTAG, "trying to attach file that belonged to us");
 492			callback.error(R.string.security_error_invalid_file_access, null);
 493			return;
 494		}
 495		final Message message;
 496		if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
 497			message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
 498		} else {
 499			message = new Message(conversation, "", conversation.getNextEncryption());
 500		}
 501		message.setCounterpart(conversation.getNextCounterpart());
 502		message.setType(Message.TYPE_FILE);
 503		final AttachFileToConversationRunnable runnable = new AttachFileToConversationRunnable(this, uri, message, callback);
 504		if (runnable.isVideoMessage()) {
 505			mVideoCompressionExecutor.execute(runnable);
 506		} else {
 507			mFileAddingExecutor.execute(runnable);
 508		}
 509	}
 510
 511	public void attachImageToConversation(final Conversation conversation, final Uri uri, final UiCallback<Message> callback) {
 512		if (FileBackend.weOwnFile(this, uri)) {
 513			Log.d(Config.LOGTAG, "trying to attach file that belonged to us");
 514			callback.error(R.string.security_error_invalid_file_access, null);
 515			return;
 516		}
 517
 518		final String mimeType = MimeUtils.guessMimeTypeFromUri(this, uri);
 519		final String compressPictures = getCompressPicturesPreference();
 520
 521		if ("never".equals(compressPictures)
 522				|| ("auto".equals(compressPictures) && getFileBackend().useImageAsIs(uri))
 523				|| (mimeType != null && mimeType.endsWith("/gif"))) {
 524			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": not compressing picture. sending as file");
 525			attachFileToConversation(conversation, uri, callback);
 526			return;
 527		}
 528		final Message message;
 529		if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
 530			message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
 531		} else {
 532			message = new Message(conversation, "", conversation.getNextEncryption());
 533		}
 534		message.setCounterpart(conversation.getNextCounterpart());
 535		message.setType(Message.TYPE_IMAGE);
 536		mFileAddingExecutor.execute(new Runnable() {
 537
 538			@Override
 539			public void run() {
 540				try {
 541					getFileBackend().copyImageToPrivateStorage(message, uri);
 542					if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
 543						final PgpEngine pgpEngine = getPgpEngine();
 544						if (pgpEngine != null) {
 545							pgpEngine.encrypt(message, callback);
 546						} else if (callback != null) {
 547							callback.error(R.string.unable_to_connect_to_keychain, null);
 548						}
 549					} else {
 550						callback.success(message);
 551					}
 552				} catch (final FileBackend.FileCopyException e) {
 553					callback.error(e.getResId(), message);
 554				}
 555			}
 556		});
 557	}
 558
 559	public Conversation find(Bookmark bookmark) {
 560		return find(bookmark.getAccount(), bookmark.getJid());
 561	}
 562
 563	public Conversation find(final Account account, final Jid jid) {
 564		return find(getConversations(), account, jid);
 565	}
 566
 567	@Override
 568	public int onStartCommand(Intent intent, int flags, int startId) {
 569		final String action = intent == null ? null : intent.getAction();
 570		String pushedAccountHash = null;
 571		boolean interactive = false;
 572		if (action != null) {
 573			final String uuid = intent.getStringExtra("uuid");
 574			switch (action) {
 575				case ConnectivityManager.CONNECTIVITY_ACTION:
 576					if (hasInternetConnection() && Config.RESET_ATTEMPT_COUNT_ON_NETWORK_CHANGE) {
 577						resetAllAttemptCounts(true, false);
 578					}
 579					break;
 580				case ACTION_MERGE_PHONE_CONTACTS:
 581					if (restoredFromDatabaseLatch.getCount() == 0) {
 582						loadPhoneContacts();
 583					}
 584					return START_STICKY;
 585				case Intent.ACTION_SHUTDOWN:
 586					logoutAndSave(true);
 587					return START_NOT_STICKY;
 588				case ACTION_CLEAR_NOTIFICATION:
 589					mNotificationExecutor.execute(() -> {
 590						try {
 591							final Conversation c = findConversationByUuid(uuid);
 592							if (c != null) {
 593								mNotificationService.clear(c);
 594							} else {
 595								mNotificationService.clear();
 596							}
 597							restoredFromDatabaseLatch.await();
 598
 599						} catch (InterruptedException e) {
 600							Log.d(Config.LOGTAG,"unable to process clear notification");
 601						}
 602					});
 603					break;
 604				case ACTION_DISMISS_ERROR_NOTIFICATIONS:
 605					dismissErrorNotifications();
 606					break;
 607				case ACTION_TRY_AGAIN:
 608					resetAllAttemptCounts(false, true);
 609					interactive = true;
 610					break;
 611				case ACTION_REPLY_TO_CONVERSATION:
 612					Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
 613					if (remoteInput == null) {
 614						break;
 615					}
 616					final CharSequence body = remoteInput.getCharSequence("text_reply");
 617					final boolean dismissNotification = intent.getBooleanExtra("dismiss_notification", false);
 618					if (body == null || body.length() <= 0) {
 619						break;
 620					}
 621					mNotificationExecutor.execute(()-> {
 622						try {
 623							restoredFromDatabaseLatch.await();
 624							final Conversation c = findConversationByUuid(uuid);
 625							if (c != null) {
 626								directReply(c, body.toString(), dismissNotification);
 627							}
 628						} catch (InterruptedException e) {
 629							Log.d(Config.LOGTAG,"unable to process direct reply");
 630						}
 631					});
 632					break;
 633				case ACTION_MARK_AS_READ:
 634					mNotificationExecutor.execute(() -> {
 635						final Conversation c = findConversationByUuid(uuid);
 636						if (c == null) {
 637							Log.d(Config.LOGTAG, "received mark read intent for unknown conversation (" + uuid + ")");
 638							return;
 639						}
 640						try {
 641							restoredFromDatabaseLatch.await();
 642							sendReadMarker(c);
 643						} catch (InterruptedException e) {
 644							Log.d(Config.LOGTAG,"unable to process notification read marker for conversation "+c.getName());
 645						}
 646
 647					});
 648					break;
 649				case AudioManager.RINGER_MODE_CHANGED_ACTION:
 650					if (dndOnSilentMode()) {
 651						refreshAllPresences();
 652					}
 653					break;
 654				case Intent.ACTION_SCREEN_ON:
 655					deactivateGracePeriod();
 656				case Intent.ACTION_SCREEN_OFF:
 657					if (awayWhenScreenOff()) {
 658						refreshAllPresences();
 659					}
 660					break;
 661				case ACTION_GCM_TOKEN_REFRESH:
 662					refreshAllGcmTokens();
 663					break;
 664				case ACTION_IDLE_PING:
 665					if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
 666						scheduleNextIdlePing();
 667					}
 668					break;
 669				case ACTION_GCM_MESSAGE_RECEIVED:
 670					Log.d(Config.LOGTAG, "gcm push message arrived in service. extras=" + intent.getExtras());
 671					pushedAccountHash = intent.getStringExtra("account");
 672					break;
 673				case Intent.ACTION_SEND:
 674					Uri uri = intent.getData();
 675					if (uri != null) {
 676						Log.d(Config.LOGTAG, "received uri permission for "+uri.toString());
 677					}
 678					return START_STICKY;
 679			}
 680		}
 681		synchronized (this) {
 682			this.wakeLock.acquire();
 683			boolean pingNow = ConnectivityManager.CONNECTIVITY_ACTION.equals(action);
 684			HashSet<Account> pingCandidates = new HashSet<>();
 685			for (Account account : accounts) {
 686				pingNow |= processAccountState(account,
 687						interactive,
 688						"ui".equals(action),
 689						CryptoHelper.getAccountFingerprint(account).equals(pushedAccountHash),
 690						pingCandidates);
 691			}
 692			if (pingNow) {
 693				for (Account account : pingCandidates) {
 694					final boolean lowTimeout = isInLowPingTimeoutMode(account);
 695					account.getXmppConnection().sendPing();
 696					Log.d(Config.LOGTAG, account.getJid().toBareJid() + " send ping (action=" + action + ",lowTimeout=" + Boolean.toString(lowTimeout) + ")");
 697					scheduleWakeUpCall(lowTimeout ? Config.LOW_PING_TIMEOUT : Config.PING_TIMEOUT, account.getUuid().hashCode());
 698				}
 699			}
 700			if (wakeLock.isHeld()) {
 701				try {
 702					wakeLock.release();
 703				} catch (final RuntimeException ignored) {
 704				}
 705			}
 706		}
 707		if (SystemClock.elapsedRealtime() - mLastExpiryRun.get() >= Config.EXPIRY_INTERVAL) {
 708			expireOldMessages();
 709		}
 710		return START_STICKY;
 711	}
 712
 713	private boolean processAccountState(Account account, boolean interactive, boolean isUiAction, boolean isAccountPushed, HashSet<Account> pingCandidates) {
 714		boolean pingNow = false;
 715		if (account.getStatus().isAttemptReconnect()) {
 716			if (!hasInternetConnection()) {
 717				account.setStatus(Account.State.NO_INTERNET);
 718				if (statusListener != null) {
 719					statusListener.onStatusChanged(account);
 720				}
 721			} else {
 722				if (account.getStatus() == Account.State.NO_INTERNET) {
 723					account.setStatus(Account.State.OFFLINE);
 724					if (statusListener != null) {
 725						statusListener.onStatusChanged(account);
 726					}
 727				}
 728				if (account.getStatus() == Account.State.ONLINE) {
 729					synchronized (mLowPingTimeoutMode) {
 730						long lastReceived = account.getXmppConnection().getLastPacketReceived();
 731						long lastSent = account.getXmppConnection().getLastPingSent();
 732						long pingInterval = isUiAction ? Config.PING_MIN_INTERVAL * 1000 : Config.PING_MAX_INTERVAL * 1000;
 733						long msToNextPing = (Math.max(lastReceived, lastSent) + pingInterval) - SystemClock.elapsedRealtime();
 734						int pingTimeout = mLowPingTimeoutMode.contains(account.getJid().toBareJid()) ? Config.LOW_PING_TIMEOUT * 1000 : Config.PING_TIMEOUT * 1000;
 735						long pingTimeoutIn = (lastSent + pingTimeout) - SystemClock.elapsedRealtime();
 736						if (lastSent > lastReceived) {
 737							if (pingTimeoutIn < 0) {
 738								Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": ping timeout");
 739								this.reconnectAccount(account, true, interactive);
 740							} else {
 741								int secs = (int) (pingTimeoutIn / 1000);
 742								this.scheduleWakeUpCall(secs, account.getUuid().hashCode());
 743							}
 744						} else {
 745							pingCandidates.add(account);
 746							if (isAccountPushed) {
 747								pingNow = true;
 748								if (mLowPingTimeoutMode.add(account.getJid().toBareJid())) {
 749									Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": entering low ping timeout mode");
 750								}
 751							} else if (msToNextPing <= 0) {
 752								pingNow = true;
 753							} else {
 754								this.scheduleWakeUpCall((int) (msToNextPing / 1000), account.getUuid().hashCode());
 755								if (mLowPingTimeoutMode.remove(account.getJid().toBareJid())) {
 756									Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": leaving low ping timeout mode");
 757								}
 758							}
 759						}
 760					}
 761				} else if (account.getStatus() == Account.State.OFFLINE) {
 762					reconnectAccount(account, true, interactive);
 763				} else if (account.getStatus() == Account.State.CONNECTING) {
 764					long secondsSinceLastConnect = (SystemClock.elapsedRealtime() - account.getXmppConnection().getLastConnect()) / 1000;
 765					long secondsSinceLastDisco = (SystemClock.elapsedRealtime() - account.getXmppConnection().getLastDiscoStarted()) / 1000;
 766					long discoTimeout = Config.CONNECT_DISCO_TIMEOUT - secondsSinceLastDisco;
 767					long timeout = Config.CONNECT_TIMEOUT - secondsSinceLastConnect;
 768					if (timeout < 0) {
 769						Log.d(Config.LOGTAG, account.getJid() + ": time out during connect reconnecting (secondsSinceLast=" + secondsSinceLastConnect + ")");
 770						account.getXmppConnection().resetAttemptCount(false);
 771						reconnectAccount(account, true, interactive);
 772					} else if (discoTimeout < 0) {
 773						account.getXmppConnection().sendDiscoTimeout();
 774						scheduleWakeUpCall((int) Math.min(timeout, discoTimeout), account.getUuid().hashCode());
 775					} else {
 776						scheduleWakeUpCall((int) Math.min(timeout, discoTimeout), account.getUuid().hashCode());
 777					}
 778				} else {
 779					if (account.getXmppConnection().getTimeToNextAttempt() <= 0) {
 780						reconnectAccount(account, true, interactive);
 781					}
 782				}
 783			}
 784		}
 785		return pingNow;
 786	}
 787
 788	public boolean isDataSaverDisabled() {
 789		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
 790			ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
 791			return !connectivityManager.isActiveNetworkMetered()
 792					|| connectivityManager.getRestrictBackgroundStatus() == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
 793		} else {
 794			return true;
 795		}
 796	}
 797
 798	private void directReply(Conversation conversation, String body, final boolean dismissAfterReply) {
 799		Message message = new Message(conversation, body, conversation.getNextEncryption());
 800		message.markUnread();
 801		if (message.getEncryption() == Message.ENCRYPTION_PGP) {
 802			getPgpEngine().encrypt(message, new UiCallback<Message>() {
 803				@Override
 804				public void success(Message message) {
 805					message.setEncryption(Message.ENCRYPTION_DECRYPTED);
 806					sendMessage(message);
 807					if (dismissAfterReply) {
 808						markRead(message.getConversation(), true);
 809					} else {
 810						mNotificationService.pushFromDirectReply(message);
 811					}
 812				}
 813
 814				@Override
 815				public void error(int errorCode, Message object) {
 816
 817				}
 818
 819				@Override
 820				public void userInputRequried(PendingIntent pi, Message object) {
 821
 822				}
 823			});
 824		} else {
 825			sendMessage(message);
 826			if (dismissAfterReply) {
 827				markRead(conversation, true);
 828			} else {
 829				mNotificationService.pushFromDirectReply(message);
 830			}
 831		}
 832	}
 833
 834	private boolean dndOnSilentMode() {
 835		return getBooleanPreference(SettingsActivity.DND_ON_SILENT_MODE, R.bool.dnd_on_silent_mode);
 836	}
 837
 838	private boolean manuallyChangePresence() {
 839		return getBooleanPreference(SettingsActivity.MANUALLY_CHANGE_PRESENCE, R.bool.manually_change_presence);
 840	}
 841
 842	private boolean treatVibrateAsSilent() {
 843		return getBooleanPreference(SettingsActivity.TREAT_VIBRATE_AS_SILENT, R.bool.treat_vibrate_as_silent);
 844	}
 845
 846	private boolean awayWhenScreenOff() {
 847		return getBooleanPreference(SettingsActivity.AWAY_WHEN_SCREEN_IS_OFF, R.bool.away_when_screen_off);
 848	}
 849
 850	private String getCompressPicturesPreference() {
 851		return getPreferences().getString("picture_compression", getResources().getString(R.string.picture_compression));
 852	}
 853
 854	private Presence.Status getTargetPresence() {
 855		if (dndOnSilentMode() && isPhoneSilenced()) {
 856			return Presence.Status.DND;
 857		} else if (awayWhenScreenOff() && !isInteractive()) {
 858			return Presence.Status.AWAY;
 859		} else {
 860			return Presence.Status.ONLINE;
 861		}
 862	}
 863
 864	@SuppressLint("NewApi")
 865	@SuppressWarnings("deprecation")
 866	public boolean isInteractive() {
 867		final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
 868
 869		final boolean isScreenOn;
 870		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
 871			isScreenOn = pm.isScreenOn();
 872		} else {
 873			isScreenOn = pm.isInteractive();
 874		}
 875		return isScreenOn;
 876	}
 877
 878	private boolean isPhoneSilenced() {
 879		AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
 880		try {
 881			if (treatVibrateAsSilent()) {
 882				return audioManager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL;
 883			} else {
 884				return audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT;
 885			}
 886		} catch (Throwable throwable) {
 887			Log.d(Config.LOGTAG, "platform bug in isPhoneSilenced (" + throwable.getMessage() + ")");
 888			return false;
 889		}
 890	}
 891
 892	private void resetAllAttemptCounts(boolean reallyAll, boolean retryImmediately) {
 893		Log.d(Config.LOGTAG, "resetting all attempt counts");
 894		for (Account account : accounts) {
 895			if (account.hasErrorStatus() || reallyAll) {
 896				final XmppConnection connection = account.getXmppConnection();
 897				if (connection != null) {
 898					connection.resetAttemptCount(retryImmediately);
 899				}
 900			}
 901			if (account.setShowErrorNotification(true)) {
 902				databaseBackend.updateAccount(account);
 903			}
 904		}
 905		mNotificationService.updateErrorNotification();
 906	}
 907
 908	private void dismissErrorNotifications() {
 909		for (final Account account : this.accounts) {
 910			if (account.hasErrorStatus()) {
 911				Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": dismissing error notification");
 912				if (account.setShowErrorNotification(false)) {
 913					databaseBackend.updateAccount(account);
 914				}
 915			}
 916		}
 917	}
 918
 919	private void expireOldMessages() {
 920		expireOldMessages(false);
 921	}
 922
 923	public void expireOldMessages(final boolean resetHasMessagesLeftOnServer) {
 924		mLastExpiryRun.set(SystemClock.elapsedRealtime());
 925		mDatabaseWriterExecutor.execute(new Runnable() {
 926			@Override
 927			public void run() {
 928				long timestamp = getAutomaticMessageDeletionDate();
 929				if (timestamp > 0) {
 930					databaseBackend.expireOldMessages(timestamp);
 931					synchronized (XmppConnectionService.this.conversations) {
 932						for (Conversation conversation : XmppConnectionService.this.conversations) {
 933							conversation.expireOldMessages(timestamp);
 934							if (resetHasMessagesLeftOnServer) {
 935								conversation.messagesLoaded.set(true);
 936								conversation.setHasMessagesLeftOnServer(true);
 937							}
 938						}
 939					}
 940					updateConversationUi();
 941				}
 942			}
 943		});
 944	}
 945
 946	public boolean hasInternetConnection() {
 947		final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
 948		try {
 949			final NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
 950			return activeNetwork != null && activeNetwork.isConnected();
 951		} catch (RuntimeException e) {
 952			Log.d(Config.LOGTAG,"unable to check for internet connection",e);
 953			return true; //if internet connection can not be checked it is probably best to just try
 954		}
 955	}
 956
 957	@SuppressLint("TrulyRandom")
 958	@Override
 959	public void onCreate() {
 960		ExceptionHelper.init(getApplicationContext());
 961		PRNGFixes.apply();
 962		Resolver.init(this);
 963		this.mRandom = new SecureRandom();
 964		updateMemorizingTrustmanager();
 965		final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
 966		final int cacheSize = maxMemory / 8;
 967		this.mBitmapCache = new LruCache<String, Bitmap>(cacheSize) {
 968			@Override
 969			protected int sizeOf(final String key, final Bitmap bitmap) {
 970				return bitmap.getByteCount() / 1024;
 971			}
 972		};
 973
 974		Log.d(Config.LOGTAG, "initializing database...");
 975		this.databaseBackend = DatabaseBackend.getInstance(getApplicationContext());
 976		Log.d(Config.LOGTAG, "restoring accounts...");
 977		this.accounts = databaseBackend.getAccounts();
 978		final SharedPreferences.Editor editor = getPreferences().edit();
 979		if (this.accounts.size() == 0 && Arrays.asList("Sony", "Sony Ericsson").contains(Build.MANUFACTURER)) {
 980			editor.putBoolean(SettingsActivity.KEEP_FOREGROUND_SERVICE, true);
 981			Log.d(Config.LOGTAG, Build.MANUFACTURER + " is on blacklist. enabling foreground service");
 982		}
 983		editor.putBoolean(EventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts()).apply();
 984		editor.apply();
 985
 986		restoreFromDatabase();
 987
 988		getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, contactObserver);
 989		new Thread(new Runnable() {
 990			@Override
 991			public void run() {
 992				fileObserver.startWatching();
 993			}
 994		}).start();
 995		if (Config.supportOpenPgp()) {
 996			this.pgpServiceConnection = new OpenPgpServiceConnection(this, "org.sufficientlysecure.keychain", new OpenPgpServiceConnection.OnBound() {
 997				@Override
 998				public void onBound(IOpenPgpService2 service) {
 999					for (Account account : accounts) {
1000						final PgpDecryptionService pgp = account.getPgpDecryptionService();
1001						if (pgp != null) {
1002							pgp.continueDecryption(true);
1003						}
1004					}
1005				}
1006
1007				@Override
1008				public void onError(Exception e) {
1009				}
1010			});
1011			this.pgpServiceConnection.bindToService();
1012		}
1013
1014		this.pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
1015		this.wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "XmppConnectionService");
1016
1017		toggleForegroundService();
1018		updateUnreadCountBadge();
1019		toggleScreenEventReceiver();
1020		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1021			scheduleNextIdlePing();
1022		}
1023		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
1024			registerReceiver(this.mEventReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
1025		}
1026	}
1027
1028	@Override
1029	public void onTrimMemory(int level) {
1030		super.onTrimMemory(level);
1031		if (level >= TRIM_MEMORY_COMPLETE) {
1032			Log.d(Config.LOGTAG, "clear cache due to low memory");
1033			getBitmapCache().evictAll();
1034		}
1035	}
1036
1037	@Override
1038	public void onDestroy() {
1039		try {
1040			unregisterReceiver(this.mEventReceiver);
1041		} catch (IllegalArgumentException e) {
1042			//ignored
1043		}
1044		fileObserver.stopWatching();
1045		super.onDestroy();
1046	}
1047
1048	public void toggleScreenEventReceiver() {
1049		if (awayWhenScreenOff() && !manuallyChangePresence()) {
1050			final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
1051			filter.addAction(Intent.ACTION_SCREEN_OFF);
1052			registerReceiver(this.mEventReceiver, filter);
1053		} else {
1054			try {
1055				unregisterReceiver(this.mEventReceiver);
1056			} catch (IllegalArgumentException e) {
1057				//ignored
1058			}
1059		}
1060	}
1061
1062	public void toggleForegroundService() {
1063		if (mForceForegroundService.get() || (keepForegroundService() && hasEnabledAccounts())) {
1064			startForeground(NotificationService.FOREGROUND_NOTIFICATION_ID, this.mNotificationService.createForegroundNotification());
1065			Log.d(Config.LOGTAG, "started foreground service");
1066		} else {
1067			stopForeground(true);
1068			Log.d(Config.LOGTAG, "stopped foreground service");
1069		}
1070	}
1071
1072	public boolean keepForegroundService() {
1073		return getBooleanPreference(SettingsActivity.KEEP_FOREGROUND_SERVICE, R.bool.enable_foreground_service);
1074	}
1075
1076	@Override
1077	public void onTaskRemoved(final Intent rootIntent) {
1078		super.onTaskRemoved(rootIntent);
1079		if (keepForegroundService() || mForceForegroundService.get()) {
1080			Log.d(Config.LOGTAG, "ignoring onTaskRemoved because foreground service is activated");
1081		} else {
1082			this.logoutAndSave(false);
1083		}
1084	}
1085
1086	private void logoutAndSave(boolean stop) {
1087		int activeAccounts = 0;
1088		for (final Account account : accounts) {
1089			if (account.getStatus() != Account.State.DISABLED) {
1090				activeAccounts++;
1091			}
1092			databaseBackend.writeRoster(account.getRoster());
1093			if (account.getXmppConnection() != null) {
1094				new Thread(new Runnable() {
1095					@Override
1096					public void run() {
1097						disconnect(account, false);
1098					}
1099				}).start();
1100			}
1101		}
1102		if (stop || activeAccounts == 0) {
1103			Log.d(Config.LOGTAG, "good bye");
1104			stopSelf();
1105		}
1106	}
1107
1108	public void scheduleWakeUpCall(int seconds, int requestCode) {
1109		final long timeToWake = SystemClock.elapsedRealtime() + (seconds < 0 ? 1 : seconds + 1) * 1000;
1110		final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1111		Intent intent = new Intent(this, EventReceiver.class);
1112		intent.setAction("ping");
1113		PendingIntent pendingIntent = PendingIntent.getBroadcast(this, requestCode, intent, 0);
1114		try {
1115			alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, pendingIntent);
1116		} catch (RuntimeException e) {
1117			Log.e(Config.LOGTAG, "unable to schedule alarm for ping", e);
1118		}
1119	}
1120
1121	@TargetApi(Build.VERSION_CODES.M)
1122	private void scheduleNextIdlePing() {
1123		final long timeToWake = SystemClock.elapsedRealtime() + (Config.IDLE_PING_INTERVAL * 1000);
1124		final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1125		Intent intent = new Intent(this, EventReceiver.class);
1126		intent.setAction(ACTION_IDLE_PING);
1127		PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
1128		try {
1129			alarmManager.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, pendingIntent);
1130		} catch (RuntimeException e) {
1131			Log.d(Config.LOGTAG, "unable to schedule alarm for idle ping", e);
1132		}
1133	}
1134
1135	public XmppConnection createConnection(final Account account) {
1136		final SharedPreferences sharedPref = getPreferences();
1137		String resource;
1138		try {
1139			resource = sharedPref.getString("resource", getString(R.string.default_resource)).toLowerCase(Locale.ENGLISH);
1140			if (resource.trim().isEmpty()) {
1141				throw new Exception();
1142			}
1143		} catch (Exception e) {
1144			resource = "conversations";
1145		}
1146		account.setResource(resource);
1147		final XmppConnection connection = new XmppConnection(account, this);
1148		connection.setOnMessagePacketReceivedListener(this.mMessageParser);
1149		connection.setOnStatusChangedListener(this.statusListener);
1150		connection.setOnPresencePacketReceivedListener(this.mPresenceParser);
1151		connection.setOnUnregisteredIqPacketReceivedListener(this.mIqParser);
1152		connection.setOnJinglePacketReceivedListener(this.jingleListener);
1153		connection.setOnBindListener(this.mOnBindListener);
1154		connection.setOnMessageAcknowledgeListener(this.mOnMessageAcknowledgedListener);
1155		connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService);
1156		connection.addOnAdvancedStreamFeaturesAvailableListener(this.mAvatarService);
1157		AxolotlService axolotlService = account.getAxolotlService();
1158		if (axolotlService != null) {
1159			connection.addOnAdvancedStreamFeaturesAvailableListener(axolotlService);
1160		}
1161		return connection;
1162	}
1163
1164	public void sendChatState(Conversation conversation) {
1165		if (sendChatStates()) {
1166			MessagePacket packet = mMessageGenerator.generateChatState(conversation);
1167			sendMessagePacket(conversation.getAccount(), packet);
1168		}
1169	}
1170
1171	private void sendFileMessage(final Message message, final boolean delay) {
1172		Log.d(Config.LOGTAG, "send file message");
1173		final Account account = message.getConversation().getAccount();
1174		if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1175				|| message.getConversation().getMode() == Conversation.MODE_MULTI) {
1176			mHttpConnectionManager.createNewUploadConnection(message, delay);
1177		} else {
1178			mJingleConnectionManager.createNewConnection(message);
1179		}
1180	}
1181
1182	public void sendMessage(final Message message) {
1183		sendMessage(message, false, false);
1184	}
1185
1186	private void sendMessage(final Message message, final boolean resend, final boolean delay) {
1187		final Account account = message.getConversation().getAccount();
1188		if (account.setShowErrorNotification(true)) {
1189			databaseBackend.updateAccount(account);
1190			mNotificationService.updateErrorNotification();
1191		}
1192		final Conversation conversation = message.getConversation();
1193		account.deactivateGracePeriod();
1194		MessagePacket packet = null;
1195		final boolean addToConversation = (conversation.getMode() != Conversation.MODE_MULTI
1196				|| !Patches.BAD_MUC_REFLECTION.contains(account.getServerIdentity()))
1197				&& !message.edited();
1198		boolean saveInDb = addToConversation;
1199		message.setStatus(Message.STATUS_WAITING);
1200
1201		if (!resend && message.getEncryption() != Message.ENCRYPTION_OTR) {
1202			message.getConversation().endOtrIfNeeded();
1203			message.getConversation().findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR,
1204					new Conversation.OnMessageFound() {
1205						@Override
1206						public void onMessageFound(Message message) {
1207							markMessage(message, Message.STATUS_SEND_FAILED);
1208						}
1209					});
1210		}
1211
1212		if (account.isOnlineAndConnected()) {
1213			switch (message.getEncryption()) {
1214				case Message.ENCRYPTION_NONE:
1215					if (message.needsUploading()) {
1216						if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1217								|| conversation.getMode() == Conversation.MODE_MULTI
1218								|| message.fixCounterpart()) {
1219							this.sendFileMessage(message, delay);
1220						} else {
1221							break;
1222						}
1223					} else {
1224						packet = mMessageGenerator.generateChat(message);
1225					}
1226					break;
1227				case Message.ENCRYPTION_PGP:
1228				case Message.ENCRYPTION_DECRYPTED:
1229					if (message.needsUploading()) {
1230						if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1231								|| conversation.getMode() == Conversation.MODE_MULTI
1232								|| message.fixCounterpart()) {
1233							this.sendFileMessage(message, delay);
1234						} else {
1235							break;
1236						}
1237					} else {
1238						packet = mMessageGenerator.generatePgpChat(message);
1239					}
1240					break;
1241				case Message.ENCRYPTION_OTR:
1242					SessionImpl otrSession = conversation.getOtrSession();
1243					if (otrSession != null && otrSession.getSessionStatus() == SessionStatus.ENCRYPTED) {
1244						try {
1245							message.setCounterpart(Jid.fromSessionID(otrSession.getSessionID()));
1246						} catch (InvalidJidException e) {
1247							break;
1248						}
1249						if (message.needsUploading()) {
1250							mJingleConnectionManager.createNewConnection(message);
1251						} else {
1252							packet = mMessageGenerator.generateOtrChat(message);
1253						}
1254					} else if (otrSession == null) {
1255						if (message.fixCounterpart()) {
1256							conversation.startOtrSession(message.getCounterpart().getResourcepart(), true);
1257						} else {
1258							Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not fix counterpart for OTR message to contact " + message.getCounterpart());
1259							break;
1260						}
1261					} else {
1262						Log.d(Config.LOGTAG, account.getJid().toBareJid() + " OTR session with " + message.getContact() + " is in wrong state: " + otrSession.getSessionStatus().toString());
1263					}
1264					break;
1265				case Message.ENCRYPTION_AXOLOTL:
1266					message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
1267					if (message.needsUploading()) {
1268						if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1269								|| conversation.getMode() == Conversation.MODE_MULTI
1270								|| message.fixCounterpart()) {
1271							this.sendFileMessage(message, delay);
1272						} else {
1273							break;
1274						}
1275					} else {
1276						XmppAxolotlMessage axolotlMessage = account.getAxolotlService().fetchAxolotlMessageFromCache(message);
1277						if (axolotlMessage == null) {
1278							account.getAxolotlService().preparePayloadMessage(message, delay);
1279						} else {
1280							packet = mMessageGenerator.generateAxolotlChat(message, axolotlMessage);
1281						}
1282					}
1283					break;
1284
1285			}
1286			if (packet != null) {
1287				if (account.getXmppConnection().getFeatures().sm()
1288						|| (conversation.getMode() == Conversation.MODE_MULTI && message.getCounterpart().isBareJid())) {
1289					message.setStatus(Message.STATUS_UNSEND);
1290				} else {
1291					message.setStatus(Message.STATUS_SEND);
1292				}
1293			}
1294		} else {
1295			switch (message.getEncryption()) {
1296				case Message.ENCRYPTION_DECRYPTED:
1297					if (!message.needsUploading()) {
1298						String pgpBody = message.getEncryptedBody();
1299						String decryptedBody = message.getBody();
1300						message.setBody(pgpBody); //TODO might throw NPE
1301						message.setEncryption(Message.ENCRYPTION_PGP);
1302						if (message.edited()) {
1303							message.setBody(decryptedBody);
1304							message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1305							databaseBackend.updateMessage(message, message.getEditedId());
1306							updateConversationUi();
1307							return;
1308						} else {
1309							databaseBackend.createMessage(message);
1310							saveInDb = false;
1311							message.setBody(decryptedBody);
1312							message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1313						}
1314					}
1315					break;
1316				case Message.ENCRYPTION_OTR:
1317					if (!conversation.hasValidOtrSession() && message.getCounterpart() != null) {
1318						Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": create otr session without starting for " + message.getContact().getJid());
1319						conversation.startOtrSession(message.getCounterpart().getResourcepart(), false);
1320					}
1321					break;
1322				case Message.ENCRYPTION_AXOLOTL:
1323					message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
1324					break;
1325			}
1326		}
1327
1328
1329		boolean mucMessage = conversation.getMode() == Conversation.MODE_MULTI && message.getType() != Message.TYPE_PRIVATE;
1330		if (mucMessage) {
1331			message.setCounterpart(conversation.getMucOptions().getSelf().getFullJid());
1332		}
1333
1334		if (resend) {
1335			if (packet != null && addToConversation) {
1336				if (account.getXmppConnection().getFeatures().sm() || mucMessage) {
1337					markMessage(message, Message.STATUS_UNSEND);
1338				} else {
1339					markMessage(message, Message.STATUS_SEND);
1340				}
1341			}
1342		} else {
1343			if (addToConversation) {
1344				conversation.add(message);
1345			}
1346			if (saveInDb) {
1347				databaseBackend.createMessage(message);
1348			} else if (message.edited()) {
1349				databaseBackend.updateMessage(message, message.getEditedId());
1350			}
1351			updateConversationUi();
1352		}
1353		if (packet != null) {
1354			if (delay) {
1355				mMessageGenerator.addDelay(packet, message.getTimeSent());
1356			}
1357			if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
1358				if (this.sendChatStates()) {
1359					packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
1360				}
1361			}
1362			sendMessagePacket(account, packet);
1363		}
1364	}
1365
1366	private void sendUnsentMessages(final Conversation conversation) {
1367		conversation.findWaitingMessages(new Conversation.OnMessageFound() {
1368
1369			@Override
1370			public void onMessageFound(Message message) {
1371				resendMessage(message, true);
1372			}
1373		});
1374	}
1375
1376	public void resendMessage(final Message message, final boolean delay) {
1377		sendMessage(message, true, delay);
1378	}
1379
1380	public void fetchRosterFromServer(final Account account) {
1381		final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1382		if (!"".equals(account.getRosterVersion())) {
1383			Log.d(Config.LOGTAG, account.getJid().toBareJid()
1384					+ ": fetching roster version " + account.getRosterVersion());
1385		} else {
1386			Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": fetching roster");
1387		}
1388		iqPacket.query(Namespace.ROSTER).setAttribute("ver", account.getRosterVersion());
1389		sendIqPacket(account, iqPacket, mIqParser);
1390	}
1391
1392	public void fetchBookmarks(final Account account) {
1393		final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1394		final Element query = iqPacket.query("jabber:iq:private");
1395		query.addChild("storage", "storage:bookmarks");
1396		final OnIqPacketReceived callback = new OnIqPacketReceived() {
1397
1398			@Override
1399			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1400				if (packet.getType() == IqPacket.TYPE.RESULT) {
1401					final Element query = packet.query();
1402					final HashMap<Jid, Bookmark> bookmarks = new HashMap<>();
1403					final Element storage = query.findChild("storage", "storage:bookmarks");
1404					final boolean autojoin = respectAutojoin();
1405					if (storage != null) {
1406						for (final Element item : storage.getChildren()) {
1407							if (item.getName().equals("conference")) {
1408								final Bookmark bookmark = Bookmark.parse(item, account);
1409								Bookmark old = bookmarks.put(bookmark.getJid(), bookmark);
1410								if (old != null && old.getBookmarkName() != null && bookmark.getBookmarkName() == null) {
1411									bookmark.setBookmarkName(old.getBookmarkName());
1412								}
1413								Conversation conversation = find(bookmark);
1414								if (conversation != null) {
1415									conversation.setBookmark(bookmark);
1416								} else if (bookmark.autojoin() && bookmark.getJid() != null && autojoin) {
1417									conversation = findOrCreateConversation(account, bookmark.getJid(), true, true, false);
1418									conversation.setBookmark(bookmark);
1419								}
1420							}
1421						}
1422					}
1423					account.setBookmarks(new ArrayList<>(bookmarks.values()));
1424				} else {
1425					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not fetch bookmarks");
1426				}
1427			}
1428		};
1429		sendIqPacket(account, iqPacket, callback);
1430	}
1431
1432	public void pushBookmarks(Account account) {
1433		Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": pushing bookmarks");
1434		IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
1435		Element query = iqPacket.query("jabber:iq:private");
1436		Element storage = query.addChild("storage", "storage:bookmarks");
1437		for (Bookmark bookmark : account.getBookmarks()) {
1438			storage.addChild(bookmark);
1439		}
1440		sendIqPacket(account, iqPacket, mDefaultIqHandler);
1441	}
1442
1443	private void restoreFromDatabase() {
1444		synchronized (this.conversations) {
1445			final Map<String, Account> accountLookupTable = new Hashtable<>();
1446			for (Account account : this.accounts) {
1447				accountLookupTable.put(account.getUuid(), account);
1448			}
1449			Log.d(Config.LOGTAG, "restoring conversations...");
1450			final long startTimeConversationsRestore = SystemClock.elapsedRealtime();
1451			this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
1452			for (Iterator<Conversation> iterator = conversations.listIterator(); iterator.hasNext(); ) {
1453				Conversation conversation = iterator.next();
1454				Account account = accountLookupTable.get(conversation.getAccountUuid());
1455				if (account != null) {
1456					conversation.setAccount(account);
1457				} else {
1458					Log.e(Config.LOGTAG, "unable to restore Conversations with " + conversation.getJid());
1459					iterator.remove();
1460				}
1461			}
1462			long diffConversationsRestore = SystemClock.elapsedRealtime() - startTimeConversationsRestore;
1463			Log.d(Config.LOGTAG, "finished restoring conversations in " + diffConversationsRestore + "ms");
1464			Runnable runnable = new Runnable() {
1465				@Override
1466				public void run() {
1467					long deletionDate = getAutomaticMessageDeletionDate();
1468					mLastExpiryRun.set(SystemClock.elapsedRealtime());
1469					if (deletionDate > 0) {
1470						Log.d(Config.LOGTAG, "deleting messages that are older than " + AbstractGenerator.getTimestamp(deletionDate));
1471						databaseBackend.expireOldMessages(deletionDate);
1472					}
1473					Log.d(Config.LOGTAG, "restoring roster...");
1474					for (Account account : accounts) {
1475						databaseBackend.readRoster(account.getRoster());
1476						account.initAccountServices(XmppConnectionService.this); //roster needs to be loaded at this stage
1477					}
1478					getBitmapCache().evictAll();
1479					loadPhoneContacts();
1480					Log.d(Config.LOGTAG, "restoring messages...");
1481					final long startMessageRestore = SystemClock.elapsedRealtime();
1482					for (Conversation conversation : conversations) {
1483						conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1484						checkDeletedFiles(conversation);
1485						conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
1486
1487							@Override
1488							public void onMessageFound(Message message) {
1489								markMessage(message, Message.STATUS_WAITING);
1490							}
1491						});
1492						conversation.findUnreadMessages(new Conversation.OnMessageFound() {
1493							@Override
1494							public void onMessageFound(Message message) {
1495								mNotificationService.pushFromBacklog(message);
1496							}
1497						});
1498					}
1499					mNotificationService.finishBacklog(false);
1500					restoredFromDatabaseLatch.countDown();
1501					final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
1502					Log.d(Config.LOGTAG, "finished restoring messages in " + diffMessageRestore + "ms");
1503					updateConversationUi();
1504				}
1505			};
1506			mDatabaseReaderExecutor.execute(runnable); //will contain one write command (expiry) but that's fine
1507		}
1508	}
1509
1510	public void loadPhoneContacts() {
1511		mContactMergerExecutor.execute(new Runnable() {
1512			@Override
1513			public void run() {
1514				PhoneHelper.loadPhoneContacts(XmppConnectionService.this, new OnPhoneContactsLoadedListener() {
1515					@Override
1516					public void onPhoneContactsLoaded(List<Bundle> phoneContacts) {
1517						Log.d(Config.LOGTAG, "start merging phone contacts with roster");
1518						for (Account account : accounts) {
1519							List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts();
1520							for (Bundle phoneContact : phoneContacts) {
1521								Jid jid;
1522								try {
1523									jid = Jid.fromString(phoneContact.getString("jid"));
1524								} catch (final InvalidJidException e) {
1525									continue;
1526								}
1527								final Contact contact = account.getRoster().getContact(jid);
1528								String systemAccount = phoneContact.getInt("phoneid")
1529										+ "#"
1530										+ phoneContact.getString("lookup");
1531								contact.setSystemAccount(systemAccount);
1532								boolean needsCacheClean = contact.setPhotoUri(phoneContact.getString("photouri"));
1533								needsCacheClean |= contact.setSystemName(phoneContact.getString("displayname"));
1534								if (needsCacheClean) {
1535									getAvatarService().clear(contact);
1536								}
1537								withSystemAccounts.remove(contact);
1538							}
1539							for (Contact contact : withSystemAccounts) {
1540								contact.setSystemAccount(null);
1541								boolean needsCacheClean = contact.setPhotoUri(null);
1542								needsCacheClean |= contact.setSystemName(null);
1543								if (needsCacheClean) {
1544									getAvatarService().clear(contact);
1545								}
1546							}
1547						}
1548						Log.d(Config.LOGTAG, "finished merging phone contacts");
1549						mShortcutService.refresh(mInitialAddressbookSyncCompleted.compareAndSet(false, true));
1550						updateAccountUi();
1551					}
1552				});
1553			}
1554		});
1555	}
1556
1557	public List<Conversation> getConversations() {
1558		return this.conversations;
1559	}
1560
1561	private void checkDeletedFiles(Conversation conversation) {
1562		conversation.findMessagesWithFiles(new Conversation.OnMessageFound() {
1563
1564			@Override
1565			public void onMessageFound(Message message) {
1566				if (!getFileBackend().isFileAvailable(message)) {
1567					message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1568					final int s = message.getStatus();
1569					if (s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
1570						markMessage(message, Message.STATUS_SEND_FAILED);
1571					}
1572				}
1573			}
1574		});
1575	}
1576
1577	private void markFileDeleted(final String path) {
1578		Log.d(Config.LOGTAG, "deleted file " + path);
1579		for (Conversation conversation : getConversations()) {
1580			conversation.findMessagesWithFiles(new Conversation.OnMessageFound() {
1581				@Override
1582				public void onMessageFound(Message message) {
1583					DownloadableFile file = fileBackend.getFile(message);
1584					if (file.getAbsolutePath().equals(path)) {
1585						if (!file.exists()) {
1586							message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1587							final int s = message.getStatus();
1588							if (s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
1589								markMessage(message, Message.STATUS_SEND_FAILED);
1590							} else {
1591								updateConversationUi();
1592							}
1593						} else {
1594							Log.d(Config.LOGTAG, "found matching message for file " + path + " but file still exists");
1595						}
1596					}
1597				}
1598			});
1599		}
1600	}
1601
1602	public void populateWithOrderedConversations(final List<Conversation> list) {
1603		populateWithOrderedConversations(list, true);
1604	}
1605
1606	public void populateWithOrderedConversations(final List<Conversation> list, boolean includeNoFileUpload) {
1607		list.clear();
1608		if (includeNoFileUpload) {
1609			list.addAll(getConversations());
1610		} else {
1611			for (Conversation conversation : getConversations()) {
1612				if (conversation.getMode() == Conversation.MODE_SINGLE
1613						|| conversation.getAccount().httpUploadAvailable()) {
1614					list.add(conversation);
1615				}
1616			}
1617		}
1618		try {
1619			Collections.sort(list);
1620		} catch (IllegalArgumentException e) {
1621			//ignore
1622		}
1623	}
1624
1625	public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
1626		if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation, callback)) {
1627			return;
1628		} else if (timestamp == 0) {
1629			return;
1630		}
1631		Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
1632		Runnable runnable = new Runnable() {
1633			@Override
1634			public void run() {
1635				final Account account = conversation.getAccount();
1636				List<Message> messages = databaseBackend.getMessages(conversation, 50, timestamp);
1637				if (messages.size() > 0) {
1638					conversation.addAll(0, messages);
1639					checkDeletedFiles(conversation);
1640					callback.onMoreMessagesLoaded(messages.size(), conversation);
1641				} else if (conversation.hasMessagesLeftOnServer()
1642						&& account.isOnlineAndConnected()
1643						&& conversation.getLastClearHistory().getTimestamp() == 0) {
1644					if ((conversation.getMode() == Conversation.MODE_SINGLE && account.getXmppConnection().getFeatures().mam())
1645							|| (conversation.getMode() == Conversation.MODE_MULTI && conversation.getMucOptions().mamSupport())) {
1646						MessageArchiveService.Query query = getMessageArchiveService().query(conversation, new MamReference(0), timestamp, false);
1647						if (query != null) {
1648							query.setCallback(callback);
1649							callback.informUser(R.string.fetching_history_from_server);
1650						} else {
1651							callback.informUser(R.string.not_fetching_history_retention_period);
1652						}
1653
1654					}
1655				}
1656			}
1657		};
1658		mDatabaseReaderExecutor.execute(runnable);
1659	}
1660
1661	public List<Account> getAccounts() {
1662		return this.accounts;
1663	}
1664
1665	public List<Conversation> findAllConferencesWith(Contact contact) {
1666		ArrayList<Conversation> results = new ArrayList<>();
1667		for (Conversation conversation : conversations) {
1668			if (conversation.getMode() == Conversation.MODE_MULTI
1669					&& conversation.getMucOptions().isContactInRoom(contact)) {
1670				results.add(conversation);
1671			}
1672		}
1673		return results;
1674	}
1675
1676	public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
1677		for (final Conversation conversation : haystack) {
1678			if (conversation.getContact() == contact) {
1679				return conversation;
1680			}
1681		}
1682		return null;
1683	}
1684
1685	public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
1686		if (jid == null) {
1687			return null;
1688		}
1689		for (final Conversation conversation : haystack) {
1690			if ((account == null || conversation.getAccount() == account)
1691					&& (conversation.getJid().toBareJid().equals(jid.toBareJid()))) {
1692				return conversation;
1693			}
1694		}
1695		return null;
1696	}
1697
1698	public Conversation findOrCreateConversation(Account account, Jid jid, boolean muc, final boolean async) {
1699		return this.findOrCreateConversation(account, jid, muc, false, async);
1700	}
1701
1702	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final boolean async) {
1703		return this.findOrCreateConversation(account, jid, muc, joinAfterCreate, null, async);
1704	}
1705
1706	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final MessageArchiveService.Query query, final boolean async) {
1707		synchronized (this.conversations) {
1708			Conversation conversation = find(account, jid);
1709			if (conversation != null) {
1710				return conversation;
1711			}
1712			conversation = databaseBackend.findConversation(account, jid);
1713			final boolean loadMessagesFromDb;
1714			if (conversation != null) {
1715				conversation.setStatus(Conversation.STATUS_AVAILABLE);
1716				conversation.setAccount(account);
1717				if (muc) {
1718					conversation.setMode(Conversation.MODE_MULTI);
1719					conversation.setContactJid(jid);
1720				} else {
1721					conversation.setMode(Conversation.MODE_SINGLE);
1722					conversation.setContactJid(jid.toBareJid());
1723				}
1724				databaseBackend.updateConversation(conversation);
1725				loadMessagesFromDb = conversation.messagesLoaded.compareAndSet(true, false);
1726			} else {
1727				String conversationName;
1728				Contact contact = account.getRoster().getContact(jid);
1729				if (contact != null) {
1730					conversationName = contact.getDisplayName();
1731				} else {
1732					conversationName = jid.getLocalpart();
1733				}
1734				if (muc) {
1735					conversation = new Conversation(conversationName, account, jid,
1736							Conversation.MODE_MULTI);
1737				} else {
1738					conversation = new Conversation(conversationName, account, jid.toBareJid(),
1739							Conversation.MODE_SINGLE);
1740				}
1741				this.databaseBackend.createConversation(conversation);
1742				loadMessagesFromDb = false;
1743			}
1744			final Conversation c = conversation;
1745			final Runnable runnable = new Runnable() {
1746				@Override
1747				public void run() {
1748					if (loadMessagesFromDb) {
1749						c.addAll(0, databaseBackend.getMessages(c, Config.PAGE_SIZE));
1750						updateConversationUi();
1751						c.messagesLoaded.set(true);
1752					}
1753					if (account.getXmppConnection() != null
1754							&& account.getXmppConnection().getFeatures().mam()
1755							&& !muc) {
1756						if (query == null) {
1757							mMessageArchiveService.query(c);
1758						} else {
1759							if (query.getConversation() == null) {
1760								mMessageArchiveService.query(c, query.getStart(), query.isCatchup());
1761							}
1762						}
1763					}
1764					checkDeletedFiles(c);
1765					if (joinAfterCreate) {
1766						joinMuc(c);
1767					}
1768				}
1769			};
1770			if (async) {
1771				mDatabaseReaderExecutor.execute(runnable);
1772			} else {
1773				runnable.run();
1774			}
1775			this.conversations.add(conversation);
1776			updateConversationUi();
1777			return conversation;
1778		}
1779	}
1780
1781	public void archiveConversation(Conversation conversation) {
1782		getNotificationService().clear(conversation);
1783		conversation.setStatus(Conversation.STATUS_ARCHIVED);
1784		synchronized (this.conversations) {
1785			if (conversation.getMode() == Conversation.MODE_MULTI) {
1786				if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1787					Bookmark bookmark = conversation.getBookmark();
1788					if (bookmark != null && bookmark.autojoin() && respectAutojoin()) {
1789						bookmark.setAutojoin(false);
1790						pushBookmarks(bookmark.getAccount());
1791					}
1792				}
1793				leaveMuc(conversation);
1794			} else {
1795				conversation.endOtrIfNeeded();
1796				if (conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1797					Log.d(Config.LOGTAG, "Canceling presence request from " + conversation.getJid().toString());
1798					sendPresencePacket(
1799							conversation.getAccount(),
1800							mPresenceGenerator.stopPresenceUpdatesTo(conversation.getContact())
1801					);
1802				}
1803			}
1804			updateConversation(conversation);
1805			this.conversations.remove(conversation);
1806			updateConversationUi();
1807		}
1808	}
1809
1810	public void createAccount(final Account account) {
1811		account.initAccountServices(this);
1812		databaseBackend.createAccount(account);
1813		this.accounts.add(account);
1814		this.reconnectAccountInBackground(account);
1815		updateAccountUi();
1816		syncEnabledAccountSetting();
1817		toggleForegroundService();
1818	}
1819
1820	private void syncEnabledAccountSetting() {
1821		getPreferences().edit().putBoolean(EventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts()).apply();
1822	}
1823
1824	public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
1825		new Thread(new Runnable() {
1826			@Override
1827			public void run() {
1828				try {
1829					X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
1830					Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
1831					if (info == null) {
1832						callback.informUser(R.string.certificate_does_not_contain_jid);
1833						return;
1834					}
1835					if (findAccountByJid(info.first) == null) {
1836						Account account = new Account(info.first, "");
1837						account.setPrivateKeyAlias(alias);
1838						account.setOption(Account.OPTION_DISABLED, true);
1839						account.setDisplayName(info.second);
1840						createAccount(account);
1841						callback.onAccountCreated(account);
1842						if (Config.X509_VERIFICATION) {
1843							try {
1844								getMemorizingTrustManager().getNonInteractive(account.getJid().getDomainpart()).checkClientTrusted(chain, "RSA");
1845							} catch (CertificateException e) {
1846								callback.informUser(R.string.certificate_chain_is_not_trusted);
1847							}
1848						}
1849					} else {
1850						callback.informUser(R.string.account_already_exists);
1851					}
1852				} catch (Exception e) {
1853					e.printStackTrace();
1854					callback.informUser(R.string.unable_to_parse_certificate);
1855				}
1856			}
1857		}).start();
1858
1859	}
1860
1861	public void updateKeyInAccount(final Account account, final String alias) {
1862		Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": update key in account " + alias);
1863		try {
1864			X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
1865			Log.d(Config.LOGTAG, account.getJid().toBareJid() + " loaded certificate chain");
1866			Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
1867			if (account.getJid().toBareJid().equals(info.first)) {
1868				account.setPrivateKeyAlias(alias);
1869				account.setDisplayName(info.second);
1870				databaseBackend.updateAccount(account);
1871				if (Config.X509_VERIFICATION) {
1872					try {
1873						getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
1874					} catch (CertificateException e) {
1875						showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
1876					}
1877					account.getAxolotlService().regenerateKeys(true);
1878				}
1879			} else {
1880				showErrorToastInUi(R.string.jid_does_not_match_certificate);
1881			}
1882		} catch (Exception e) {
1883			e.printStackTrace();
1884		}
1885	}
1886
1887	public boolean updateAccount(final Account account) {
1888		if (databaseBackend.updateAccount(account)) {
1889			account.setShowErrorNotification(true);
1890			this.statusListener.onStatusChanged(account);
1891			databaseBackend.updateAccount(account);
1892			reconnectAccountInBackground(account);
1893			updateAccountUi();
1894			getNotificationService().updateErrorNotification();
1895			toggleForegroundService();
1896			syncEnabledAccountSetting();
1897			return true;
1898		} else {
1899			return false;
1900		}
1901	}
1902
1903	public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
1904		final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
1905		sendIqPacket(account, iq, new OnIqPacketReceived() {
1906			@Override
1907			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1908				if (packet.getType() == IqPacket.TYPE.RESULT) {
1909					account.setPassword(newPassword);
1910					account.setOption(Account.OPTION_MAGIC_CREATE, false);
1911					databaseBackend.updateAccount(account);
1912					callback.onPasswordChangeSucceeded();
1913				} else {
1914					callback.onPasswordChangeFailed();
1915				}
1916			}
1917		});
1918	}
1919
1920	public void deleteAccount(final Account account) {
1921		synchronized (this.conversations) {
1922			for (final Conversation conversation : conversations) {
1923				if (conversation.getAccount() == account) {
1924					if (conversation.getMode() == Conversation.MODE_MULTI) {
1925						leaveMuc(conversation);
1926					} else if (conversation.getMode() == Conversation.MODE_SINGLE) {
1927						conversation.endOtrIfNeeded();
1928					}
1929					conversations.remove(conversation);
1930				}
1931			}
1932			if (account.getXmppConnection() != null) {
1933				new Thread(new Runnable() {
1934					@Override
1935					public void run() {
1936						disconnect(account, true);
1937					}
1938				}).start();
1939			}
1940			Runnable runnable = new Runnable() {
1941				@Override
1942				public void run() {
1943					if (!databaseBackend.deleteAccount(account)) {
1944						Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": unable to delete account");
1945					}
1946				}
1947			};
1948			mDatabaseWriterExecutor.execute(runnable);
1949			this.accounts.remove(account);
1950			updateAccountUi();
1951			getNotificationService().updateErrorNotification();
1952			syncEnabledAccountSetting();
1953		}
1954	}
1955
1956	public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1957		synchronized (this) {
1958			this.mLastActivity = System.currentTimeMillis();
1959			if (checkListeners()) {
1960				switchToForeground();
1961			}
1962			this.mOnConversationUpdate = listener;
1963			this.mNotificationService.setIsInForeground(true);
1964			if (this.convChangedListenerCount < 2) {
1965				this.convChangedListenerCount++;
1966			}
1967		}
1968	}
1969
1970	public void removeOnConversationListChangedListener() {
1971		synchronized (this) {
1972			this.convChangedListenerCount--;
1973			if (this.convChangedListenerCount <= 0) {
1974				this.convChangedListenerCount = 0;
1975				this.mOnConversationUpdate = null;
1976				this.mNotificationService.setIsInForeground(false);
1977				if (checkListeners()) {
1978					switchToBackground();
1979				}
1980			}
1981		}
1982	}
1983
1984	public void setOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
1985		synchronized (this) {
1986			if (checkListeners()) {
1987				switchToForeground();
1988			}
1989			this.mOnShowErrorToast = onShowErrorToast;
1990			if (this.showErrorToastListenerCount < 2) {
1991				this.showErrorToastListenerCount++;
1992			}
1993		}
1994		this.mOnShowErrorToast = onShowErrorToast;
1995	}
1996
1997	public void removeOnShowErrorToastListener() {
1998		synchronized (this) {
1999			this.showErrorToastListenerCount--;
2000			if (this.showErrorToastListenerCount <= 0) {
2001				this.showErrorToastListenerCount = 0;
2002				this.mOnShowErrorToast = null;
2003				if (checkListeners()) {
2004					switchToBackground();
2005				}
2006			}
2007		}
2008	}
2009
2010	public void setOnAccountListChangedListener(OnAccountUpdate listener) {
2011		synchronized (this) {
2012			if (checkListeners()) {
2013				switchToForeground();
2014			}
2015			this.mOnAccountUpdate = listener;
2016			if (this.accountChangedListenerCount < 2) {
2017				this.accountChangedListenerCount++;
2018			}
2019		}
2020	}
2021
2022	public void removeOnAccountListChangedListener() {
2023		synchronized (this) {
2024			this.accountChangedListenerCount--;
2025			if (this.accountChangedListenerCount <= 0) {
2026				this.mOnAccountUpdate = null;
2027				this.accountChangedListenerCount = 0;
2028				if (checkListeners()) {
2029					switchToBackground();
2030				}
2031			}
2032		}
2033	}
2034
2035	public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
2036		synchronized (this) {
2037			if (checkListeners()) {
2038				switchToForeground();
2039			}
2040			this.mOnCaptchaRequested = listener;
2041			if (this.captchaRequestedListenerCount < 2) {
2042				this.captchaRequestedListenerCount++;
2043			}
2044		}
2045	}
2046
2047	public void removeOnCaptchaRequestedListener() {
2048		synchronized (this) {
2049			this.captchaRequestedListenerCount--;
2050			if (this.captchaRequestedListenerCount <= 0) {
2051				this.mOnCaptchaRequested = null;
2052				this.captchaRequestedListenerCount = 0;
2053				if (checkListeners()) {
2054					switchToBackground();
2055				}
2056			}
2057		}
2058	}
2059
2060	public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
2061		synchronized (this) {
2062			if (checkListeners()) {
2063				switchToForeground();
2064			}
2065			this.mOnRosterUpdate = listener;
2066			if (this.rosterChangedListenerCount < 2) {
2067				this.rosterChangedListenerCount++;
2068			}
2069		}
2070	}
2071
2072	public void removeOnRosterUpdateListener() {
2073		synchronized (this) {
2074			this.rosterChangedListenerCount--;
2075			if (this.rosterChangedListenerCount <= 0) {
2076				this.rosterChangedListenerCount = 0;
2077				this.mOnRosterUpdate = null;
2078				if (checkListeners()) {
2079					switchToBackground();
2080				}
2081			}
2082		}
2083	}
2084
2085	public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2086		synchronized (this) {
2087			if (checkListeners()) {
2088				switchToForeground();
2089			}
2090			this.mOnUpdateBlocklist = listener;
2091			if (this.updateBlocklistListenerCount < 2) {
2092				this.updateBlocklistListenerCount++;
2093			}
2094		}
2095	}
2096
2097	public void removeOnUpdateBlocklistListener() {
2098		synchronized (this) {
2099			this.updateBlocklistListenerCount--;
2100			if (this.updateBlocklistListenerCount <= 0) {
2101				this.updateBlocklistListenerCount = 0;
2102				this.mOnUpdateBlocklist = null;
2103				if (checkListeners()) {
2104					switchToBackground();
2105				}
2106			}
2107		}
2108	}
2109
2110	public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
2111		synchronized (this) {
2112			if (checkListeners()) {
2113				switchToForeground();
2114			}
2115			this.mOnKeyStatusUpdated = listener;
2116			if (this.keyStatusUpdatedListenerCount < 2) {
2117				this.keyStatusUpdatedListenerCount++;
2118			}
2119		}
2120	}
2121
2122	public void removeOnNewKeysAvailableListener() {
2123		synchronized (this) {
2124			this.keyStatusUpdatedListenerCount--;
2125			if (this.keyStatusUpdatedListenerCount <= 0) {
2126				this.keyStatusUpdatedListenerCount = 0;
2127				this.mOnKeyStatusUpdated = null;
2128				if (checkListeners()) {
2129					switchToBackground();
2130				}
2131			}
2132		}
2133	}
2134
2135	public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
2136		synchronized (this) {
2137			if (checkListeners()) {
2138				switchToForeground();
2139			}
2140			this.mOnMucRosterUpdate = listener;
2141			if (this.mucRosterChangedListenerCount < 2) {
2142				this.mucRosterChangedListenerCount++;
2143			}
2144		}
2145	}
2146
2147	public void removeOnMucRosterUpdateListener() {
2148		synchronized (this) {
2149			this.mucRosterChangedListenerCount--;
2150			if (this.mucRosterChangedListenerCount <= 0) {
2151				this.mucRosterChangedListenerCount = 0;
2152				this.mOnMucRosterUpdate = null;
2153				if (checkListeners()) {
2154					switchToBackground();
2155				}
2156			}
2157		}
2158	}
2159
2160	public boolean checkListeners() {
2161		return (this.mOnAccountUpdate == null
2162				&& this.mOnConversationUpdate == null
2163				&& this.mOnRosterUpdate == null
2164				&& this.mOnCaptchaRequested == null
2165				&& this.mOnUpdateBlocklist == null
2166				&& this.mOnShowErrorToast == null
2167				&& this.mOnKeyStatusUpdated == null);
2168	}
2169
2170	private void switchToForeground() {
2171		final boolean broadcastLastActivity = broadcastLastActivity();
2172		for (Conversation conversation : getConversations()) {
2173			if (conversation.getMode() == Conversation.MODE_MULTI) {
2174				conversation.getMucOptions().resetChatState();
2175			} else {
2176				conversation.setIncomingChatState(Config.DEFAULT_CHATSTATE);
2177			}
2178		}
2179		for (Account account : getAccounts()) {
2180			if (account.getStatus() == Account.State.ONLINE) {
2181				account.deactivateGracePeriod();
2182				final XmppConnection connection = account.getXmppConnection();
2183				if (connection != null) {
2184					if (connection.getFeatures().csi()) {
2185						connection.sendActive();
2186					}
2187					if (broadcastLastActivity) {
2188						sendPresence(account, false); //send new presence but don't include idle because we are not
2189					}
2190				}
2191			}
2192		}
2193		Log.d(Config.LOGTAG, "app switched into foreground");
2194	}
2195
2196	private void switchToBackground() {
2197		final boolean broadcastLastActivity = broadcastLastActivity();
2198		for (Account account : getAccounts()) {
2199			if (account.getStatus() == Account.State.ONLINE) {
2200				XmppConnection connection = account.getXmppConnection();
2201				if (connection != null) {
2202					if (broadcastLastActivity) {
2203						sendPresence(account, true);
2204					}
2205					if (connection.getFeatures().csi()) {
2206						connection.sendInactive();
2207					}
2208				}
2209			}
2210		}
2211		this.mNotificationService.setIsInForeground(false);
2212		Log.d(Config.LOGTAG, "app switched into background");
2213	}
2214
2215	private void connectMultiModeConversations(Account account) {
2216		List<Conversation> conversations = getConversations();
2217		for (Conversation conversation : conversations) {
2218			if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
2219				joinMuc(conversation);
2220			}
2221		}
2222	}
2223
2224	public void joinMuc(Conversation conversation) {
2225		joinMuc(conversation, null, false);
2226	}
2227
2228	public void joinMuc(Conversation conversation, boolean followedInvite) {
2229		joinMuc(conversation, null, followedInvite);
2230	}
2231
2232	private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined) {
2233		joinMuc(conversation, onConferenceJoined, false);
2234	}
2235
2236	private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined, final boolean followedInvite) {
2237		Account account = conversation.getAccount();
2238		account.pendingConferenceJoins.remove(conversation);
2239		account.pendingConferenceLeaves.remove(conversation);
2240		if (account.getStatus() == Account.State.ONLINE) {
2241			sendPresencePacket(account, mPresenceGenerator.leave(conversation.getMucOptions()));
2242			conversation.resetMucOptions();
2243			if (onConferenceJoined != null) {
2244				conversation.getMucOptions().flagNoAutoPushConfiguration();
2245			}
2246			conversation.setHasMessagesLeftOnServer(false);
2247			fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
2248
2249				private void join(Conversation conversation) {
2250					Account account = conversation.getAccount();
2251					final MucOptions mucOptions = conversation.getMucOptions();
2252					final Jid joinJid = mucOptions.getSelf().getFullJid();
2253					Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString());
2254					PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous() || onConferenceJoined != null);
2255					packet.setTo(joinJid);
2256					Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
2257					if (conversation.getMucOptions().getPassword() != null) {
2258						x.addChild("password").setContent(mucOptions.getPassword());
2259					}
2260
2261					if (mucOptions.mamSupport()) {
2262						// Use MAM instead of the limited muc history to get history
2263						x.addChild("history").setAttribute("maxchars", "0");
2264					} else {
2265						// Fallback to muc history
2266						x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted().getTimestamp()));
2267					}
2268					sendPresencePacket(account, packet);
2269					if (onConferenceJoined != null) {
2270						onConferenceJoined.onConferenceJoined(conversation);
2271					}
2272					if (!joinJid.equals(conversation.getJid())) {
2273						conversation.setContactJid(joinJid);
2274						databaseBackend.updateConversation(conversation);
2275					}
2276
2277					if (mucOptions.mamSupport()) {
2278						getMessageArchiveService().catchupMUC(conversation);
2279					}
2280					if (mucOptions.isPrivateAndNonAnonymous()) {
2281						fetchConferenceMembers(conversation);
2282						if (followedInvite && conversation.getBookmark() == null) {
2283							saveConversationAsBookmark(conversation, null);
2284						}
2285					}
2286					sendUnsentMessages(conversation);
2287				}
2288
2289				@Override
2290				public void onConferenceConfigurationFetched(Conversation conversation) {
2291					join(conversation);
2292				}
2293
2294				@Override
2295				public void onFetchFailed(final Conversation conversation, Element error) {
2296					if (error != null && "remote-server-not-found".equals(error.getName())) {
2297						conversation.getMucOptions().setError(MucOptions.Error.SERVER_NOT_FOUND);
2298						updateConversationUi();
2299					} else {
2300						join(conversation);
2301						fetchConferenceConfiguration(conversation);
2302					}
2303				}
2304			});
2305			updateConversationUi();
2306		} else {
2307			account.pendingConferenceJoins.add(conversation);
2308			conversation.resetMucOptions();
2309			conversation.setHasMessagesLeftOnServer(false);
2310			updateConversationUi();
2311		}
2312	}
2313
2314	private void fetchConferenceMembers(final Conversation conversation) {
2315		final Account account = conversation.getAccount();
2316		final AxolotlService axolotlService = account.getAxolotlService();
2317		final String[] affiliations = {"member", "admin", "owner"};
2318		OnIqPacketReceived callback = new OnIqPacketReceived() {
2319
2320			private int i = 0;
2321			private boolean success = true;
2322
2323			@Override
2324			public void onIqPacketReceived(Account account, IqPacket packet) {
2325
2326				Element query = packet.query("http://jabber.org/protocol/muc#admin");
2327				if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2328					for (Element child : query.getChildren()) {
2329						if ("item".equals(child.getName())) {
2330							MucOptions.User user = AbstractParser.parseItem(conversation, child);
2331							if (!user.realJidMatchesAccount()) {
2332								boolean isNew = conversation.getMucOptions().updateUser(user);
2333								if (isNew && user.getRealJid() != null && axolotlService.hasEmptyDeviceList(user.getRealJid())) {
2334									axolotlService.fetchDeviceIds(user.getRealJid());
2335								}
2336							}
2337						}
2338					}
2339				} else {
2340					success = false;
2341					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not request affiliation " + affiliations[i] + " in " + conversation.getJid().toBareJid());
2342				}
2343				++i;
2344				if (i >= affiliations.length) {
2345					List<Jid> members = conversation.getMucOptions().getMembers();
2346					if (success) {
2347						List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
2348						boolean changed = false;
2349						for (ListIterator<Jid> iterator = cryptoTargets.listIterator(); iterator.hasNext(); ) {
2350							Jid jid = iterator.next();
2351							if (!members.contains(jid)) {
2352								iterator.remove();
2353								Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
2354								changed = true;
2355							}
2356						}
2357						if (changed) {
2358							conversation.setAcceptedCryptoTargets(cryptoTargets);
2359							updateConversation(conversation);
2360						}
2361					}
2362					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": retrieved members for " + conversation.getJid().toBareJid() + ": " + conversation.getMucOptions().getMembers());
2363					getAvatarService().clear(conversation);
2364					updateMucRosterUi();
2365					updateConversationUi();
2366				}
2367			}
2368		};
2369		for (String affiliation : affiliations) {
2370			sendIqPacket(account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
2371		}
2372		Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": fetching members for " + conversation.getName());
2373	}
2374
2375	public void providePasswordForMuc(Conversation conversation, String password) {
2376		if (conversation.getMode() == Conversation.MODE_MULTI) {
2377			conversation.getMucOptions().setPassword(password);
2378			if (conversation.getBookmark() != null) {
2379				if (respectAutojoin()) {
2380					conversation.getBookmark().setAutojoin(true);
2381				}
2382				pushBookmarks(conversation.getAccount());
2383			}
2384			updateConversation(conversation);
2385			joinMuc(conversation);
2386		}
2387	}
2388
2389	private boolean hasEnabledAccounts() {
2390		for (Account account : this.accounts) {
2391			if (account.isEnabled()) {
2392				return true;
2393			}
2394		}
2395		return false;
2396	}
2397
2398	public boolean renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
2399		final MucOptions options = conversation.getMucOptions();
2400		final Jid joinJid = options.createJoinJid(nick);
2401		if (joinJid == null) {
2402			return false;
2403		}
2404		if (options.online()) {
2405			Account account = conversation.getAccount();
2406			options.setOnRenameListener(new OnRenameListener() {
2407
2408				@Override
2409				public void onSuccess() {
2410					conversation.setContactJid(joinJid);
2411					databaseBackend.updateConversation(conversation);
2412					Bookmark bookmark = conversation.getBookmark();
2413					if (bookmark != null) {
2414						bookmark.setNick(nick);
2415						pushBookmarks(bookmark.getAccount());
2416					}
2417					callback.success(conversation);
2418				}
2419
2420				@Override
2421				public void onFailure() {
2422					callback.error(R.string.nick_in_use, conversation);
2423				}
2424			});
2425
2426			PresencePacket packet = new PresencePacket();
2427			packet.setTo(joinJid);
2428			packet.setFrom(conversation.getAccount().getJid());
2429
2430			String sig = account.getPgpSignature();
2431			if (sig != null) {
2432				packet.addChild("status").setContent("online");
2433				packet.addChild("x", "jabber:x:signed").setContent(sig);
2434			}
2435			sendPresencePacket(account, packet);
2436		} else {
2437			conversation.setContactJid(joinJid);
2438			databaseBackend.updateConversation(conversation);
2439			if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2440				Bookmark bookmark = conversation.getBookmark();
2441				if (bookmark != null) {
2442					bookmark.setNick(nick);
2443					pushBookmarks(bookmark.getAccount());
2444				}
2445				joinMuc(conversation);
2446			}
2447		}
2448		return true;
2449	}
2450
2451	public void leaveMuc(Conversation conversation) {
2452		leaveMuc(conversation, false);
2453	}
2454
2455	private void leaveMuc(Conversation conversation, boolean now) {
2456		Account account = conversation.getAccount();
2457		account.pendingConferenceJoins.remove(conversation);
2458		account.pendingConferenceLeaves.remove(conversation);
2459		if (account.getStatus() == Account.State.ONLINE || now) {
2460			sendPresencePacket(conversation.getAccount(), mPresenceGenerator.leave(conversation.getMucOptions()));
2461			conversation.getMucOptions().setOffline();
2462			conversation.deregisterWithBookmark();
2463			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": leaving muc " + conversation.getJid());
2464		} else {
2465			account.pendingConferenceLeaves.add(conversation);
2466		}
2467	}
2468
2469	public String findConferenceServer(final Account account) {
2470		String server;
2471		if (account.getXmppConnection() != null) {
2472			server = account.getXmppConnection().getMucServer();
2473			if (server != null) {
2474				return server;
2475			}
2476		}
2477		for (Account other : getAccounts()) {
2478			if (other != account && other.getXmppConnection() != null) {
2479				server = other.getXmppConnection().getMucServer();
2480				if (server != null) {
2481					return server;
2482				}
2483			}
2484		}
2485		return null;
2486	}
2487
2488	public boolean createAdhocConference(final Account account,
2489	                                     final String subject,
2490	                                     final Iterable<Jid> jids,
2491	                                     final UiCallback<Conversation> callback) {
2492		Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
2493		if (account.getStatus() == Account.State.ONLINE) {
2494			try {
2495				String server = findConferenceServer(account);
2496				if (server == null) {
2497					if (callback != null) {
2498						callback.error(R.string.no_conference_server_found, null);
2499					}
2500					return false;
2501				}
2502				final Jid jid = Jid.fromParts(new BigInteger(64, getRNG()).toString(Character.MAX_RADIX), server, null);
2503				final Conversation conversation = findOrCreateConversation(account, jid, true, false, true);
2504				joinMuc(conversation, new OnConferenceJoined() {
2505					@Override
2506					public void onConferenceJoined(final Conversation conversation) {
2507						pushConferenceConfiguration(conversation, IqGenerator.defaultRoomConfiguration(), new OnConfigurationPushed() {
2508							@Override
2509							public void onPushSucceeded() {
2510								if (subject != null && !subject.trim().isEmpty()) {
2511									pushSubjectToConference(conversation, subject.trim());
2512								}
2513								for (Jid invite : jids) {
2514									invite(conversation, invite);
2515								}
2516								if (account.countPresences() > 1) {
2517									directInvite(conversation, account.getJid().toBareJid());
2518								}
2519								saveConversationAsBookmark(conversation, subject);
2520								if (callback != null) {
2521									callback.success(conversation);
2522								}
2523							}
2524
2525							@Override
2526							public void onPushFailed() {
2527								archiveConversation(conversation);
2528								if (callback != null) {
2529									callback.error(R.string.conference_creation_failed, conversation);
2530								}
2531							}
2532						});
2533					}
2534				});
2535				return true;
2536			} catch (InvalidJidException e) {
2537				if (callback != null) {
2538					callback.error(R.string.conference_creation_failed, null);
2539				}
2540				return false;
2541			}
2542		} else {
2543			if (callback != null) {
2544				callback.error(R.string.not_connected_try_again, null);
2545			}
2546			return false;
2547		}
2548	}
2549
2550	public void fetchConferenceConfiguration(final Conversation conversation) {
2551		fetchConferenceConfiguration(conversation, null);
2552	}
2553
2554	public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
2555		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2556		request.setTo(conversation.getJid().toBareJid());
2557		request.query("http://jabber.org/protocol/disco#info");
2558		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2559			@Override
2560			public void onIqPacketReceived(Account account, IqPacket packet) {
2561				Element query = packet.findChild("query", "http://jabber.org/protocol/disco#info");
2562				if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2563					ArrayList<String> features = new ArrayList<>();
2564					for (Element child : query.getChildren()) {
2565						if (child != null && child.getName().equals("feature")) {
2566							String var = child.getAttribute("var");
2567							if (var != null) {
2568								features.add(var);
2569							}
2570						}
2571					}
2572					Element form = query.findChild("x", "jabber:x:data");
2573					if (form != null) {
2574						conversation.getMucOptions().updateFormData(Data.parse(form));
2575					}
2576					conversation.getMucOptions().updateFeatures(features);
2577					if (callback != null) {
2578						callback.onConferenceConfigurationFetched(conversation);
2579					}
2580					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": fetched muc configuration for " + conversation.getJid().toBareJid() + " - " + features.toString());
2581					updateConversationUi();
2582				} else if (packet.getType() == IqPacket.TYPE.ERROR) {
2583					if (callback != null) {
2584						callback.onFetchFailed(conversation, packet.getError());
2585					}
2586				}
2587			}
2588		});
2589	}
2590
2591	public void pushNodeConfiguration(Account account, final String node, final Bundle options, final OnConfigurationPushed callback) {
2592		pushNodeConfiguration(account, account.getJid().toBareJid(), node, options, callback);
2593	}
2594
2595	public void pushNodeConfiguration(Account account, final Jid jid, final String node, final Bundle options, final OnConfigurationPushed callback) {
2596		sendIqPacket(account, mIqGenerator.requestPubsubConfiguration(jid, node), new OnIqPacketReceived() {
2597			@Override
2598			public void onIqPacketReceived(Account account, IqPacket packet) {
2599				if (packet.getType() == IqPacket.TYPE.RESULT) {
2600					Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub#owner");
2601					Element configuration = pubsub == null ? null : pubsub.findChild("configure");
2602					Element x = configuration == null ? null : configuration.findChild("x", "jabber:x:data");
2603					if (x != null) {
2604						Data data = Data.parse(x);
2605						data.submit(options);
2606						sendIqPacket(account, mIqGenerator.publishPubsubConfiguration(jid, node, data), new OnIqPacketReceived() {
2607							@Override
2608							public void onIqPacketReceived(Account account, IqPacket packet) {
2609								if (packet.getType() == IqPacket.TYPE.RESULT && callback != null) {
2610									callback.onPushSucceeded();
2611								} else {
2612									Log.d(Config.LOGTAG, packet.toString());
2613								}
2614							}
2615						});
2616					} else if (callback != null) {
2617						callback.onPushFailed();
2618					}
2619				} else if (callback != null) {
2620					callback.onPushFailed();
2621				}
2622			}
2623		});
2624	}
2625
2626	public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConfigurationPushed callback) {
2627		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2628		request.setTo(conversation.getJid().toBareJid());
2629		request.query("http://jabber.org/protocol/muc#owner");
2630		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2631			@Override
2632			public void onIqPacketReceived(Account account, IqPacket packet) {
2633				if (packet.getType() == IqPacket.TYPE.RESULT) {
2634					Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
2635					data.submit(options);
2636					IqPacket set = new IqPacket(IqPacket.TYPE.SET);
2637					set.setTo(conversation.getJid().toBareJid());
2638					set.query("http://jabber.org/protocol/muc#owner").addChild(data);
2639					sendIqPacket(account, set, new OnIqPacketReceived() {
2640						@Override
2641						public void onIqPacketReceived(Account account, IqPacket packet) {
2642							if (callback != null) {
2643								if (packet.getType() == IqPacket.TYPE.RESULT) {
2644									callback.onPushSucceeded();
2645								} else {
2646									callback.onPushFailed();
2647								}
2648							}
2649						}
2650					});
2651				} else {
2652					if (callback != null) {
2653						callback.onPushFailed();
2654					}
2655				}
2656			}
2657		});
2658	}
2659
2660	public void pushSubjectToConference(final Conversation conference, final String subject) {
2661		MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
2662		this.sendMessagePacket(conference.getAccount(), packet);
2663		final MucOptions mucOptions = conference.getMucOptions();
2664		final MucOptions.User self = mucOptions.getSelf();
2665		if (self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
2666			Bundle options = new Bundle();
2667			options.putString("muc#roomconfig_persistentroom", "1");
2668			options.putString("muc#roomconfig_roomname", subject);
2669			this.pushConferenceConfiguration(conference, options, null);
2670		}
2671	}
2672
2673	public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
2674		final Jid jid = user.toBareJid();
2675		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
2676		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2677			@Override
2678			public void onIqPacketReceived(Account account, IqPacket packet) {
2679				if (packet.getType() == IqPacket.TYPE.RESULT) {
2680					conference.getMucOptions().changeAffiliation(jid, affiliation);
2681					getAvatarService().clear(conference);
2682					callback.onAffiliationChangedSuccessful(jid);
2683				} else {
2684					callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
2685				}
2686			}
2687		});
2688	}
2689
2690	public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
2691		List<Jid> jids = new ArrayList<>();
2692		for (MucOptions.User user : conference.getMucOptions().getUsers()) {
2693			if (user.getAffiliation() == before && user.getRealJid() != null) {
2694				jids.add(user.getRealJid());
2695			}
2696		}
2697		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
2698		sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
2699	}
2700
2701	public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
2702		IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
2703		Log.d(Config.LOGTAG, request.toString());
2704		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2705			@Override
2706			public void onIqPacketReceived(Account account, IqPacket packet) {
2707				Log.d(Config.LOGTAG, packet.toString());
2708				if (packet.getType() == IqPacket.TYPE.RESULT) {
2709					callback.onRoleChangedSuccessful(nick);
2710				} else {
2711					callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
2712				}
2713			}
2714		});
2715	}
2716
2717	private void disconnect(Account account, boolean force) {
2718		if ((account.getStatus() == Account.State.ONLINE)
2719				|| (account.getStatus() == Account.State.DISABLED)) {
2720			final XmppConnection connection = account.getXmppConnection();
2721			if (!force) {
2722				List<Conversation> conversations = getConversations();
2723				for (Conversation conversation : conversations) {
2724					if (conversation.getAccount() == account) {
2725						if (conversation.getMode() == Conversation.MODE_MULTI) {
2726							leaveMuc(conversation, true);
2727						} else {
2728							if (conversation.endOtrIfNeeded()) {
2729								Log.d(Config.LOGTAG, account.getJid().toBareJid()
2730										+ ": ended otr session with "
2731										+ conversation.getJid());
2732							}
2733						}
2734					}
2735				}
2736				sendOfflinePresence(account);
2737			}
2738			connection.disconnect(force);
2739		}
2740	}
2741
2742	@Override
2743	public IBinder onBind(Intent intent) {
2744		return mBinder;
2745	}
2746
2747	public void updateMessage(Message message) {
2748		databaseBackend.updateMessage(message);
2749		updateConversationUi();
2750	}
2751
2752	public void updateMessage(Message message, String uuid) {
2753		databaseBackend.updateMessage(message, uuid);
2754		updateConversationUi();
2755	}
2756
2757	protected void syncDirtyContacts(Account account) {
2758		for (Contact contact : account.getRoster().getContacts()) {
2759			if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
2760				pushContactToServer(contact);
2761			}
2762			if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
2763				deleteContactOnServer(contact);
2764			}
2765		}
2766	}
2767
2768	public void createContact(Contact contact) {
2769		boolean autoGrant = getBooleanPreference("grant_new_contacts", R.bool.grant_new_contacts);
2770		if (autoGrant) {
2771			contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
2772			contact.setOption(Contact.Options.ASKING);
2773		}
2774		pushContactToServer(contact);
2775	}
2776
2777	public void onOtrSessionEstablished(Conversation conversation) {
2778		final Account account = conversation.getAccount();
2779		final Session otrSession = conversation.getOtrSession();
2780		Log.d(Config.LOGTAG,
2781				account.getJid().toBareJid() + " otr session established with "
2782						+ conversation.getJid() + "/"
2783						+ otrSession.getSessionID().getUserID());
2784		conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR, new Conversation.OnMessageFound() {
2785
2786			@Override
2787			public void onMessageFound(Message message) {
2788				SessionID id = otrSession.getSessionID();
2789				try {
2790					message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
2791				} catch (InvalidJidException e) {
2792					return;
2793				}
2794				if (message.needsUploading()) {
2795					mJingleConnectionManager.createNewConnection(message);
2796				} else {
2797					MessagePacket outPacket = mMessageGenerator.generateOtrChat(message);
2798					if (outPacket != null) {
2799						mMessageGenerator.addDelay(outPacket, message.getTimeSent());
2800						message.setStatus(Message.STATUS_SEND);
2801						databaseBackend.updateMessage(message);
2802						sendMessagePacket(account, outPacket);
2803					}
2804				}
2805				updateConversationUi();
2806			}
2807		});
2808	}
2809
2810	public boolean renewSymmetricKey(Conversation conversation) {
2811		Account account = conversation.getAccount();
2812		byte[] symmetricKey = new byte[32];
2813		this.mRandom.nextBytes(symmetricKey);
2814		Session otrSession = conversation.getOtrSession();
2815		if (otrSession != null) {
2816			MessagePacket packet = new MessagePacket();
2817			packet.setType(MessagePacket.TYPE_CHAT);
2818			packet.setFrom(account.getJid());
2819			MessageGenerator.addMessageHints(packet);
2820			packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
2821					+ otrSession.getSessionID().getUserID());
2822			try {
2823				packet.setBody(otrSession
2824						.transformSending(CryptoHelper.FILETRANSFER
2825								+ CryptoHelper.bytesToHex(symmetricKey))[0]);
2826				sendMessagePacket(account, packet);
2827				conversation.setSymmetricKey(symmetricKey);
2828				return true;
2829			} catch (OtrException e) {
2830				return false;
2831			}
2832		}
2833		return false;
2834	}
2835
2836	public void pushContactToServer(final Contact contact) {
2837		contact.resetOption(Contact.Options.DIRTY_DELETE);
2838		contact.setOption(Contact.Options.DIRTY_PUSH);
2839		final Account account = contact.getAccount();
2840		if (account.getStatus() == Account.State.ONLINE) {
2841			final boolean ask = contact.getOption(Contact.Options.ASKING);
2842			final boolean sendUpdates = contact
2843					.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
2844					&& contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
2845			final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2846			iq.query(Namespace.ROSTER).addChild(contact.asElement());
2847			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2848			if (sendUpdates) {
2849				sendPresencePacket(account,
2850						mPresenceGenerator.sendPresenceUpdatesTo(contact));
2851			}
2852			if (ask) {
2853				sendPresencePacket(account,
2854						mPresenceGenerator.requestPresenceUpdatesFrom(contact));
2855			}
2856		}
2857	}
2858
2859	public void publishAvatar(final Account account, final Uri image, final UiCallback<Avatar> callback) {
2860		new Thread(() -> {
2861			final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
2862			final int size = Config.AVATAR_SIZE;
2863			final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
2864			if (avatar != null) {
2865				if (!getFileBackend().save(avatar)) {
2866					callback.error(R.string.error_saving_avatar, avatar);
2867					return;
2868				}
2869				publishAvatar(account, avatar, callback);
2870			} else {
2871				callback.error(R.string.error_publish_avatar_converting, null);
2872			}
2873		}).start();
2874
2875	}
2876
2877	public void publishAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2878		IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
2879		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2880
2881			@Override
2882			public void onIqPacketReceived(Account account, IqPacket result) {
2883				if (result.getType() == IqPacket.TYPE.RESULT) {
2884					final IqPacket packet = XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar);
2885					sendIqPacket(account, packet, new OnIqPacketReceived() {
2886						@Override
2887						public void onIqPacketReceived(Account account, IqPacket result) {
2888							if (result.getType() == IqPacket.TYPE.RESULT) {
2889								if (account.setAvatar(avatar.getFilename())) {
2890									getAvatarService().clear(account);
2891									databaseBackend.updateAccount(account);
2892								}
2893								Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": published avatar " + (avatar.size / 1024) + "KiB");
2894								if (callback != null) {
2895									callback.success(avatar);
2896								}
2897							} else {
2898								if (callback != null) {
2899									callback.error(R.string.error_publish_avatar_server_reject, avatar);
2900								}
2901							}
2902						}
2903					});
2904				} else {
2905					Element error = result.findChild("error");
2906					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": server rejected avatar " + (avatar.size / 1024) + "KiB " + (error != null ? error.toString() : ""));
2907					if (callback != null) {
2908						callback.error(R.string.error_publish_avatar_server_reject, avatar);
2909					}
2910				}
2911			}
2912		});
2913	}
2914
2915	public void republishAvatarIfNeeded(Account account) {
2916		if (account.getAxolotlService().isPepBroken()) {
2917			Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": skipping republication of avatar because pep is broken");
2918			return;
2919		}
2920		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2921		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2922
2923			private Avatar parseAvatar(IqPacket packet) {
2924				Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
2925				if (pubsub != null) {
2926					Element items = pubsub.findChild("items");
2927					if (items != null) {
2928						return Avatar.parseMetadata(items);
2929					}
2930				}
2931				return null;
2932			}
2933
2934			private boolean errorIsItemNotFound(IqPacket packet) {
2935				Element error = packet.findChild("error");
2936				return packet.getType() == IqPacket.TYPE.ERROR
2937						&& error != null
2938						&& error.hasChild("item-not-found");
2939			}
2940
2941			@Override
2942			public void onIqPacketReceived(Account account, IqPacket packet) {
2943				if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
2944					Avatar serverAvatar = parseAvatar(packet);
2945					if (serverAvatar == null && account.getAvatar() != null) {
2946						Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
2947						if (avatar != null) {
2948							Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": avatar on server was null. republishing");
2949							publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
2950						} else {
2951							Log.e(Config.LOGTAG, account.getJid().toBareJid() + ": error rereading avatar");
2952						}
2953					}
2954				}
2955			}
2956		});
2957	}
2958
2959	public void fetchAvatar(Account account, Avatar avatar) {
2960		fetchAvatar(account, avatar, null);
2961	}
2962
2963	public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2964		final String KEY = generateFetchKey(account, avatar);
2965		synchronized (this.mInProgressAvatarFetches) {
2966			if (!this.mInProgressAvatarFetches.contains(KEY)) {
2967				switch (avatar.origin) {
2968					case PEP:
2969						this.mInProgressAvatarFetches.add(KEY);
2970						fetchAvatarPep(account, avatar, callback);
2971						break;
2972					case VCARD:
2973						this.mInProgressAvatarFetches.add(KEY);
2974						fetchAvatarVcard(account, avatar, callback);
2975						break;
2976				}
2977			}
2978		}
2979	}
2980
2981	private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2982		IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
2983		sendIqPacket(account, packet, new OnIqPacketReceived() {
2984
2985			@Override
2986			public void onIqPacketReceived(Account account, IqPacket result) {
2987				synchronized (mInProgressAvatarFetches) {
2988					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2989				}
2990				final String ERROR = account.getJid().toBareJid()
2991						+ ": fetching avatar for " + avatar.owner + " failed ";
2992				if (result.getType() == IqPacket.TYPE.RESULT) {
2993					avatar.image = mIqParser.avatarData(result);
2994					if (avatar.image != null) {
2995						if (getFileBackend().save(avatar)) {
2996							if (account.getJid().toBareJid().equals(avatar.owner)) {
2997								if (account.setAvatar(avatar.getFilename())) {
2998									databaseBackend.updateAccount(account);
2999								}
3000								getAvatarService().clear(account);
3001								updateConversationUi();
3002								updateAccountUi();
3003							} else {
3004								Contact contact = account.getRoster()
3005										.getContact(avatar.owner);
3006								contact.setAvatar(avatar);
3007								getAvatarService().clear(contact);
3008								updateConversationUi();
3009								updateRosterUi();
3010							}
3011							if (callback != null) {
3012								callback.success(avatar);
3013							}
3014							Log.d(Config.LOGTAG, account.getJid().toBareJid()
3015									+ ": successfully fetched pep avatar for " + avatar.owner);
3016							return;
3017						}
3018					} else {
3019
3020						Log.d(Config.LOGTAG, ERROR + "(parsing error)");
3021					}
3022				} else {
3023					Element error = result.findChild("error");
3024					if (error == null) {
3025						Log.d(Config.LOGTAG, ERROR + "(server error)");
3026					} else {
3027						Log.d(Config.LOGTAG, ERROR + error.toString());
3028					}
3029				}
3030				if (callback != null) {
3031					callback.error(0, null);
3032				}
3033
3034			}
3035		});
3036	}
3037
3038	private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3039		IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
3040		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3041			@Override
3042			public void onIqPacketReceived(Account account, IqPacket packet) {
3043				synchronized (mInProgressAvatarFetches) {
3044					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
3045				}
3046				if (packet.getType() == IqPacket.TYPE.RESULT) {
3047					Element vCard = packet.findChild("vCard", "vcard-temp");
3048					Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
3049					String image = photo != null ? photo.findChildContent("BINVAL") : null;
3050					if (image != null) {
3051						avatar.image = image;
3052						if (getFileBackend().save(avatar)) {
3053							Log.d(Config.LOGTAG, account.getJid().toBareJid()
3054									+ ": successfully fetched vCard avatar for " + avatar.owner);
3055							if (avatar.owner.isBareJid()) {
3056								if (account.getJid().toBareJid().equals(avatar.owner) && account.getAvatar() == null) {
3057									Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": had no avatar. replacing with vcard");
3058									account.setAvatar(avatar.getFilename());
3059									databaseBackend.updateAccount(account);
3060									getAvatarService().clear(account);
3061									updateAccountUi();
3062								} else {
3063									Contact contact = account.getRoster().getContact(avatar.owner);
3064									contact.setAvatar(avatar);
3065									getAvatarService().clear(contact);
3066									updateRosterUi();
3067								}
3068								updateConversationUi();
3069							} else {
3070								Conversation conversation = find(account, avatar.owner.toBareJid());
3071								if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
3072									MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
3073									if (user != null) {
3074										if (user.setAvatar(avatar)) {
3075											getAvatarService().clear(user);
3076											updateConversationUi();
3077											updateMucRosterUi();
3078										}
3079									}
3080								}
3081							}
3082						}
3083					}
3084				}
3085			}
3086		});
3087	}
3088
3089	public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
3090		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
3091		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3092
3093			@Override
3094			public void onIqPacketReceived(Account account, IqPacket packet) {
3095				if (packet.getType() == IqPacket.TYPE.RESULT) {
3096					Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
3097					if (pubsub != null) {
3098						Element items = pubsub.findChild("items");
3099						if (items != null) {
3100							Avatar avatar = Avatar.parseMetadata(items);
3101							if (avatar != null) {
3102								avatar.owner = account.getJid().toBareJid();
3103								if (fileBackend.isAvatarCached(avatar)) {
3104									if (account.setAvatar(avatar.getFilename())) {
3105										databaseBackend.updateAccount(account);
3106									}
3107									getAvatarService().clear(account);
3108									callback.success(avatar);
3109								} else {
3110									fetchAvatarPep(account, avatar, callback);
3111								}
3112								return;
3113							}
3114						}
3115					}
3116				}
3117				callback.error(0, null);
3118			}
3119		});
3120	}
3121
3122	public void deleteContactOnServer(Contact contact) {
3123		contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
3124		contact.resetOption(Contact.Options.DIRTY_PUSH);
3125		contact.setOption(Contact.Options.DIRTY_DELETE);
3126		Account account = contact.getAccount();
3127		if (account.getStatus() == Account.State.ONLINE) {
3128			IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
3129			Element item = iq.query(Namespace.ROSTER).addChild("item");
3130			item.setAttribute("jid", contact.getJid().toString());
3131			item.setAttribute("subscription", "remove");
3132			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
3133		}
3134	}
3135
3136	public void updateConversation(final Conversation conversation) {
3137		mDatabaseWriterExecutor.execute(new Runnable() {
3138			@Override
3139			public void run() {
3140				databaseBackend.updateConversation(conversation);
3141			}
3142		});
3143	}
3144
3145	private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
3146		synchronized (account) {
3147			XmppConnection connection = account.getXmppConnection();
3148			if (connection == null) {
3149				connection = createConnection(account);
3150				account.setXmppConnection(connection);
3151			}
3152			boolean hasInternet = hasInternetConnection();
3153			if (account.isEnabled() && hasInternet) {
3154				if (!force) {
3155					disconnect(account, false);
3156				}
3157				Thread thread = new Thread(connection);
3158				connection.setInteractive(interactive);
3159				connection.prepareNewConnection();
3160				connection.interrupt();
3161				thread.start();
3162				scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
3163			} else {
3164				disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
3165				account.getRoster().clearPresences();
3166				connection.resetEverything();
3167				final AxolotlService axolotlService = account.getAxolotlService();
3168				if (axolotlService != null) {
3169					axolotlService.resetBrokenness();
3170				}
3171				if (!hasInternet) {
3172					account.setStatus(Account.State.NO_INTERNET);
3173				}
3174			}
3175		}
3176	}
3177
3178	public void reconnectAccountInBackground(final Account account) {
3179		new Thread(new Runnable() {
3180			@Override
3181			public void run() {
3182				reconnectAccount(account, false, true);
3183			}
3184		}).start();
3185	}
3186
3187	public void invite(Conversation conversation, Jid contact) {
3188		Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": inviting " + contact + " to " + conversation.getJid().toBareJid());
3189		MessagePacket packet = mMessageGenerator.invite(conversation, contact);
3190		sendMessagePacket(conversation.getAccount(), packet);
3191	}
3192
3193	public void directInvite(Conversation conversation, Jid jid) {
3194		MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
3195		sendMessagePacket(conversation.getAccount(), packet);
3196	}
3197
3198	public void resetSendingToWaiting(Account account) {
3199		for (Conversation conversation : getConversations()) {
3200			if (conversation.getAccount() == account) {
3201				conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
3202
3203					@Override
3204					public void onMessageFound(Message message) {
3205						markMessage(message, Message.STATUS_WAITING);
3206					}
3207				});
3208			}
3209		}
3210	}
3211
3212	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
3213		return markMessage(account, recipient, uuid, status, null);
3214	}
3215
3216	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status, String errorMessage) {
3217		if (uuid == null) {
3218			return null;
3219		}
3220		for (Conversation conversation : getConversations()) {
3221			if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
3222				final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
3223				if (message != null) {
3224					markMessage(message, status, errorMessage);
3225				}
3226				return message;
3227			}
3228		}
3229		return null;
3230	}
3231
3232	public boolean markMessage(Conversation conversation, String uuid, int status, String serverMessageId) {
3233		if (uuid == null) {
3234			return false;
3235		} else {
3236			Message message = conversation.findSentMessageWithUuid(uuid);
3237			if (message != null) {
3238				if (message.getServerMsgId() == null) {
3239					message.setServerMsgId(serverMessageId);
3240				}
3241				markMessage(message, status);
3242				return true;
3243			} else {
3244				return false;
3245			}
3246		}
3247	}
3248
3249	public void markMessage(Message message, int status) {
3250		markMessage(message, status, null);
3251	}
3252
3253
3254	public void markMessage(Message message, int status, String errorMessage) {
3255		if (status == Message.STATUS_SEND_FAILED
3256				&& (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
3257				.getStatus() == Message.STATUS_SEND_DISPLAYED)) {
3258			return;
3259		}
3260		message.setErrorMessage(errorMessage);
3261		message.setStatus(status);
3262		databaseBackend.updateMessage(message);
3263		updateConversationUi();
3264	}
3265
3266	private SharedPreferences getPreferences() {
3267		return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
3268	}
3269
3270	public long getAutomaticMessageDeletionDate() {
3271		final long timeout = getLongPreference(SettingsActivity.AUTOMATIC_MESSAGE_DELETION, R.integer.automatic_message_deletion);
3272		return timeout == 0 ? timeout : (System.currentTimeMillis() - (timeout * 1000));
3273	}
3274
3275	public long getLongPreference(String name, @IntegerRes int res) {
3276		long defaultValue = getResources().getInteger(res);
3277		try {
3278			return Long.parseLong(getPreferences().getString(name, String.valueOf(defaultValue)));
3279		} catch (NumberFormatException e) {
3280			return defaultValue;
3281		}
3282	}
3283
3284	public boolean getBooleanPreference(String name, @BoolRes int res) {
3285		return getPreferences().getBoolean(name, getResources().getBoolean(res));
3286	}
3287
3288	public boolean confirmMessages() {
3289		return getBooleanPreference("confirm_messages", R.bool.confirm_messages);
3290	}
3291
3292	public boolean allowMessageCorrection() {
3293		return getBooleanPreference("allow_message_correction", R.bool.allow_message_correction);
3294	}
3295
3296	public boolean sendChatStates() {
3297		return getBooleanPreference("chat_states", R.bool.chat_states);
3298	}
3299
3300	private boolean respectAutojoin() {
3301		return getBooleanPreference("autojoin", R.bool.autojoin);
3302	}
3303
3304	public boolean indicateReceived() {
3305		return getBooleanPreference("indicate_received", R.bool.indicate_received);
3306	}
3307
3308	public boolean useTorToConnect() {
3309		return Config.FORCE_ORBOT || getBooleanPreference("use_tor", R.bool.use_tor);
3310	}
3311
3312	public boolean showExtendedConnectionOptions() {
3313		return getBooleanPreference("show_connection_options", R.bool.show_connection_options);
3314	}
3315
3316	public boolean broadcastLastActivity() {
3317		return getBooleanPreference(SettingsActivity.BROADCAST_LAST_ACTIVITY, R.bool.last_activity);
3318	}
3319
3320	public int unreadCount() {
3321		int count = 0;
3322		for (Conversation conversation : getConversations()) {
3323			count += conversation.unreadCount();
3324		}
3325		return count;
3326	}
3327
3328
3329	public void showErrorToastInUi(int resId) {
3330		if (mOnShowErrorToast != null) {
3331			mOnShowErrorToast.onShowErrorToast(resId);
3332		}
3333	}
3334
3335	public void updateConversationUi() {
3336		if (mOnConversationUpdate != null) {
3337			mOnConversationUpdate.onConversationUpdate();
3338		}
3339	}
3340
3341	public void updateAccountUi() {
3342		if (mOnAccountUpdate != null) {
3343			mOnAccountUpdate.onAccountUpdate();
3344		}
3345	}
3346
3347	public void updateRosterUi() {
3348		if (mOnRosterUpdate != null) {
3349			mOnRosterUpdate.onRosterUpdate();
3350		}
3351	}
3352
3353	public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
3354		if (mOnCaptchaRequested != null) {
3355			DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
3356			Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
3357					(int) (captcha.getHeight() * metrics.scaledDensity), false);
3358
3359			mOnCaptchaRequested.onCaptchaRequested(account, id, data, scaled);
3360			return true;
3361		}
3362		return false;
3363	}
3364
3365	public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
3366		if (mOnUpdateBlocklist != null) {
3367			mOnUpdateBlocklist.OnUpdateBlocklist(status);
3368		}
3369	}
3370
3371	public void updateMucRosterUi() {
3372		if (mOnMucRosterUpdate != null) {
3373			mOnMucRosterUpdate.onMucRosterUpdate();
3374		}
3375	}
3376
3377	public void keyStatusUpdated(AxolotlService.FetchStatus report) {
3378		if (mOnKeyStatusUpdated != null) {
3379			mOnKeyStatusUpdated.onKeyStatusUpdated(report);
3380		}
3381	}
3382
3383	public Account findAccountByJid(final Jid accountJid) {
3384		for (Account account : this.accounts) {
3385			if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
3386				return account;
3387			}
3388		}
3389		return null;
3390	}
3391
3392	public Conversation findConversationByUuid(String uuid) {
3393		for (Conversation conversation : getConversations()) {
3394			if (conversation.getUuid().equals(uuid)) {
3395				return conversation;
3396			}
3397		}
3398		return null;
3399	}
3400
3401	public boolean markRead(final Conversation conversation) {
3402		return markRead(conversation, true);
3403	}
3404
3405	public boolean markRead(final Conversation conversation, boolean clear) {
3406		if (clear) {
3407			mNotificationService.clear(conversation);
3408		}
3409		final List<Message> readMessages = conversation.markRead();
3410		if (readMessages.size() > 0) {
3411			Runnable runnable = new Runnable() {
3412				@Override
3413				public void run() {
3414					for (Message message : readMessages) {
3415						databaseBackend.updateMessage(message);
3416					}
3417				}
3418			};
3419			mDatabaseWriterExecutor.execute(runnable);
3420			updateUnreadCountBadge();
3421			return true;
3422		} else {
3423			return false;
3424		}
3425	}
3426
3427	public synchronized void updateUnreadCountBadge() {
3428		int count = unreadCount();
3429		if (unreadCount != count) {
3430			Log.d(Config.LOGTAG, "update unread count to " + count);
3431			if (count > 0) {
3432				ShortcutBadger.applyCount(getApplicationContext(), count);
3433			} else {
3434				ShortcutBadger.removeCount(getApplicationContext());
3435			}
3436			unreadCount = count;
3437		}
3438	}
3439
3440	public void sendReadMarker(final Conversation conversation) {
3441		final boolean isPrivateAndNonAnonymousMuc = conversation.getMode() == Conversation.MODE_MULTI && conversation.isPrivateAndNonAnonymous();
3442		final Message markable = conversation.getLatestMarkableMessage(isPrivateAndNonAnonymousMuc);
3443		if (this.markRead(conversation)) {
3444			updateConversationUi();
3445		}
3446		if (confirmMessages()
3447				&& markable != null
3448				&& (markable.trusted() || isPrivateAndNonAnonymousMuc)
3449				&& markable.getRemoteMsgId() != null) {
3450			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
3451			Account account = conversation.getAccount();
3452			final Jid to = markable.getCounterpart();
3453			final boolean groupChat = conversation.getMode() == Conversation.MODE_MULTI;
3454			MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId(), markable.getCounterpart(), groupChat);
3455			this.sendMessagePacket(conversation.getAccount(), packet);
3456		}
3457	}
3458
3459	public SecureRandom getRNG() {
3460		return this.mRandom;
3461	}
3462
3463	public MemorizingTrustManager getMemorizingTrustManager() {
3464		return this.mMemorizingTrustManager;
3465	}
3466
3467	public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
3468		this.mMemorizingTrustManager = trustManager;
3469	}
3470
3471	public void updateMemorizingTrustmanager() {
3472		final MemorizingTrustManager tm;
3473		final boolean dontTrustSystemCAs = getBooleanPreference("dont_trust_system_cas", R.bool.dont_trust_system_cas);
3474		if (dontTrustSystemCAs) {
3475			tm = new MemorizingTrustManager(getApplicationContext(), null);
3476		} else {
3477			tm = new MemorizingTrustManager(getApplicationContext());
3478		}
3479		setMemorizingTrustManager(tm);
3480	}
3481
3482	public PowerManager getPowerManager() {
3483		return this.pm;
3484	}
3485
3486	public LruCache<String, Bitmap> getBitmapCache() {
3487		return this.mBitmapCache;
3488	}
3489
3490	public void syncRosterToDisk(final Account account) {
3491		Runnable runnable = new Runnable() {
3492
3493			@Override
3494			public void run() {
3495				databaseBackend.writeRoster(account.getRoster());
3496			}
3497		};
3498		mDatabaseWriterExecutor.execute(runnable);
3499
3500	}
3501
3502	public List<String> getKnownHosts() {
3503		final List<String> hosts = new ArrayList<>();
3504		for (final Account account : getAccounts()) {
3505			if (!hosts.contains(account.getServer().toString())) {
3506				hosts.add(account.getServer().toString());
3507			}
3508			for (final Contact contact : account.getRoster().getContacts()) {
3509				if (contact.showInRoster()) {
3510					final String server = contact.getServer().toString();
3511					if (server != null && !hosts.contains(server)) {
3512						hosts.add(server);
3513					}
3514				}
3515			}
3516		}
3517		if (Config.DOMAIN_LOCK != null && !hosts.contains(Config.DOMAIN_LOCK)) {
3518			hosts.add(Config.DOMAIN_LOCK);
3519		}
3520		if (Config.MAGIC_CREATE_DOMAIN != null && !hosts.contains(Config.MAGIC_CREATE_DOMAIN)) {
3521			hosts.add(Config.MAGIC_CREATE_DOMAIN);
3522		}
3523		return hosts;
3524	}
3525
3526	public List<String> getKnownConferenceHosts() {
3527		final ArrayList<String> mucServers = new ArrayList<>();
3528		for (final Account account : accounts) {
3529			if (account.getXmppConnection() != null) {
3530				final String server = account.getXmppConnection().getMucServer();
3531				if (server != null && !mucServers.contains(server)) {
3532					mucServers.add(server);
3533				}
3534				for (Bookmark bookmark : account.getBookmarks()) {
3535					final Jid jid = bookmark.getJid();
3536					final String s = jid == null ? null : jid.getDomainpart();
3537					if (s != null && !mucServers.contains(s)) {
3538						mucServers.add(s);
3539					}
3540				}
3541			}
3542		}
3543		return mucServers;
3544	}
3545
3546	public void sendMessagePacket(Account account, MessagePacket packet) {
3547		XmppConnection connection = account.getXmppConnection();
3548		if (connection != null) {
3549			connection.sendMessagePacket(packet);
3550		}
3551	}
3552
3553	public void sendPresencePacket(Account account, PresencePacket packet) {
3554		XmppConnection connection = account.getXmppConnection();
3555		if (connection != null) {
3556			connection.sendPresencePacket(packet);
3557		}
3558	}
3559
3560	public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
3561		final XmppConnection connection = account.getXmppConnection();
3562		if (connection != null) {
3563			IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
3564			connection.sendUnmodifiedIqPacket(request, connection.registrationResponseListener);
3565		}
3566	}
3567
3568	public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
3569		final XmppConnection connection = account.getXmppConnection();
3570		if (connection != null) {
3571			connection.sendIqPacket(packet, callback);
3572		}
3573	}
3574
3575	public void sendPresence(final Account account) {
3576		sendPresence(account, checkListeners() && broadcastLastActivity());
3577	}
3578
3579	private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
3580		PresencePacket packet;
3581		if (manuallyChangePresence()) {
3582			packet = mPresenceGenerator.selfPresence(account, account.getPresenceStatus());
3583			String message = account.getPresenceStatusMessage();
3584			if (message != null && !message.isEmpty()) {
3585				packet.addChild(new Element("status").setContent(message));
3586			}
3587		} else {
3588			packet = mPresenceGenerator.selfPresence(account, getTargetPresence());
3589		}
3590		if (mLastActivity > 0 && includeIdleTimestamp) {
3591			long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
3592			packet.addChild("idle", Namespace.IDLE).setAttribute("since", AbstractGenerator.getTimestamp(since));
3593		}
3594		sendPresencePacket(account, packet);
3595	}
3596
3597	private void deactivateGracePeriod() {
3598		for (Account account : getAccounts()) {
3599			account.deactivateGracePeriod();
3600		}
3601	}
3602
3603	public void refreshAllPresences() {
3604		boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
3605		for (Account account : getAccounts()) {
3606			if (account.isEnabled()) {
3607				sendPresence(account, includeIdleTimestamp);
3608			}
3609		}
3610	}
3611
3612	private void refreshAllGcmTokens() {
3613		for (Account account : getAccounts()) {
3614			if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
3615				mPushManagementService.registerPushTokenOnServer(account);
3616			}
3617		}
3618	}
3619
3620	private void sendOfflinePresence(final Account account) {
3621		Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": sending offline presence");
3622		sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
3623	}
3624
3625	public MessageGenerator getMessageGenerator() {
3626		return this.mMessageGenerator;
3627	}
3628
3629	public PresenceGenerator getPresenceGenerator() {
3630		return this.mPresenceGenerator;
3631	}
3632
3633	public IqGenerator getIqGenerator() {
3634		return this.mIqGenerator;
3635	}
3636
3637	public IqParser getIqParser() {
3638		return this.mIqParser;
3639	}
3640
3641	public JingleConnectionManager getJingleConnectionManager() {
3642		return this.mJingleConnectionManager;
3643	}
3644
3645	public MessageArchiveService getMessageArchiveService() {
3646		return this.mMessageArchiveService;
3647	}
3648
3649	public List<Contact> findContacts(Jid jid, String accountJid) {
3650		ArrayList<Contact> contacts = new ArrayList<>();
3651		for (Account account : getAccounts()) {
3652			if ((account.isEnabled() || accountJid != null)
3653					&& (accountJid == null || accountJid.equals(account.getJid().toBareJid().toString()))) {
3654				Contact contact = account.getRoster().getContactFromRoster(jid);
3655				if (contact != null) {
3656					contacts.add(contact);
3657				}
3658			}
3659		}
3660		return contacts;
3661	}
3662
3663	public Conversation findFirstMuc(Jid jid) {
3664		for (Conversation conversation : getConversations()) {
3665			if (conversation.getAccount().isEnabled() && conversation.getJid().toBareJid().equals(jid.toBareJid()) && conversation.getMode() == Conversation.MODE_MULTI) {
3666				return conversation;
3667			}
3668		}
3669		return null;
3670	}
3671
3672	public NotificationService getNotificationService() {
3673		return this.mNotificationService;
3674	}
3675
3676	public HttpConnectionManager getHttpConnectionManager() {
3677		return this.mHttpConnectionManager;
3678	}
3679
3680	public void resendFailedMessages(final Message message) {
3681		final Collection<Message> messages = new ArrayList<>();
3682		Message current = message;
3683		while (current.getStatus() == Message.STATUS_SEND_FAILED) {
3684			messages.add(current);
3685			if (current.mergeable(current.next())) {
3686				current = current.next();
3687			} else {
3688				break;
3689			}
3690		}
3691		for (final Message msg : messages) {
3692			msg.setTime(System.currentTimeMillis());
3693			markMessage(msg, Message.STATUS_WAITING);
3694			this.resendMessage(msg, false);
3695		}
3696	}
3697
3698	public void clearConversationHistory(final Conversation conversation) {
3699		final long clearDate;
3700		final String reference;
3701		if (conversation.countMessages() > 0) {
3702			Message latestMessage = conversation.getLatestMessage();
3703			clearDate = latestMessage.getTimeSent() + 1000;
3704			reference = latestMessage.getServerMsgId();
3705		} else {
3706			clearDate = System.currentTimeMillis();
3707			reference = null;
3708		}
3709		conversation.clearMessages();
3710		conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
3711		conversation.setLastClearHistory(clearDate, reference);
3712		Runnable runnable = new Runnable() {
3713			@Override
3714			public void run() {
3715				databaseBackend.deleteMessagesInConversation(conversation);
3716				databaseBackend.updateConversation(conversation);
3717			}
3718		};
3719		mDatabaseWriterExecutor.execute(runnable);
3720	}
3721
3722	public boolean sendBlockRequest(final Blockable blockable, boolean reportSpam) {
3723		if (blockable != null && blockable.getBlockedJid() != null) {
3724			final Jid jid = blockable.getBlockedJid();
3725			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid, reportSpam), new OnIqPacketReceived() {
3726
3727				@Override
3728				public void onIqPacketReceived(final Account account, final IqPacket packet) {
3729					if (packet.getType() == IqPacket.TYPE.RESULT) {
3730						account.getBlocklist().add(jid);
3731						updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
3732					}
3733				}
3734			});
3735			if (removeBlockedConversations(blockable.getAccount(), jid)) {
3736				updateConversationUi();
3737				return true;
3738			} else {
3739				return false;
3740			}
3741		} else {
3742			return false;
3743		}
3744	}
3745
3746	public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
3747		boolean removed = false;
3748		synchronized (this.conversations) {
3749			boolean domainJid = blockedJid.isDomainJid();
3750			for (Conversation conversation : this.conversations) {
3751				boolean jidMatches = (domainJid && blockedJid.getDomainpart().equals(conversation.getJid().getDomainpart()))
3752						|| blockedJid.equals(conversation.getJid().toBareJid());
3753				if (conversation.getAccount() == account
3754						&& conversation.getMode() == Conversation.MODE_SINGLE
3755						&& jidMatches) {
3756					this.conversations.remove(conversation);
3757					markRead(conversation);
3758					conversation.setStatus(Conversation.STATUS_ARCHIVED);
3759					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": archiving conversation " + conversation.getJid().toBareJid() + " because jid was blocked");
3760					updateConversation(conversation);
3761					removed = true;
3762				}
3763			}
3764		}
3765		return removed;
3766	}
3767
3768	public void sendUnblockRequest(final Blockable blockable) {
3769		if (blockable != null && blockable.getJid() != null) {
3770			final Jid jid = blockable.getBlockedJid();
3771			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
3772				@Override
3773				public void onIqPacketReceived(final Account account, final IqPacket packet) {
3774					if (packet.getType() == IqPacket.TYPE.RESULT) {
3775						account.getBlocklist().remove(jid);
3776						updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
3777					}
3778				}
3779			});
3780		}
3781	}
3782
3783	public void publishDisplayName(Account account) {
3784		String displayName = account.getDisplayName();
3785		if (displayName != null && !displayName.isEmpty()) {
3786			IqPacket publish = mIqGenerator.publishNick(displayName);
3787			sendIqPacket(account, publish, new OnIqPacketReceived() {
3788				@Override
3789				public void onIqPacketReceived(Account account, IqPacket packet) {
3790					if (packet.getType() == IqPacket.TYPE.ERROR) {
3791						Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not publish nick");
3792					}
3793				}
3794			});
3795		}
3796	}
3797
3798	public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
3799		ServiceDiscoveryResult result = discoCache.get(key);
3800		if (result != null) {
3801			return result;
3802		} else {
3803			result = databaseBackend.findDiscoveryResult(key.first, key.second);
3804			if (result != null) {
3805				discoCache.put(key, result);
3806			}
3807			return result;
3808		}
3809	}
3810
3811	public void fetchCaps(Account account, final Jid jid, final Presence presence) {
3812		final Pair<String, String> key = new Pair<>(presence.getHash(), presence.getVer());
3813		ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
3814		if (disco != null) {
3815			presence.setServiceDiscoveryResult(disco);
3816		} else {
3817			if (!account.inProgressDiscoFetches.contains(key)) {
3818				account.inProgressDiscoFetches.add(key);
3819				IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3820				request.setTo(jid);
3821				request.query("http://jabber.org/protocol/disco#info");
3822				Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": making disco request for " + key.second + " to " + jid);
3823				sendIqPacket(account, request, new OnIqPacketReceived() {
3824					@Override
3825					public void onIqPacketReceived(Account account, IqPacket discoPacket) {
3826						if (discoPacket.getType() == IqPacket.TYPE.RESULT) {
3827							ServiceDiscoveryResult disco = new ServiceDiscoveryResult(discoPacket);
3828							if (presence.getVer().equals(disco.getVer())) {
3829								databaseBackend.insertDiscoveryResult(disco);
3830								injectServiceDiscorveryResult(account.getRoster(), presence.getHash(), presence.getVer(), disco);
3831							} else {
3832								Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + disco.getVer());
3833							}
3834						}
3835						account.inProgressDiscoFetches.remove(key);
3836					}
3837				});
3838			}
3839		}
3840	}
3841
3842	private void injectServiceDiscorveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
3843		for (Contact contact : roster.getContacts()) {
3844			for (Presence presence : contact.getPresences().getPresences().values()) {
3845				if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
3846					presence.setServiceDiscoveryResult(disco);
3847				}
3848			}
3849		}
3850	}
3851
3852	public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
3853		final boolean legacy = account.getXmppConnection().getFeatures().mamLegacy();
3854		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3855		request.addChild("prefs", legacy ? Namespace.MAM_LEGACY : Namespace.MAM);
3856		sendIqPacket(account, request, new OnIqPacketReceived() {
3857			@Override
3858			public void onIqPacketReceived(Account account, IqPacket packet) {
3859				Element prefs = packet.findChild("prefs", legacy ? Namespace.MAM_LEGACY : Namespace.MAM);
3860				if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
3861					callback.onPreferencesFetched(prefs);
3862				} else {
3863					callback.onPreferencesFetchFailed();
3864				}
3865			}
3866		});
3867	}
3868
3869	public PushManagementService getPushManagementService() {
3870		return mPushManagementService;
3871	}
3872
3873	public Account getPendingAccount() {
3874		Account pending = null;
3875		for (Account account : getAccounts()) {
3876			if (account.isOptionSet(Account.OPTION_REGISTER)) {
3877				pending = account;
3878			} else {
3879				return null;
3880			}
3881		}
3882		return pending;
3883	}
3884
3885	public void changeStatus(Account account, Presence.Status status, String statusMessage, boolean send) {
3886		if (!statusMessage.isEmpty()) {
3887			databaseBackend.insertPresenceTemplate(new PresenceTemplate(status, statusMessage));
3888		}
3889		changeStatusReal(account, status, statusMessage, send);
3890	}
3891
3892	private void changeStatusReal(Account account, Presence.Status status, String statusMessage, boolean send) {
3893		account.setPresenceStatus(status);
3894		account.setPresenceStatusMessage(statusMessage);
3895		databaseBackend.updateAccount(account);
3896		if (account.isEnabled() && send) {
3897			sendPresence(account);
3898		}
3899	}
3900
3901	public void changeStatus(Presence.Status status, String statusMessage) {
3902		if (!statusMessage.isEmpty()) {
3903			databaseBackend.insertPresenceTemplate(new PresenceTemplate(status, statusMessage));
3904		}
3905		for (Account account : getAccounts()) {
3906			changeStatusReal(account, status, statusMessage, true);
3907		}
3908	}
3909
3910	public List<PresenceTemplate> getPresenceTemplates(Account account) {
3911		List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
3912		for (PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
3913			if (!templates.contains(template)) {
3914				templates.add(0, template);
3915			}
3916		}
3917		return templates;
3918	}
3919
3920	public void saveConversationAsBookmark(Conversation conversation, String name) {
3921		Account account = conversation.getAccount();
3922		Bookmark bookmark = new Bookmark(account, conversation.getJid().toBareJid());
3923		if (!conversation.getJid().isBareJid()) {
3924			bookmark.setNick(conversation.getJid().getResourcepart());
3925		}
3926		if (name != null && !name.trim().isEmpty()) {
3927			bookmark.setBookmarkName(name.trim());
3928		}
3929		bookmark.setAutojoin(getPreferences().getBoolean("autojoin", getResources().getBoolean(R.bool.autojoin)));
3930		account.getBookmarks().add(bookmark);
3931		pushBookmarks(account);
3932		conversation.setBookmark(bookmark);
3933	}
3934
3935	public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
3936		boolean needsRosterWrite = false;
3937		boolean performedVerification = false;
3938		final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
3939		for (XmppUri.Fingerprint fp : fingerprints) {
3940			if (fp.type == XmppUri.FingerprintType.OTR) {
3941				performedVerification |= contact.addOtrFingerprint(fp.fingerprint);
3942				needsRosterWrite |= performedVerification;
3943			} else if (fp.type == XmppUri.FingerprintType.OMEMO) {
3944				String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
3945				FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
3946				if (fingerprintStatus != null) {
3947					if (!fingerprintStatus.isVerified()) {
3948						performedVerification = true;
3949						axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
3950					}
3951				} else {
3952					axolotlService.preVerifyFingerprint(contact, fingerprint);
3953				}
3954			}
3955		}
3956		if (needsRosterWrite) {
3957			syncRosterToDisk(contact.getAccount());
3958		}
3959		return performedVerification;
3960	}
3961
3962	public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
3963		final AxolotlService axolotlService = account.getAxolotlService();
3964		boolean verifiedSomething = false;
3965		for (XmppUri.Fingerprint fp : fingerprints) {
3966			if (fp.type == XmppUri.FingerprintType.OMEMO) {
3967				String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
3968				Log.d(Config.LOGTAG, "trying to verify own fp=" + fingerprint);
3969				FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
3970				if (fingerprintStatus != null) {
3971					if (!fingerprintStatus.isVerified()) {
3972						axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
3973						verifiedSomething = true;
3974					}
3975				} else {
3976					axolotlService.preVerifyFingerprint(account, fingerprint);
3977					verifiedSomething = true;
3978				}
3979			}
3980		}
3981		return verifiedSomething;
3982	}
3983
3984	public boolean blindTrustBeforeVerification() {
3985		return getBooleanPreference(SettingsActivity.BLIND_TRUST_BEFORE_VERIFICATION, R.bool.btbv);
3986	}
3987
3988	public ShortcutService getShortcutService() {
3989		return mShortcutService;
3990	}
3991
3992	public interface OnMamPreferencesFetched {
3993		void onPreferencesFetched(Element prefs);
3994
3995		void onPreferencesFetchFailed();
3996	}
3997
3998	public void pushMamPreferences(Account account, Element prefs) {
3999		IqPacket set = new IqPacket(IqPacket.TYPE.SET);
4000		set.addChild(prefs);
4001		sendIqPacket(account, set, null);
4002	}
4003
4004	public interface OnAccountCreated {
4005		void onAccountCreated(Account account);
4006
4007		void informUser(int r);
4008	}
4009
4010	public interface OnMoreMessagesLoaded {
4011		void onMoreMessagesLoaded(int count, Conversation conversation);
4012
4013		void informUser(int r);
4014	}
4015
4016	public interface OnAccountPasswordChanged {
4017		void onPasswordChangeSucceeded();
4018
4019		void onPasswordChangeFailed();
4020	}
4021
4022	public interface OnAffiliationChanged {
4023		void onAffiliationChangedSuccessful(Jid jid);
4024
4025		void onAffiliationChangeFailed(Jid jid, int resId);
4026	}
4027
4028	public interface OnRoleChanged {
4029		void onRoleChangedSuccessful(String nick);
4030
4031		void onRoleChangeFailed(String nick, int resid);
4032	}
4033
4034	public interface OnConversationUpdate {
4035		void onConversationUpdate();
4036	}
4037
4038	public interface OnAccountUpdate {
4039		void onAccountUpdate();
4040	}
4041
4042	public interface OnCaptchaRequested {
4043		void onCaptchaRequested(Account account,
4044		                        String id,
4045		                        Data data,
4046		                        Bitmap captcha);
4047	}
4048
4049	public interface OnRosterUpdate {
4050		void onRosterUpdate();
4051	}
4052
4053	public interface OnMucRosterUpdate {
4054		void onMucRosterUpdate();
4055	}
4056
4057	public interface OnConferenceConfigurationFetched {
4058		void onConferenceConfigurationFetched(Conversation conversation);
4059
4060		void onFetchFailed(Conversation conversation, Element error);
4061	}
4062
4063	public interface OnConferenceJoined {
4064		void onConferenceJoined(Conversation conversation);
4065	}
4066
4067	public interface OnConfigurationPushed {
4068		void onPushSucceeded();
4069
4070		void onPushFailed();
4071	}
4072
4073	public interface OnShowErrorToast {
4074		void onShowErrorToast(int resId);
4075	}
4076
4077	public class XmppConnectionBinder extends Binder {
4078		public XmppConnectionService getService() {
4079			return XmppConnectionService.this;
4080		}
4081	}
4082}