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