XmppConnectionService.java

   1package eu.siacs.conversations.services;
   2
   3import android.annotation.SuppressLint;
   4import android.app.AlarmManager;
   5import android.app.PendingIntent;
   6import android.app.Service;
   7import android.content.Context;
   8import android.content.Intent;
   9import android.content.SharedPreferences;
  10import android.database.ContentObserver;
  11import android.graphics.Bitmap;
  12import android.net.ConnectivityManager;
  13import android.net.NetworkInfo;
  14import android.net.Uri;
  15import android.os.Binder;
  16import android.os.Bundle;
  17import android.os.FileObserver;
  18import android.os.IBinder;
  19import android.os.Looper;
  20import android.os.PowerManager;
  21import android.os.PowerManager.WakeLock;
  22import android.os.SystemClock;
  23import android.preference.PreferenceManager;
  24import android.provider.ContactsContract;
  25import android.util.Log;
  26import android.util.LruCache;
  27
  28import net.java.otr4j.OtrException;
  29import net.java.otr4j.session.Session;
  30import net.java.otr4j.session.SessionID;
  31import net.java.otr4j.session.SessionImpl;
  32import net.java.otr4j.session.SessionStatus;
  33
  34import org.openintents.openpgp.util.OpenPgpApi;
  35import org.openintents.openpgp.util.OpenPgpServiceConnection;
  36
  37import java.math.BigInteger;
  38import java.security.SecureRandom;
  39import java.util.ArrayList;
  40import java.util.Arrays;
  41import java.util.Collection;
  42import java.util.Collections;
  43import java.util.Comparator;
  44import java.util.Hashtable;
  45import java.util.Iterator;
  46import java.util.List;
  47import java.util.Locale;
  48import java.util.Map;
  49import java.util.concurrent.CopyOnWriteArrayList;
  50
  51import de.duenndns.ssl.MemorizingTrustManager;
  52import eu.siacs.conversations.Config;
  53import eu.siacs.conversations.R;
  54import eu.siacs.conversations.crypto.PgpEngine;
  55import eu.siacs.conversations.entities.Account;
  56import eu.siacs.conversations.entities.Blockable;
  57import eu.siacs.conversations.entities.Bookmark;
  58import eu.siacs.conversations.entities.Contact;
  59import eu.siacs.conversations.entities.Conversation;
  60import eu.siacs.conversations.entities.Message;
  61import eu.siacs.conversations.entities.MucOptions;
  62import eu.siacs.conversations.entities.MucOptions.OnRenameListener;
  63import eu.siacs.conversations.entities.Transferable;
  64import eu.siacs.conversations.entities.TransferablePlaceholder;
  65import eu.siacs.conversations.generator.IqGenerator;
  66import eu.siacs.conversations.generator.MessageGenerator;
  67import eu.siacs.conversations.generator.PresenceGenerator;
  68import eu.siacs.conversations.http.HttpConnectionManager;
  69import eu.siacs.conversations.parser.IqParser;
  70import eu.siacs.conversations.parser.MessageParser;
  71import eu.siacs.conversations.parser.PresenceParser;
  72import eu.siacs.conversations.persistance.DatabaseBackend;
  73import eu.siacs.conversations.persistance.FileBackend;
  74import eu.siacs.conversations.ui.UiCallback;
  75import eu.siacs.conversations.utils.CryptoHelper;
  76import eu.siacs.conversations.utils.ExceptionHelper;
  77import eu.siacs.conversations.utils.OnPhoneContactsLoadedListener;
  78import eu.siacs.conversations.utils.PRNGFixes;
  79import eu.siacs.conversations.utils.PhoneHelper;
  80import eu.siacs.conversations.utils.SerialSingleThreadExecutor;
  81import eu.siacs.conversations.utils.Xmlns;
  82import eu.siacs.conversations.xml.Element;
  83import eu.siacs.conversations.xmpp.OnBindListener;
  84import eu.siacs.conversations.xmpp.OnContactStatusChanged;
  85import eu.siacs.conversations.xmpp.OnIqPacketReceived;
  86import eu.siacs.conversations.xmpp.OnMessageAcknowledged;
  87import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
  88import eu.siacs.conversations.xmpp.OnNewKeysAvailable;
  89import eu.siacs.conversations.xmpp.OnPresencePacketReceived;
  90import eu.siacs.conversations.xmpp.OnStatusChanged;
  91import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
  92import eu.siacs.conversations.xmpp.XmppConnection;
  93import eu.siacs.conversations.xmpp.chatstate.ChatState;
  94import eu.siacs.conversations.xmpp.forms.Data;
  95import eu.siacs.conversations.xmpp.forms.Field;
  96import eu.siacs.conversations.xmpp.jid.InvalidJidException;
  97import eu.siacs.conversations.xmpp.jid.Jid;
  98import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
  99import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
 100import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
 101import eu.siacs.conversations.xmpp.pep.Avatar;
 102import eu.siacs.conversations.xmpp.stanzas.IqPacket;
 103import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
 104import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
 105import me.leolin.shortcutbadger.ShortcutBadger;
 106
 107public class XmppConnectionService extends Service implements OnPhoneContactsLoadedListener {
 108
 109	public static final String ACTION_CLEAR_NOTIFICATION = "clear_notification";
 110	public static final String ACTION_DISABLE_FOREGROUND = "disable_foreground";
 111	private static final String ACTION_MERGE_PHONE_CONTACTS = "merge_phone_contacts";
 112	public static final String ACTION_TRY_AGAIN = "try_again";
 113	public static final String ACTION_DISABLE_ACCOUNT = "disable_account";
 114	private ContentObserver contactObserver = new ContentObserver(null) {
 115		@Override
 116		public void onChange(boolean selfChange) {
 117			super.onChange(selfChange);
 118			Intent intent = new Intent(getApplicationContext(),
 119					XmppConnectionService.class);
 120			intent.setAction(ACTION_MERGE_PHONE_CONTACTS);
 121			startService(intent);
 122		}
 123	};
 124
 125	private final SerialSingleThreadExecutor mFileAddingExecutor = new SerialSingleThreadExecutor();
 126	private final SerialSingleThreadExecutor mDatabaseExecutor = new SerialSingleThreadExecutor();
 127
 128	private final IBinder mBinder = new XmppConnectionBinder();
 129	private final List<Conversation> conversations = new CopyOnWriteArrayList<>();
 130	private final FileObserver fileObserver = new FileObserver(
 131			FileBackend.getConversationsImageDirectory()) {
 132
 133		@Override
 134		public void onEvent(int event, String path) {
 135			if (event == FileObserver.DELETE) {
 136				markFileDeleted(path.split("\\.")[0]);
 137			}
 138		}
 139	};
 140	private final OnJinglePacketReceived jingleListener = new OnJinglePacketReceived() {
 141
 142		@Override
 143		public void onJinglePacketReceived(Account account, JinglePacket packet) {
 144			mJingleConnectionManager.deliverPacket(account, packet);
 145		}
 146	};
 147	private final OnBindListener mOnBindListener = new OnBindListener() {
 148
 149		@Override
 150		public void onBind(final Account account) {
 151			account.getRoster().clearPresences();
 152			account.pendingConferenceJoins.clear();
 153			account.pendingConferenceLeaves.clear();
 154			fetchRosterFromServer(account);
 155			fetchBookmarks(account);
 156			sendPresence(account);
 157			connectMultiModeConversations(account);
 158			updateConversationUi();
 159		}
 160	};
 161	private final OnMessageAcknowledged mOnMessageAcknowledgedListener = new OnMessageAcknowledged() {
 162
 163		@Override
 164		public void onMessageAcknowledged(Account account, String uuid) {
 165			for (final Conversation conversation : getConversations()) {
 166				if (conversation.getAccount() == account) {
 167					Message message = conversation.findUnsentMessageWithUuid(uuid);
 168					if (message != null) {
 169						markMessage(message, Message.STATUS_SEND);
 170						if (conversation.setLastMessageTransmitted(System.currentTimeMillis())) {
 171							databaseBackend.updateConversation(conversation);
 172						}
 173					}
 174				}
 175			}
 176		}
 177	};
 178	private final IqGenerator mIqGenerator = new IqGenerator(this);
 179	public DatabaseBackend databaseBackend;
 180	public OnContactStatusChanged onContactStatusChanged = new OnContactStatusChanged() {
 181
 182		@Override
 183		public void onContactStatusChanged(Contact contact, boolean online) {
 184			Conversation conversation = find(getConversations(), contact);
 185			if (conversation != null) {
 186				if (online) {
 187					conversation.endOtrIfNeeded();
 188					if (contact.getPresences().size() == 1) {
 189						sendUnsentMessages(conversation);
 190					}
 191				} else {
 192					if (contact.getPresences().size() >= 1) {
 193						if (conversation.hasValidOtrSession()) {
 194							String otrResource = conversation.getOtrSession().getSessionID().getUserID();
 195							if (!(Arrays.asList(contact.getPresences().asStringArray()).contains(otrResource))) {
 196								conversation.endOtrIfNeeded();
 197							}
 198						}
 199					} else {
 200						conversation.endOtrIfNeeded();
 201					}
 202				}
 203			}
 204		}
 205	};
 206	private FileBackend fileBackend = new FileBackend(this);
 207	private MemorizingTrustManager mMemorizingTrustManager;
 208	private NotificationService mNotificationService = new NotificationService(
 209			this);
 210	private OnMessagePacketReceived mMessageParser = new MessageParser(this);
 211	private OnPresencePacketReceived mPresenceParser = new PresenceParser(this);
 212	private IqParser mIqParser = new IqParser(this);
 213	private OnIqPacketReceived mDefaultIqHandler = new OnIqPacketReceived() {
 214		@Override
 215		public void onIqPacketReceived(Account account, IqPacket packet) {
 216			if (packet.getType() == IqPacket.TYPE.ERROR) {
 217				Element error = packet.findChild("error");
 218				String text = error != null ? error.findChildContent("text") : null;
 219				if (text != null) {
 220					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": received iq error - "+text);
 221				}
 222			}
 223		}
 224	};
 225	private MessageGenerator mMessageGenerator = new MessageGenerator(this);
 226	private PresenceGenerator mPresenceGenerator = new PresenceGenerator(this);
 227	private List<Account> accounts;
 228	private JingleConnectionManager mJingleConnectionManager = new JingleConnectionManager(
 229			this);
 230	private HttpConnectionManager mHttpConnectionManager = new HttpConnectionManager(
 231			this);
 232	private AvatarService mAvatarService = new AvatarService(this);
 233	private final List<String> mInProgressAvatarFetches = new ArrayList<>();
 234	private MessageArchiveService mMessageArchiveService = new MessageArchiveService(this);
 235	private OnConversationUpdate mOnConversationUpdate = null;
 236	private int convChangedListenerCount = 0;
 237	private OnShowErrorToast mOnShowErrorToast = null;
 238	private int showErrorToastListenerCount = 0;
 239	private int unreadCount = -1;
 240	private OnAccountUpdate mOnAccountUpdate = null;
 241	private OnStatusChanged statusListener = new OnStatusChanged() {
 242
 243		@Override
 244		public void onStatusChanged(Account account) {
 245			XmppConnection connection = account.getXmppConnection();
 246			if (mOnAccountUpdate != null) {
 247				mOnAccountUpdate.onAccountUpdate();
 248			}
 249			if (account.getStatus() == Account.State.ONLINE) {
 250				for (Conversation conversation : account.pendingConferenceLeaves) {
 251					leaveMuc(conversation);
 252				}
 253				for (Conversation conversation : account.pendingConferenceJoins) {
 254					joinMuc(conversation);
 255				}
 256				mMessageArchiveService.executePendingQueries(account);
 257				mJingleConnectionManager.cancelInTransmission();
 258				List<Conversation> conversations = getConversations();
 259				for (Conversation conversation : conversations) {
 260					if (conversation.getAccount() == account) {
 261						conversation.startOtrIfNeeded();
 262						sendUnsentMessages(conversation);
 263					}
 264				}
 265				if (connection != null && connection.getFeatures().csi()) {
 266					if (checkListeners()) {
 267						Log.d(Config.LOGTAG, account.getJid().toBareJid()
 268								+ " sending csi//inactive");
 269						connection.sendInactive();
 270					} else {
 271						Log.d(Config.LOGTAG, account.getJid().toBareJid()
 272								+ " sending csi//active");
 273						connection.sendActive();
 274					}
 275				}
 276				syncDirtyContacts(account);
 277				account.getAxolotlService().publishOwnDeviceIdIfNeeded();
 278				account.getAxolotlService().publishBundlesIfNeeded();
 279
 280				scheduleWakeUpCall(Config.PING_MAX_INTERVAL, account.getUuid().hashCode());
 281			} else if (account.getStatus() == Account.State.OFFLINE) {
 282				resetSendingToWaiting(account);
 283				if (!account.isOptionSet(Account.OPTION_DISABLED)) {
 284					int timeToReconnect = mRandom.nextInt(50) + 10;
 285					scheduleWakeUpCall(timeToReconnect,account.getUuid().hashCode());
 286				}
 287			} else if (account.getStatus() == Account.State.REGISTRATION_SUCCESSFUL) {
 288				databaseBackend.updateAccount(account);
 289				reconnectAccount(account, true);
 290			} else if ((account.getStatus() != Account.State.CONNECTING)
 291					&& (account.getStatus() != Account.State.NO_INTERNET)) {
 292				if (connection != null) {
 293					int next = connection.getTimeToNextAttempt();
 294					Log.d(Config.LOGTAG, account.getJid().toBareJid()
 295							+ ": error connecting account. try again in "
 296							+ next + "s for the "
 297							+ (connection.getAttempt() + 1) + " time");
 298					scheduleWakeUpCall(next,account.getUuid().hashCode());
 299				}
 300					}
 301			getNotificationService().updateErrorNotification();
 302		}
 303	};
 304	private int accountChangedListenerCount = 0;
 305	private OnRosterUpdate mOnRosterUpdate = null;
 306	private OnUpdateBlocklist mOnUpdateBlocklist = null;
 307	private int updateBlocklistListenerCount = 0;
 308	private int rosterChangedListenerCount = 0;
 309	private OnMucRosterUpdate mOnMucRosterUpdate = null;
 310	private int mucRosterChangedListenerCount = 0;
 311	private OnNewKeysAvailable mOnNewKeysAvailable = null;
 312	private int newKeysAvailableListenerCount = 0;
 313	private SecureRandom mRandom;
 314	private OpenPgpServiceConnection pgpServiceConnection;
 315	private PgpEngine mPgpEngine = null;
 316	private WakeLock wakeLock;
 317	private PowerManager pm;
 318	private LruCache<String, Bitmap> mBitmapCache;
 319	private Thread mPhoneContactMergerThread;
 320
 321	private boolean mRestoredFromDatabase = false;
 322	public boolean areMessagesInitialized() {
 323		return this.mRestoredFromDatabase;
 324	}
 325
 326	public PgpEngine getPgpEngine() {
 327		if (pgpServiceConnection.isBound()) {
 328			if (this.mPgpEngine == null) {
 329				this.mPgpEngine = new PgpEngine(new OpenPgpApi(
 330							getApplicationContext(),
 331							pgpServiceConnection.getService()), this);
 332			}
 333			return mPgpEngine;
 334		} else {
 335			return null;
 336		}
 337
 338	}
 339
 340	public FileBackend getFileBackend() {
 341		return this.fileBackend;
 342	}
 343
 344	public AvatarService getAvatarService() {
 345		return this.mAvatarService;
 346	}
 347
 348	public void attachLocationToConversation(final Conversation conversation,
 349											 final Uri uri,
 350											 final UiCallback<Message> callback) {
 351		int encryption = conversation.getNextEncryption(forceEncryption());
 352		if (encryption == Message.ENCRYPTION_PGP) {
 353			encryption = Message.ENCRYPTION_DECRYPTED;
 354		}
 355		Message message = new Message(conversation,uri.toString(),encryption);
 356		if (conversation.getNextCounterpart() != null) {
 357			message.setCounterpart(conversation.getNextCounterpart());
 358		}
 359		if (encryption == Message.ENCRYPTION_DECRYPTED) {
 360			getPgpEngine().encrypt(message, callback);
 361		} else {
 362			callback.success(message);
 363		}
 364	}
 365
 366	public void attachFileToConversation(final Conversation conversation,
 367			final Uri uri,
 368			final UiCallback<Message> callback) {
 369		final Message message;
 370		if (conversation.getNextEncryption(forceEncryption()) == Message.ENCRYPTION_PGP) {
 371			message = new Message(conversation, "",
 372					Message.ENCRYPTION_DECRYPTED);
 373		} else {
 374			message = new Message(conversation, "",
 375					conversation.getNextEncryption(forceEncryption()));
 376		}
 377		message.setCounterpart(conversation.getNextCounterpart());
 378		message.setType(Message.TYPE_FILE);
 379		String path = getFileBackend().getOriginalPath(uri);
 380		if (path!=null) {
 381			message.setRelativeFilePath(path);
 382			getFileBackend().updateFileParams(message);
 383			if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
 384				getPgpEngine().encrypt(message, callback);
 385			} else {
 386				callback.success(message);
 387			}
 388		} else {
 389			mFileAddingExecutor.execute(new Runnable() {
 390				@Override
 391				public void run() {
 392					try {
 393						getFileBackend().copyFileToPrivateStorage(message, uri);
 394						getFileBackend().updateFileParams(message);
 395						if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
 396							getPgpEngine().encrypt(message, callback);
 397						} else {
 398							callback.success(message);
 399						}
 400					} catch (FileBackend.FileCopyException e) {
 401						callback.error(e.getResId(), message);
 402					}
 403				}
 404			});
 405		}
 406	}
 407
 408	public void attachImageToConversation(final Conversation conversation,
 409			final Uri uri, final UiCallback<Message> callback) {
 410		final Message message;
 411		if (conversation.getNextEncryption(forceEncryption()) == Message.ENCRYPTION_PGP) {
 412			message = new Message(conversation, "",
 413					Message.ENCRYPTION_DECRYPTED);
 414		} else {
 415			message = new Message(conversation, "",
 416					conversation.getNextEncryption(forceEncryption()));
 417		}
 418		message.setCounterpart(conversation.getNextCounterpart());
 419		message.setType(Message.TYPE_IMAGE);
 420		mFileAddingExecutor.execute(new Runnable() {
 421
 422			@Override
 423			public void run() {
 424				try {
 425					getFileBackend().copyImageToPrivateStorage(message, uri);
 426					if (conversation.getNextEncryption(forceEncryption()) == Message.ENCRYPTION_PGP) {
 427						getPgpEngine().encrypt(message, callback);
 428					} else {
 429						callback.success(message);
 430					}
 431				} catch (final FileBackend.FileCopyException e) {
 432					callback.error(e.getResId(), message);
 433				}
 434			}
 435		});
 436	}
 437
 438	public Conversation find(Bookmark bookmark) {
 439		return find(bookmark.getAccount(), bookmark.getJid());
 440	}
 441
 442	public Conversation find(final Account account, final Jid jid) {
 443		return find(getConversations(), account, jid);
 444	}
 445
 446	@Override
 447	public int onStartCommand(Intent intent, int flags, int startId) {
 448		final String action = intent == null ? null : intent.getAction();
 449		if (action != null) {
 450			switch (action) {
 451				case ConnectivityManager.CONNECTIVITY_ACTION:
 452					if (hasInternetConnection() && Config.RESET_ATTEMPT_COUNT_ON_NETWORK_CHANGE) {
 453						resetAllAttemptCounts(true);
 454					}
 455					break;
 456				case ACTION_MERGE_PHONE_CONTACTS:
 457					if (mRestoredFromDatabase) {
 458						PhoneHelper.loadPhoneContacts(getApplicationContext(),
 459								new CopyOnWriteArrayList<Bundle>(),
 460								this);
 461					}
 462					return START_STICKY;
 463				case Intent.ACTION_SHUTDOWN:
 464					logoutAndSave();
 465					return START_NOT_STICKY;
 466				case ACTION_CLEAR_NOTIFICATION:
 467					mNotificationService.clear();
 468					break;
 469				case ACTION_DISABLE_FOREGROUND:
 470					getPreferences().edit().putBoolean("keep_foreground_service",false).commit();
 471					toggleForegroundService();
 472					break;
 473				case ACTION_TRY_AGAIN:
 474					resetAllAttemptCounts(false);
 475					break;
 476				case ACTION_DISABLE_ACCOUNT:
 477					try {
 478						String jid = intent.getStringExtra("account");
 479						Account account = jid == null ? null : findAccountByJid(Jid.fromString(jid));
 480						if (account != null) {
 481							account.setOption(Account.OPTION_DISABLED,true);
 482							updateAccount(account);
 483						}
 484					} catch (final InvalidJidException ignored) {
 485						break;
 486					}
 487					break;
 488			}
 489		}
 490		this.wakeLock.acquire();
 491
 492		for (Account account : accounts) {
 493			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
 494				if (!hasInternetConnection()) {
 495					account.setStatus(Account.State.NO_INTERNET);
 496					if (statusListener != null) {
 497						statusListener.onStatusChanged(account);
 498					}
 499				} else {
 500					if (account.getStatus() == Account.State.NO_INTERNET) {
 501						account.setStatus(Account.State.OFFLINE);
 502						if (statusListener != null) {
 503							statusListener.onStatusChanged(account);
 504						}
 505					}
 506					if (account.getStatus() == Account.State.ONLINE) {
 507						long lastReceived = account.getXmppConnection().getLastPacketReceived();
 508						long lastSent = account.getXmppConnection().getLastPingSent();
 509						long pingInterval = "ui".equals(action) ? Config.PING_MIN_INTERVAL * 1000 : Config.PING_MAX_INTERVAL * 1000;
 510						long msToNextPing = (Math.max(lastReceived,lastSent) + pingInterval) - SystemClock.elapsedRealtime();
 511						long pingTimeoutIn = (lastSent + Config.PING_TIMEOUT * 1000) - SystemClock.elapsedRealtime();
 512						if (lastSent > lastReceived) {
 513							if (pingTimeoutIn < 0) {
 514								Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": ping timeout");
 515								this.reconnectAccount(account, true);
 516							} else {
 517								int secs = (int) (pingTimeoutIn / 1000);
 518								this.scheduleWakeUpCall(secs,account.getUuid().hashCode());
 519							}
 520						} else if (msToNextPing <= 0) {
 521							account.getXmppConnection().sendPing();
 522							Log.d(Config.LOGTAG, account.getJid().toBareJid()+" send ping");
 523							this.scheduleWakeUpCall(Config.PING_TIMEOUT,account.getUuid().hashCode());
 524						} else {
 525							this.scheduleWakeUpCall((int) (msToNextPing / 1000), account.getUuid().hashCode());
 526						}
 527					} else if (account.getStatus() == Account.State.OFFLINE) {
 528						reconnectAccount(account,true);
 529					} else if (account.getStatus() == Account.State.CONNECTING) {
 530						long timeout = Config.CONNECT_TIMEOUT - ((SystemClock.elapsedRealtime() - account.getXmppConnection().getLastConnect()) / 1000);
 531						if (timeout < 0) {
 532							Log.d(Config.LOGTAG, account.getJid() + ": time out during connect reconnecting");
 533							reconnectAccount(account, true);
 534						} else {
 535							scheduleWakeUpCall((int) timeout,account.getUuid().hashCode());
 536						}
 537					} else {
 538						if (account.getXmppConnection().getTimeToNextAttempt() <= 0) {
 539							reconnectAccount(account, true);
 540						}
 541					}
 542
 543				}
 544				if (mOnAccountUpdate != null) {
 545					mOnAccountUpdate.onAccountUpdate();
 546				}
 547			}
 548		}
 549		/*PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
 550			if (!pm.isScreenOn()) {
 551			removeStaleListeners();
 552			}*/
 553		if (wakeLock.isHeld()) {
 554			try {
 555				wakeLock.release();
 556			} catch (final RuntimeException ignored) {
 557			}
 558		}
 559		return START_STICKY;
 560	}
 561
 562	private void resetAllAttemptCounts(boolean reallyAll) {
 563		Log.d(Config.LOGTAG,"resetting all attepmt counts");
 564		for(Account account : accounts) {
 565			if (account.hasErrorStatus() || reallyAll) {
 566				final XmppConnection connection = account.getXmppConnection();
 567				if (connection != null) {
 568					connection.resetAttemptCount();
 569				}
 570			}
 571		}
 572	}
 573
 574	public boolean hasInternetConnection() {
 575		ConnectivityManager cm = (ConnectivityManager) getApplicationContext()
 576			.getSystemService(Context.CONNECTIVITY_SERVICE);
 577		NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
 578		return activeNetwork != null && activeNetwork.isConnected();
 579	}
 580
 581	@SuppressLint("TrulyRandom")
 582	@Override
 583	public void onCreate() {
 584		ExceptionHelper.init(getApplicationContext());
 585		PRNGFixes.apply();
 586		this.mRandom = new SecureRandom();
 587		updateMemorizingTrustmanager();
 588		final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
 589		final int cacheSize = maxMemory / 8;
 590		this.mBitmapCache = new LruCache<String, Bitmap>(cacheSize) {
 591			@Override
 592			protected int sizeOf(final String key, final Bitmap bitmap) {
 593				return bitmap.getByteCount() / 1024;
 594			}
 595		};
 596
 597		this.databaseBackend = DatabaseBackend.getInstance(getApplicationContext());
 598		this.accounts = databaseBackend.getAccounts();
 599
 600		restoreFromDatabase();
 601
 602		getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, contactObserver);
 603		this.fileObserver.startWatching();
 604		this.pgpServiceConnection = new OpenPgpServiceConnection(getApplicationContext(), "org.sufficientlysecure.keychain");
 605		this.pgpServiceConnection.bindToService();
 606
 607		this.pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
 608		this.wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"XmppConnectionService");
 609		toggleForegroundService();
 610		updateUnreadCountBadge();
 611	}
 612
 613	public void toggleForegroundService() {
 614		if (getPreferences().getBoolean("keep_foreground_service",false)) {
 615			startForeground(NotificationService.FOREGROUND_NOTIFICATION_ID, this.mNotificationService.createForegroundNotification());
 616		} else {
 617			stopForeground(true);
 618		}
 619	}
 620
 621	@Override
 622	public void onTaskRemoved(final Intent rootIntent) {
 623		super.onTaskRemoved(rootIntent);
 624		if (!getPreferences().getBoolean("keep_foreground_service",false)) {
 625			this.logoutAndSave();
 626		}
 627	}
 628
 629	private void logoutAndSave() {
 630		for (final Account account : accounts) {
 631			databaseBackend.writeRoster(account.getRoster());
 632			if (account.getXmppConnection() != null) {
 633				disconnect(account, false);
 634			}
 635		}
 636		Context context = getApplicationContext();
 637		AlarmManager alarmManager = (AlarmManager) context
 638				.getSystemService(Context.ALARM_SERVICE);
 639		Intent intent = new Intent(context, EventReceiver.class);
 640		alarmManager.cancel(PendingIntent.getBroadcast(context, 0, intent, 0));
 641		Log.d(Config.LOGTAG, "good bye");
 642		stopSelf();
 643	}
 644
 645	protected void scheduleWakeUpCall(int seconds, int requestCode) {
 646		final long timeToWake = SystemClock.elapsedRealtime() + (seconds < 0 ? 1 : seconds + 1) * 1000;
 647
 648		Context context = getApplicationContext();
 649		AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
 650
 651		Intent intent = new Intent(context, EventReceiver.class);
 652		intent.setAction("ping");
 653		PendingIntent alarmIntent = PendingIntent.getBroadcast(context, requestCode, intent, 0);
 654		alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, alarmIntent);
 655	}
 656
 657	public XmppConnection createConnection(final Account account) {
 658		final SharedPreferences sharedPref = getPreferences();
 659		account.setResource(sharedPref.getString("resource", "mobile")
 660				.toLowerCase(Locale.getDefault()));
 661		final XmppConnection connection = new XmppConnection(account, this);
 662		connection.setOnMessagePacketReceivedListener(this.mMessageParser);
 663		connection.setOnStatusChangedListener(this.statusListener);
 664		connection.setOnPresencePacketReceivedListener(this.mPresenceParser);
 665		connection.setOnUnregisteredIqPacketReceivedListener(this.mIqParser);
 666		connection.setOnJinglePacketReceivedListener(this.jingleListener);
 667		connection.setOnBindListener(this.mOnBindListener);
 668		connection.setOnMessageAcknowledgeListener(this.mOnMessageAcknowledgedListener);
 669		connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService);
 670		return connection;
 671	}
 672
 673	public void sendChatState(Conversation conversation) {
 674		if (sendChatStates()) {
 675			MessagePacket packet = mMessageGenerator.generateChatState(conversation);
 676			sendMessagePacket(conversation.getAccount(), packet);
 677		}
 678	}
 679
 680	private void sendFileMessage(final Message message, final boolean delay) {
 681		Log.d(Config.LOGTAG, "send file message");
 682		final Account account = message.getConversation().getAccount();
 683		final XmppConnection connection = account.getXmppConnection();
 684		if (connection != null && connection.getFeatures().httpUpload()) {
 685			mHttpConnectionManager.createNewUploadConnection(message, delay);
 686		} else {
 687			mJingleConnectionManager.createNewConnection(message);
 688		}
 689	}
 690
 691	public void sendMessage(final Message message) {
 692		sendMessage(message, false, false);
 693	}
 694
 695	private void sendMessage(final Message message, final boolean resend, final boolean delay) {
 696		final Account account = message.getConversation().getAccount();
 697		final Conversation conversation = message.getConversation();
 698		account.deactivateGracePeriod();
 699		MessagePacket packet = null;
 700		boolean saveInDb = true;
 701		message.setStatus(Message.STATUS_WAITING);
 702
 703		if (!resend && message.getEncryption() != Message.ENCRYPTION_OTR) {
 704			message.getConversation().endOtrIfNeeded();
 705			message.getConversation().findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR,
 706					new Conversation.OnMessageFound() {
 707				@Override
 708				public void onMessageFound(Message message) {
 709					markMessage(message,Message.STATUS_SEND_FAILED);
 710				}
 711			});
 712		}
 713
 714		if (account.isOnlineAndConnected()) {
 715			switch (message.getEncryption()) {
 716				case Message.ENCRYPTION_NONE:
 717					if (message.needsUploading()) {
 718						if (account.httpUploadAvailable() || message.fixCounterpart()) {
 719							this.sendFileMessage(message,delay);
 720						} else {
 721							break;
 722						}
 723					} else {
 724						packet = mMessageGenerator.generateChat(message);
 725					}
 726					break;
 727				case Message.ENCRYPTION_PGP:
 728				case Message.ENCRYPTION_DECRYPTED:
 729					if (message.needsUploading()) {
 730						if (account.httpUploadAvailable() || message.fixCounterpart()) {
 731							this.sendFileMessage(message,delay);
 732						} else {
 733							break;
 734						}
 735					} else {
 736						packet = mMessageGenerator.generatePgpChat(message);
 737					}
 738					break;
 739				case Message.ENCRYPTION_OTR:
 740					SessionImpl otrSession = conversation.getOtrSession();
 741					if (otrSession != null && otrSession.getSessionStatus() == SessionStatus.ENCRYPTED) {
 742						try {
 743							message.setCounterpart(Jid.fromSessionID(otrSession.getSessionID()));
 744						} catch (InvalidJidException e) {
 745							break;
 746						}
 747						if (message.needsUploading()) {
 748							mJingleConnectionManager.createNewConnection(message);
 749						} else {
 750							packet = mMessageGenerator.generateOtrChat(message);
 751						}
 752					} else if (otrSession == null) {
 753						if (message.fixCounterpart()) {
 754							conversation.startOtrSession(message.getCounterpart().getResourcepart(), true);
 755						} else {
 756							break;
 757						}
 758					}
 759					break;
 760				case Message.ENCRYPTION_AXOLOTL:
 761					if (message.needsUploading()) {
 762						if (account.httpUploadAvailable() || message.fixCounterpart()) {
 763							this.sendFileMessage(message,delay);
 764						} else {
 765							break;
 766						}
 767					} else {
 768						packet = account.getAxolotlService().fetchPacketFromCache(message);
 769						if (packet == null) {
 770							account.getAxolotlService().prepareMessage(message,delay);
 771							message.setAxolotlFingerprint(account.getAxolotlService().getOwnPublicKey().getFingerprint().replaceAll("\\s", ""));
 772						}
 773					}
 774					break;
 775
 776			}
 777			if (packet != null) {
 778				if (account.getXmppConnection().getFeatures().sm() || conversation.getMode() == Conversation.MODE_MULTI) {
 779					message.setStatus(Message.STATUS_UNSEND);
 780				} else {
 781					message.setStatus(Message.STATUS_SEND);
 782				}
 783			}
 784		} else {
 785			switch(message.getEncryption()) {
 786				case Message.ENCRYPTION_DECRYPTED:
 787					if (!message.needsUploading()) {
 788						String pgpBody = message.getEncryptedBody();
 789						String decryptedBody = message.getBody();
 790						message.setBody(pgpBody);
 791						message.setEncryption(Message.ENCRYPTION_PGP);
 792						databaseBackend.createMessage(message);
 793						saveInDb = false;
 794						message.setBody(decryptedBody);
 795						message.setEncryption(Message.ENCRYPTION_DECRYPTED);
 796					}
 797					break;
 798				case Message.ENCRYPTION_OTR:
 799					if (!conversation.hasValidOtrSession() && message.getCounterpart() != null) {
 800						conversation.startOtrSession(message.getCounterpart().getResourcepart(), false);
 801					}
 802					break;
 803				case Message.ENCRYPTION_AXOLOTL:
 804					message.setAxolotlFingerprint(account.getAxolotlService().getOwnPublicKey().getFingerprint().replaceAll("\\s", ""));
 805					break;
 806			}
 807		}
 808
 809		if (resend) {
 810			if (packet != null) {
 811				if (account.getXmppConnection().getFeatures().sm() || conversation.getMode() == Conversation.MODE_MULTI) {
 812					markMessage(message,Message.STATUS_UNSEND);
 813				} else {
 814					markMessage(message,Message.STATUS_SEND);
 815				}
 816			}
 817		} else {
 818			conversation.add(message);
 819			if (saveInDb && (message.getEncryption() == Message.ENCRYPTION_NONE || saveEncryptedMessages())) {
 820				databaseBackend.createMessage(message);
 821			}
 822			updateConversationUi();
 823		}
 824		if (packet != null) {
 825			if (delay) {
 826				mMessageGenerator.addDelay(packet,message.getTimeSent());
 827			}
 828			if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
 829				if (this.sendChatStates()) {
 830					packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
 831				}
 832			}
 833			sendMessagePacket(account, packet);
 834		}
 835	}
 836
 837	private void sendUnsentMessages(final Conversation conversation) {
 838		conversation.findWaitingMessages(new Conversation.OnMessageFound() {
 839
 840			@Override
 841			public void onMessageFound(Message message) {
 842				resendMessage(message,true);
 843			}
 844		});
 845	}
 846
 847	public void resendMessage(final Message message, final boolean delay) {
 848		sendMessage(message, true, delay);
 849	}
 850
 851	public void fetchRosterFromServer(final Account account) {
 852		final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
 853		if (!"".equals(account.getRosterVersion())) {
 854			Log.d(Config.LOGTAG, account.getJid().toBareJid()
 855					+ ": fetching roster version " + account.getRosterVersion());
 856		} else {
 857			Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": fetching roster");
 858		}
 859		iqPacket.query(Xmlns.ROSTER).setAttribute("ver",account.getRosterVersion());
 860		sendIqPacket(account,iqPacket,mIqParser);
 861	}
 862
 863	public void fetchBookmarks(final Account account) {
 864		final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
 865		final Element query = iqPacket.query("jabber:iq:private");
 866		query.addChild("storage", "storage:bookmarks");
 867		final OnIqPacketReceived callback = new OnIqPacketReceived() {
 868
 869			@Override
 870			public void onIqPacketReceived(final Account account, final IqPacket packet) {
 871				final Element query = packet.query();
 872				final List<Bookmark> bookmarks = new CopyOnWriteArrayList<>();
 873				final Element storage = query.findChild("storage",
 874						"storage:bookmarks");
 875				if (storage != null) {
 876					for (final Element item : storage.getChildren()) {
 877						if (item.getName().equals("conference")) {
 878							final Bookmark bookmark = Bookmark.parse(item, account);
 879							bookmarks.add(bookmark);
 880							Conversation conversation = find(bookmark);
 881							if (conversation != null) {
 882								conversation.setBookmark(bookmark);
 883							} else if (bookmark.autojoin() && bookmark.getJid() != null) {
 884								conversation = findOrCreateConversation(
 885										account, bookmark.getJid(), true);
 886								conversation.setBookmark(bookmark);
 887								joinMuc(conversation);
 888							}
 889						}
 890					}
 891				}
 892				account.setBookmarks(bookmarks);
 893			}
 894		};
 895		sendIqPacket(account, iqPacket, callback);
 896	}
 897
 898	public void pushBookmarks(Account account) {
 899		IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
 900		Element query = iqPacket.query("jabber:iq:private");
 901		Element storage = query.addChild("storage", "storage:bookmarks");
 902		for (Bookmark bookmark : account.getBookmarks()) {
 903			storage.addChild(bookmark);
 904		}
 905		sendIqPacket(account, iqPacket, mDefaultIqHandler);
 906	}
 907
 908	public void onPhoneContactsLoaded(final List<Bundle> phoneContacts) {
 909		if (mPhoneContactMergerThread != null) {
 910			mPhoneContactMergerThread.interrupt();
 911		}
 912		mPhoneContactMergerThread = new Thread(new Runnable() {
 913			@Override
 914			public void run() {
 915				Log.d(Config.LOGTAG,"start merging phone contacts with roster");
 916				for (Account account : accounts) {
 917					List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts();
 918					for (Bundle phoneContact : phoneContacts) {
 919						if (Thread.interrupted()) {
 920							Log.d(Config.LOGTAG,"interrupted merging phone contacts");
 921							return;
 922						}
 923						Jid jid;
 924						try {
 925							jid = Jid.fromString(phoneContact.getString("jid"));
 926						} catch (final InvalidJidException e) {
 927							continue;
 928						}
 929						final Contact contact = account.getRoster().getContact(jid);
 930						String systemAccount = phoneContact.getInt("phoneid")
 931							+ "#"
 932							+ phoneContact.getString("lookup");
 933						contact.setSystemAccount(systemAccount);
 934						if (contact.setPhotoUri(phoneContact.getString("photouri"))) {
 935							getAvatarService().clear(contact);
 936						}
 937						contact.setSystemName(phoneContact.getString("displayname"));
 938						withSystemAccounts.remove(contact);
 939					}
 940					for(Contact contact : withSystemAccounts) {
 941						contact.setSystemAccount(null);
 942						contact.setSystemName(null);
 943						if (contact.setPhotoUri(null)) {
 944							getAvatarService().clear(contact);
 945						}
 946					}
 947				}
 948				Log.d(Config.LOGTAG,"finished merging phone contacts");
 949				updateAccountUi();
 950			}
 951		});
 952		mPhoneContactMergerThread.start();
 953	}
 954
 955	private void restoreFromDatabase() {
 956		synchronized (this.conversations) {
 957			final Map<String, Account> accountLookupTable = new Hashtable<>();
 958			for (Account account : this.accounts) {
 959				accountLookupTable.put(account.getUuid(), account);
 960			}
 961			this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
 962			for (Conversation conversation : this.conversations) {
 963				Account account = accountLookupTable.get(conversation.getAccountUuid());
 964				conversation.setAccount(account);
 965			}
 966			Runnable runnable =new Runnable() {
 967				@Override
 968				public void run() {
 969					Log.d(Config.LOGTAG,"restoring roster");
 970					for(Account account : accounts) {
 971						databaseBackend.readRoster(account.getRoster());
 972						account.initAccountServices(XmppConnectionService.this);
 973					}
 974					getBitmapCache().evictAll();
 975					Looper.prepare();
 976					PhoneHelper.loadPhoneContacts(getApplicationContext(),
 977							new CopyOnWriteArrayList<Bundle>(),
 978							XmppConnectionService.this);
 979					Log.d(Config.LOGTAG,"restoring messages");
 980					for (Conversation conversation : conversations) {
 981						conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
 982						checkDeletedFiles(conversation);
 983					}
 984					mRestoredFromDatabase = true;
 985					Log.d(Config.LOGTAG,"restored all messages");
 986					updateConversationUi();
 987				}
 988			};
 989			mDatabaseExecutor.execute(runnable);
 990		}
 991	}
 992
 993	public List<Conversation> getConversations() {
 994		return this.conversations;
 995	}
 996
 997	private void checkDeletedFiles(Conversation conversation) {
 998		conversation.findMessagesWithFiles(new Conversation.OnMessageFound() {
 999
1000			@Override
1001			public void onMessageFound(Message message) {
1002				if (!getFileBackend().isFileAvailable(message)) {
1003					message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1004				}
1005			}
1006		});
1007	}
1008
1009	private void markFileDeleted(String uuid) {
1010		for (Conversation conversation : getConversations()) {
1011			Message message = conversation.findMessageWithFileAndUuid(uuid);
1012			if (message != null) {
1013				if (!getFileBackend().isFileAvailable(message)) {
1014					message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1015					updateConversationUi();
1016				}
1017				return;
1018			}
1019		}
1020	}
1021
1022	public void populateWithOrderedConversations(final List<Conversation> list) {
1023		populateWithOrderedConversations(list, true);
1024	}
1025
1026	public void populateWithOrderedConversations(final List<Conversation> list, boolean includeNoFileUpload) {
1027		list.clear();
1028		if (includeNoFileUpload) {
1029			list.addAll(getConversations());
1030		} else {
1031			for (Conversation conversation : getConversations()) {
1032				if (conversation.getMode() == Conversation.MODE_SINGLE
1033						|| conversation.getAccount().httpUploadAvailable()) {
1034					list.add(conversation);
1035				}
1036			}
1037		}
1038		Collections.sort(list, new Comparator<Conversation>() {
1039			@Override
1040			public int compare(Conversation lhs, Conversation rhs) {
1041				Message left = lhs.getLatestMessage();
1042				Message right = rhs.getLatestMessage();
1043				if (left.getTimeSent() > right.getTimeSent()) {
1044					return -1;
1045				} else if (left.getTimeSent() < right.getTimeSent()) {
1046					return 1;
1047				} else {
1048					return 0;
1049				}
1050			}
1051		});
1052	}
1053
1054	public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
1055		Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
1056		if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation,callback)) {
1057			return;
1058		}
1059		Runnable runnable = new Runnable() {
1060			@Override
1061			public void run() {
1062				final Account account = conversation.getAccount();
1063				List<Message> messages = databaseBackend.getMessages(conversation, 50,timestamp);
1064				if (messages.size() > 0) {
1065					conversation.addAll(0, messages);
1066					checkDeletedFiles(conversation);
1067					callback.onMoreMessagesLoaded(messages.size(), conversation);
1068				} else if (conversation.hasMessagesLeftOnServer()
1069						&& account.isOnlineAndConnected()
1070						&& account.getXmppConnection().getFeatures().mam()) {
1071					MessageArchiveService.Query query = getMessageArchiveService().query(conversation,0,timestamp - 1);
1072					if (query != null) {
1073						query.setCallback(callback);
1074					}
1075					callback.informUser(R.string.fetching_history_from_server);
1076				}
1077			}
1078		};
1079		mDatabaseExecutor.execute(runnable);
1080	}
1081
1082	public List<Account> getAccounts() {
1083		return this.accounts;
1084	}
1085
1086	public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
1087		for (final Conversation conversation : haystack) {
1088			if (conversation.getContact() == contact) {
1089				return conversation;
1090			}
1091		}
1092		return null;
1093	}
1094
1095	public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
1096		if (jid == null) {
1097			return null;
1098		}
1099		for (final Conversation conversation : haystack) {
1100			if ((account == null || conversation.getAccount() == account)
1101					&& (conversation.getJid().toBareJid().equals(jid.toBareJid()))) {
1102				return conversation;
1103			}
1104		}
1105		return null;
1106	}
1107
1108	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc) {
1109		return this.findOrCreateConversation(account, jid, muc, null);
1110	}
1111
1112	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final MessageArchiveService.Query query) {
1113		synchronized (this.conversations) {
1114			Conversation conversation = find(account, jid);
1115			if (conversation != null) {
1116				return conversation;
1117			}
1118			conversation = databaseBackend.findConversation(account, jid);
1119			if (conversation != null) {
1120				conversation.setStatus(Conversation.STATUS_AVAILABLE);
1121				conversation.setAccount(account);
1122				if (muc) {
1123					conversation.setMode(Conversation.MODE_MULTI);
1124					conversation.setContactJid(jid);
1125				} else {
1126					conversation.setMode(Conversation.MODE_SINGLE);
1127					conversation.setContactJid(jid.toBareJid());
1128				}
1129				conversation.setNextEncryption(-1);
1130				conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1131				this.databaseBackend.updateConversation(conversation);
1132			} else {
1133				String conversationName;
1134				Contact contact = account.getRoster().getContact(jid);
1135				if (contact != null) {
1136					conversationName = contact.getDisplayName();
1137				} else {
1138					conversationName = jid.getLocalpart();
1139				}
1140				if (muc) {
1141					conversation = new Conversation(conversationName, account, jid,
1142							Conversation.MODE_MULTI);
1143				} else {
1144					conversation = new Conversation(conversationName, account, jid.toBareJid(),
1145							Conversation.MODE_SINGLE);
1146				}
1147				this.databaseBackend.createConversation(conversation);
1148			}
1149			if (account.getXmppConnection() != null
1150					&& account.getXmppConnection().getFeatures().mam()
1151					&& !muc) {
1152				if (query == null) {
1153					this.mMessageArchiveService.query(conversation);
1154				} else {
1155					if (query.getConversation() == null) {
1156						this.mMessageArchiveService.query(conversation, query.getStart());
1157					}
1158				}
1159			}
1160			checkDeletedFiles(conversation);
1161			this.conversations.add(conversation);
1162			updateConversationUi();
1163			return conversation;
1164		}
1165	}
1166
1167	public void archiveConversation(Conversation conversation) {
1168		getNotificationService().clear(conversation);
1169		conversation.setStatus(Conversation.STATUS_ARCHIVED);
1170		conversation.setNextEncryption(-1);
1171		synchronized (this.conversations) {
1172			if (conversation.getMode() == Conversation.MODE_MULTI) {
1173				if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1174					Bookmark bookmark = conversation.getBookmark();
1175					if (bookmark != null && bookmark.autojoin()) {
1176						bookmark.setAutojoin(false);
1177						pushBookmarks(bookmark.getAccount());
1178					}
1179				}
1180				leaveMuc(conversation);
1181			} else {
1182				conversation.endOtrIfNeeded();
1183			}
1184			this.databaseBackend.updateConversation(conversation);
1185			this.conversations.remove(conversation);
1186			updateConversationUi();
1187		}
1188	}
1189
1190	public void createAccount(final Account account) {
1191		account.initAccountServices(this);
1192		databaseBackend.createAccount(account);
1193		this.accounts.add(account);
1194		this.reconnectAccountInBackground(account);
1195		updateAccountUi();
1196	}
1197
1198	public void updateAccount(final Account account) {
1199		this.statusListener.onStatusChanged(account);
1200		databaseBackend.updateAccount(account);
1201		reconnectAccount(account, false);
1202		updateAccountUi();
1203		getNotificationService().updateErrorNotification();
1204	}
1205
1206	public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
1207		final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
1208		sendIqPacket(account, iq, new OnIqPacketReceived() {
1209			@Override
1210			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1211				if (packet.getType() == IqPacket.TYPE.RESULT) {
1212					account.setPassword(newPassword);
1213					databaseBackend.updateAccount(account);
1214					callback.onPasswordChangeSucceeded();
1215				} else {
1216					callback.onPasswordChangeFailed();
1217				}
1218			}
1219		});
1220	}
1221
1222	public void deleteAccount(final Account account) {
1223		synchronized (this.conversations) {
1224			for (final Conversation conversation : conversations) {
1225				if (conversation.getAccount() == account) {
1226					if (conversation.getMode() == Conversation.MODE_MULTI) {
1227						leaveMuc(conversation);
1228					} else if (conversation.getMode() == Conversation.MODE_SINGLE) {
1229						conversation.endOtrIfNeeded();
1230					}
1231					conversations.remove(conversation);
1232				}
1233			}
1234			if (account.getXmppConnection() != null) {
1235				this.disconnect(account, true);
1236			}
1237			databaseBackend.deleteAccount(account);
1238			this.accounts.remove(account);
1239			updateAccountUi();
1240			getNotificationService().updateErrorNotification();
1241		}
1242	}
1243
1244	public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1245		synchronized (this) {
1246			if (checkListeners()) {
1247				switchToForeground();
1248			}
1249			this.mOnConversationUpdate = listener;
1250			this.mNotificationService.setIsInForeground(true);
1251			if (this.convChangedListenerCount < 2) {
1252				this.convChangedListenerCount++;
1253			}
1254		}
1255	}
1256
1257	public void removeOnConversationListChangedListener() {
1258		synchronized (this) {
1259			this.convChangedListenerCount--;
1260			if (this.convChangedListenerCount <= 0) {
1261				this.convChangedListenerCount = 0;
1262				this.mOnConversationUpdate = null;
1263				this.mNotificationService.setIsInForeground(false);
1264				if (checkListeners()) {
1265					switchToBackground();
1266				}
1267			}
1268		}
1269	}
1270
1271	public void setOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
1272		synchronized (this) {
1273			if (checkListeners()) {
1274				switchToForeground();
1275			}
1276			this.mOnShowErrorToast = onShowErrorToast;
1277			if (this.showErrorToastListenerCount < 2) {
1278				this.showErrorToastListenerCount++;
1279			}
1280		}
1281		this.mOnShowErrorToast = onShowErrorToast;
1282	}
1283
1284	public void removeOnShowErrorToastListener() {
1285		synchronized (this) {
1286			this.showErrorToastListenerCount--;
1287			if (this.showErrorToastListenerCount <= 0) {
1288				this.showErrorToastListenerCount = 0;
1289				this.mOnShowErrorToast = null;
1290				if (checkListeners()) {
1291					switchToBackground();
1292				}
1293			}
1294		}
1295	}
1296
1297	public void setOnAccountListChangedListener(OnAccountUpdate listener) {
1298		synchronized (this) {
1299			if (checkListeners()) {
1300				switchToForeground();
1301			}
1302			this.mOnAccountUpdate = listener;
1303			if (this.accountChangedListenerCount < 2) {
1304				this.accountChangedListenerCount++;
1305			}
1306		}
1307	}
1308
1309	public void removeOnAccountListChangedListener() {
1310		synchronized (this) {
1311			this.accountChangedListenerCount--;
1312			if (this.accountChangedListenerCount <= 0) {
1313				this.mOnAccountUpdate = null;
1314				this.accountChangedListenerCount = 0;
1315				if (checkListeners()) {
1316					switchToBackground();
1317				}
1318			}
1319		}
1320	}
1321
1322	public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
1323		synchronized (this) {
1324			if (checkListeners()) {
1325				switchToForeground();
1326			}
1327			this.mOnRosterUpdate = listener;
1328			if (this.rosterChangedListenerCount < 2) {
1329				this.rosterChangedListenerCount++;
1330			}
1331		}
1332	}
1333
1334	public void removeOnRosterUpdateListener() {
1335		synchronized (this) {
1336			this.rosterChangedListenerCount--;
1337			if (this.rosterChangedListenerCount <= 0) {
1338				this.rosterChangedListenerCount = 0;
1339				this.mOnRosterUpdate = null;
1340				if (checkListeners()) {
1341					switchToBackground();
1342				}
1343			}
1344		}
1345	}
1346
1347	public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
1348		synchronized (this) {
1349			if (checkListeners()) {
1350				switchToForeground();
1351			}
1352			this.mOnUpdateBlocklist = listener;
1353			if (this.updateBlocklistListenerCount < 2) {
1354				this.updateBlocklistListenerCount++;
1355			}
1356		}
1357	}
1358
1359	public void removeOnUpdateBlocklistListener() {
1360		synchronized (this) {
1361			this.updateBlocklistListenerCount--;
1362			if (this.updateBlocklistListenerCount <= 0) {
1363				this.updateBlocklistListenerCount = 0;
1364				this.mOnUpdateBlocklist = null;
1365				if (checkListeners()) {
1366					switchToBackground();
1367				}
1368			}
1369		}
1370	}
1371
1372	public void setOnNewKeysAvailableListener(final OnNewKeysAvailable listener) {
1373		synchronized (this) {
1374			if (checkListeners()) {
1375				switchToForeground();
1376			}
1377			this.mOnNewKeysAvailable = listener;
1378			if (this.newKeysAvailableListenerCount < 2) {
1379				this.newKeysAvailableListenerCount++;
1380			}
1381		}
1382	}
1383
1384	public void removeOnNewKeysAvailableListener() {
1385		synchronized (this) {
1386			this.newKeysAvailableListenerCount--;
1387			if (this.newKeysAvailableListenerCount <= 0) {
1388				this.newKeysAvailableListenerCount = 0;
1389				this.mOnNewKeysAvailable = null;
1390				if (checkListeners()) {
1391					switchToBackground();
1392				}
1393			}
1394		}
1395	}
1396	public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
1397		synchronized (this) {
1398			if (checkListeners()) {
1399				switchToForeground();
1400			}
1401			this.mOnMucRosterUpdate = listener;
1402			if (this.mucRosterChangedListenerCount < 2) {
1403				this.mucRosterChangedListenerCount++;
1404			}
1405		}
1406	}
1407
1408	public void removeOnMucRosterUpdateListener() {
1409		synchronized (this) {
1410			this.mucRosterChangedListenerCount--;
1411			if (this.mucRosterChangedListenerCount <= 0) {
1412				this.mucRosterChangedListenerCount = 0;
1413				this.mOnMucRosterUpdate = null;
1414				if (checkListeners()) {
1415					switchToBackground();
1416				}
1417			}
1418		}
1419	}
1420
1421	private boolean checkListeners() {
1422		return (this.mOnAccountUpdate == null
1423				&& this.mOnConversationUpdate == null
1424				&& this.mOnRosterUpdate == null
1425				&& this.mOnUpdateBlocklist == null
1426				&& this.mOnShowErrorToast == null
1427				&& this.mOnNewKeysAvailable == null);
1428	}
1429
1430	private void switchToForeground() {
1431		for (Account account : getAccounts()) {
1432			if (account.getStatus() == Account.State.ONLINE) {
1433				XmppConnection connection = account.getXmppConnection();
1434				if (connection != null && connection.getFeatures().csi()) {
1435					connection.sendActive();
1436				}
1437			}
1438		}
1439		Log.d(Config.LOGTAG, "app switched into foreground");
1440	}
1441
1442	private void switchToBackground() {
1443		for (Account account : getAccounts()) {
1444			if (account.getStatus() == Account.State.ONLINE) {
1445				XmppConnection connection = account.getXmppConnection();
1446				if (connection != null && connection.getFeatures().csi()) {
1447					connection.sendInactive();
1448				}
1449			}
1450		}
1451		for(Conversation conversation : getConversations()) {
1452			conversation.setIncomingChatState(ChatState.ACTIVE);
1453		}
1454		this.mNotificationService.setIsInForeground(false);
1455		Log.d(Config.LOGTAG, "app switched into background");
1456	}
1457
1458	private void connectMultiModeConversations(Account account) {
1459		List<Conversation> conversations = getConversations();
1460		for (Conversation conversation : conversations) {
1461			if ((conversation.getMode() == Conversation.MODE_MULTI)
1462					&& (conversation.getAccount() == account)) {
1463				conversation.resetMucOptions();
1464				joinMuc(conversation);
1465			}
1466		}
1467	}
1468
1469	public void joinMuc(Conversation conversation) {
1470		Account account = conversation.getAccount();
1471		account.pendingConferenceJoins.remove(conversation);
1472		account.pendingConferenceLeaves.remove(conversation);
1473		if (account.getStatus() == Account.State.ONLINE) {
1474			final String nick = conversation.getMucOptions().getProposedNick();
1475			final Jid joinJid = conversation.getMucOptions().createJoinJid(nick);
1476			if (joinJid == null) {
1477				return; //safety net
1478			}
1479			Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString());
1480			PresencePacket packet = new PresencePacket();
1481			packet.setFrom(conversation.getAccount().getJid());
1482			packet.setTo(joinJid);
1483			Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
1484			if (conversation.getMucOptions().getPassword() != null) {
1485				x.addChild("password").setContent(conversation.getMucOptions().getPassword());
1486			}
1487			x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted()));
1488			String sig = account.getPgpSignature();
1489			if (sig != null) {
1490				packet.addChild("status").setContent("online");
1491				packet.addChild("x", "jabber:x:signed").setContent(sig);
1492			}
1493			sendPresencePacket(account, packet);
1494			fetchConferenceConfiguration(conversation);
1495			if (!joinJid.equals(conversation.getJid())) {
1496				conversation.setContactJid(joinJid);
1497				databaseBackend.updateConversation(conversation);
1498			}
1499			conversation.setHasMessagesLeftOnServer(false);
1500		} else {
1501			account.pendingConferenceJoins.add(conversation);
1502		}
1503	}
1504
1505	public void providePasswordForMuc(Conversation conversation, String password) {
1506		if (conversation.getMode() == Conversation.MODE_MULTI) {
1507			conversation.getMucOptions().setPassword(password);
1508			if (conversation.getBookmark() != null) {
1509				conversation.getBookmark().setAutojoin(true);
1510				pushBookmarks(conversation.getAccount());
1511			}
1512			databaseBackend.updateConversation(conversation);
1513			joinMuc(conversation);
1514		}
1515	}
1516
1517	public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
1518		final MucOptions options = conversation.getMucOptions();
1519		final Jid joinJid = options.createJoinJid(nick);
1520		if (options.online()) {
1521			Account account = conversation.getAccount();
1522			options.setOnRenameListener(new OnRenameListener() {
1523
1524				@Override
1525				public void onSuccess() {
1526					conversation.setContactJid(joinJid);
1527					databaseBackend.updateConversation(conversation);
1528					Bookmark bookmark = conversation.getBookmark();
1529					if (bookmark != null) {
1530						bookmark.setNick(nick);
1531						pushBookmarks(bookmark.getAccount());
1532					}
1533					callback.success(conversation);
1534				}
1535
1536				@Override
1537				public void onFailure() {
1538					callback.error(R.string.nick_in_use, conversation);
1539				}
1540			});
1541
1542			PresencePacket packet = new PresencePacket();
1543			packet.setTo(joinJid);
1544			packet.setFrom(conversation.getAccount().getJid());
1545
1546			String sig = account.getPgpSignature();
1547			if (sig != null) {
1548				packet.addChild("status").setContent("online");
1549				packet.addChild("x", "jabber:x:signed").setContent(sig);
1550			}
1551			sendPresencePacket(account, packet);
1552		} else {
1553			conversation.setContactJid(joinJid);
1554			databaseBackend.updateConversation(conversation);
1555			if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1556				Bookmark bookmark = conversation.getBookmark();
1557				if (bookmark != null) {
1558					bookmark.setNick(nick);
1559					pushBookmarks(bookmark.getAccount());
1560				}
1561				joinMuc(conversation);
1562			}
1563		}
1564	}
1565
1566	public void leaveMuc(Conversation conversation) {
1567		Account account = conversation.getAccount();
1568		account.pendingConferenceJoins.remove(conversation);
1569		account.pendingConferenceLeaves.remove(conversation);
1570		if (account.getStatus() == Account.State.ONLINE) {
1571			PresencePacket packet = new PresencePacket();
1572			packet.setTo(conversation.getJid());
1573			packet.setFrom(conversation.getAccount().getJid());
1574			packet.setAttribute("type", "unavailable");
1575			sendPresencePacket(conversation.getAccount(), packet);
1576			conversation.getMucOptions().setOffline();
1577			conversation.deregisterWithBookmark();
1578			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
1579					+ ": leaving muc " + conversation.getJid());
1580		} else {
1581			account.pendingConferenceLeaves.add(conversation);
1582		}
1583	}
1584
1585	private String findConferenceServer(final Account account) {
1586		String server;
1587		if (account.getXmppConnection() != null) {
1588			server = account.getXmppConnection().getMucServer();
1589			if (server != null) {
1590				return server;
1591			}
1592		}
1593		for (Account other : getAccounts()) {
1594			if (other != account && other.getXmppConnection() != null) {
1595				server = other.getXmppConnection().getMucServer();
1596				if (server != null) {
1597					return server;
1598				}
1599			}
1600		}
1601		return null;
1602	}
1603
1604	public void createAdhocConference(final Account account, final Iterable<Jid> jids, final UiCallback<Conversation> callback) {
1605		Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
1606		if (account.getStatus() == Account.State.ONLINE) {
1607			try {
1608				String server = findConferenceServer(account);
1609				if (server == null) {
1610					if (callback != null) {
1611						callback.error(R.string.no_conference_server_found, null);
1612					}
1613					return;
1614				}
1615				String name = new BigInteger(75, getRNG()).toString(32);
1616				Jid jid = Jid.fromParts(name, server, null);
1617				final Conversation conversation = findOrCreateConversation(account, jid, true);
1618				joinMuc(conversation);
1619				Bundle options = new Bundle();
1620				options.putString("muc#roomconfig_persistentroom", "1");
1621				options.putString("muc#roomconfig_membersonly", "1");
1622				options.putString("muc#roomconfig_publicroom", "0");
1623				options.putString("muc#roomconfig_whois", "anyone");
1624				pushConferenceConfiguration(conversation, options, new OnConferenceOptionsPushed() {
1625					@Override
1626					public void onPushSucceeded() {
1627						for (Jid invite : jids) {
1628							invite(conversation, invite);
1629						}
1630						if (account.countPresences() > 1) {
1631							directInvite(conversation, account.getJid().toBareJid());
1632						}
1633						if (callback != null) {
1634							callback.success(conversation);
1635						}
1636					}
1637
1638					@Override
1639					public void onPushFailed() {
1640						if (callback != null) {
1641							callback.error(R.string.conference_creation_failed, conversation);
1642						}
1643					}
1644				});
1645
1646			} catch (InvalidJidException e) {
1647				if (callback != null) {
1648					callback.error(R.string.conference_creation_failed, null);
1649				}
1650			}
1651		} else {
1652			if (callback != null) {
1653				callback.error(R.string.not_connected_try_again, null);
1654			}
1655		}
1656	}
1657
1658	public void fetchConferenceConfiguration(final Conversation conversation) {
1659		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1660		request.setTo(conversation.getJid().toBareJid());
1661		request.query("http://jabber.org/protocol/disco#info");
1662		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1663			@Override
1664			public void onIqPacketReceived(Account account, IqPacket packet) {
1665				if (packet.getType() != IqPacket.TYPE.ERROR) {
1666					ArrayList<String> features = new ArrayList<>();
1667					for (Element child : packet.query().getChildren()) {
1668						if (child != null && child.getName().equals("feature")) {
1669							String var = child.getAttribute("var");
1670							if (var != null) {
1671								features.add(var);
1672							}
1673						}
1674					}
1675					conversation.getMucOptions().updateFeatures(features);
1676					updateConversationUi();
1677				}
1678			}
1679		});
1680	}
1681
1682	public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConferenceOptionsPushed callback) {
1683		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1684		request.setTo(conversation.getJid().toBareJid());
1685		request.query("http://jabber.org/protocol/muc#owner");
1686		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1687			@Override
1688			public void onIqPacketReceived(Account account, IqPacket packet) {
1689				if (packet.getType() != IqPacket.TYPE.ERROR) {
1690					Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
1691					for (Field field : data.getFields()) {
1692						if (options.containsKey(field.getName())) {
1693							field.setValue(options.getString(field.getName()));
1694						}
1695					}
1696					data.submit();
1697					IqPacket set = new IqPacket(IqPacket.TYPE.SET);
1698					set.setTo(conversation.getJid().toBareJid());
1699					set.query("http://jabber.org/protocol/muc#owner").addChild(data);
1700					sendIqPacket(account, set, new OnIqPacketReceived() {
1701						@Override
1702						public void onIqPacketReceived(Account account, IqPacket packet) {
1703							if (packet.getType() == IqPacket.TYPE.RESULT) {
1704								if (callback != null) {
1705									callback.onPushSucceeded();
1706								}
1707							} else {
1708								if (callback != null) {
1709									callback.onPushFailed();
1710								}
1711							}
1712						}
1713					});
1714				} else {
1715					if (callback != null) {
1716						callback.onPushFailed();
1717					}
1718				}
1719			}
1720		});
1721	}
1722
1723	public void pushSubjectToConference(final Conversation conference, final String subject) {
1724		MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
1725		this.sendMessagePacket(conference.getAccount(), packet);
1726		final MucOptions mucOptions = conference.getMucOptions();
1727		final MucOptions.User self = mucOptions.getSelf();
1728		if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
1729			Bundle options = new Bundle();
1730			options.putString("muc#roomconfig_persistentroom", "1");
1731			this.pushConferenceConfiguration(conference, options, null);
1732		}
1733	}
1734
1735	public void changeAffiliationInConference(final Conversation conference, Jid user, MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
1736		final Jid jid = user.toBareJid();
1737		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
1738		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1739			@Override
1740			public void onIqPacketReceived(Account account, IqPacket packet) {
1741				if (packet.getType() == IqPacket.TYPE.RESULT) {
1742					callback.onAffiliationChangedSuccessful(jid);
1743				} else {
1744					callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
1745				}
1746			}
1747		});
1748	}
1749
1750	public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
1751		List<Jid> jids = new ArrayList<>();
1752		for (MucOptions.User user : conference.getMucOptions().getUsers()) {
1753			if (user.getAffiliation() == before && user.getJid() != null) {
1754				jids.add(user.getJid());
1755			}
1756		}
1757		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
1758		sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
1759	}
1760
1761	public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
1762		IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
1763		Log.d(Config.LOGTAG, request.toString());
1764		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1765			@Override
1766			public void onIqPacketReceived(Account account, IqPacket packet) {
1767				Log.d(Config.LOGTAG, packet.toString());
1768				if (packet.getType() == IqPacket.TYPE.RESULT) {
1769					callback.onRoleChangedSuccessful(nick);
1770				} else {
1771					callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
1772				}
1773			}
1774		});
1775	}
1776
1777	public void disconnect(Account account, boolean force) {
1778		if ((account.getStatus() == Account.State.ONLINE)
1779				|| (account.getStatus() == Account.State.DISABLED)) {
1780			if (!force) {
1781				List<Conversation> conversations = getConversations();
1782				for (Conversation conversation : conversations) {
1783					if (conversation.getAccount() == account) {
1784						if (conversation.getMode() == Conversation.MODE_MULTI) {
1785							leaveMuc(conversation);
1786						} else {
1787							if (conversation.endOtrIfNeeded()) {
1788								Log.d(Config.LOGTAG, account.getJid().toBareJid()
1789										+ ": ended otr session with "
1790										+ conversation.getJid());
1791							}
1792						}
1793					}
1794				}
1795				sendOfflinePresence(account);
1796			}
1797			account.getXmppConnection().disconnect(force);
1798		}
1799	}
1800
1801	@Override
1802	public IBinder onBind(Intent intent) {
1803		return mBinder;
1804	}
1805
1806	public void updateMessage(Message message) {
1807		databaseBackend.updateMessage(message);
1808		updateConversationUi();
1809	}
1810
1811	protected void syncDirtyContacts(Account account) {
1812		for (Contact contact : account.getRoster().getContacts()) {
1813			if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
1814				pushContactToServer(contact);
1815			}
1816			if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
1817				deleteContactOnServer(contact);
1818			}
1819		}
1820	}
1821
1822	public void createContact(Contact contact) {
1823		SharedPreferences sharedPref = getPreferences();
1824		boolean autoGrant = sharedPref.getBoolean("grant_new_contacts", true);
1825		if (autoGrant) {
1826			contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
1827			contact.setOption(Contact.Options.ASKING);
1828		}
1829		pushContactToServer(contact);
1830	}
1831
1832	public void onOtrSessionEstablished(Conversation conversation) {
1833		final Account account = conversation.getAccount();
1834		final Session otrSession = conversation.getOtrSession();
1835		Log.d(Config.LOGTAG,
1836				account.getJid().toBareJid() + " otr session established with "
1837						+ conversation.getJid() + "/"
1838						+ otrSession.getSessionID().getUserID());
1839		conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR, new Conversation.OnMessageFound() {
1840
1841			@Override
1842			public void onMessageFound(Message message) {
1843				SessionID id = otrSession.getSessionID();
1844				try {
1845					message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
1846				} catch (InvalidJidException e) {
1847					return;
1848				}
1849				if (message.needsUploading()) {
1850					mJingleConnectionManager.createNewConnection(message);
1851				} else {
1852					MessagePacket outPacket = mMessageGenerator.generateOtrChat(message);
1853					if (outPacket != null) {
1854						mMessageGenerator.addDelay(outPacket,message.getTimeSent());
1855						message.setStatus(Message.STATUS_SEND);
1856						databaseBackend.updateMessage(message);
1857						sendMessagePacket(account, outPacket);
1858					}
1859				}
1860				updateConversationUi();
1861			}
1862		});
1863	}
1864
1865	public boolean renewSymmetricKey(Conversation conversation) {
1866		Account account = conversation.getAccount();
1867		byte[] symmetricKey = new byte[32];
1868		this.mRandom.nextBytes(symmetricKey);
1869		Session otrSession = conversation.getOtrSession();
1870		if (otrSession != null) {
1871			MessagePacket packet = new MessagePacket();
1872			packet.setType(MessagePacket.TYPE_CHAT);
1873			packet.setFrom(account.getJid());
1874			packet.addChild("private", "urn:xmpp:carbons:2");
1875			packet.addChild("no-copy", "urn:xmpp:hints");
1876			packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
1877					+ otrSession.getSessionID().getUserID());
1878			try {
1879				packet.setBody(otrSession
1880						.transformSending(CryptoHelper.FILETRANSFER
1881								+ CryptoHelper.bytesToHex(symmetricKey))[0]);
1882				sendMessagePacket(account, packet);
1883				conversation.setSymmetricKey(symmetricKey);
1884				return true;
1885			} catch (OtrException e) {
1886				return false;
1887			}
1888		}
1889		return false;
1890	}
1891
1892	public void pushContactToServer(final Contact contact) {
1893		contact.resetOption(Contact.Options.DIRTY_DELETE);
1894		contact.setOption(Contact.Options.DIRTY_PUSH);
1895		final Account account = contact.getAccount();
1896		if (account.getStatus() == Account.State.ONLINE) {
1897			final boolean ask = contact.getOption(Contact.Options.ASKING);
1898			final boolean sendUpdates = contact
1899					.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
1900					&& contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
1901			final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1902			iq.query(Xmlns.ROSTER).addChild(contact.asElement());
1903			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
1904			if (sendUpdates) {
1905				sendPresencePacket(account,
1906						mPresenceGenerator.sendPresenceUpdatesTo(contact));
1907			}
1908			if (ask) {
1909				sendPresencePacket(account,
1910						mPresenceGenerator.requestPresenceUpdatesFrom(contact));
1911			}
1912		}
1913	}
1914
1915	public void publishAvatar(final Account account,
1916							  final Uri image,
1917							  final UiCallback<Avatar> callback) {
1918		final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
1919		final int size = Config.AVATAR_SIZE;
1920		final Avatar avatar = getFileBackend()
1921				.getPepAvatar(image, size, format);
1922		if (avatar != null) {
1923			avatar.height = size;
1924			avatar.width = size;
1925			if (format.equals(Bitmap.CompressFormat.WEBP)) {
1926				avatar.type = "image/webp";
1927			} else if (format.equals(Bitmap.CompressFormat.JPEG)) {
1928				avatar.type = "image/jpeg";
1929			} else if (format.equals(Bitmap.CompressFormat.PNG)) {
1930				avatar.type = "image/png";
1931			}
1932			if (!getFileBackend().save(avatar)) {
1933				callback.error(R.string.error_saving_avatar, avatar);
1934				return;
1935			}
1936			final IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
1937			this.sendIqPacket(account, packet, new OnIqPacketReceived() {
1938
1939				@Override
1940				public void onIqPacketReceived(Account account, IqPacket result) {
1941					if (result.getType() == IqPacket.TYPE.RESULT) {
1942						final IqPacket packet = XmppConnectionService.this.mIqGenerator
1943								.publishAvatarMetadata(avatar);
1944						sendIqPacket(account, packet, new OnIqPacketReceived() {
1945
1946							@Override
1947							public void onIqPacketReceived(Account account,
1948														   IqPacket result) {
1949								if (result.getType() == IqPacket.TYPE.RESULT) {
1950									if (account.setAvatar(avatar.getFilename())) {
1951										getAvatarService().clear(account);
1952										databaseBackend.updateAccount(account);
1953									}
1954									callback.success(avatar);
1955								} else {
1956									callback.error(
1957											R.string.error_publish_avatar_server_reject,
1958											avatar);
1959								}
1960							}
1961						});
1962					} else {
1963						callback.error(
1964								R.string.error_publish_avatar_server_reject,
1965								avatar);
1966					}
1967				}
1968			});
1969		} else {
1970			callback.error(R.string.error_publish_avatar_converting, null);
1971		}
1972	}
1973
1974	public void fetchAvatar(Account account, Avatar avatar) {
1975		fetchAvatar(account, avatar, null);
1976	}
1977
1978	private static String generateFetchKey(Account account, final Avatar avatar) {
1979		return account.getJid().toBareJid()+"_"+avatar.owner+"_"+avatar.sha1sum;
1980	}
1981
1982	public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
1983		final String KEY = generateFetchKey(account, avatar);
1984		synchronized(this.mInProgressAvatarFetches) {
1985			if (this.mInProgressAvatarFetches.contains(KEY)) {
1986				return;
1987			} else {
1988				switch (avatar.origin) {
1989					case PEP:
1990						this.mInProgressAvatarFetches.add(KEY);
1991						fetchAvatarPep(account, avatar, callback);
1992						break;
1993					case VCARD:
1994						this.mInProgressAvatarFetches.add(KEY);
1995						fetchAvatarVcard(account, avatar, callback);
1996						break;
1997				}
1998			}
1999		}
2000	}
2001
2002	private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2003		IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
2004		sendIqPacket(account, packet, new OnIqPacketReceived() {
2005
2006			@Override
2007			public void onIqPacketReceived(Account account, IqPacket result) {
2008				synchronized (mInProgressAvatarFetches) {
2009					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2010				}
2011				final String ERROR = account.getJid().toBareJid()
2012						+ ": fetching avatar for " + avatar.owner + " failed ";
2013				if (result.getType() == IqPacket.TYPE.RESULT) {
2014					avatar.image = mIqParser.avatarData(result);
2015					if (avatar.image != null) {
2016						if (getFileBackend().save(avatar)) {
2017							if (account.getJid().toBareJid().equals(avatar.owner)) {
2018								if (account.setAvatar(avatar.getFilename())) {
2019									databaseBackend.updateAccount(account);
2020								}
2021								getAvatarService().clear(account);
2022								updateConversationUi();
2023								updateAccountUi();
2024							} else {
2025								Contact contact = account.getRoster()
2026										.getContact(avatar.owner);
2027								contact.setAvatar(avatar);
2028								getAvatarService().clear(contact);
2029								updateConversationUi();
2030								updateRosterUi();
2031							}
2032							if (callback != null) {
2033								callback.success(avatar);
2034							}
2035							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2036									+ ": succesfuly fetched pep avatar for " + avatar.owner);
2037							return;
2038						}
2039					} else {
2040
2041						Log.d(Config.LOGTAG, ERROR + "(parsing error)");
2042					}
2043				} else {
2044					Element error = result.findChild("error");
2045					if (error == null) {
2046						Log.d(Config.LOGTAG, ERROR + "(server error)");
2047					} else {
2048						Log.d(Config.LOGTAG, ERROR + error.toString());
2049					}
2050				}
2051				if (callback != null) {
2052					callback.error(0, null);
2053				}
2054
2055			}
2056		});
2057	}
2058
2059	private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2060		IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
2061		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2062			@Override
2063			public void onIqPacketReceived(Account account, IqPacket packet) {
2064				synchronized (mInProgressAvatarFetches) {
2065					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2066				}
2067				if (packet.getType() == IqPacket.TYPE.RESULT) {
2068					Element vCard = packet.findChild("vCard", "vcard-temp");
2069					Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
2070					String image = photo != null ? photo.findChildContent("BINVAL") : null;
2071					if (image != null) {
2072						avatar.image = image;
2073						if (getFileBackend().save(avatar)) {
2074							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2075									+ ": successfully fetched vCard avatar for " + avatar.owner);
2076							Contact contact = account.getRoster()
2077									.getContact(avatar.owner);
2078							contact.setAvatar(avatar);
2079							getAvatarService().clear(contact);
2080							updateConversationUi();
2081							updateRosterUi();
2082						}
2083					}
2084				}
2085			}
2086		});
2087	}
2088
2089	public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
2090		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2091		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2092
2093			@Override
2094			public void onIqPacketReceived(Account account, IqPacket packet) {
2095				if (packet.getType() == IqPacket.TYPE.RESULT) {
2096					Element pubsub = packet.findChild("pubsub",
2097							"http://jabber.org/protocol/pubsub");
2098					if (pubsub != null) {
2099						Element items = pubsub.findChild("items");
2100						if (items != null) {
2101							Avatar avatar = Avatar.parseMetadata(items);
2102							if (avatar != null) {
2103								avatar.owner = account.getJid().toBareJid();
2104								if (fileBackend.isAvatarCached(avatar)) {
2105									if (account.setAvatar(avatar.getFilename())) {
2106										databaseBackend.updateAccount(account);
2107									}
2108									getAvatarService().clear(account);
2109									callback.success(avatar);
2110								} else {
2111									fetchAvatarPep(account, avatar, callback);
2112								}
2113								return;
2114							}
2115						}
2116					}
2117				}
2118				callback.error(0, null);
2119			}
2120		});
2121	}
2122
2123	public void deleteContactOnServer(Contact contact) {
2124		contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
2125		contact.resetOption(Contact.Options.DIRTY_PUSH);
2126		contact.setOption(Contact.Options.DIRTY_DELETE);
2127		Account account = contact.getAccount();
2128		if (account.getStatus() == Account.State.ONLINE) {
2129			IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2130			Element item = iq.query(Xmlns.ROSTER).addChild("item");
2131			item.setAttribute("jid", contact.getJid().toString());
2132			item.setAttribute("subscription", "remove");
2133			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2134		}
2135	}
2136
2137	public void updateConversation(Conversation conversation) {
2138		this.databaseBackend.updateConversation(conversation);
2139	}
2140
2141	public void reconnectAccount(final Account account, final boolean force) {
2142		synchronized (account) {
2143			if (account.getXmppConnection() != null) {
2144				disconnect(account, force);
2145			}
2146			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2147
2148				synchronized (this.mInProgressAvatarFetches) {
2149					for(Iterator<String> iterator = this.mInProgressAvatarFetches.iterator(); iterator.hasNext();) {
2150						final String KEY = iterator.next();
2151						if (KEY.startsWith(account.getJid().toBareJid()+"_")) {
2152							iterator.remove();
2153						}
2154					}
2155				}
2156
2157				if (account.getXmppConnection() == null) {
2158					account.setXmppConnection(createConnection(account));
2159				}
2160				Thread thread = new Thread(account.getXmppConnection());
2161				thread.start();
2162				scheduleWakeUpCall(Config.CONNECT_TIMEOUT, account.getUuid().hashCode());
2163			} else {
2164				account.getRoster().clearPresences();
2165				account.setXmppConnection(null);
2166			}
2167		}
2168	}
2169
2170	public void reconnectAccountInBackground(final Account account) {
2171		new Thread(new Runnable() {
2172			@Override
2173			public void run() {
2174				reconnectAccount(account,false);
2175			}
2176		}).start();
2177	}
2178
2179	public void invite(Conversation conversation, Jid contact) {
2180		Log.d(Config.LOGTAG,conversation.getAccount().getJid().toBareJid()+": inviting "+contact+" to "+conversation.getJid().toBareJid());
2181		MessagePacket packet = mMessageGenerator.invite(conversation, contact);
2182		sendMessagePacket(conversation.getAccount(), packet);
2183	}
2184
2185	public void directInvite(Conversation conversation, Jid jid) {
2186		MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
2187		sendMessagePacket(conversation.getAccount(),packet);
2188	}
2189
2190	public void resetSendingToWaiting(Account account) {
2191		for (Conversation conversation : getConversations()) {
2192			if (conversation.getAccount() == account) {
2193				conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
2194
2195					@Override
2196					public void onMessageFound(Message message) {
2197						markMessage(message, Message.STATUS_WAITING);
2198					}
2199				});
2200			}
2201		}
2202	}
2203
2204	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
2205		if (uuid == null) {
2206			return null;
2207		}
2208		for (Conversation conversation : getConversations()) {
2209			if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
2210				final Message message = conversation.findSentMessageWithUuid(uuid);
2211				if (message != null) {
2212					markMessage(message, status);
2213				}
2214				return message;
2215			}
2216		}
2217		return null;
2218	}
2219
2220	public boolean markMessage(Conversation conversation, String uuid,
2221							   int status) {
2222		if (uuid == null) {
2223			return false;
2224		} else {
2225			Message message = conversation.findSentMessageWithUuid(uuid);
2226			if (message != null) {
2227				markMessage(message, status);
2228				return true;
2229			} else {
2230				return false;
2231			}
2232		}
2233	}
2234
2235	public void markMessage(Message message, int status) {
2236		if (status == Message.STATUS_SEND_FAILED
2237				&& (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
2238				.getStatus() == Message.STATUS_SEND_DISPLAYED)) {
2239			return;
2240		}
2241		message.setStatus(status);
2242		databaseBackend.updateMessage(message);
2243		updateConversationUi();
2244	}
2245
2246	public SharedPreferences getPreferences() {
2247		return PreferenceManager
2248				.getDefaultSharedPreferences(getApplicationContext());
2249	}
2250
2251	public boolean forceEncryption() {
2252		return getPreferences().getBoolean("force_encryption", false);
2253	}
2254
2255	public boolean confirmMessages() {
2256		return getPreferences().getBoolean("confirm_messages", true);
2257	}
2258
2259	public boolean sendChatStates() {
2260		return getPreferences().getBoolean("chat_states", false);
2261	}
2262
2263	public boolean saveEncryptedMessages() {
2264		return !getPreferences().getBoolean("dont_save_encrypted", false);
2265	}
2266
2267	public boolean indicateReceived() {
2268		return getPreferences().getBoolean("indicate_received", false);
2269	}
2270
2271	public int unreadCount() {
2272		int count = 0;
2273		for(Conversation conversation : getConversations()) {
2274			count += conversation.unreadCount();
2275		}
2276		return count;
2277	}
2278
2279
2280	public void showErrorToastInUi(int resId) {
2281		if (mOnShowErrorToast != null) {
2282			mOnShowErrorToast.onShowErrorToast(resId);
2283		}
2284	}
2285
2286	public void updateConversationUi() {
2287		if (mOnConversationUpdate != null) {
2288			mOnConversationUpdate.onConversationUpdate();
2289		}
2290	}
2291
2292	public void updateAccountUi() {
2293		if (mOnAccountUpdate != null) {
2294			mOnAccountUpdate.onAccountUpdate();
2295		}
2296	}
2297
2298	public void updateRosterUi() {
2299		if (mOnRosterUpdate != null) {
2300			mOnRosterUpdate.onRosterUpdate();
2301		}
2302	}
2303
2304	public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
2305		if (mOnUpdateBlocklist != null) {
2306			mOnUpdateBlocklist.OnUpdateBlocklist(status);
2307		}
2308	}
2309
2310	public void updateMucRosterUi() {
2311		if (mOnMucRosterUpdate != null) {
2312			mOnMucRosterUpdate.onMucRosterUpdate();
2313		}
2314	}
2315
2316	public void newKeysAvailable() {
2317		if(mOnNewKeysAvailable != null) {
2318			mOnNewKeysAvailable.onNewKeysAvailable();
2319		}
2320	}
2321
2322	public Account findAccountByJid(final Jid accountJid) {
2323		for (Account account : this.accounts) {
2324			if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
2325				return account;
2326			}
2327		}
2328		return null;
2329	}
2330
2331	public Conversation findConversationByUuid(String uuid) {
2332		for (Conversation conversation : getConversations()) {
2333			if (conversation.getUuid().equals(uuid)) {
2334				return conversation;
2335			}
2336		}
2337		return null;
2338	}
2339
2340	public void markRead(final Conversation conversation) {
2341		mNotificationService.clear(conversation);
2342		conversation.markRead();
2343		updateUnreadCountBadge();
2344	}
2345
2346	public synchronized void updateUnreadCountBadge() {
2347		int count = unreadCount();
2348		if (unreadCount != count) {
2349			Log.d(Config.LOGTAG, "update unread count to " + count);
2350			if (count > 0) {
2351				ShortcutBadger.with(getApplicationContext()).count(count);
2352			} else {
2353				ShortcutBadger.with(getApplicationContext()).remove();
2354			}
2355			unreadCount = count;
2356		}
2357	}
2358
2359	public void sendReadMarker(final Conversation conversation) {
2360		final Message markable = conversation.getLatestMarkableMessage();
2361		this.markRead(conversation);
2362		if (confirmMessages() && markable != null && markable.getRemoteMsgId() != null) {
2363			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
2364			Account account = conversation.getAccount();
2365			final Jid to = markable.getCounterpart();
2366			MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
2367			this.sendMessagePacket(conversation.getAccount(), packet);
2368		}
2369		updateConversationUi();
2370	}
2371
2372	public SecureRandom getRNG() {
2373		return this.mRandom;
2374	}
2375
2376	public MemorizingTrustManager getMemorizingTrustManager() {
2377		return this.mMemorizingTrustManager;
2378	}
2379
2380	public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
2381		this.mMemorizingTrustManager = trustManager;
2382	}
2383
2384	public void updateMemorizingTrustmanager() {
2385		final MemorizingTrustManager tm;
2386		final boolean dontTrustSystemCAs = getPreferences().getBoolean("dont_trust_system_cas", false);
2387		if (dontTrustSystemCAs) {
2388			 tm = new MemorizingTrustManager(getApplicationContext(), null);
2389		} else {
2390			tm = new MemorizingTrustManager(getApplicationContext());
2391		}
2392		setMemorizingTrustManager(tm);
2393	}
2394
2395	public PowerManager getPowerManager() {
2396		return this.pm;
2397	}
2398
2399	public LruCache<String, Bitmap> getBitmapCache() {
2400		return this.mBitmapCache;
2401	}
2402
2403	public void syncRosterToDisk(final Account account) {
2404		Runnable runnable = new Runnable() {
2405
2406			@Override
2407			public void run() {
2408				databaseBackend.writeRoster(account.getRoster());
2409			}
2410		};
2411		mDatabaseExecutor.execute(runnable);
2412
2413	}
2414
2415	public List<String> getKnownHosts() {
2416		final List<String> hosts = new ArrayList<>();
2417		for (final Account account : getAccounts()) {
2418			if (!hosts.contains(account.getServer().toString())) {
2419				hosts.add(account.getServer().toString());
2420			}
2421			for (final Contact contact : account.getRoster().getContacts()) {
2422				if (contact.showInRoster()) {
2423					final String server = contact.getServer().toString();
2424					if (server != null && !hosts.contains(server)) {
2425						hosts.add(server);
2426					}
2427				}
2428			}
2429		}
2430		return hosts;
2431	}
2432
2433	public List<String> getKnownConferenceHosts() {
2434		final ArrayList<String> mucServers = new ArrayList<>();
2435		for (final Account account : accounts) {
2436			if (account.getXmppConnection() != null) {
2437				final String server = account.getXmppConnection().getMucServer();
2438				if (server != null && !mucServers.contains(server)) {
2439					mucServers.add(server);
2440				}
2441			}
2442		}
2443		return mucServers;
2444	}
2445
2446	public void sendMessagePacket(Account account, MessagePacket packet) {
2447		XmppConnection connection = account.getXmppConnection();
2448		if (connection != null) {
2449			connection.sendMessagePacket(packet);
2450		}
2451	}
2452
2453	public void sendPresencePacket(Account account, PresencePacket packet) {
2454		XmppConnection connection = account.getXmppConnection();
2455		if (connection != null) {
2456			connection.sendPresencePacket(packet);
2457		}
2458	}
2459
2460	public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
2461		final XmppConnection connection = account.getXmppConnection();
2462		if (connection != null) {
2463			connection.sendIqPacket(packet, callback);
2464		}
2465	}
2466
2467	public void sendPresence(final Account account) {
2468		sendPresencePacket(account, mPresenceGenerator.sendPresence(account));
2469	}
2470
2471	public void sendOfflinePresence(final Account account) {
2472		sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
2473	}
2474
2475	public MessageGenerator getMessageGenerator() {
2476		return this.mMessageGenerator;
2477	}
2478
2479	public PresenceGenerator getPresenceGenerator() {
2480		return this.mPresenceGenerator;
2481	}
2482
2483	public IqGenerator getIqGenerator() {
2484		return this.mIqGenerator;
2485	}
2486
2487	public IqParser getIqParser() {
2488		return this.mIqParser;
2489	}
2490
2491	public JingleConnectionManager getJingleConnectionManager() {
2492		return this.mJingleConnectionManager;
2493	}
2494
2495	public MessageArchiveService getMessageArchiveService() {
2496		return this.mMessageArchiveService;
2497	}
2498
2499	public List<Contact> findContacts(Jid jid) {
2500		ArrayList<Contact> contacts = new ArrayList<>();
2501		for (Account account : getAccounts()) {
2502			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2503				Contact contact = account.getRoster().getContactFromRoster(jid);
2504				if (contact != null) {
2505					contacts.add(contact);
2506				}
2507			}
2508		}
2509		return contacts;
2510	}
2511
2512	public NotificationService getNotificationService() {
2513		return this.mNotificationService;
2514	}
2515
2516	public HttpConnectionManager getHttpConnectionManager() {
2517		return this.mHttpConnectionManager;
2518	}
2519
2520	public void resendFailedMessages(final Message message) {
2521		final Collection<Message> messages = new ArrayList<>();
2522		Message current = message;
2523		while (current.getStatus() == Message.STATUS_SEND_FAILED) {
2524			messages.add(current);
2525			if (current.mergeable(current.next())) {
2526				current = current.next();
2527			} else {
2528				break;
2529			}
2530		}
2531		for (final Message msg : messages) {
2532			markMessage(msg, Message.STATUS_WAITING);
2533			this.resendMessage(msg,true);
2534		}
2535	}
2536
2537	public void clearConversationHistory(final Conversation conversation) {
2538		conversation.clearMessages();
2539		conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
2540		new Thread(new Runnable() {
2541			@Override
2542			public void run() {
2543				databaseBackend.deleteMessagesInConversation(conversation);
2544			}
2545		}).start();
2546	}
2547
2548	public void sendBlockRequest(final Blockable blockable) {
2549		if (blockable != null && blockable.getBlockedJid() != null) {
2550			final Jid jid = blockable.getBlockedJid();
2551			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid), new OnIqPacketReceived() {
2552
2553				@Override
2554				public void onIqPacketReceived(final Account account, final IqPacket packet) {
2555					if (packet.getType() == IqPacket.TYPE.RESULT) {
2556						account.getBlocklist().add(jid);
2557						updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
2558					}
2559				}
2560			});
2561		}
2562	}
2563
2564	public void sendUnblockRequest(final Blockable blockable) {
2565		if (blockable != null && blockable.getJid() != null) {
2566			final Jid jid = blockable.getBlockedJid();
2567			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
2568				@Override
2569				public void onIqPacketReceived(final Account account, final IqPacket packet) {
2570					if (packet.getType() == IqPacket.TYPE.RESULT) {
2571						account.getBlocklist().remove(jid);
2572						updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
2573					}
2574				}
2575			});
2576		}
2577	}
2578
2579	public interface OnMoreMessagesLoaded {
2580		public void onMoreMessagesLoaded(int count, Conversation conversation);
2581
2582		public void informUser(int r);
2583	}
2584
2585	public interface OnAccountPasswordChanged {
2586		public void onPasswordChangeSucceeded();
2587
2588		public void onPasswordChangeFailed();
2589	}
2590
2591	public interface OnAffiliationChanged {
2592		public void onAffiliationChangedSuccessful(Jid jid);
2593
2594		public void onAffiliationChangeFailed(Jid jid, int resId);
2595	}
2596
2597	public interface OnRoleChanged {
2598		public void onRoleChangedSuccessful(String nick);
2599
2600		public void onRoleChangeFailed(String nick, int resid);
2601	}
2602
2603	public interface OnConversationUpdate {
2604		public void onConversationUpdate();
2605	}
2606
2607	public interface OnAccountUpdate {
2608		public void onAccountUpdate();
2609	}
2610
2611	public interface OnRosterUpdate {
2612		public void onRosterUpdate();
2613	}
2614
2615	public interface OnMucRosterUpdate {
2616		public void onMucRosterUpdate();
2617	}
2618
2619	public interface OnConferenceOptionsPushed {
2620		public void onPushSucceeded();
2621
2622		public void onPushFailed();
2623	}
2624
2625	public interface OnShowErrorToast {
2626		void onShowErrorToast(int resId);
2627	}
2628
2629	public class XmppConnectionBinder extends Binder {
2630		public XmppConnectionService getService() {
2631			return XmppConnectionService.this;
2632		}
2633	}
2634}