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